Remove altivec specific memory clearing
[llpp.git] / link.c
blob11c1eb7f0c4adbcf09f03fe5e8f97fbff8ec36e7
1 /* lots of code c&p-ed directly from mupdf */
2 #ifdef __clang__
3 #pragma GCC diagnostic error "-Weverything"
4 #pragma GCC diagnostic ignored "-Wpadded"
5 #pragma GCC diagnostic ignored "-Wsign-conversion"
6 #pragma GCC diagnostic ignored "-Wdocumentation-unknown-command"
7 #pragma GCC diagnostic ignored "-Wdocumentation"
8 #pragma GCC diagnostic ignored "-Wmissing-prototypes"
9 #endif
11 #define CAML_NAME_SPACE
12 #define FIXME 0
14 extern char **environ;
16 #include <errno.h>
17 #include <stdio.h>
18 #include <ctype.h>
19 #include <string.h>
20 #include <stdlib.h>
21 #include <signal.h>
23 #include <math.h>
24 #include <wchar.h>
25 #include <locale.h>
26 #include <langinfo.h>
28 #include <unistd.h>
29 #include <pthread.h>
30 #include <sys/uio.h>
31 #include <sys/time.h>
32 #include <sys/stat.h>
33 #include <fcntl.h>
34 #include <sys/types.h>
35 #include <sys/ioctl.h>
36 #include <sys/utsname.h>
38 #include <spawn.h>
40 #include <regex.h>
41 #include <stdarg.h>
42 #include <limits.h>
43 #include <inttypes.h>
45 #ifdef __COCOA__
46 #include <CoreFoundation/CoreFoundation.h>
47 #endif
49 #ifdef __APPLE__
50 #include <OpenGL/gl.h>
51 #else
52 #include <GL/gl.h>
53 #endif
55 #pragma GCC diagnostic push
56 #ifdef __clang__
57 #pragma GCC diagnostic ignored "-Wreserved-id-macro"
58 #endif
59 #pragma GCC diagnostic ignored "-Wpedantic"
60 #include <caml/fail.h>
61 #include <caml/alloc.h>
62 #include <caml/memory.h>
63 #include <caml/unixsupport.h>
65 #pragma GCC diagnostic push
66 #pragma GCC diagnostic ignored "-Wfloat-equal"
67 #pragma GCC diagnostic ignored "-Wundef"
68 #include <mupdf/fitz.h>
69 #include <mupdf/pdf.h>
70 #pragma GCC diagnostic pop
72 #include <ft2build.h>
73 #include FT_FREETYPE_H
74 #pragma GCC diagnostic pop
76 #include "cutils.h"
78 #define PIGGYBACK
79 #define CACHE_PAGEREFS
81 #ifndef GL_TEXTURE_RECTANGLE_ARB
82 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
83 #endif
85 #ifdef USE_NPOT
86 #define TEXT_TYPE GL_TEXTURE_2D
87 #else
88 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
89 #endif
91 #ifndef GL_BGRA
92 #define GL_BGRA 0x80E1
93 #endif
95 #ifndef GL_UNSIGNED_INT_8_8_8_8
96 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
97 #endif
99 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
100 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
101 #endif
103 #if 0
104 #define lprintf printf
105 #else
106 #define lprintf(...)
107 #endif
109 #define ARSERT(cond) for (;;) { \
110 if (!(cond)) { \
111 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
113 break; \
116 struct slice {
117 int h;
118 int texindex;
121 struct tile {
122 int w, h;
123 int slicecount;
124 int sliceheight;
125 struct bo *pbo;
126 fz_pixmap *pixmap;
127 struct slice slices[1];
130 struct pagedim {
131 int pageno;
132 int rotate;
133 int left;
134 int tctmready;
135 fz_irect bounds;
136 fz_rect pagebox;
137 fz_rect mediabox;
138 fz_matrix ctm, zoomctm, tctm;
141 struct slink {
142 enum { SLINK, SANNOT } tag;
143 fz_irect bbox;
144 union {
145 fz_link *link;
146 fz_annot *annot;
147 } u;
150 struct annot {
151 fz_irect bbox;
152 fz_annot *annot;
155 struct page {
156 int tgen;
157 int sgen;
158 int agen;
159 int pageno;
160 int pdimno;
161 fz_stext_page *text;
162 fz_page *fzpage;
163 fz_display_list *dlist;
164 fz_link *links;
165 int slinkcount;
166 struct slink *slinks;
167 int annotcount;
168 struct annot *annots;
169 fz_stext_char *fmark, *lmark;
172 enum { FitWidth, FitProportional, FitPage };
174 static struct {
175 int sliceheight;
176 struct pagedim *pagedims;
177 int pagecount;
178 int pagedimcount;
179 fz_document *doc;
180 fz_context *ctx;
181 int w, h;
183 int texindex;
184 int texcount;
185 GLuint *texids;
187 GLenum texiform;
188 GLenum texform;
189 GLenum texty;
191 fz_colorspace *colorspace;
193 struct {
194 int w, h;
195 struct slice *slice;
196 } *texowners;
198 int rotate;
199 int fitmodel;
200 int trimmargins;
201 int needoutline;
202 int gen;
203 int aalevel;
205 int trimanew;
206 fz_irect trimfuzz;
207 fz_pixmap *pig;
209 pthread_t thread;
210 int csock;
211 FT_Face face;
213 char *trimcachepath;
214 int dirty;
216 GLuint stid;
218 int bo_usable;
219 GLuint boid;
221 void (*glBindBufferARB) (GLenum, GLuint);
222 GLboolean (*glUnmapBufferARB) (GLenum);
223 void *(*glMapBufferARB) (GLenum, GLenum);
224 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
225 void (*glGenBuffersARB) (GLsizei, GLuint *);
226 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
228 GLfloat texcoords[8];
229 GLfloat vertices[16];
231 #ifdef CACHE_PAGEREFS
232 struct {
233 int idx;
234 int count;
235 pdf_obj **objs;
236 pdf_document *pdf;
237 } pdflut;
238 #endif
239 int utf8cs;
240 } state;
242 struct bo {
243 GLuint id;
244 void *ptr;
245 size_t size;
248 #pragma GCC diagnostic ignored "-Wdouble-promotion"
249 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
251 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
254 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
256 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
259 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
261 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
262 m.a, m.b, m.c, m.d, m.e, m.f);
264 #pragma GCC diagnostic error "-Wdouble-promotion"
266 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
268 static void lock (const char *cap)
270 int ret = pthread_mutex_lock (&mutex);
271 if (ret) {
272 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
276 static void unlock (const char *cap)
278 int ret = pthread_mutex_unlock (&mutex);
279 if (ret) {
280 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
284 static int trylock (const char *cap)
286 int ret = pthread_mutex_trylock (&mutex);
287 if (ret && ret != EBUSY) {
288 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
290 return ret == EBUSY;
293 static int hasdata (void)
295 int ret, avail;
296 ret = ioctl (state.csock, FIONREAD, &avail);
297 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
298 return avail > 0;
301 CAMLprim value ml_hasdata (value fd_v)
303 CAMLparam1 (fd_v);
304 int ret, avail;
306 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
307 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
308 CAMLreturn (Val_bool (avail > 0));
311 static void readdata (int fd, void *p, int size)
313 ssize_t n;
315 again:
316 n = read (fd, p, size);
317 if (n - size) {
318 if (n < 0 && errno == EINTR) goto again;
319 if (!n) errx (1, "EOF while reading");
320 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
324 static void writedata (int fd, char *p, int size)
326 ssize_t n;
327 uint32_t size4 = size;
328 struct iovec iov[2] = {
329 { .iov_base = &size4, .iov_len = 4 },
330 { .iov_base = p, .iov_len = size }
333 again:
334 n = writev (fd, iov, 2);
335 if (n < 0 && errno == EINTR) goto again;
336 if (n - size - 4) {
337 if (!n) errx (1, "EOF while writing data");
338 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
342 static int readlen (int fd)
344 uint32_t u;
345 readdata (fd, &u, 4);
346 return u;
349 CAMLprim void ml_wcmd (value fd_v, value bytes_v, value len_v)
351 CAMLparam3 (fd_v, bytes_v, len_v);
352 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
353 CAMLreturn0;
356 CAMLprim value ml_rcmd (value fd_v)
358 CAMLparam1 (fd_v);
359 CAMLlocal1 (strdata_v);
360 int fd = Int_val (fd_v);
361 int len = readlen (fd);
362 strdata_v = caml_alloc_string (len);
363 readdata (fd, String_val (strdata_v), len);
364 CAMLreturn (strdata_v);
367 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
369 char fbuf[64];
370 int size = sizeof (fbuf), len;
371 va_list ap;
372 char *buf = fbuf;
374 for (;;) {
375 va_start (ap, fmt);
376 len = vsnprintf (buf, size, fmt, ap);
377 va_end (ap);
379 if (len > -1) {
380 if (len < size - 4) {
381 writedata (state.csock, buf, len);
382 break;
384 else size = len + 5;
386 else {
387 err (1, "vsnprintf for `%s' failed", fmt);
389 buf = realloc (buf == fbuf ? NULL : buf, size);
390 if (!buf) err (1, "realloc for temp buf (%d bytes) failed", size);
392 if (buf != fbuf) free (buf);
395 static void closedoc (void)
397 #ifdef CACHE_PAGEREFS
398 if (state.pdflut.objs) {
399 for (int i = 0; i < state.pdflut.count; ++i) {
400 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
402 free (state.pdflut.objs);
403 state.pdflut.objs = NULL;
404 state.pdflut.idx = 0;
406 #endif
407 if (state.doc) {
408 fz_drop_document (state.ctx, state.doc);
409 state.doc = NULL;
413 static int openxref (char *filename, char *password, int layouth)
415 for (int i = 0; i < state.texcount; ++i) {
416 state.texowners[i].w = -1;
417 state.texowners[i].slice = NULL;
420 closedoc ();
422 state.dirty = 0;
423 if (state.pagedims) {
424 free (state.pagedims);
425 state.pagedims = NULL;
427 state.pagedimcount = 0;
429 fz_set_aa_level (state.ctx, state.aalevel);
430 state.doc = fz_open_document (state.ctx, filename);
431 if (fz_needs_password (state.ctx, state.doc)) {
432 if (password && !*password) {
433 printd ("pass");
434 return 0;
436 else {
437 int ok = fz_authenticate_password (state.ctx, state.doc, password);
438 if (!ok) {
439 printd ("pass fail");
440 return 0;
444 if (layouth >= 0)
445 fz_layout_document (state.ctx, state.doc, 460, layouth, 12);
446 state.pagecount = fz_count_pages (state.ctx, state.doc);
447 return 1;
450 static void docinfo (void)
452 struct { char *tag; char *name; } metatbl[] = {
453 { FZ_META_INFO_TITLE, "Title" },
454 { FZ_META_INFO_AUTHOR, "Author" },
455 { FZ_META_FORMAT, "Format" },
456 { FZ_META_ENCRYPTION, "Encryption" },
457 { "info:Creator", "Creator" },
458 { "info:Producer", "Producer" },
459 { "info:CreationDate", "Creation date" },
461 int len = 0;
462 char *buf = NULL;
464 for (size_t i = 0; i < sizeof (metatbl) / sizeof (metatbl[1]); ++i) {
465 int need;
466 again:
467 need = fz_lookup_metadata (state.ctx, state.doc,
468 metatbl[i].tag, buf, len);
469 if (need > 0) {
470 if (need <= len) {
471 printd ("info %s\t%s", metatbl[i].name, buf);
473 else {
474 buf = realloc (buf, need + 1);
475 if (!buf) err (1, "docinfo realloc %d", need + 1);
476 len = need + 1;
477 goto again;
481 free (buf);
483 printd ("infoend");
486 static void unlinktile (struct tile *tile)
488 for (int i = 0; i < tile->slicecount; ++i) {
489 struct slice *s = &tile->slices[i];
491 if (s->texindex != -1) {
492 if (state.texowners[s->texindex].slice == s) {
493 state.texowners[s->texindex].slice = NULL;
499 static void freepage (struct page *page)
501 if (!page) return;
502 if (page->text) {
503 fz_drop_stext_page (state.ctx, page->text);
505 if (page->slinks) {
506 free (page->slinks);
508 fz_drop_display_list (state.ctx, page->dlist);
509 fz_drop_page (state.ctx, page->fzpage);
510 free (page);
513 static void freetile (struct tile *tile)
515 unlinktile (tile);
516 if (!tile->pbo) {
517 #ifndef PIGGYBACK
518 fz_drop_pixmap (state.ctx, tile->pixmap);
519 #else
520 if (state.pig) {
521 fz_drop_pixmap (state.ctx, state.pig);
523 state.pig = tile->pixmap;
524 #endif
526 else {
527 free (tile->pbo);
528 fz_drop_pixmap (state.ctx, tile->pixmap);
530 free (tile);
533 static void trimctm (pdf_page *page, int pindex)
535 fz_matrix ctm;
536 struct pagedim *pdim = &state.pagedims[pindex];
538 if (!page) return;
539 if (!pdim->tctmready) {
540 fz_rect realbox, mediabox;
541 fz_matrix rm, sm, tm, im, ctm1, page_ctm;
543 fz_rotate (&rm, -pdim->rotate);
544 fz_scale (&sm, 1, -1);
545 fz_concat (&ctm, &rm, &sm);
546 realbox = pdim->mediabox;
547 fz_transform_rect (&realbox, &ctm);
548 fz_translate (&tm, -realbox.x0, -realbox.y0);
549 fz_concat (&ctm1, &ctm, &tm);
550 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
551 fz_invert_matrix (&im, &page_ctm);
552 fz_concat (&ctm, &im, &ctm1);
553 pdim->tctm = ctm;
554 pdim->tctmready = 1;
558 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
560 fz_matrix ctm, tm;
561 ptrdiff_t pdimno = pdim - state.pagedims;
563 ARSERT (pdim - state.pagedims < INT_MAX);
564 if (pdf_specifics (state.ctx, state.doc)) {
565 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), (int) pdimno);
566 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
568 else {
569 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
570 fz_concat (&ctm, &tm, &pdim->ctm);
572 return ctm;
575 static fz_matrix pagectm (struct page *page)
577 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
580 static void *loadpage (int pageno, int pindex)
582 fz_device *dev;
583 struct page *page;
585 page = calloc (sizeof (struct page), 1);
586 if (!page) {
587 err (1, "calloc page %d", pageno);
590 page->dlist = fz_new_display_list (state.ctx, NULL);
591 dev = fz_new_list_device (state.ctx, page->dlist);
592 fz_try (state.ctx) {
593 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
594 fz_run_page (state.ctx, page->fzpage, dev,
595 &fz_identity, NULL);
597 fz_catch (state.ctx) {
598 page->fzpage = NULL;
600 fz_close_device (state.ctx, dev);
601 fz_drop_device (state.ctx, dev);
603 page->pdimno = pindex;
604 page->pageno = pageno;
605 page->sgen = state.gen;
606 page->agen = state.gen;
607 page->tgen = state.gen;
608 return page;
611 static struct tile *alloctile (int h)
613 int slicecount;
614 size_t tilesize;
615 struct tile *tile;
617 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
618 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
619 tile = calloc (tilesize, 1);
620 if (!tile) {
621 err (1, "cannot allocate tile (%zu bytes)", tilesize);
623 for (int i = 0; i < slicecount; ++i) {
624 int sh = fz_mini (h, state.sliceheight);
625 tile->slices[i].h = sh;
626 tile->slices[i].texindex = -1;
627 h -= sh;
629 tile->slicecount = slicecount;
630 tile->sliceheight = state.sliceheight;
631 return tile;
634 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
635 struct bo *pbo)
637 fz_rect rect;
638 fz_irect bbox;
639 fz_matrix ctm;
640 fz_device *dev;
641 struct tile *tile;
642 struct pagedim *pdim;
644 tile = alloctile (h);
645 pdim = &state.pagedims[page->pdimno];
647 bbox = pdim->bounds;
648 bbox.x0 += x;
649 bbox.y0 += y;
650 bbox.x1 = bbox.x0 + w;
651 bbox.y1 = bbox.y0 + h;
653 if (state.pig) {
654 if (state.pig->w == w
655 && state.pig->h == h
656 && state.pig->colorspace == state.colorspace) {
657 tile->pixmap = state.pig;
658 tile->pixmap->x = bbox.x0;
659 tile->pixmap->y = bbox.y0;
661 else {
662 fz_drop_pixmap (state.ctx, state.pig);
664 state.pig = NULL;
666 if (!tile->pixmap) {
667 if (pbo) {
668 tile->pixmap =
669 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
670 &bbox, NULL, 1, pbo->ptr);
671 tile->pbo = pbo;
673 else {
674 tile->pixmap =
675 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox,
676 NULL, 1);
680 tile->w = w;
681 tile->h = h;
682 fz_clear_pixmap_with_value (state.ctx, tile->pixmap, 0xff);
684 dev = fz_new_draw_device (state.ctx, NULL, tile->pixmap);
685 ctm = pagectm (page);
686 fz_rect_from_irect (&rect, &bbox);
687 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
688 fz_close_device (state.ctx, dev);
689 fz_drop_device (state.ctx, dev);
691 return tile;
694 #ifdef CACHE_PAGEREFS
695 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
696 thanks to Robin Watts */
697 static void
698 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
700 fz_context *ctx = state.ctx; /* doc->ctx; */
701 pdf_obj *kids;
702 int len;
704 if (state.pdflut.idx == state.pagecount) return;
706 kids = pdf_dict_gets (ctx, node, "Kids");
707 len = pdf_array_len (ctx, kids);
709 if (len == 0)
710 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
712 if (pdf_mark_obj (ctx, node))
713 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
714 for (int i = 0; i < len; i++) {
715 pdf_obj *kid = pdf_array_get (ctx, kids, i);
716 const char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
717 if (*type
718 ? !strcmp (type, "Pages")
719 : pdf_dict_gets (ctx, kid, "Kids")
720 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
721 pdf_collect_pages (doc, kid);
723 else {
724 if (*type
725 ? strcmp (type, "Page") != 0
726 : !pdf_dict_gets (ctx, kid, "MediaBox"))
727 fz_warn (ctx, "non-page object in page tree (%s)", type);
728 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
731 pdf_unmark_obj (ctx, node);
734 static void
735 pdf_load_page_objs (pdf_document *doc)
737 pdf_obj *root = pdf_dict_gets (state.ctx,
738 pdf_trailer (state.ctx, doc), "Root");
739 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
741 if (!node)
742 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
744 state.pdflut.idx = 0;
745 pdf_collect_pages (doc, node);
747 #endif
749 static void initpdims (void)
751 double start, end;
752 FILE *trimf = NULL;
753 fz_rect rootmediabox = fz_empty_rect;
754 int pageno, trim, show;
755 int trimw = 0, cxcount;
756 fz_context *ctx = state.ctx;
757 pdf_document *pdf = pdf_specifics (ctx, state.doc);
759 fz_var (trimw);
760 fz_var (trimf);
761 fz_var (cxcount);
762 start = now ();
764 if (state.trimmargins && state.trimcachepath) {
765 trimf = fopen (state.trimcachepath, "rb");
766 if (!trimf) {
767 trimf = fopen (state.trimcachepath, "wb");
768 trimw = 1;
772 if (state.trimmargins || pdf)
773 cxcount = state.pagecount;
774 else
775 cxcount = fz_mini (state.pagecount, 1);
777 if (pdf) {
778 pdf_obj *obj;
779 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
780 "Root/Pages/MediaBox");
781 pdf_to_rect (ctx, obj, &rootmediabox);
784 #ifdef CACHE_PAGEREFS
785 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
786 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
787 if (!state.pdflut.objs) {
788 err (1, "malloc pageobjs %zu %d %zu failed",
789 sizeof (*state.pdflut.objs), cxcount,
790 sizeof (*state.pdflut.objs) * cxcount);
792 state.pdflut.count = cxcount;
793 pdf_load_page_objs (pdf);
794 state.pdflut.pdf = pdf;
796 #endif
798 for (pageno = 0; pageno < cxcount; ++pageno) {
799 int rotate = 0;
800 struct pagedim *p;
801 fz_rect mediabox = fz_empty_rect;
803 fz_var (rotate);
804 if (pdf) {
805 pdf_obj *pageref, *pageobj;
807 #ifdef CACHE_PAGEREFS
808 pageref = state.pdflut.objs[pageno];
809 #else
810 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
811 #endif
812 pageobj = pdf_resolve_indirect (ctx, pageref);
813 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
815 if (state.trimmargins) {
816 pdf_obj *obj;
817 pdf_page *page;
819 fz_try (ctx) {
820 page = pdf_load_page (ctx, pdf, pageno);
821 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
822 trim = state.trimanew || !obj;
823 if (trim) {
824 fz_rect rect;
825 fz_device *dev;
826 fz_matrix ctm, page_ctm;
828 dev = fz_new_bbox_device (ctx, &rect);
829 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
830 fz_invert_matrix (&ctm, &page_ctm);
831 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
832 fz_close_device (ctx, dev);
833 fz_drop_device (ctx, dev);
835 rect.x0 += state.trimfuzz.x0;
836 rect.x1 += state.trimfuzz.x1;
837 rect.y0 += state.trimfuzz.y0;
838 rect.y1 += state.trimfuzz.y1;
839 fz_transform_rect (&rect, &ctm);
840 fz_intersect_rect (&rect, &mediabox);
842 if (!fz_is_empty_rect (&rect)) {
843 mediabox = rect;
846 obj = pdf_new_array (ctx, pdf, 4);
847 pdf_array_push (ctx, obj,
848 pdf_new_real (ctx, mediabox.x0));
849 pdf_array_push (ctx, obj,
850 pdf_new_real (ctx, mediabox.y0));
851 pdf_array_push (ctx, obj,
852 pdf_new_real (ctx, mediabox.x1));
853 pdf_array_push (ctx, obj,
854 pdf_new_real (ctx, mediabox.y1));
855 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
857 else {
858 mediabox.x0 = pdf_to_real (ctx,
859 pdf_array_get (ctx, obj, 0));
860 mediabox.y0 = pdf_to_real (ctx,
861 pdf_array_get (ctx, obj, 1));
862 mediabox.x1 = pdf_to_real (ctx,
863 pdf_array_get (ctx, obj, 2));
864 mediabox.y1 = pdf_to_real (ctx,
865 pdf_array_get (ctx, obj, 3));
868 fz_drop_page (ctx, &page->super);
869 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
870 if (show) {
871 printd ("progress %f Trimming %d",
872 (double) (pageno + 1) / state.pagecount,
873 pageno + 1);
876 fz_catch (ctx) {
877 printd ("emsg failed to load page %d", pageno);
880 else {
881 int empty = 0;
882 fz_rect cropbox;
884 pdf_to_rect (ctx,
885 pdf_dict_gets (ctx, pageobj, "MediaBox"),
886 &mediabox);
887 if (fz_is_empty_rect (&mediabox)) {
888 mediabox.x0 = 0;
889 mediabox.y0 = 0;
890 mediabox.x1 = 612;
891 mediabox.y1 = 792;
892 empty = 1;
895 pdf_to_rect (ctx,
896 pdf_dict_gets (ctx, pageobj, "CropBox"),
897 &cropbox);
898 if (!fz_is_empty_rect (&cropbox)) {
899 if (empty) {
900 mediabox = cropbox;
902 else {
903 fz_intersect_rect (&mediabox, &cropbox);
906 else {
907 if (empty) {
908 if (fz_is_empty_rect (&rootmediabox)) {
909 printd ("emsg cannot find page size for page %d",
910 pageno);
912 else {
913 mediabox = rootmediabox;
919 else {
920 if (state.trimmargins && trimw) {
921 fz_page *page;
923 fz_try (ctx) {
924 page = fz_load_page (ctx, state.doc, pageno);
925 fz_bound_page (ctx, page, &mediabox);
926 if (state.trimmargins) {
927 fz_rect rect;
928 fz_device *dev;
930 dev = fz_new_bbox_device (ctx, &rect);
931 fz_run_page (ctx, page, dev, &fz_identity, NULL);
932 fz_close_device (ctx, dev);
933 fz_drop_device (ctx, dev);
935 rect.x0 += state.trimfuzz.x0;
936 rect.x1 += state.trimfuzz.x1;
937 rect.y0 += state.trimfuzz.y0;
938 rect.y1 += state.trimfuzz.y1;
939 fz_intersect_rect (&rect, &mediabox);
941 if (!fz_is_empty_rect (&rect)) {
942 mediabox = rect;
945 fz_drop_page (ctx, page);
947 fz_catch (ctx) {
949 if (trimf) {
950 size_t n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
951 if (n - 1) {
952 err (1, "fwrite trim mediabox");
956 else {
957 if (trimf) {
958 size_t n = fread (&mediabox, sizeof (mediabox), 1, trimf);
959 if (n - 1) {
960 err (1, "fread trim mediabox %d", pageno);
963 else {
964 fz_page *page;
965 fz_try (ctx) {
966 page = fz_load_page (ctx, state.doc, pageno);
967 fz_bound_page (ctx, page, &mediabox);
968 fz_drop_page (ctx, page);
970 show = !state.trimmargins && pageno % 20 == 0;
971 if (show) {
972 printd ("progress %f Gathering dimensions %d",
973 (double) (pageno) / state.pagecount,
974 pageno);
977 fz_catch (ctx) {
978 printd ("emsg failed to load page %d", pageno);
984 if (state.pagedimcount == 0
985 || ((void) (p = &state.pagedims[state.pagedimcount-1])
986 , p->rotate != rotate)
987 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
988 size_t size;
990 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
991 state.pagedims = realloc (state.pagedims, size);
992 if (!state.pagedims) {
993 err (1, "realloc pagedims to %zu (%d elems)",
994 size, state.pagedimcount + 1);
997 p = &state.pagedims[state.pagedimcount++];
998 p->rotate = rotate;
999 p->mediabox = mediabox;
1000 p->pageno = pageno;
1003 end = now ();
1004 printd ("progress 1 %s %d pages in %f seconds",
1005 state.trimmargins ? "Trimmed" : "Processed",
1006 state.pagecount, end - start);
1007 state.trimanew = 0;
1008 if (trimf) {
1009 if (fclose (trimf)) {
1010 err (1, "fclose");
1015 static void layout (void)
1017 int pindex;
1018 fz_rect box;
1019 fz_matrix ctm, rm;
1020 struct pagedim *p = NULL;
1021 float zw, w, maxw = 0.0, zoom = 1.0;
1023 if (state.pagedimcount == 0) return;
1025 switch (state.fitmodel) {
1026 case FitProportional:
1027 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1028 float x0, x1;
1030 p = &state.pagedims[pindex];
1031 fz_rotate (&rm, p->rotate + state.rotate);
1032 box = p->mediabox;
1033 fz_transform_rect (&box, &rm);
1035 x0 = fz_min (box.x0, box.x1);
1036 x1 = fz_max (box.x0, box.x1);
1038 w = x1 - x0;
1039 maxw = fz_max (w, maxw);
1040 zoom = state.w / maxw;
1042 break;
1044 case FitPage:
1045 maxw = state.w;
1046 break;
1048 case FitWidth:
1049 break;
1051 default:
1052 ARSERT (0 && state.fitmodel);
1055 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1056 fz_rect rect;
1057 fz_matrix tm, sm;
1059 p = &state.pagedims[pindex];
1060 fz_rotate (&ctm, state.rotate);
1061 fz_rotate (&rm, p->rotate + state.rotate);
1062 box = p->mediabox;
1063 fz_transform_rect (&box, &rm);
1064 w = box.x1 - box.x0;
1065 switch (state.fitmodel) {
1066 case FitProportional:
1067 p->left = (int) (((maxw - w) * zoom) / 2.f);
1068 break;
1069 case FitPage:
1071 float zh, h;
1072 zw = maxw / w;
1073 h = box.y1 - box.y0;
1074 zh = state.h / h;
1075 zoom = fz_min (zw, zh);
1076 p->left = (int) ((maxw - (w * zoom)) / 2.f);
1078 break;
1079 case FitWidth:
1080 p->left = 0;
1081 zoom = state.w / w;
1082 break;
1085 fz_scale (&p->zoomctm, zoom, zoom);
1086 fz_concat (&ctm, &p->zoomctm, &ctm);
1088 fz_rotate (&rm, p->rotate);
1089 p->pagebox = p->mediabox;
1090 fz_transform_rect (&p->pagebox, &rm);
1091 p->pagebox.x1 -= p->pagebox.x0;
1092 p->pagebox.y1 -= p->pagebox.y0;
1093 p->pagebox.x0 = 0;
1094 p->pagebox.y0 = 0;
1095 rect = p->pagebox;
1096 fz_transform_rect (&rect, &ctm);
1097 fz_round_rect (&p->bounds, &rect);
1098 p->ctm = ctm;
1100 fz_translate (&tm, 0, -p->mediabox.y1);
1101 fz_scale (&sm, zoom, -zoom);
1102 fz_concat (&ctm, &tm, &sm);
1104 p->tctmready = 0;
1107 do {
1108 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1109 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1110 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1111 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1112 int boundw = x1 - x0;
1113 int boundh = y1 - y0;
1115 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1116 } while (p-- != state.pagedims);
1119 struct pagedim *pdimofpageno (int pageno)
1121 struct pagedim *pdim = state.pagedims;
1123 for (int i = 0; i < state.pagedimcount; ++i) {
1124 if (state.pagedims[i].pageno > pageno)
1125 break;
1126 pdim = &state.pagedims[i];
1128 return pdim;
1131 static void recurse_outline (fz_outline *outline, int level)
1133 while (outline) {
1134 if (outline->page >= 0) {
1135 fz_point p = {.x = outline->x, .y = outline->y};
1136 struct pagedim *pdim = pdimofpageno (outline->page);
1137 int h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1138 fz_transform_point (&p, &pdim->ctm);
1139 printd ("o %d %d %d %d %s",
1140 level, outline->page, (int) p.y, h, outline->title);
1142 else {
1143 printd ("on %d %s", level, outline->title);
1145 if (outline->down) {
1146 recurse_outline (outline->down, level + 1);
1148 outline = outline->next;
1152 static void process_outline (void)
1154 fz_outline *outline;
1156 if (!state.needoutline || !state.pagedimcount) return;
1158 state.needoutline = 0;
1159 outline = fz_load_outline (state.ctx, state.doc);
1160 if (outline) {
1161 recurse_outline (outline, 0);
1162 fz_drop_outline (state.ctx, outline);
1166 static char *strofline (fz_stext_line *line)
1168 char *p;
1169 char utf8[10];
1170 fz_stext_char *ch;
1171 size_t size = 0, cap = 80;
1173 p = malloc (cap + 1);
1174 if (!p) return NULL;
1176 for (ch = line->first_char; ch; ch = ch->next) {
1177 int n = fz_runetochar (utf8, ch->c);
1178 if (size + n > cap) {
1179 cap *= 2;
1180 p = realloc (p, cap + 1);
1181 if (!p) return NULL;
1184 memcpy (p + size, utf8, n);
1185 size += n;
1187 p[size] = 0;
1188 return p;
1191 static int matchline (regex_t *re, fz_stext_line *line,
1192 int stop, int pageno, double start)
1194 int ret;
1195 char *p;
1196 regmatch_t rm;
1198 p = strofline (line);
1199 if (!p) return -1;
1201 ret = regexec (re, p, 1, &rm, 0);
1202 if (ret) {
1203 free (p);
1204 if (ret != REG_NOMATCH) {
1205 size_t size;
1206 char errbuf[80];
1207 size = regerror (ret, re, errbuf, sizeof (errbuf));
1208 printd ("msg regexec error `%.*s'",
1209 (int) size, errbuf);
1210 return -1;
1212 return 0;
1214 else {
1215 fz_point p1, p2, p3, p4;
1216 fz_rect s = {0,0,0,0}, e;
1217 fz_stext_char *ch;
1218 int o = 0;
1220 for (ch = line->first_char; ch; ch = ch->next) {
1221 o += fz_runelen (ch->c);
1222 if (o > rm.rm_so) {
1223 s = ch->bbox;
1224 break;
1227 for (;ch; ch = ch->next) {
1228 o += fz_runelen (ch->c);
1229 if (o > rm.rm_eo) break;
1231 e = ch->bbox;
1233 p1.x = s.x0;
1234 p1.y = s.y0;
1235 p2.x = e.x1;
1236 p2.y = s.y0;
1237 p3.x = e.x1;
1238 p3.y = e.y1;
1239 p4.x = s.x0;
1240 p4.y = e.y1;
1242 #pragma GCC diagnostic ignored "-Wdouble-promotion"
1243 if (!stop) {
1244 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1245 pageno, 1,
1246 p1.x, p1.y,
1247 p2.x, p2.y,
1248 p3.x, p3.y,
1249 p4.x, p4.y);
1251 printd ("progress 1 found at %d `%.*s' in %f sec",
1252 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1253 now () - start);
1255 else {
1256 printd ("match %d %d %f %f %f %f %f %f %f %f",
1257 pageno, 2,
1258 p1.x, p1.y,
1259 p2.x, p2.y,
1260 p3.x, p3.y,
1261 p4.x, p4.y);
1263 #pragma GCC diagnostic error "-Wdouble-promotion"
1264 free (p);
1265 return 1;
1269 /* wishful thinking function */
1270 static void search (regex_t *re, int pageno, int y, int forward)
1272 fz_device *tdev;
1273 fz_stext_page *text;
1274 struct pagedim *pdim;
1275 int stop = 0, niters = 0;
1276 double start, end;
1277 fz_page *page;
1278 fz_stext_block *block;
1280 start = now ();
1281 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1282 if (niters++ == 5) {
1283 niters = 0;
1284 if (hasdata ()) {
1285 printd ("progress 1 attention requested aborting search at %d",
1286 pageno);
1287 stop = 1;
1289 else {
1290 printd ("progress %f searching in page %d",
1291 (double) (pageno + 1) / state.pagecount,
1292 pageno);
1295 pdim = pdimofpageno (pageno);
1296 text = fz_new_stext_page (state.ctx, &pdim->mediabox);
1297 tdev = fz_new_stext_device (state.ctx, text, 0);
1299 page = fz_load_page (state.ctx, state.doc, pageno);
1301 fz_matrix ctm = pagectm1 (page, pdim);
1302 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1305 fz_close_device (state.ctx, tdev);
1306 fz_drop_device (state.ctx, tdev);
1308 if (forward) {
1309 for (block = text->first_block; block; block = block->next) {
1310 fz_stext_line *line;
1312 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1313 for (line = block->u.t.first_line; line; line = line->next) {
1314 if (line->bbox.y0 < y + 1) continue;
1316 switch (matchline (re, line, stop, pageno, start)) {
1317 case 0: break;
1318 case 1: stop = 1; break;
1319 case -1: stop = 1; goto endloop;
1324 else {
1325 for (block = text->last_block; block; block = block->prev) {
1326 fz_stext_line *line;
1328 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1329 for (line = block->u.t.last_line; line; line = line->prev) {
1330 if (line->bbox.y0 < y + 1) continue;
1332 switch (matchline (re, line, stop, pageno, start)) {
1333 case 0: break;
1334 case 1: stop = 1; break;
1335 case -1: stop = 1; goto endloop;
1341 if (forward) {
1342 pageno += 1;
1343 y = 0;
1345 else {
1346 pageno -= 1;
1347 y = INT_MAX;
1349 endloop:
1350 fz_drop_stext_page (state.ctx, text);
1351 fz_drop_page (state.ctx, page);
1353 end = now ();
1354 if (!stop) {
1355 printd ("progress 1 no matches %f sec", end - start);
1357 printd ("clearrects");
1360 static void set_tex_params (int colorspace)
1362 switch (colorspace) {
1363 case 0:
1364 state.texiform = GL_RGBA8;
1365 state.texform = GL_RGBA;
1366 state.texty = GL_UNSIGNED_BYTE;
1367 state.colorspace = fz_device_rgb (state.ctx);
1368 break;
1369 case 1:
1370 state.texiform = GL_RGBA8;
1371 state.texform = GL_BGRA;
1372 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1373 state.texty = GL_UNSIGNED_INT_8_8_8_8_REV;
1374 #else
1375 state.texty = GL_UNSIGNED_INT_8_8_8_8;
1376 #endif
1377 state.colorspace = fz_device_bgr (state.ctx);
1378 break;
1379 case 2:
1380 state.texiform = GL_LUMINANCE_ALPHA;
1381 state.texform = GL_LUMINANCE_ALPHA;
1382 state.texty = GL_UNSIGNED_BYTE;
1383 state.colorspace = fz_device_gray (state.ctx);
1384 break;
1385 default:
1386 errx (1, "invalid colorspce %d", colorspace);
1390 static void realloctexts (int texcount)
1392 size_t size;
1394 if (texcount == state.texcount) return;
1396 if (texcount < state.texcount) {
1397 glDeleteTextures (state.texcount - texcount,
1398 state.texids + texcount);
1401 size = texcount * (sizeof (*state.texids) + sizeof (*state.texowners));
1402 state.texids = realloc (state.texids, size);
1403 if (!state.texids) {
1404 err (1, "realloc texs %zu", size);
1407 state.texowners = (void *) (state.texids + texcount);
1408 if (texcount > state.texcount) {
1409 glGenTextures (texcount - state.texcount,
1410 state.texids + state.texcount);
1411 for (int i = state.texcount; i < texcount; ++i) {
1412 state.texowners[i].w = -1;
1413 state.texowners[i].slice = NULL;
1416 state.texcount = texcount;
1417 state.texindex = 0;
1420 static char *mbtoutf8 (char *s)
1422 char *p, *r;
1423 wchar_t *tmp;
1424 size_t i, ret, len;
1426 if (state.utf8cs) {
1427 return s;
1430 len = mbstowcs (NULL, s, strlen (s));
1431 if (len == 0) {
1432 return s;
1434 else {
1435 if (len == (size_t) -1) {
1436 printd ("emsg mbtoutf8: mbstowcs: %d:%s", errno, strerror (errno));
1437 return s;
1441 tmp = calloc (len, sizeof (wchar_t));
1442 if (!tmp) {
1443 printd ("emsg mbtoutf8: calloc(%zu, %zu): %d:%s",
1444 len, sizeof (wchar_t), errno, strerror (errno));
1445 return s;
1448 ret = mbstowcs (tmp, s, len);
1449 if (ret == (size_t) -1) {
1450 printd ("emsg mbtoutf8: mbswcs %zu characters failed: %d:%s",
1451 len, errno, strerror (errno));
1452 free (tmp);
1453 return s;
1456 len = 0;
1457 for (i = 0; i < ret; ++i) {
1458 len += fz_runelen (tmp[i]);
1461 p = r = malloc (len + 1);
1462 if (!r) {
1463 printd ("emsg mbtoutf8: malloc(%zu)", len);
1464 free (tmp);
1465 return s;
1468 for (i = 0; i < ret; ++i) {
1469 p += fz_runetochar (p, tmp[i]);
1471 *p = 0;
1472 free (tmp);
1473 return r;
1476 CAMLprim value ml_mbtoutf8 (value s_v)
1478 CAMLparam1 (s_v);
1479 CAMLlocal1 (ret_v);
1480 char *s, *r;
1482 s = String_val (s_v);
1483 r = mbtoutf8 (s);
1484 if (r == s) {
1485 ret_v = s_v;
1487 else {
1488 ret_v = caml_copy_string (r);
1489 free (r);
1491 CAMLreturn (ret_v);
1494 static void * mainloop (void UNUSED_ATTR *unused)
1496 char *p = NULL;
1497 int len, ret, oldlen = 0;
1499 fz_var (p);
1500 fz_var (oldlen);
1501 for (;;) {
1502 len = readlen (state.csock);
1503 if (len == 0) {
1504 errx (1, "readlen returned 0");
1507 if (oldlen < len + 1) {
1508 p = realloc (p, len + 1);
1509 if (!p) {
1510 err (1, "realloc %d failed", len + 1);
1512 oldlen = len + 1;
1514 readdata (state.csock, p, len);
1515 p[len] = 0;
1517 if (!strncmp ("open", p, 4)) {
1518 int off, usedoccss, ok = 0, layouth;
1519 char *password;
1520 char *filename;
1521 char *utf8filename;
1522 size_t filenamelen;
1524 fz_var (ok);
1525 ret = sscanf (p + 5, " %d %d %n", &usedoccss, &layouth, &off);
1526 if (ret != 2) {
1527 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1530 filename = p + 5 + off;
1531 filenamelen = strlen (filename);
1532 password = filename + filenamelen + 1;
1534 if (password[strlen (password) + 1]) {
1535 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1538 lock ("open");
1539 fz_set_use_document_css (state.ctx, usedoccss);
1540 fz_try (state.ctx) {
1541 ok = openxref (filename, password, layouth);
1543 fz_catch (state.ctx) {
1544 utf8filename = mbtoutf8 (filename);
1545 printd ("msg Could not open %s", utf8filename);
1546 if (utf8filename != filename) {
1547 free (utf8filename);
1550 if (ok) {
1551 docinfo ();
1552 initpdims ();
1554 unlock ("open");
1556 if (ok) {
1557 utf8filename = mbtoutf8 (filename);
1558 printd ("msg Opened %s (press h/F1 to get help)", utf8filename);
1559 if (utf8filename != filename) {
1560 free (utf8filename);
1562 state.needoutline = 1;
1565 else if (!strncmp ("cs", p, 2)) {
1566 int i, colorspace;
1568 ret = sscanf (p + 2, " %d", &colorspace);
1569 if (ret != 1) {
1570 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1572 lock ("cs");
1573 set_tex_params (colorspace);
1574 for (i = 0; i < state.texcount; ++i) {
1575 state.texowners[i].w = -1;
1576 state.texowners[i].slice = NULL;
1578 unlock ("cs");
1580 else if (!strncmp ("freepage", p, 8)) {
1581 void *ptr;
1583 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1584 if (ret != 1) {
1585 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1587 lock ("freepage");
1588 freepage (ptr);
1589 unlock ("freepage");
1591 else if (!strncmp ("freetile", p, 8)) {
1592 void *ptr;
1594 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1595 if (ret != 1) {
1596 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1598 lock ("freetile");
1599 freetile (ptr);
1600 unlock ("freetile");
1602 else if (!strncmp ("search", p, 6)) {
1603 int icase, pageno, y, len2, forward;
1604 char *pattern;
1605 regex_t re;
1607 ret = sscanf (p + 6, " %d %d %d %d,%n",
1608 &icase, &pageno, &y, &forward, &len2);
1609 if (ret != 4) {
1610 errx (1, "malformed search `%s' ret=%d", p, ret);
1613 pattern = p + 6 + len2;
1614 ret = regcomp (&re, pattern,
1615 REG_EXTENDED | (icase ? REG_ICASE : 0));
1616 if (ret) {
1617 char errbuf[80];
1618 size_t size;
1620 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1621 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1623 else {
1624 search (&re, pageno, y, forward);
1625 regfree (&re);
1628 else if (!strncmp ("geometry", p, 8)) {
1629 int w, h, fitmodel;
1631 printd ("clear");
1632 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1633 if (ret != 3) {
1634 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1637 lock ("geometry");
1638 state.h = h;
1639 if (w != state.w) {
1640 state.w = w;
1641 for (int i = 0; i < state.texcount; ++i) {
1642 state.texowners[i].slice = NULL;
1645 state.fitmodel = fitmodel;
1646 layout ();
1647 process_outline ();
1649 state.gen++;
1650 unlock ("geometry");
1651 printd ("continue %d", state.pagecount);
1653 else if (!strncmp ("reqlayout", p, 9)) {
1654 char *nameddest;
1655 int rotate, off, h;
1656 int fitmodel;
1657 pdf_document *pdf;
1659 printd ("clear");
1660 ret = sscanf (p + 9, " %d %d %d %n",
1661 &rotate, &fitmodel, &h, &off);
1662 if (ret != 3) {
1663 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1665 lock ("reqlayout");
1666 pdf = pdf_specifics (state.ctx, state.doc);
1667 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1668 state.gen += 1;
1670 state.rotate = rotate;
1671 state.fitmodel = fitmodel;
1672 state.h = h;
1673 layout ();
1674 process_outline ();
1676 nameddest = p + 9 + off;
1677 if (pdf && nameddest && *nameddest) {
1678 fz_point xy;
1679 struct pagedim *pdim;
1680 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1681 &xy.x, &xy.y);
1682 pdim = pdimofpageno (pageno);
1683 fz_transform_point (&xy, &pdim->ctm);
1684 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1687 state.gen++;
1688 unlock ("reqlayout");
1689 printd ("continue %d", state.pagecount);
1691 else if (!strncmp ("page", p, 4)) {
1692 double a, b;
1693 struct page *page;
1694 int pageno, pindex;
1696 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1697 if (ret != 2) {
1698 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1701 lock ("page");
1702 a = now ();
1703 page = loadpage (pageno, pindex);
1704 b = now ();
1705 unlock ("page");
1707 printd ("page %" PRIxPTR " %f", (uintptr_t) page, b - a);
1709 else if (!strncmp ("tile", p, 4)) {
1710 int x, y, w, h;
1711 struct page *page;
1712 struct tile *tile;
1713 double a, b;
1714 void *data;
1716 ret = sscanf (p + 4, " %" SCNxPTR " %d %d %d %d %" SCNxPTR,
1717 (uintptr_t *) &page, &x, &y, &w, &h,
1718 (uintptr_t *) &data);
1719 if (ret != 6) {
1720 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1723 lock ("tile");
1724 a = now ();
1725 tile = rendertile (page, x, y, w, h, data);
1726 b = now ();
1727 unlock ("tile");
1729 printd ("tile %d %d %" PRIxPTR " %u %f",
1730 x, y, (uintptr_t) (tile),
1731 tile->w * tile->h * tile->pixmap->n,
1732 b - a);
1734 else if (!strncmp ("trimset", p, 7)) {
1735 fz_irect fuzz;
1736 int trimmargins;
1738 ret = sscanf (p + 7, " %d %d %d %d %d",
1739 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1740 if (ret != 5) {
1741 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1743 lock ("trimset");
1744 state.trimmargins = trimmargins;
1745 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1746 state.trimanew = 1;
1747 state.trimfuzz = fuzz;
1749 unlock ("trimset");
1751 else if (!strncmp ("settrim", p, 7)) {
1752 fz_irect fuzz;
1753 int trimmargins;
1755 ret = sscanf (p + 7, " %d %d %d %d %d",
1756 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1757 if (ret != 5) {
1758 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1760 printd ("clear");
1761 lock ("settrim");
1762 state.trimmargins = trimmargins;
1763 state.needoutline = 1;
1764 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1765 state.trimanew = 1;
1766 state.trimfuzz = fuzz;
1768 state.pagedimcount = 0;
1769 free (state.pagedims);
1770 state.pagedims = NULL;
1771 initpdims ();
1772 layout ();
1773 process_outline ();
1774 unlock ("settrim");
1775 printd ("continue %d", state.pagecount);
1777 else if (!strncmp ("sliceh", p, 6)) {
1778 int h;
1780 ret = sscanf (p + 6, " %d", &h);
1781 if (ret != 1) {
1782 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1784 if (h != state.sliceheight) {
1785 state.sliceheight = h;
1786 for (int i = 0; i < state.texcount; ++i) {
1787 state.texowners[i].w = -1;
1788 state.texowners[i].h = -1;
1789 state.texowners[i].slice = NULL;
1793 else if (!strncmp ("interrupt", p, 9)) {
1794 printd ("vmsg interrupted");
1796 else {
1797 errx (1, "unknown command %.*s", len, p);
1800 return 0;
1803 CAMLprim value ml_isexternallink (value uri_v)
1805 CAMLparam1 (uri_v);
1806 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1807 CAMLreturn (Val_bool (ext));
1810 CAMLprim value ml_uritolocation (value uri_v)
1812 CAMLparam1 (uri_v);
1813 CAMLlocal1 (ret_v);
1814 int pageno;
1815 fz_point xy;
1816 struct pagedim *pdim;
1818 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1819 &xy.x, &xy.y);
1820 pdim = pdimofpageno (pageno);
1821 fz_transform_point (&xy, &pdim->ctm);
1822 ret_v = caml_alloc_tuple (3);
1823 Field (ret_v, 0) = Val_int (pageno);
1824 Field (ret_v, 1) = caml_copy_double ((double) xy.x);
1825 Field (ret_v, 2) = caml_copy_double ((double) xy.y);
1826 CAMLreturn (ret_v);
1829 CAMLprim value ml_realloctexts (value texcount_v)
1831 CAMLparam1 (texcount_v);
1832 int ok;
1834 if (trylock (__func__)) {
1835 ok = 0;
1836 goto done;
1838 realloctexts (Int_val (texcount_v));
1839 ok = 1;
1840 unlock (__func__);
1842 done:
1843 CAMLreturn (Val_bool (ok));
1846 static void recti (int x0, int y0, int x1, int y1)
1848 GLfloat *v = state.vertices;
1850 glVertexPointer (2, GL_FLOAT, 0, v);
1851 v[0] = x0; v[1] = y0;
1852 v[2] = x1; v[3] = y0;
1853 v[4] = x0; v[5] = y1;
1854 v[6] = x1; v[7] = y1;
1855 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1858 static void showsel (struct page *page, int ox, int oy)
1860 fz_irect bbox;
1861 fz_rect rect;
1862 fz_stext_block *block;
1863 int seen = 0;
1864 unsigned char selcolor[] = {15,15,15,140};
1866 if (!page->fmark || !page->lmark) return;
1868 glEnable (GL_BLEND);
1869 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1870 glColor4ubv (selcolor);
1872 ox += state.pagedims[page->pdimno].bounds.x0;
1873 oy += state.pagedims[page->pdimno].bounds.y0;
1875 for (block = page->text->first_block; block; block = block->next) {
1876 fz_stext_line *line;
1878 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1879 for (line = block->u.t.first_line; line; line = line->next) {
1880 fz_stext_char *ch;
1882 rect = fz_empty_rect;
1883 for (ch = line->first_char; ch; ch = ch->next) {
1884 if (ch == page->fmark) seen = 1;
1885 if (seen) fz_union_rect (&rect, &ch->bbox);
1886 if (ch == page->lmark) {
1887 fz_round_rect (&bbox, &rect);
1888 recti (bbox.x0 + ox, bbox.y0 + oy,
1889 bbox.x1 + ox, bbox.y1 + oy);
1890 goto done;
1893 fz_round_rect (&bbox, &rect);
1894 recti (bbox.x0 + ox, bbox.y0 + oy,
1895 bbox.x1 + ox, bbox.y1 + oy);
1898 done:
1899 glDisable (GL_BLEND);
1902 #pragma GCC diagnostic push
1903 #pragma GCC diagnostic ignored "-Wdouble-promotion"
1904 #pragma GCC diagnostic ignored "-Wconversion"
1905 #include "glfont.c"
1906 #pragma GCC diagnostic pop
1908 static void stipplerect (fz_matrix *m,
1909 fz_point *p1,
1910 fz_point *p2,
1911 fz_point *p3,
1912 fz_point *p4,
1913 GLfloat *texcoords,
1914 GLfloat *vertices)
1916 fz_transform_point (p1, m);
1917 fz_transform_point (p2, m);
1918 fz_transform_point (p3, m);
1919 fz_transform_point (p4, m);
1921 float w, h, s, t;
1923 w = p2->x - p1->x;
1924 h = p2->y - p1->y;
1925 t = hypotf (w, h) * .25f;
1927 w = p3->x - p2->x;
1928 h = p3->y - p2->y;
1929 s = hypotf (w, h) * .25f;
1931 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
1932 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
1934 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
1935 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
1937 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
1938 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
1940 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
1941 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
1943 glDrawArrays (GL_LINES, 0, 8);
1946 static void solidrect (fz_matrix *m,
1947 fz_point *p1,
1948 fz_point *p2,
1949 fz_point *p3,
1950 fz_point *p4,
1951 GLfloat *vertices)
1953 fz_transform_point (p1, m);
1954 fz_transform_point (p2, m);
1955 fz_transform_point (p3, m);
1956 fz_transform_point (p4, m);
1957 vertices[0] = p1->x; vertices[1] = p1->y;
1958 vertices[2] = p2->x; vertices[3] = p2->y;
1960 vertices[4] = p3->x; vertices[5] = p3->y;
1961 vertices[6] = p4->x; vertices[7] = p4->y;
1962 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
1965 static void ensurelinks (struct page *page)
1967 if (!page->links)
1968 page->links = fz_load_links (state.ctx, page->fzpage);
1971 static void highlightlinks (struct page *page, int xoff, int yoff)
1973 fz_matrix ctm, tm, pm;
1974 fz_link *link;
1975 GLfloat *texcoords = state.texcoords;
1976 GLfloat *vertices = state.vertices;
1978 ensurelinks (page);
1980 glEnable (GL_TEXTURE_1D);
1981 glEnable (GL_BLEND);
1982 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1983 glBindTexture (GL_TEXTURE_1D, state.stid);
1985 xoff -= state.pagedims[page->pdimno].bounds.x0;
1986 yoff -= state.pagedims[page->pdimno].bounds.y0;
1987 fz_translate (&tm, xoff, yoff);
1988 pm = pagectm (page);
1989 fz_concat (&ctm, &pm, &tm);
1991 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
1992 glVertexPointer (2, GL_FLOAT, 0, vertices);
1994 for (link = page->links; link; link = link->next) {
1995 fz_point p1, p2, p3, p4;
1997 p1.x = link->rect.x0;
1998 p1.y = link->rect.y0;
2000 p2.x = link->rect.x1;
2001 p2.y = link->rect.y0;
2003 p3.x = link->rect.x1;
2004 p3.y = link->rect.y1;
2006 p4.x = link->rect.x0;
2007 p4.y = link->rect.y1;
2009 /* TODO: different colours for different schemes */
2010 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
2011 else glColor3ub (255, 0, 0);
2013 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2016 for (int i = 0; i < page->annotcount; ++i) {
2017 fz_point p1, p2, p3, p4;
2018 struct annot *annot = &page->annots[i];
2020 p1.x = annot->bbox.x0;
2021 p1.y = annot->bbox.y0;
2023 p2.x = annot->bbox.x1;
2024 p2.y = annot->bbox.y0;
2026 p3.x = annot->bbox.x1;
2027 p3.y = annot->bbox.y1;
2029 p4.x = annot->bbox.x0;
2030 p4.y = annot->bbox.y1;
2032 glColor3ub (0, 0, 128);
2033 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2036 glDisable (GL_BLEND);
2037 glDisable (GL_TEXTURE_1D);
2040 static int compareslinks (const void *l, const void *r)
2042 struct slink const *ls = l;
2043 struct slink const *rs = r;
2044 if (ls->bbox.y0 == rs->bbox.y0) {
2045 return rs->bbox.x0 - rs->bbox.x0;
2047 return ls->bbox.y0 - rs->bbox.y0;
2050 static void droptext (struct page *page)
2052 if (page->text) {
2053 fz_drop_stext_page (state.ctx, page->text);
2054 page->fmark = NULL;
2055 page->lmark = NULL;
2056 page->text = NULL;
2060 static void dropannots (struct page *page)
2062 if (page->annots) {
2063 free (page->annots);
2064 page->annots = NULL;
2065 page->annotcount = 0;
2069 static void ensureannots (struct page *page)
2071 int i, count = 0;
2072 size_t annotsize = sizeof (*page->annots);
2073 fz_annot *annot;
2075 if (state.gen != page->agen) {
2076 dropannots (page);
2077 page->agen = state.gen;
2079 if (page->annots) return;
2081 for (annot = fz_first_annot (state.ctx, page->fzpage);
2082 annot;
2083 annot = fz_next_annot (state.ctx, annot)) {
2084 count++;
2087 if (count > 0) {
2088 page->annotcount = count;
2089 page->annots = calloc (count, annotsize);
2090 if (!page->annots) {
2091 err (1, "calloc annots %d", count);
2094 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2095 annot;
2096 annot = fz_next_annot (state.ctx, annot), i++) {
2097 fz_rect rect;
2099 fz_bound_annot (state.ctx, annot, &rect);
2100 page->annots[i].annot = annot;
2101 fz_round_rect (&page->annots[i].bbox, &rect);
2106 static void dropslinks (struct page *page)
2108 if (page->slinks) {
2109 free (page->slinks);
2110 page->slinks = NULL;
2111 page->slinkcount = 0;
2113 if (page->links) {
2114 fz_drop_link (state.ctx, page->links);
2115 page->links = NULL;
2119 static void ensureslinks (struct page *page)
2121 fz_matrix ctm;
2122 int i, count;
2123 size_t slinksize = sizeof (*page->slinks);
2124 fz_link *link;
2126 ensureannots (page);
2127 if (state.gen != page->sgen) {
2128 dropslinks (page);
2129 page->sgen = state.gen;
2131 if (page->slinks) return;
2133 ensurelinks (page);
2134 ctm = pagectm (page);
2136 count = page->annotcount;
2137 for (link = page->links; link; link = link->next) {
2138 count++;
2140 if (count > 0) {
2141 int j;
2143 page->slinkcount = count;
2144 page->slinks = calloc (count, slinksize);
2145 if (!page->slinks) {
2146 err (1, "calloc slinks %d", count);
2149 for (i = 0, link = page->links; link; ++i, link = link->next) {
2150 fz_rect rect;
2152 rect = link->rect;
2153 fz_transform_rect (&rect, &ctm);
2154 page->slinks[i].tag = SLINK;
2155 page->slinks[i].u.link = link;
2156 fz_round_rect (&page->slinks[i].bbox, &rect);
2158 for (j = 0; j < page->annotcount; ++j, ++i) {
2159 fz_rect rect;
2160 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2161 fz_transform_rect (&rect, &ctm);
2162 fz_round_rect (&page->slinks[i].bbox, &rect);
2164 page->slinks[i].tag = SANNOT;
2165 page->slinks[i].u.annot = page->annots[j].annot;
2167 qsort (page->slinks, count, slinksize, compareslinks);
2171 static void highlightslinks (struct page *page, int xoff, int yoff,
2172 int noff, char *targ, mlsize_t tlen, int hfsize)
2174 char buf[40];
2175 struct slink *slink;
2176 float x0, y0, x1, y1, w;
2178 ensureslinks (page);
2179 glColor3ub (0xc3, 0xb0, 0x91);
2180 for (int i = 0; i < page->slinkcount; ++i) {
2181 fmt_linkn (buf, i + noff);
2182 if (!tlen || !strncmp (targ, buf, tlen)) {
2183 slink = &page->slinks[i];
2185 x0 = slink->bbox.x0 + xoff - 5;
2186 y1 = slink->bbox.y0 + yoff - 5;
2187 y0 = y1 + 10 + hfsize;
2188 w = measure_string (state.face, hfsize, buf);
2189 x1 = x0 + w + 10;
2190 recti ((int) x0, (int) y0, (int) x1, (int) y1);
2194 glEnable (GL_BLEND);
2195 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2196 glEnable (GL_TEXTURE_2D);
2197 glColor3ub (0, 0, 0);
2198 for (int i = 0; i < page->slinkcount; ++i) {
2199 fmt_linkn (buf, i + noff);
2200 if (!tlen || !strncmp (targ, buf, tlen)) {
2201 slink = &page->slinks[i];
2203 x0 = slink->bbox.x0 + xoff;
2204 y0 = slink->bbox.y0 + yoff + hfsize;
2205 draw_string (state.face, hfsize, x0, y0, buf);
2208 glDisable (GL_TEXTURE_2D);
2209 glDisable (GL_BLEND);
2212 static void uploadslice (struct tile *tile, struct slice *slice)
2214 int offset;
2215 struct slice *slice1;
2216 unsigned char *texdata;
2218 offset = 0;
2219 for (slice1 = tile->slices; slice != slice1; slice1++) {
2220 offset += slice1->h * tile->w * tile->pixmap->n;
2222 if (slice->texindex != -1 && slice->texindex < state.texcount
2223 && state.texowners[slice->texindex].slice == slice) {
2224 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2226 else {
2227 int subimage = 0;
2228 int texindex = state.texindex++ % state.texcount;
2230 if (state.texowners[texindex].w == tile->w) {
2231 if (state.texowners[texindex].h >= slice->h) {
2232 subimage = 1;
2234 else {
2235 state.texowners[texindex].h = slice->h;
2238 else {
2239 state.texowners[texindex].h = slice->h;
2242 state.texowners[texindex].w = tile->w;
2243 state.texowners[texindex].slice = slice;
2244 slice->texindex = texindex;
2246 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2247 #if TEXT_TYPE == GL_TEXTURE_2D
2248 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2249 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2250 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2251 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2252 #endif
2253 if (tile->pbo) {
2254 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2255 texdata = 0;
2257 else {
2258 texdata = tile->pixmap->samples;
2260 if (subimage) {
2261 glTexSubImage2D (TEXT_TYPE,
2265 tile->w,
2266 slice->h,
2267 state.texform,
2268 state.texty,
2269 texdata+offset
2272 else {
2273 glTexImage2D (TEXT_TYPE,
2275 state.texiform,
2276 tile->w,
2277 slice->h,
2279 state.texform,
2280 state.texty,
2281 texdata+offset
2284 if (tile->pbo) {
2285 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2290 CAMLprim void ml_begintiles (value unit_v)
2292 CAMLparam1 (unit_v);
2293 glEnable (TEXT_TYPE);
2294 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2295 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2296 CAMLreturn0;
2299 CAMLprim void ml_endtiles (value unit_v)
2301 CAMLparam1 (unit_v);
2302 glDisable (TEXT_TYPE);
2303 CAMLreturn0;
2306 CAMLprim void ml_drawtile (value args_v, value ptr_v)
2308 CAMLparam2 (args_v, ptr_v);
2309 int dispx = Int_val (Field (args_v, 0));
2310 int dispy = Int_val (Field (args_v, 1));
2311 int dispw = Int_val (Field (args_v, 2));
2312 int disph = Int_val (Field (args_v, 3));
2313 int tilex = Int_val (Field (args_v, 4));
2314 int tiley = Int_val (Field (args_v, 5));
2315 char *s = String_val (ptr_v);
2316 struct tile *tile = parse_pointer (__func__, s);
2317 int slicey, firstslice;
2318 struct slice *slice;
2319 GLfloat *texcoords = state.texcoords;
2320 GLfloat *vertices = state.vertices;
2322 firstslice = tiley / tile->sliceheight;
2323 slice = &tile->slices[firstslice];
2324 slicey = tiley % tile->sliceheight;
2326 while (disph > 0) {
2327 int dh;
2329 dh = slice->h - slicey;
2330 dh = fz_mini (disph, dh);
2331 uploadslice (tile, slice);
2333 texcoords[0] = tilex; texcoords[1] = slicey;
2334 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2335 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2336 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2338 vertices[0] = dispx; vertices[1] = dispy;
2339 vertices[2] = dispx+dispw; vertices[3] = dispy;
2340 vertices[4] = dispx; vertices[5] = dispy+dh;
2341 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2343 #if TEXT_TYPE == GL_TEXTURE_2D
2344 for (int i = 0; i < 8; ++i) {
2345 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2347 #endif
2349 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2350 dispy += dh;
2351 disph -= dh;
2352 slice++;
2353 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2354 slicey = 0;
2356 CAMLreturn0;
2359 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2361 fz_matrix ctm, tm, pm;
2362 fz_point p1, p2, p3, p4;
2363 GLfloat *vertices = state.vertices;
2364 double *v = (double *) rects_v;
2366 xoff -= state.pagedims[page->pdimno].bounds.x0;
2367 yoff -= state.pagedims[page->pdimno].bounds.y0;
2368 fz_translate (&tm, xoff, yoff);
2369 pm = pagectm (page);
2370 fz_concat (&ctm, &pm, &tm);
2372 glEnable (GL_BLEND);
2373 glVertexPointer (2, GL_FLOAT, 0, vertices);
2375 glColor4dv (v);
2376 p1.x = (float) v[4];
2377 p1.y = (float) v[5];
2379 p2.x = (float) v[6];
2380 p2.y = (float) v[5];
2382 p3.x = (float) v[6];
2383 p3.y = (float) v[7];
2385 p4.x = (float) v[4];
2386 p4.y = (float) v[7];
2387 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2388 glDisable (GL_BLEND);
2391 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2392 value xoff_v, value yoff_v,
2393 value li_v)
2395 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2396 int xoff = Int_val (xoff_v);
2397 int yoff = Int_val (yoff_v);
2398 int noff = Int_val (Field (li_v, 0));
2399 char *targ = String_val (Field (li_v, 1));
2400 mlsize_t tlen = caml_string_length (Field (li_v, 1));
2401 int hfsize = Int_val (Field (li_v, 2));
2402 char *s = String_val (ptr_v);
2403 int hlmask = Int_val (hlinks_v);
2404 struct page *page = parse_pointer (__func__, s);
2406 if (!page->fzpage) {
2407 /* deal with loadpage failed pages */
2408 goto done;
2411 if (trylock (__func__)) {
2412 noff = -1;
2413 goto done;
2416 ensureannots (page);
2417 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2418 if (hlmask & 2) {
2419 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2420 noff = page->slinkcount;
2422 if (page->tgen == state.gen) {
2423 showsel (page, xoff, yoff);
2425 unlock (__func__);
2427 done:
2428 CAMLreturn (Val_int (noff));
2431 CAMLprim void ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2432 value rects_v)
2434 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2435 int xoff = Int_val (xoff_v);
2436 int yoff = Int_val (yoff_v);
2437 char *s = String_val (ptr_v);
2438 struct page *page = parse_pointer (__func__, s);
2440 drawprect (page, xoff, yoff, rects_v);
2441 CAMLreturn0;
2444 static struct annot *getannot (struct page *page, int x, int y)
2446 fz_point p;
2447 fz_matrix ctm;
2448 const fz_matrix *tctm;
2449 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2451 if (!page->annots) return NULL;
2453 if (pdf) {
2454 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2455 tctm = &state.pagedims[page->pdimno].tctm;
2457 else {
2458 tctm = &fz_identity;
2461 p.x = x;
2462 p.y = y;
2464 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2465 fz_invert_matrix (&ctm, &ctm);
2466 fz_transform_point (&p, &ctm);
2468 if (pdf) {
2469 for (int i = 0; i < page->annotcount; ++i) {
2470 struct annot *a = &page->annots[i];
2471 fz_rect rect;
2473 fz_bound_annot (state.ctx, a->annot, &rect);
2474 if (p.x >= rect.x0 && p.x <= rect.x1) {
2475 if (p.y >= rect.y0 && p.y <= rect.y1)
2476 return a;
2480 return NULL;
2483 static fz_link *getlink (struct page *page, int x, int y)
2485 fz_point p;
2486 fz_matrix ctm;
2487 fz_link *link;
2489 ensureslinks (page);
2491 p.x = x;
2492 p.y = y;
2494 ctm = pagectm (page);
2495 fz_invert_matrix (&ctm, &ctm);
2496 fz_transform_point (&p, &ctm);
2498 for (link = page->links; link; link = link->next) {
2499 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2500 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2501 return link;
2505 return NULL;
2508 static void ensuretext (struct page *page)
2510 if (state.gen != page->tgen) {
2511 droptext (page);
2512 page->tgen = state.gen;
2514 if (!page->text) {
2515 fz_matrix ctm;
2516 fz_device *tdev;
2518 page->text = fz_new_stext_page (state.ctx,
2519 &state.pagedims[page->pdimno].mediabox);
2520 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2521 ctm = pagectm (page);
2522 fz_run_display_list (state.ctx, page->dlist,
2523 tdev, &ctm, &fz_infinite_rect, NULL);
2524 fz_close_device (state.ctx, tdev);
2525 fz_drop_device (state.ctx, tdev);
2529 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2531 CAMLparam2 (start_page_v, dir_v);
2532 CAMLlocal1 (ret_v);
2533 int i, dir = Int_val (dir_v);
2534 int start_page = Int_val (start_page_v);
2535 int end_page = dir > 0 ? state.pagecount : -1;
2536 pdf_document *pdf;
2538 fz_var (end_page);
2539 ret_v = Val_int (0);
2540 lock (__func__);
2541 pdf = pdf_specifics (state.ctx, state.doc);
2542 for (i = start_page + dir; i != end_page; i += dir) {
2543 int found;
2545 fz_var (found);
2546 if (pdf) {
2547 pdf_page *page = NULL;
2549 fz_var (page);
2550 fz_try (state.ctx) {
2551 page = pdf_load_page (state.ctx, pdf, i);
2552 found = !!page->links || !!page->annots;
2554 fz_catch (state.ctx) {
2555 found = 0;
2557 if (page) {
2558 fz_drop_page (state.ctx, &page->super);
2561 else {
2562 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2563 fz_link *link = fz_load_links (state.ctx, page);
2564 found = !!link;
2565 fz_drop_link (state.ctx, link);
2566 fz_drop_page (state.ctx, page);
2569 if (found) {
2570 ret_v = caml_alloc_small (1, 1);
2571 Field (ret_v, 0) = Val_int (i);
2572 goto unlock;
2575 unlock:
2576 unlock (__func__);
2577 CAMLreturn (ret_v);
2580 enum { dir_first, dir_last };
2581 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2583 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2585 CAMLparam2 (ptr_v, dir_v);
2586 CAMLlocal2 (ret_v, pos_v);
2587 struct page *page;
2588 int dirtag, i, slinkindex;
2589 struct slink *found = NULL ,*slink;
2590 char *s = String_val (ptr_v);
2592 page = parse_pointer (__func__, s);
2593 ret_v = Val_int (0);
2594 lock (__func__);
2595 ensureslinks (page);
2597 if (Is_block (dir_v)) {
2598 dirtag = Tag_val (dir_v);
2599 switch (dirtag) {
2600 case dir_first_visible:
2602 int x0, y0, dir, first_index, last_index;
2604 pos_v = Field (dir_v, 0);
2605 x0 = Int_val (Field (pos_v, 0));
2606 y0 = Int_val (Field (pos_v, 1));
2607 dir = Int_val (Field (pos_v, 2));
2609 if (dir >= 0) {
2610 dir = 1;
2611 first_index = 0;
2612 last_index = page->slinkcount;
2614 else {
2615 first_index = page->slinkcount - 1;
2616 last_index = -1;
2619 for (i = first_index; i != last_index; i += dir) {
2620 slink = &page->slinks[i];
2621 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2622 found = slink;
2623 break;
2627 break;
2629 case dir_left:
2630 slinkindex = Int_val (Field (dir_v, 0));
2631 found = &page->slinks[slinkindex];
2632 for (i = slinkindex - 1; i >= 0; --i) {
2633 slink = &page->slinks[i];
2634 if (slink->bbox.x0 < found->bbox.x0) {
2635 found = slink;
2636 break;
2639 break;
2641 case dir_right:
2642 slinkindex = Int_val (Field (dir_v, 0));
2643 found = &page->slinks[slinkindex];
2644 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2645 slink = &page->slinks[i];
2646 if (slink->bbox.x0 > found->bbox.x0) {
2647 found = slink;
2648 break;
2651 break;
2653 case dir_down:
2654 slinkindex = Int_val (Field (dir_v, 0));
2655 found = &page->slinks[slinkindex];
2656 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2657 slink = &page->slinks[i];
2658 if (slink->bbox.y0 >= found->bbox.y0) {
2659 found = slink;
2660 break;
2663 break;
2665 case dir_up:
2666 slinkindex = Int_val (Field (dir_v, 0));
2667 found = &page->slinks[slinkindex];
2668 for (i = slinkindex - 1; i >= 0; --i) {
2669 slink = &page->slinks[i];
2670 if (slink->bbox.y0 <= found->bbox.y0) {
2671 found = slink;
2672 break;
2675 break;
2678 else {
2679 dirtag = Int_val (dir_v);
2680 switch (dirtag) {
2681 case dir_first:
2682 found = page->slinks;
2683 break;
2685 case dir_last:
2686 if (page->slinks) {
2687 found = page->slinks + (page->slinkcount - 1);
2689 break;
2692 if (found) {
2693 ret_v = caml_alloc_small (2, 1);
2694 Field (ret_v, 0) = Val_int (found - page->slinks);
2697 unlock (__func__);
2698 CAMLreturn (ret_v);
2701 enum { uuri, utext, uannot };
2703 CAMLprim value ml_getlink (value ptr_v, value n_v)
2705 CAMLparam2 (ptr_v, n_v);
2706 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2707 fz_link *link;
2708 struct page *page;
2709 char *s = String_val (ptr_v);
2710 struct slink *slink;
2712 ret_v = Val_int (0);
2713 page = parse_pointer (__func__, s);
2715 lock (__func__);
2716 ensureslinks (page);
2717 slink = &page->slinks[Int_val (n_v)];
2718 if (slink->tag == SLINK) {
2719 link = slink->u.link;
2720 str_v = caml_copy_string (link->uri);
2721 ret_v = caml_alloc_small (1, uuri);
2722 Field (ret_v, 0) = str_v;
2724 else {
2725 ret_v = caml_alloc_small (1, uannot);
2726 tup_v = caml_alloc_tuple (2);
2727 Field (ret_v, 0) = tup_v;
2728 Field (tup_v, 0) = ptr_v;
2729 Field (tup_v, 1) = n_v;
2731 unlock (__func__);
2733 CAMLreturn (ret_v);
2736 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2738 CAMLparam2 (ptr_v, n_v);
2739 CAMLlocal1 (ret_v);
2740 pdf_document *pdf;
2741 char *contents = NULL;
2743 lock (__func__);
2744 pdf = pdf_specifics (state.ctx, state.doc);
2745 if (pdf) {
2746 char *s = String_val (ptr_v);
2747 struct page *page;
2748 struct slink *slink;
2750 page = parse_pointer (__func__, s);
2751 slink = &page->slinks[Int_val (n_v)];
2752 contents = pdf_copy_annot_contents (state.ctx,
2753 (pdf_annot *) slink->u.annot);
2755 unlock (__func__);
2756 if (contents) {
2757 ret_v = caml_copy_string (contents);
2758 fz_free (state.ctx, contents);
2760 else {
2761 ret_v = caml_copy_string ("");
2763 CAMLreturn (ret_v);
2766 CAMLprim value ml_getlinkcount (value ptr_v)
2768 CAMLparam1 (ptr_v);
2769 struct page *page;
2770 char *s = String_val (ptr_v);
2772 page = parse_pointer (__func__, s);
2773 CAMLreturn (Val_int (page->slinkcount));
2776 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2778 CAMLparam2 (ptr_v, n_v);
2779 CAMLlocal1 (ret_v);
2780 struct page *page;
2781 struct slink *slink;
2782 char *s = String_val (ptr_v);
2784 page = parse_pointer (__func__, s);
2785 ret_v = caml_alloc_tuple (4);
2786 lock (__func__);
2787 ensureslinks (page);
2789 slink = &page->slinks[Int_val (n_v)];
2790 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2791 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2792 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2793 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2794 unlock (__func__);
2795 CAMLreturn (ret_v);
2798 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2800 CAMLparam3 (ptr_v, x_v, y_v);
2801 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2802 fz_link *link;
2803 struct annot *annot;
2804 struct page *page;
2805 char *ptr = String_val (ptr_v);
2806 int x = Int_val (x_v), y = Int_val (y_v);
2807 struct pagedim *pdim;
2809 ret_v = Val_int (0);
2810 if (trylock (__func__)) {
2811 goto done;
2814 page = parse_pointer (__func__, ptr);
2815 pdim = &state.pagedims[page->pdimno];
2816 x += pdim->bounds.x0;
2817 y += pdim->bounds.y0;
2820 annot = getannot (page, x, y);
2821 if (annot) {
2822 int i, n = -1;
2824 ensureslinks (page);
2825 for (i = 0; i < page->slinkcount; ++i) {
2826 if (page->slinks[i].tag == SANNOT
2827 && page->slinks[i].u.annot == annot->annot) {
2828 n = i;
2829 break;
2832 ret_v = caml_alloc_small (1, uannot);
2833 tup_v = caml_alloc_tuple (2);
2834 Field (ret_v, 0) = tup_v;
2835 Field (tup_v, 0) = ptr_v;
2836 Field (tup_v, 1) = Val_int (n);
2837 goto unlock;
2841 link = getlink (page, x, y);
2842 if (link) {
2843 str_v = caml_copy_string (link->uri);
2844 ret_v = caml_alloc_small (1, uuri);
2845 Field (ret_v, 0) = str_v;
2847 else {
2848 fz_rect *b;
2849 fz_stext_block *block;
2851 ensuretext (page);
2853 for (block = page->text->first_block; block; block = block->next) {
2854 fz_stext_line *line;
2856 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2857 b = &block->bbox;
2858 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2859 continue;
2861 for (line = block->u.t.first_line; line; line = line->next) {
2862 fz_stext_char *ch;
2864 b = &line->bbox;
2865 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2866 continue;
2868 for (ch = line->first_char; ch; ch = ch->next) {
2869 b = &ch->bbox;
2871 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
2872 const char *n2 = fz_font_name (state.ctx, ch->font);
2873 FT_FaceRec *face = fz_font_ft_face (state.ctx,
2874 ch->font);
2876 if (!n2) n2 = "<unknown font>";
2878 if (face && face->family_name) {
2879 char *s;
2880 char *n1 = face->family_name;
2881 size_t l1 = strlen (n1);
2882 size_t l2 = strlen (n2);
2884 if (l1 != l2 || memcmp (n1, n2, l1)) {
2885 s = malloc (l1 + l2 + 2);
2886 if (s) {
2887 memcpy (s, n2, l2);
2888 s[l2] = '=';
2889 memcpy (s + l2 + 1, n1, l1 + 1);
2890 str_v = caml_copy_string (s);
2891 free (s);
2895 if (str_v == Val_unit) {
2896 str_v = caml_copy_string (n2);
2898 ret_v = caml_alloc_small (1, utext);
2899 Field (ret_v, 0) = str_v;
2900 goto unlock;
2906 unlock:
2907 unlock (__func__);
2909 done:
2910 CAMLreturn (ret_v);
2913 enum { mark_page, mark_block, mark_line, mark_word };
2915 CAMLprim void ml_clearmark (value ptr_v)
2917 CAMLparam1 (ptr_v);
2918 char *s = String_val (ptr_v);
2919 struct page *page;
2921 if (trylock (__func__)) {
2922 goto done;
2925 page = parse_pointer (__func__, s);
2926 page->fmark = NULL;
2927 page->lmark = NULL;
2929 unlock (__func__);
2930 done:
2931 CAMLreturn0;
2934 static int uninteresting (int c)
2936 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
2937 || ispunct (c);
2940 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
2942 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
2943 CAMLlocal1 (ret_v);
2944 fz_rect *b;
2945 struct page *page;
2946 fz_stext_line *line;
2947 fz_stext_block *block;
2948 struct pagedim *pdim;
2949 int mark = Int_val (mark_v);
2950 char *s = String_val (ptr_v);
2951 int x = Int_val (x_v), y = Int_val (y_v);
2953 ret_v = Val_bool (0);
2954 if (trylock (__func__)) {
2955 goto done;
2958 page = parse_pointer (__func__, s);
2959 pdim = &state.pagedims[page->pdimno];
2961 ensuretext (page);
2963 if (mark == mark_page) {
2964 page->fmark = page->text->first_block->u.t.first_line->first_char;
2965 page->lmark = page->text->last_block->u.t.last_line->last_char;
2966 ret_v = Val_bool (1);
2967 goto unlock;
2970 x += pdim->bounds.x0;
2971 y += pdim->bounds.y0;
2973 for (block = page->text->first_block; block; block = block->next) {
2974 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2975 b = &block->bbox;
2976 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2977 continue;
2979 if (mark == mark_block) {
2980 page->fmark = block->u.t.first_line->first_char;
2981 page->lmark = block->u.t.last_line->last_char;
2982 ret_v = Val_bool (1);
2983 goto unlock;
2986 for (line = block->u.t.first_line; line; line = line->next) {
2987 fz_stext_char *ch;
2989 b = &line->bbox;
2990 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2991 continue;
2993 if (mark == mark_line) {
2994 page->fmark = line->first_char;
2995 page->lmark = line->last_char;
2996 ret_v = Val_bool (1);
2997 goto unlock;
3000 for (ch = line->first_char; ch; ch = ch->next) {
3001 fz_stext_char *ch2, *first = NULL, *last = NULL;
3002 b = &ch->bbox;
3003 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3004 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
3005 if (uninteresting (ch2->c)) first = NULL;
3006 else if (!first) first = ch2;
3008 for (ch2 = ch; ch2; ch2 = ch2->next) {
3009 if (uninteresting (ch2->c)) break;
3010 last = ch2;
3013 page->fmark = first;
3014 page->lmark = last;
3015 ret_v = Val_bool (1);
3016 goto unlock;
3021 unlock:
3022 if (!Bool_val (ret_v)) {
3023 page->fmark = NULL;
3024 page->lmark = NULL;
3026 unlock (__func__);
3028 done:
3029 CAMLreturn (ret_v);
3032 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3034 CAMLparam3 (ptr_v, x_v, y_v);
3035 CAMLlocal2 (ret_v, res_v);
3036 fz_rect *b = NULL;
3037 struct page *page;
3038 struct pagedim *pdim;
3039 fz_stext_block *block;
3040 char *s = String_val (ptr_v);
3041 int x = Int_val (x_v), y = Int_val (y_v);
3043 ret_v = Val_int (0);
3044 if (trylock (__func__)) {
3045 goto done;
3048 page = parse_pointer (__func__, s);
3049 pdim = &state.pagedims[page->pdimno];
3050 x += pdim->bounds.x0;
3051 y += pdim->bounds.y0;
3053 ensuretext (page);
3055 for (block = page->text->first_block; block; block = block->next) {
3056 switch (block->type) {
3057 case FZ_STEXT_BLOCK_TEXT:
3058 b = &block->bbox;
3059 break;
3061 case FZ_STEXT_BLOCK_IMAGE:
3062 b = &block->bbox;
3063 break;
3065 default:
3066 continue;
3069 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3070 break;
3071 b = NULL;
3073 if (b) {
3074 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3075 ret_v = caml_alloc_small (1, 1);
3076 Store_double_field (res_v, 0, (double) b->x0);
3077 Store_double_field (res_v, 1, (double) b->x1);
3078 Store_double_field (res_v, 2, (double) b->y0);
3079 Store_double_field (res_v, 3, (double) b->y1);
3080 Field (ret_v, 0) = res_v;
3082 unlock (__func__);
3084 done:
3085 CAMLreturn (ret_v);
3088 CAMLprim void ml_seltext (value ptr_v, value rect_v)
3090 CAMLparam2 (ptr_v, rect_v);
3091 fz_rect b;
3092 struct page *page;
3093 struct pagedim *pdim;
3094 char *s = String_val (ptr_v);
3095 int x0, x1, y0, y1;
3096 fz_stext_char *ch;
3097 fz_stext_line *line;
3098 fz_stext_block *block;
3099 fz_stext_char *fc, *lc;
3101 if (trylock (__func__)) {
3102 goto done;
3105 page = parse_pointer (__func__, s);
3106 ensuretext (page);
3108 pdim = &state.pagedims[page->pdimno];
3109 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3110 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3111 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3112 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3114 if (y0 > y1) {
3115 int t = y0;
3116 y0 = y1;
3117 y1 = t;
3118 x0 = x1;
3119 x1 = t;
3122 fc = page->fmark;
3123 lc = page->lmark;
3125 for (block = page->text->first_block; block; block = block->next) {
3126 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3127 for (line = block->u.t.first_line; line; line = line->next) {
3128 for (ch = line->first_char; ch; ch = ch->next) {
3129 b = ch->bbox;
3130 if (x0 >= b.x0 && x0 <= b.x1 && y0 >= b.y0 && y0 <= b.y1) {
3131 fc = ch;
3133 if (x1 >= b.x0 && x1 <= b.x1 && y1 >= b.y0 && y1 <= b.y1) {
3134 lc = ch;
3139 if (x1 < x0 && fc == lc) {
3140 fz_stext_char *t;
3142 t = fc;
3143 fc = lc;
3144 lc = t;
3147 page->fmark = fc;
3148 page->lmark = lc;
3150 unlock (__func__);
3152 done:
3153 CAMLreturn0;
3156 static int pipechar (FILE *f, fz_stext_char *ch)
3158 char buf[4];
3159 int len;
3160 size_t ret;
3162 len = fz_runetochar (buf, ch->c);
3163 ret = fwrite (buf, len, 1, f);
3164 if (ret != 1) {
3165 printd ("emsg failed to write %d bytes ret=%zu: %d:%s",
3166 len, ret, errno, strerror (errno));
3167 return -1;
3169 return 0;
3172 CAMLprim value ml_spawn (value command_v, value fds_v)
3174 CAMLparam2 (command_v, fds_v);
3175 CAMLlocal2 (l_v, tup_v);
3176 int ret, ret1;
3177 pid_t pid = (pid_t) -1;
3178 char *msg = NULL;
3179 value earg_v = Nothing;
3180 posix_spawnattr_t attr;
3181 posix_spawn_file_actions_t fa;
3182 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3184 argv[2] = String_val (command_v);
3186 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3187 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3190 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3191 msg = "posix_spawnattr_init";
3192 goto fail1;
3195 #ifdef POSIX_SPAWN_USEVFORK
3196 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3197 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3198 goto fail;
3200 #endif
3202 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3203 int fd1, fd2;
3205 tup_v = Field (l_v, 0);
3206 fd1 = Int_val (Field (tup_v, 0));
3207 fd2 = Int_val (Field (tup_v, 1));
3208 if (fd2 < 0) {
3209 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3210 msg = "posix_spawn_file_actions_addclose";
3211 earg_v = tup_v;
3212 goto fail;
3215 else {
3216 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3217 msg = "posix_spawn_file_actions_adddup2";
3218 earg_v = tup_v;
3219 goto fail;
3224 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3225 msg = "posix_spawn";
3226 goto fail;
3229 fail:
3230 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3231 printd ("emsg posix_spawnattr_destroy: %d:%s", ret1, strerror (ret1));
3234 fail1:
3235 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3236 printd ("emsg posix_spawn_file_actions_destroy: %d:%s",
3237 ret1, strerror (ret1));
3240 if (msg)
3241 unix_error (ret, msg, earg_v);
3243 CAMLreturn (Val_int (pid));
3246 CAMLprim value ml_hassel (value ptr_v)
3248 CAMLparam1 (ptr_v);
3249 CAMLlocal1 (ret_v);
3250 struct page *page;
3251 char *s = String_val (ptr_v);
3253 ret_v = Val_bool (0);
3254 if (trylock (__func__)) {
3255 goto done;
3258 page = parse_pointer (__func__, s);
3259 ret_v = Val_bool (page->fmark && page->lmark);
3260 unlock (__func__);
3261 done:
3262 CAMLreturn (ret_v);
3265 CAMLprim void ml_copysel (value fd_v, value ptr_v)
3267 CAMLparam2 (fd_v, ptr_v);
3268 FILE *f;
3269 int seen = 0;
3270 struct page *page;
3271 fz_stext_line *line;
3272 fz_stext_block *block;
3273 int fd = Int_val (fd_v);
3274 char *s = String_val (ptr_v);
3276 if (trylock (__func__)) {
3277 goto done;
3280 page = parse_pointer (__func__, s);
3282 if (!page->fmark || !page->lmark) {
3283 printd ("emsg nothing to copy on page %d", page->pageno);
3284 goto unlock;
3287 f = fdopen (fd, "w");
3288 if (!f) {
3289 printd ("emsg failed to fdopen sel pipe (from fd %d): %d:%s",
3290 fd, errno, strerror (errno));
3291 f = stdout;
3294 for (block = page->text->first_block; block; block = block->next) {
3295 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3296 for (line = block->u.t.first_line; line; line = line->next) {
3297 fz_stext_char *ch;
3298 for (ch = line->first_char; ch; ch = ch->next) {
3299 if (seen || ch == page->fmark) {
3300 do {
3301 pipechar (f, ch);
3302 if (ch == page->lmark) goto close;
3303 } while ((ch = ch->next));
3304 seen = 1;
3305 break;
3308 if (seen) fputc ('\n', f);
3311 close:
3312 if (f != stdout) {
3313 int ret = fclose (f);
3314 fd = -1;
3315 if (ret == -1) {
3316 if (errno != ECHILD) {
3317 printd ("emsg failed to close sel pipe: %d:%s",
3318 errno, strerror (errno));
3322 unlock:
3323 unlock (__func__);
3325 done:
3326 if (fd >= 0) {
3327 if (close (fd)) {
3328 printd ("emsg failed to close sel pipe: %d:%s",
3329 errno, strerror (errno));
3332 CAMLreturn0;
3335 CAMLprim value ml_getpdimrect (value pagedimno_v)
3337 CAMLparam1 (pagedimno_v);
3338 CAMLlocal1 (ret_v);
3339 int pagedimno = Int_val (pagedimno_v);
3340 fz_rect box;
3342 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3343 if (trylock (__func__)) {
3344 box = fz_empty_rect;
3346 else {
3347 box = state.pagedims[pagedimno].mediabox;
3348 unlock (__func__);
3351 Store_double_field (ret_v, 0, (double) box.x0);
3352 Store_double_field (ret_v, 1, (double) box.x1);
3353 Store_double_field (ret_v, 2, (double) box.y0);
3354 Store_double_field (ret_v, 3, (double) box.y1);
3356 CAMLreturn (ret_v);
3359 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3360 value dw_v, value cols_v)
3362 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3363 CAMLlocal1 (ret_v);
3364 int i;
3365 float zoom = -1.;
3366 float maxh = 0.0;
3367 struct pagedim *p;
3368 float winw = Int_val (winw_v);
3369 float winh = Int_val (winh_v);
3370 float dw = Int_val (dw_v);
3371 float cols = Int_val (cols_v);
3372 float pw = 1.0, ph = 1.0;
3374 if (trylock (__func__)) {
3375 goto done;
3378 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3379 float w = p->pagebox.x1 / cols;
3380 float h = p->pagebox.y1;
3381 if (h > maxh) {
3382 maxh = h;
3383 ph = h;
3384 if (state.fitmodel != FitProportional) pw = w;
3386 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3389 zoom = (((winh / ph) * pw) + dw) / winw;
3390 unlock (__func__);
3391 done:
3392 ret_v = caml_copy_double ((double) zoom);
3393 CAMLreturn (ret_v);
3396 CAMLprim value ml_getmaxw (value unit_v)
3398 CAMLparam1 (unit_v);
3399 CAMLlocal1 (ret_v);
3400 int i;
3401 float maxw = -1.;
3402 struct pagedim *p;
3404 if (trylock (__func__)) {
3405 goto done;
3408 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3409 float w = p->pagebox.x1;
3410 maxw = fz_max (maxw, w);
3413 unlock (__func__);
3414 done:
3415 ret_v = caml_copy_double ((double) maxw);
3416 CAMLreturn (ret_v);
3419 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3421 CAMLparam4 (pt_v, x_v, y_v, string_v);
3422 CAMLlocal1 (ret_v);
3423 int pt = Int_val(pt_v);
3424 int x = Int_val (x_v);
3425 int y = Int_val (y_v);
3426 double w;
3428 w = (double) draw_string (state.face, pt, x, y, String_val (string_v));
3429 ret_v = caml_copy_double (w);
3430 CAMLreturn (ret_v);
3433 CAMLprim value ml_measure_string (value pt_v, value string_v)
3435 CAMLparam2 (pt_v, string_v);
3436 CAMLlocal1 (ret_v);
3437 int pt = Int_val (pt_v);
3438 double w;
3440 w = (double) measure_string (state.face, pt, String_val (string_v));
3441 ret_v = caml_copy_double (w);
3442 CAMLreturn (ret_v);
3445 CAMLprim value ml_getpagebox (value opaque_v)
3447 CAMLparam1 (opaque_v);
3448 CAMLlocal1 (ret_v);
3449 fz_rect rect;
3450 fz_irect bbox;
3451 fz_matrix ctm;
3452 fz_device *dev;
3453 char *s = String_val (opaque_v);
3454 struct page *page = parse_pointer (__func__, s);
3456 ret_v = caml_alloc_tuple (4);
3457 dev = fz_new_bbox_device (state.ctx, &rect);
3459 ctm = pagectm (page);
3460 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3462 fz_close_device (state.ctx, dev);
3463 fz_drop_device (state.ctx, dev);
3464 fz_round_rect (&bbox, &rect);
3465 Field (ret_v, 0) = Val_int (bbox.x0);
3466 Field (ret_v, 1) = Val_int (bbox.y0);
3467 Field (ret_v, 2) = Val_int (bbox.x1);
3468 Field (ret_v, 3) = Val_int (bbox.y1);
3470 CAMLreturn (ret_v);
3473 CAMLprim void ml_setaalevel (value level_v)
3475 CAMLparam1 (level_v);
3477 state.aalevel = Int_val (level_v);
3478 CAMLreturn0;
3481 #ifndef __COCOA__
3482 #pragma GCC diagnostic push
3483 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3484 #include <X11/Xlib.h>
3485 #include <X11/cursorfont.h>
3486 #pragma GCC diagnostic pop
3488 #ifdef USE_EGL
3489 #include <EGL/egl.h>
3490 #else
3491 #include <GL/glx.h>
3492 #endif
3494 static const int shapes[] = {
3495 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3498 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3500 static struct {
3501 Window wid;
3502 Display *dpy;
3503 #ifdef USE_EGL
3504 EGLContext ctx;
3505 EGLConfig conf;
3506 EGLSurface win;
3507 EGLDisplay *edpy;
3508 #else
3509 GLXContext ctx;
3510 #endif
3511 XVisualInfo *visual;
3512 Cursor curs[CURS_COUNT];
3513 } glx;
3516 static void initcurs (void)
3518 for (size_t n = 0; n < CURS_COUNT; ++n) {
3519 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3523 #ifdef USE_EGL
3524 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3526 CAMLparam3 (display_v, wid_v, screen_v);
3527 int major, minor;
3528 int num_conf;
3529 EGLint visid;
3530 EGLint attribs[] = {
3531 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
3532 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
3533 EGL_NONE
3535 EGLConfig conf;
3537 glx.dpy = XOpenDisplay (String_val (display_v));
3538 if (!glx.dpy) {
3539 caml_failwith ("XOpenDisplay");
3542 eglBindAPI (EGL_OPENGL_API);
3544 glx.edpy = eglGetDisplay (glx.dpy);
3545 if (glx.edpy == EGL_NO_DISPLAY) {
3546 caml_failwith ("eglGetDisplay");
3549 if (!eglInitialize (glx.edpy, &major, &minor)) {
3550 caml_failwith ("eglInitialize");
3553 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
3554 !num_conf) {
3555 caml_failwith ("eglChooseConfig");
3558 if (!eglGetConfigAttrib (glx.edpy, conf, EGL_NATIVE_VISUAL_ID, &visid)) {
3559 caml_failwith ("eglGetConfigAttrib");
3562 glx.conf = conf;
3563 initcurs ();
3565 glx.wid = Int_val (wid_v);
3566 CAMLreturn (Val_int (visid));
3569 CAMLprim void ml_glxcompleteinit (value unit_v)
3571 CAMLparam1 (unit_v);
3573 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
3574 if (!glx.ctx) {
3575 caml_failwith ("eglCreateContext");
3578 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
3579 glx.wid, NULL);
3580 if (glx.win == EGL_NO_SURFACE) {
3581 caml_failwith ("eglCreateWindowSurface");
3584 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
3585 glx.ctx = NULL;
3586 caml_failwith ("eglMakeCurrent");
3588 CAMLreturn0;
3590 #else
3591 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3593 CAMLparam3 (display_v, wid_v, screen_v);
3595 glx.dpy = XOpenDisplay (String_val (display_v));
3596 if (!glx.dpy) {
3597 caml_failwith ("XOpenDisplay");
3600 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3601 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
3602 if (!glx.visual) {
3603 XCloseDisplay (glx.dpy);
3604 caml_failwith ("glXChooseVisual");
3607 initcurs ();
3609 glx.wid = Int_val (wid_v);
3610 CAMLreturn (Val_int (glx.visual->visualid));
3613 CAMLprim void ml_glxcompleteinit (value unit_v)
3615 CAMLparam1 (unit_v);
3617 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
3618 if (!glx.ctx) {
3619 caml_failwith ("glXCreateContext");
3622 XFree (glx.visual);
3623 glx.visual = NULL;
3625 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
3626 glXDestroyContext (glx.dpy, glx.ctx);
3627 glx.ctx = NULL;
3628 caml_failwith ("glXMakeCurrent");
3630 CAMLreturn0;
3632 #endif
3634 CAMLprim void ml_setcursor (value cursor_v)
3636 CAMLparam1 (cursor_v);
3637 size_t cursn = Int_val (cursor_v);
3639 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
3640 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
3641 XFlush (glx.dpy);
3642 CAMLreturn0;
3645 CAMLprim void ml_swapb (value unit_v)
3647 CAMLparam1 (unit_v);
3648 #ifdef USE_EGL
3649 if (!eglSwapBuffers (glx.edpy, glx.win)) {
3650 caml_failwith ("eglSwapBuffers");
3652 #else
3653 glXSwapBuffers (glx.dpy, glx.wid);
3654 #endif
3655 CAMLreturn0;
3658 long keysym2ucs (KeySym);
3659 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3661 CAMLparam1 (keysym_v);
3662 CAMLlocal1 (str_v);
3663 KeySym keysym = Int_val (keysym_v);
3664 Rune rune;
3665 int len;
3666 char buf[5];
3668 rune = (Rune) keysym2ucs (keysym);
3669 len = fz_runetochar (buf, rune);
3670 buf[len] = 0;
3671 str_v = caml_copy_string (buf);
3672 CAMLreturn (str_v);
3674 #else
3675 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3677 CAMLparam1 (keysym_v);
3678 CAMLlocal1 (str_v);
3679 long ucs_v = Long_val (keysym_v);
3680 int len;
3681 char buf[5];
3683 len = fz_runetochar (buf, (int) ucs_v);
3684 buf[len] = 0;
3685 str_v = caml_copy_string (buf);
3686 CAMLreturn (str_v);
3688 #endif
3690 enum { piunknown, pilinux, piosx, pisun, pibsd };
3692 CAMLprim value ml_platform (value unit_v)
3694 CAMLparam1 (unit_v);
3695 CAMLlocal2 (tup_v, arr_v);
3696 int platid = piunknown;
3697 struct utsname buf;
3699 #if defined __linux__
3700 platid = pilinux;
3701 #elif defined __DragonFly__ || defined __FreeBSD__
3702 || defined __OpenBSD__ || defined __NetBSD__
3703 platid = pibsd;
3704 #elif defined __sun__
3705 platid = pisun;
3706 #elif defined __APPLE__
3707 platid = piosx;
3708 #endif
3709 if (uname (&buf)) err (1, "uname");
3711 tup_v = caml_alloc_tuple (2);
3713 char const *sar[] = {
3714 buf.sysname,
3715 buf.release,
3716 buf.version,
3717 buf.machine,
3718 NULL
3720 arr_v = caml_copy_string_array (sar);
3722 Field (tup_v, 0) = Val_int (platid);
3723 Field (tup_v, 1) = arr_v;
3724 CAMLreturn (tup_v);
3727 CAMLprim void ml_cloexec (value fd_v)
3729 CAMLparam1 (fd_v);
3730 int fd = Int_val (fd_v);
3732 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3733 uerror ("fcntl", Nothing);
3735 CAMLreturn0;
3738 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
3740 CAMLparam2 (w_v, h_v);
3741 CAMLlocal1 (ret_v);
3742 struct bo *pbo;
3743 int w = Int_val (w_v);
3744 int h = Int_val (h_v);
3745 int cs = Int_val (cs_v);
3747 if (state.bo_usable) {
3748 pbo = calloc (sizeof (*pbo), 1);
3749 if (!pbo) {
3750 err (1, "calloc pbo");
3753 switch (cs) {
3754 case 0:
3755 case 1:
3756 pbo->size = w*h*4;
3757 break;
3758 case 2:
3759 pbo->size = w*h*2;
3760 break;
3761 default:
3762 errx (1, "%s: invalid colorspace %d", __func__, cs);
3765 state.glGenBuffersARB (1, &pbo->id);
3766 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3767 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, (GLsizei) pbo->size,
3768 NULL, GL_STREAM_DRAW);
3769 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3770 GL_READ_WRITE);
3771 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3772 if (!pbo->ptr) {
3773 printd ("emsg glMapBufferARB failed: %#x", glGetError ());
3774 state.glDeleteBuffersARB (1, &pbo->id);
3775 free (pbo);
3776 ret_v = caml_copy_string ("0");
3778 else {
3779 int res;
3780 char *s;
3782 res = snprintf (NULL, 0, "%" PRIxPTR, (uintptr_t) pbo);
3783 if (res < 0) {
3784 err (1, "snprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3786 s = malloc (res+1);
3787 if (!s) {
3788 err (1, "malloc %d bytes failed", res+1);
3790 res = sprintf (s, "%" PRIxPTR, (uintptr_t) pbo);
3791 if (res < 0) {
3792 err (1, "sprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3794 ret_v = caml_copy_string (s);
3795 free (s);
3798 else {
3799 ret_v = caml_copy_string ("0");
3801 CAMLreturn (ret_v);
3804 CAMLprim void ml_freepbo (value s_v)
3806 CAMLparam1 (s_v);
3807 char *s = String_val (s_v);
3808 struct tile *tile = parse_pointer (__func__, s);
3810 if (tile->pbo) {
3811 state.glDeleteBuffersARB (1, &tile->pbo->id);
3812 tile->pbo->id = -1;
3813 tile->pbo->ptr = NULL;
3814 tile->pbo->size = -1;
3816 CAMLreturn0;
3819 CAMLprim void ml_unmappbo (value s_v)
3821 CAMLparam1 (s_v);
3822 char *s = String_val (s_v);
3823 struct tile *tile = parse_pointer (__func__, s);
3825 if (tile->pbo) {
3826 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3827 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3828 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3830 tile->pbo->ptr = NULL;
3831 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3833 CAMLreturn0;
3836 static void setuppbo (void)
3838 #ifdef __clang__
3839 #pragma GCC diagnostic ignored "-Wunused-macros"
3840 #endif
3841 #ifdef __COCOA__
3842 static CFBundleRef framework = NULL;
3843 if (framework == NULL)
3844 framework = CFBundleGetBundleWithIdentifier (CFSTR ("com.apple.opengl"));
3845 #define GGPA(n) (&state.n = CFBundleGetFunctionPointerForName (framework, CFSTR (#n)))
3846 #else
3847 #ifdef USE_EGL
3848 #define GGPA(n) (*(void (**) (void)) &state.n = eglGetProcAddress (#n))
3849 #else
3850 #define GGPA(n) (*(void (**) (void)) &state.n = glXGetProcAddress ((GLubyte *) #n))
3851 #endif
3852 state.bo_usable = GGPA (glBindBufferARB)
3853 && GGPA (glUnmapBufferARB)
3854 && GGPA (glMapBufferARB)
3855 && GGPA (glBufferDataARB)
3856 && GGPA (glGenBuffersARB)
3857 && GGPA (glDeleteBuffersARB);
3858 #endif
3859 #undef GGPA
3862 CAMLprim value ml_bo_usable (value unit_v)
3864 CAMLparam1 (unit_v);
3865 CAMLreturn (Val_bool (state.bo_usable));
3868 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
3870 CAMLparam3 (ptr_v, x_v, y_v);
3871 CAMLlocal2 (ret_v, tup_v);
3872 struct page *page;
3873 char *s = String_val (ptr_v);
3874 int x = Int_val (x_v), y = Int_val (y_v);
3875 struct pagedim *pdim;
3876 fz_point p;
3877 fz_matrix ctm;
3879 page = parse_pointer (__func__, s);
3880 pdim = &state.pagedims[page->pdimno];
3882 ret_v = Val_int (0);
3883 if (trylock (__func__)) {
3884 goto done;
3887 if (pdf_specifics (state.ctx, state.doc)) {
3888 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
3889 ctm = state.pagedims[page->pdimno].tctm;
3891 else {
3892 ctm = fz_identity;
3894 p.x = x + pdim->bounds.x0;
3895 p.y = y + pdim->bounds.y0;
3897 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
3898 fz_invert_matrix (&ctm, &ctm);
3899 fz_transform_point (&p, &ctm);
3901 tup_v = caml_alloc_tuple (2);
3902 ret_v = caml_alloc_small (1, 1);
3903 Field (tup_v, 0) = Val_int (p.x);
3904 Field (tup_v, 1) = Val_int (p.y);
3905 Field (ret_v, 0) = tup_v;
3907 unlock (__func__);
3908 done:
3909 CAMLreturn (ret_v);
3912 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
3913 value x_v, value y_v)
3915 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
3916 CAMLlocal1 (ret_v);
3917 struct page *page;
3918 char *s = String_val (ptr_v);
3919 int pageno = Int_val (pageno_v);
3920 int pdimno = Int_val (pdimno_v);
3921 float x = (float) Double_val (x_v), y = (float) Double_val (y_v);
3922 struct pagedim *pdim;
3923 fz_point p;
3924 fz_matrix ctm;
3926 ret_v = Val_int (0);
3927 lock (__func__);
3929 if (!*s) {
3930 page = loadpage (pageno, pdimno);
3932 else {
3933 page = parse_pointer (__func__, s);
3935 pdim = &state.pagedims[pdimno];
3937 if (pdf_specifics (state.ctx, state.doc)) {
3938 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
3939 ctm = state.pagedims[page->pdimno].tctm;
3941 else {
3942 ctm = fz_identity;
3944 p.x = x + pdim->bounds.x0;
3945 p.y = y + pdim->bounds.y0;
3947 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
3948 fz_transform_point (&p, &ctm);
3950 ret_v = caml_alloc_tuple (2);
3951 Field (ret_v, 0) = caml_copy_double ((double) p.x);
3952 Field (ret_v, 1) = caml_copy_double ((double) p.y);
3954 if (!*s) {
3955 freepage (page);
3957 unlock (__func__);
3958 CAMLreturn (ret_v);
3961 CAMLprim void ml_addannot (value ptr_v, value x_v, value y_v,
3962 value contents_v)
3964 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
3965 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3967 if (pdf) {
3968 pdf_annot *annot;
3969 struct page *page;
3970 fz_point p;
3971 char *s = String_val (ptr_v);
3973 page = parse_pointer (__func__, s);
3974 annot = pdf_create_annot (state.ctx,
3975 pdf_page_from_fz_page (state.ctx,
3976 page->fzpage),
3977 PDF_ANNOT_TEXT);
3978 p.x = Int_val (x_v);
3979 p.y = Int_val (y_v);
3980 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
3981 pdf_set_text_annot_position (state.ctx, annot, p);
3982 state.dirty = 1;
3984 CAMLreturn0;
3987 CAMLprim void ml_delannot (value ptr_v, value n_v)
3989 CAMLparam2 (ptr_v, n_v);
3990 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3992 if (pdf) {
3993 struct page *page;
3994 char *s = String_val (ptr_v);
3995 struct slink *slink;
3997 page = parse_pointer (__func__, s);
3998 slink = &page->slinks[Int_val (n_v)];
3999 pdf_delete_annot (state.ctx,
4000 pdf_page_from_fz_page (state.ctx, page->fzpage),
4001 (pdf_annot *) slink->u.annot);
4002 state.dirty = 1;
4004 CAMLreturn0;
4007 CAMLprim void ml_modannot (value ptr_v, value n_v, value str_v)
4009 CAMLparam3 (ptr_v, n_v, str_v);
4010 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4012 if (pdf) {
4013 struct page *page;
4014 char *s = String_val (ptr_v);
4015 struct slink *slink;
4017 page = parse_pointer (__func__, s);
4018 slink = &page->slinks[Int_val (n_v)];
4019 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
4020 String_val (str_v));
4021 state.dirty = 1;
4023 CAMLreturn0;
4026 CAMLprim value ml_hasunsavedchanges (value unit_v)
4028 CAMLparam1 (unit_v);
4029 CAMLreturn (Val_bool (state.dirty));
4032 CAMLprim void ml_savedoc (value path_v)
4034 CAMLparam1 (path_v);
4035 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4037 if (pdf) {
4038 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
4040 CAMLreturn0;
4043 static void makestippletex (void)
4045 const char pixels[] = "\xff\xff\0\0";
4046 glGenTextures (1, &state.stid);
4047 glBindTexture (GL_TEXTURE_1D, state.stid);
4048 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4049 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4050 glTexImage1D (
4051 GL_TEXTURE_1D,
4053 GL_ALPHA,
4056 GL_ALPHA,
4057 GL_UNSIGNED_BYTE,
4058 pixels
4062 CAMLprim value ml_fz_version (void)
4064 return caml_copy_string (FZ_VERSION);
4067 CAMLprim value ml_llpp_version (void)
4069 extern char llpp_version[];
4070 return caml_copy_string (llpp_version);
4073 CAMLprim void ml_init (value csock_v, value params_v)
4075 CAMLparam2 (csock_v, params_v);
4076 CAMLlocal2 (trim_v, fuzz_v);
4077 int ret;
4078 int texcount;
4079 char *fontpath;
4080 int colorspace;
4081 int mustoresize;
4082 int haspboext;
4084 state.csock = Int_val (csock_v);
4085 state.rotate = Int_val (Field (params_v, 0));
4086 state.fitmodel = Int_val (Field (params_v, 1));
4087 trim_v = Field (params_v, 2);
4088 texcount = Int_val (Field (params_v, 3));
4089 state.sliceheight = Int_val (Field (params_v, 4));
4090 mustoresize = Int_val (Field (params_v, 5));
4091 colorspace = Int_val (Field (params_v, 6));
4092 fontpath = String_val (Field (params_v, 7));
4094 #ifdef __COCOA__
4095 state.utf8cs = 1;
4096 #else
4097 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html */
4098 if (setlocale (LC_CTYPE, "")) {
4099 const char *cset = nl_langinfo (CODESET);
4100 state.utf8cs = !strcmp (cset, "UTF-8");
4102 else {
4103 printd ("emsg setlocale: %d:%s", errno, strerror (errno));
4105 #endif
4107 if (caml_string_length (Field (params_v, 8)) > 0) {
4108 state.trimcachepath = ystrdup (String_val (Field (params_v, 8)));
4110 if (!state.trimcachepath) {
4111 printd ("emsg failed to strdup trimcachepath: %d:%s",
4112 errno, strerror (errno));
4116 haspboext = Bool_val (Field (params_v, 9));
4118 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4119 fz_register_document_handlers (state.ctx);
4121 state.trimmargins = Bool_val (Field (trim_v, 0));
4122 fuzz_v = Field (trim_v, 1);
4123 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4124 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4125 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4126 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4128 set_tex_params (colorspace);
4130 if (*fontpath) {
4131 state.face = load_font (fontpath);
4133 else {
4134 int len;
4135 const unsigned char *data;
4137 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
4138 state.face = load_builtin_font (data, len);
4140 if (!state.face) _exit (1);
4142 realloctexts (texcount);
4144 if (haspboext) {
4145 setuppbo ();
4148 makestippletex ();
4150 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4151 if (ret) {
4152 errx (1, "pthread_create: %s", strerror (ret));
4155 CAMLreturn0;
4158 #if FIXME || !FIXME
4159 static void UNUSED_ATTR NO_OPTIMIZE_ATTR refmacs (void) {}
4160 #endif