Remove EGL code
[llpp.git] / link.c
blob0a72cc8dc07d3e960f71e5862e717631df268bab
1 /* lots of code c&p-ed directly from mupdf */
2 extern char **environ;
4 #ifdef __clang__
5 #pragma GCC diagnostic error "-Weverything"
6 #pragma GCC diagnostic ignored "-Wpadded"
7 #pragma GCC diagnostic ignored "-Wsign-conversion"
8 #pragma GCC diagnostic ignored "-Wdocumentation-unknown-command"
9 #pragma GCC diagnostic ignored "-Wdocumentation"
10 #pragma GCC diagnostic ignored "-Wmissing-prototypes"
11 #endif
13 #define CAML_NAME_SPACE
14 #define FIXME 0
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 #include <mupdf/fitz.h>
68 #include <mupdf/pdf.h>
69 #pragma GCC diagnostic pop
71 #include <ft2build.h>
72 #include FT_FREETYPE_H
73 #pragma GCC diagnostic pop
75 #include "cutils.h"
77 #define PIGGYBACK
78 #define CACHE_PAGEREFS
80 #ifndef GL_TEXTURE_RECTANGLE_ARB
81 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
82 #endif
84 #ifdef USE_NPOT
85 #define TEXT_TYPE GL_TEXTURE_2D
86 #else
87 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
88 #endif
90 #ifndef GL_BGRA
91 #define GL_BGRA 0x80E1
92 #endif
94 #ifndef GL_UNSIGNED_INT_8_8_8_8
95 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
96 #endif
98 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
99 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
100 #endif
102 #if 0
103 #define lprintf printf
104 #else
105 #define lprintf(...)
106 #endif
108 #define ARSERT(cond) for (;;) { \
109 if (!(cond)) { \
110 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
112 break; \
115 struct slice {
116 int h;
117 int texindex;
120 struct tile {
121 int w, h;
122 int slicecount;
123 int sliceheight;
124 struct bo *pbo;
125 fz_pixmap *pixmap;
126 struct slice slices[1];
129 struct pagedim {
130 int pageno;
131 int rotate;
132 int left;
133 int tctmready;
134 fz_irect bounds;
135 fz_rect pagebox;
136 fz_rect mediabox;
137 fz_matrix ctm, zoomctm, tctm;
140 struct slink {
141 enum { SLINK, SANNOT } tag;
142 fz_irect bbox;
143 union {
144 fz_link *link;
145 fz_annot *annot;
146 } u;
149 struct annot {
150 fz_irect bbox;
151 fz_annot *annot;
154 struct page {
155 int tgen;
156 int sgen;
157 int agen;
158 int pageno;
159 int pdimno;
160 fz_stext_page *text;
161 fz_page *fzpage;
162 fz_display_list *dlist;
163 fz_link *links;
164 int slinkcount;
165 struct slink *slinks;
166 int annotcount;
167 struct annot *annots;
168 fz_stext_char *fmark, *lmark;
171 enum { FitWidth, FitProportional, FitPage };
173 static struct {
174 int sliceheight;
175 struct pagedim *pagedims;
176 int pagecount;
177 int pagedimcount;
178 fz_document *doc;
179 fz_context *ctx;
180 int w, h;
182 int texindex;
183 int texcount;
184 GLuint *texids;
186 GLenum texiform;
187 GLenum texform;
188 GLenum texty;
190 fz_colorspace *colorspace;
192 struct {
193 int w, h;
194 struct slice *slice;
195 } *texowners;
197 int rotate;
198 int fitmodel;
199 int trimmargins;
200 int needoutline;
201 int gen;
202 int aalevel;
204 int trimanew;
205 fz_irect trimfuzz;
206 fz_pixmap *pig;
208 pthread_t thread;
209 int csock;
210 FT_Face face;
212 char *trimcachepath;
213 int dirty;
215 GLuint stid;
217 int bo_usable;
218 GLuint boid;
220 void (*glBindBufferARB) (GLenum, GLuint);
221 GLboolean (*glUnmapBufferARB) (GLenum);
222 void *(*glMapBufferARB) (GLenum, GLenum);
223 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
224 void (*glGenBuffersARB) (GLsizei, GLuint *);
225 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
227 GLfloat texcoords[8];
228 GLfloat vertices[16];
230 #ifdef CACHE_PAGEREFS
231 struct {
232 int idx;
233 int count;
234 pdf_obj **objs;
235 pdf_document *pdf;
236 } pdflut;
237 #endif
238 int utf8cs;
239 } state;
241 struct bo {
242 GLuint id;
243 void *ptr;
244 size_t size;
247 #pragma GCC diagnostic ignored "-Wdouble-promotion"
248 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
250 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
253 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
255 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
258 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
260 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
261 m.a, m.b, m.c, m.d, m.e, m.f);
263 #pragma GCC diagnostic error "-Wdouble-promotion"
265 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
267 static void lock (const char *cap)
269 int ret = pthread_mutex_lock (&mutex);
270 if (ret) {
271 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
275 static void unlock (const char *cap)
277 int ret = pthread_mutex_unlock (&mutex);
278 if (ret) {
279 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
283 static int trylock (const char *cap)
285 int ret = pthread_mutex_trylock (&mutex);
286 if (ret && ret != EBUSY) {
287 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
289 return ret == EBUSY;
292 static int hasdata (void)
294 int ret, avail;
295 ret = ioctl (state.csock, FIONREAD, &avail);
296 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
297 return avail > 0;
300 CAMLprim value ml_hasdata (value fd_v)
302 CAMLparam1 (fd_v);
303 int ret, avail;
305 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
306 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
307 CAMLreturn (Val_bool (avail > 0));
310 static void readdata (int fd, void *p, int size)
312 ssize_t n;
314 again:
315 n = read (fd, p, size);
316 if (n - size) {
317 if (n < 0 && errno == EINTR) goto again;
318 if (!n) errx (1, "EOF while reading");
319 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
323 static void writedata (int fd, char *p, int size)
325 ssize_t n;
326 uint32_t size4 = size;
327 struct iovec iov[2] = {
328 { .iov_base = &size4, .iov_len = 4 },
329 { .iov_base = p, .iov_len = size }
332 again:
333 n = writev (fd, iov, 2);
334 if (n < 0 && errno == EINTR) goto again;
335 if (n - size - 4) {
336 if (!n) errx (1, "EOF while writing data");
337 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
341 static int readlen (int fd)
343 uint32_t u;
344 readdata (fd, &u, 4);
345 return u;
348 CAMLprim void ml_wcmd (value fd_v, value bytes_v, value len_v)
350 CAMLparam3 (fd_v, bytes_v, len_v);
351 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
352 CAMLreturn0;
355 CAMLprim value ml_rcmd (value fd_v)
357 CAMLparam1 (fd_v);
358 CAMLlocal1 (strdata_v);
359 int fd = Int_val (fd_v);
360 int len = readlen (fd);
361 strdata_v = caml_alloc_string (len);
362 readdata (fd, String_val (strdata_v), len);
363 CAMLreturn (strdata_v);
366 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
368 char fbuf[64];
369 int size = sizeof (fbuf), len;
370 va_list ap;
371 char *buf = fbuf;
373 for (;;) {
374 va_start (ap, fmt);
375 len = vsnprintf (buf, size, fmt, ap);
376 va_end (ap);
378 if (len > -1) {
379 if (len < size - 4) {
380 writedata (state.csock, buf, len);
381 break;
383 else size = len + 5;
385 else {
386 err (1, "vsnprintf for `%s' failed", fmt);
388 buf = realloc (buf == fbuf ? NULL : buf, size);
389 if (!buf) err (1, "realloc for temp buf (%d bytes) failed", size);
391 if (buf != fbuf) free (buf);
394 static void closedoc (void)
396 #ifdef CACHE_PAGEREFS
397 if (state.pdflut.objs) {
398 for (int i = 0; i < state.pdflut.count; ++i) {
399 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
401 free (state.pdflut.objs);
402 state.pdflut.objs = NULL;
403 state.pdflut.idx = 0;
405 #endif
406 if (state.doc) {
407 fz_drop_document (state.ctx, state.doc);
408 state.doc = NULL;
412 static int openxref (char *filename, char *password, int layouth)
414 for (int i = 0; i < state.texcount; ++i) {
415 state.texowners[i].w = -1;
416 state.texowners[i].slice = NULL;
419 closedoc ();
421 state.dirty = 0;
422 if (state.pagedims) {
423 free (state.pagedims);
424 state.pagedims = NULL;
426 state.pagedimcount = 0;
428 fz_set_aa_level (state.ctx, state.aalevel);
429 state.doc = fz_open_document (state.ctx, filename);
430 if (fz_needs_password (state.ctx, state.doc)) {
431 if (password && !*password) {
432 printd ("pass");
433 return 0;
435 else {
436 int ok = fz_authenticate_password (state.ctx, state.doc, password);
437 if (!ok) {
438 printd ("pass fail");
439 return 0;
443 if (layouth >= 0)
444 fz_layout_document (state.ctx, state.doc, 460, layouth, 12);
445 state.pagecount = fz_count_pages (state.ctx, state.doc);
446 return 1;
449 static void docinfo (void)
451 struct { char *tag; char *name; } metatbl[] = {
452 { FZ_META_INFO_TITLE, "Title" },
453 { FZ_META_INFO_AUTHOR, "Author" },
454 { FZ_META_FORMAT, "Format" },
455 { FZ_META_ENCRYPTION, "Encryption" },
456 { "info:Creator", "Creator" },
457 { "info:Producer", "Producer" },
458 { "info:CreationDate", "Creation date" },
460 int len = 0;
461 char *buf = NULL;
463 for (size_t i = 0; i < sizeof (metatbl) / sizeof (metatbl[1]); ++i) {
464 int need;
465 again:
466 need = fz_lookup_metadata (state.ctx, state.doc,
467 metatbl[i].tag, buf, len);
468 if (need > 0) {
469 if (need <= len) {
470 printd ("info %s\t%s", metatbl[i].name, buf);
472 else {
473 buf = realloc (buf, need + 1);
474 if (!buf) err (1, "docinfo realloc %d", need + 1);
475 len = need + 1;
476 goto again;
480 free (buf);
482 printd ("infoend");
485 static void unlinktile (struct tile *tile)
487 for (int i = 0; i < tile->slicecount; ++i) {
488 struct slice *s = &tile->slices[i];
490 if (s->texindex != -1) {
491 if (state.texowners[s->texindex].slice == s) {
492 state.texowners[s->texindex].slice = NULL;
498 static void freepage (struct page *page)
500 if (!page) return;
501 if (page->text) {
502 fz_drop_stext_page (state.ctx, page->text);
504 if (page->slinks) {
505 free (page->slinks);
507 fz_drop_display_list (state.ctx, page->dlist);
508 fz_drop_page (state.ctx, page->fzpage);
509 free (page);
512 static void freetile (struct tile *tile)
514 unlinktile (tile);
515 if (!tile->pbo) {
516 #ifndef PIGGYBACK
517 fz_drop_pixmap (state.ctx, tile->pixmap);
518 #else
519 if (state.pig) {
520 fz_drop_pixmap (state.ctx, state.pig);
522 state.pig = tile->pixmap;
523 #endif
525 else {
526 free (tile->pbo);
527 fz_drop_pixmap (state.ctx, tile->pixmap);
529 free (tile);
532 static void trimctm (pdf_page *page, int pindex)
534 fz_matrix ctm;
535 struct pagedim *pdim = &state.pagedims[pindex];
537 if (!page) return;
538 if (!pdim->tctmready) {
539 fz_rect realbox, mediabox;
540 fz_matrix rm, sm, tm, im, ctm1, page_ctm;
542 fz_rotate (&rm, -pdim->rotate);
543 fz_scale (&sm, 1, -1);
544 fz_concat (&ctm, &rm, &sm);
545 realbox = pdim->mediabox;
546 fz_transform_rect (&realbox, &ctm);
547 fz_translate (&tm, -realbox.x0, -realbox.y0);
548 fz_concat (&ctm1, &ctm, &tm);
549 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
550 fz_invert_matrix (&im, &page_ctm);
551 fz_concat (&ctm, &im, &ctm1);
552 pdim->tctm = ctm;
553 pdim->tctmready = 1;
557 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
559 fz_matrix ctm, tm;
560 ptrdiff_t pdimno = pdim - state.pagedims;
562 ARSERT (pdim - state.pagedims < INT_MAX);
563 if (pdf_specifics (state.ctx, state.doc)) {
564 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), (int) pdimno);
565 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
567 else {
568 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
569 fz_concat (&ctm, &tm, &pdim->ctm);
571 return ctm;
574 static fz_matrix pagectm (struct page *page)
576 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
579 static void *loadpage (int pageno, int pindex)
581 fz_device *dev;
582 struct page *page;
584 page = calloc (sizeof (struct page), 1);
585 if (!page) {
586 err (1, "calloc page %d", pageno);
589 page->dlist = fz_new_display_list (state.ctx, NULL);
590 dev = fz_new_list_device (state.ctx, page->dlist);
591 fz_try (state.ctx) {
592 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
593 fz_run_page (state.ctx, page->fzpage, dev,
594 &fz_identity, NULL);
596 fz_catch (state.ctx) {
597 page->fzpage = NULL;
599 fz_close_device (state.ctx, dev);
600 fz_drop_device (state.ctx, dev);
602 page->pdimno = pindex;
603 page->pageno = pageno;
604 page->sgen = state.gen;
605 page->agen = state.gen;
606 page->tgen = state.gen;
607 return page;
610 static struct tile *alloctile (int h)
612 int slicecount;
613 size_t tilesize;
614 struct tile *tile;
616 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
617 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
618 tile = calloc (tilesize, 1);
619 if (!tile) {
620 err (1, "cannot allocate tile (%zu bytes)", tilesize);
622 for (int i = 0; i < slicecount; ++i) {
623 int sh = fz_mini (h, state.sliceheight);
624 tile->slices[i].h = sh;
625 tile->slices[i].texindex = -1;
626 h -= sh;
628 tile->slicecount = slicecount;
629 tile->sliceheight = state.sliceheight;
630 return tile;
633 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
634 struct bo *pbo)
636 fz_rect rect;
637 fz_irect bbox;
638 fz_matrix ctm;
639 fz_device *dev;
640 struct tile *tile;
641 struct pagedim *pdim;
643 tile = alloctile (h);
644 pdim = &state.pagedims[page->pdimno];
646 bbox = pdim->bounds;
647 bbox.x0 += x;
648 bbox.y0 += y;
649 bbox.x1 = bbox.x0 + w;
650 bbox.y1 = bbox.y0 + h;
652 if (state.pig) {
653 if (state.pig->w == w
654 && state.pig->h == h
655 && state.pig->colorspace == state.colorspace) {
656 tile->pixmap = state.pig;
657 tile->pixmap->x = bbox.x0;
658 tile->pixmap->y = bbox.y0;
660 else {
661 fz_drop_pixmap (state.ctx, state.pig);
663 state.pig = NULL;
665 if (!tile->pixmap) {
666 if (pbo) {
667 tile->pixmap =
668 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
669 &bbox, NULL, 1, pbo->ptr);
670 tile->pbo = pbo;
672 else {
673 tile->pixmap =
674 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox,
675 NULL, 1);
679 tile->w = w;
680 tile->h = h;
681 fz_clear_pixmap_with_value (state.ctx, tile->pixmap, 0xff);
683 dev = fz_new_draw_device (state.ctx, NULL, tile->pixmap);
684 ctm = pagectm (page);
685 fz_rect_from_irect (&rect, &bbox);
686 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
687 fz_close_device (state.ctx, dev);
688 fz_drop_device (state.ctx, dev);
690 return tile;
693 #ifdef CACHE_PAGEREFS
694 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
695 thanks to Robin Watts */
696 static void
697 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
699 fz_context *ctx = state.ctx; /* doc->ctx; */
700 pdf_obj *kids;
701 int len;
703 if (state.pdflut.idx == state.pagecount) return;
705 kids = pdf_dict_gets (ctx, node, "Kids");
706 len = pdf_array_len (ctx, kids);
708 if (len == 0)
709 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
711 if (pdf_mark_obj (ctx, node))
712 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
713 for (int i = 0; i < len; i++) {
714 pdf_obj *kid = pdf_array_get (ctx, kids, i);
715 const char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
716 if (*type
717 ? !strcmp (type, "Pages")
718 : pdf_dict_gets (ctx, kid, "Kids")
719 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
720 pdf_collect_pages (doc, kid);
722 else {
723 if (*type
724 ? strcmp (type, "Page") != 0
725 : !pdf_dict_gets (ctx, kid, "MediaBox"))
726 fz_warn (ctx, "non-page object in page tree (%s)", type);
727 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
730 pdf_unmark_obj (ctx, node);
733 static void
734 pdf_load_page_objs (pdf_document *doc)
736 pdf_obj *root = pdf_dict_gets (state.ctx,
737 pdf_trailer (state.ctx, doc), "Root");
738 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
740 if (!node)
741 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
743 state.pdflut.idx = 0;
744 pdf_collect_pages (doc, node);
746 #endif
748 static void initpdims (void)
750 double start, end;
751 FILE *trimf = NULL;
752 fz_rect rootmediabox = fz_empty_rect;
753 int pageno, trim, show;
754 int trimw = 0, cxcount;
755 fz_context *ctx = state.ctx;
756 pdf_document *pdf = pdf_specifics (ctx, state.doc);
758 fz_var (trimw);
759 fz_var (trimf);
760 fz_var (cxcount);
761 start = now ();
763 if (state.trimmargins && state.trimcachepath) {
764 trimf = fopen (state.trimcachepath, "rb");
765 if (!trimf) {
766 trimf = fopen (state.trimcachepath, "wb");
767 trimw = 1;
771 if (state.trimmargins || pdf)
772 cxcount = state.pagecount;
773 else
774 cxcount = fz_mini (state.pagecount, 1);
776 if (pdf) {
777 pdf_obj *obj;
778 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
779 "Root/Pages/MediaBox");
780 pdf_to_rect (ctx, obj, &rootmediabox);
783 #ifdef CACHE_PAGEREFS
784 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
785 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
786 if (!state.pdflut.objs) {
787 err (1, "malloc pageobjs %zu %d %zu failed",
788 sizeof (*state.pdflut.objs), cxcount,
789 sizeof (*state.pdflut.objs) * cxcount);
791 state.pdflut.count = cxcount;
792 pdf_load_page_objs (pdf);
793 state.pdflut.pdf = pdf;
795 #endif
797 for (pageno = 0; pageno < cxcount; ++pageno) {
798 int rotate = 0;
799 struct pagedim *p;
800 fz_rect mediabox = fz_empty_rect;
802 fz_var (rotate);
803 if (pdf) {
804 pdf_obj *pageref, *pageobj;
806 #ifdef CACHE_PAGEREFS
807 pageref = state.pdflut.objs[pageno];
808 #else
809 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
810 #endif
811 pageobj = pdf_resolve_indirect (ctx, pageref);
812 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
814 if (state.trimmargins) {
815 pdf_obj *obj;
816 pdf_page *page;
818 fz_try (ctx) {
819 page = pdf_load_page (ctx, pdf, pageno);
820 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
821 trim = state.trimanew || !obj;
822 if (trim) {
823 fz_rect rect;
824 fz_device *dev;
825 fz_matrix ctm, page_ctm;
827 dev = fz_new_bbox_device (ctx, &rect);
828 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
829 fz_invert_matrix (&ctm, &page_ctm);
830 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
831 fz_close_device (ctx, dev);
832 fz_drop_device (ctx, dev);
834 rect.x0 += state.trimfuzz.x0;
835 rect.x1 += state.trimfuzz.x1;
836 rect.y0 += state.trimfuzz.y0;
837 rect.y1 += state.trimfuzz.y1;
838 fz_transform_rect (&rect, &ctm);
839 fz_intersect_rect (&rect, &mediabox);
841 if (!fz_is_empty_rect (&rect)) {
842 mediabox = rect;
845 obj = pdf_new_array (ctx, pdf, 4);
846 pdf_array_push (ctx, obj,
847 pdf_new_real (ctx, mediabox.x0));
848 pdf_array_push (ctx, obj,
849 pdf_new_real (ctx, mediabox.y0));
850 pdf_array_push (ctx, obj,
851 pdf_new_real (ctx, mediabox.x1));
852 pdf_array_push (ctx, obj,
853 pdf_new_real (ctx, mediabox.y1));
854 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
856 else {
857 mediabox.x0 = pdf_to_real (ctx,
858 pdf_array_get (ctx, obj, 0));
859 mediabox.y0 = pdf_to_real (ctx,
860 pdf_array_get (ctx, obj, 1));
861 mediabox.x1 = pdf_to_real (ctx,
862 pdf_array_get (ctx, obj, 2));
863 mediabox.y1 = pdf_to_real (ctx,
864 pdf_array_get (ctx, obj, 3));
867 fz_drop_page (ctx, &page->super);
868 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
869 if (show) {
870 printd ("progress %f Trimming %d",
871 (double) (pageno + 1) / state.pagecount,
872 pageno + 1);
875 fz_catch (ctx) {
876 printd ("emsg failed to load page %d", pageno);
879 else {
880 int empty = 0;
881 fz_rect cropbox;
883 pdf_to_rect (ctx,
884 pdf_dict_gets (ctx, pageobj, "MediaBox"),
885 &mediabox);
886 if (fz_is_empty_rect (&mediabox)) {
887 mediabox.x0 = 0;
888 mediabox.y0 = 0;
889 mediabox.x1 = 612;
890 mediabox.y1 = 792;
891 empty = 1;
894 pdf_to_rect (ctx,
895 pdf_dict_gets (ctx, pageobj, "CropBox"),
896 &cropbox);
897 if (!fz_is_empty_rect (&cropbox)) {
898 if (empty) {
899 mediabox = cropbox;
901 else {
902 fz_intersect_rect (&mediabox, &cropbox);
905 else {
906 if (empty) {
907 if (fz_is_empty_rect (&rootmediabox)) {
908 printd ("emsg cannot find page size for page %d",
909 pageno);
911 else {
912 mediabox = rootmediabox;
918 else {
919 if (state.trimmargins && trimw) {
920 fz_page *page;
922 fz_try (ctx) {
923 page = fz_load_page (ctx, state.doc, pageno);
924 fz_bound_page (ctx, page, &mediabox);
925 if (state.trimmargins) {
926 fz_rect rect;
927 fz_device *dev;
929 dev = fz_new_bbox_device (ctx, &rect);
930 fz_run_page (ctx, page, dev, &fz_identity, NULL);
931 fz_close_device (ctx, dev);
932 fz_drop_device (ctx, dev);
934 rect.x0 += state.trimfuzz.x0;
935 rect.x1 += state.trimfuzz.x1;
936 rect.y0 += state.trimfuzz.y0;
937 rect.y1 += state.trimfuzz.y1;
938 fz_intersect_rect (&rect, &mediabox);
940 if (!fz_is_empty_rect (&rect)) {
941 mediabox = rect;
944 fz_drop_page (ctx, page);
946 fz_catch (ctx) {
948 if (trimf) {
949 size_t n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
950 if (n - 1) {
951 err (1, "fwrite trim mediabox");
955 else {
956 if (trimf) {
957 size_t n = fread (&mediabox, sizeof (mediabox), 1, trimf);
958 if (n - 1) {
959 err (1, "fread trim mediabox %d", pageno);
962 else {
963 fz_page *page;
964 fz_try (ctx) {
965 page = fz_load_page (ctx, state.doc, pageno);
966 fz_bound_page (ctx, page, &mediabox);
967 fz_drop_page (ctx, page);
969 show = !state.trimmargins && pageno % 20 == 0;
970 if (show) {
971 printd ("progress %f Gathering dimensions %d",
972 (double) (pageno) / state.pagecount,
973 pageno);
976 fz_catch (ctx) {
977 printd ("emsg failed to load page %d", pageno);
983 if (state.pagedimcount == 0
984 || ((void) (p = &state.pagedims[state.pagedimcount-1])
985 , p->rotate != rotate)
986 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
987 size_t size;
989 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
990 state.pagedims = realloc (state.pagedims, size);
991 if (!state.pagedims) {
992 err (1, "realloc pagedims to %zu (%d elems)",
993 size, state.pagedimcount + 1);
996 p = &state.pagedims[state.pagedimcount++];
997 p->rotate = rotate;
998 p->mediabox = mediabox;
999 p->pageno = pageno;
1002 end = now ();
1003 printd ("progress 1 %s %d pages in %f seconds",
1004 state.trimmargins ? "Trimmed" : "Processed",
1005 state.pagecount, end - start);
1006 state.trimanew = 0;
1007 if (trimf) {
1008 if (fclose (trimf)) {
1009 err (1, "fclose");
1014 static void layout (void)
1016 int pindex;
1017 fz_rect box;
1018 fz_matrix ctm, rm;
1019 struct pagedim *p = NULL;
1020 float zw, w, maxw = 0.0, zoom = 1.0;
1022 if (state.pagedimcount == 0) return;
1024 switch (state.fitmodel) {
1025 case FitProportional:
1026 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1027 float x0, x1;
1029 p = &state.pagedims[pindex];
1030 fz_rotate (&rm, p->rotate + state.rotate);
1031 box = p->mediabox;
1032 fz_transform_rect (&box, &rm);
1034 x0 = fz_min (box.x0, box.x1);
1035 x1 = fz_max (box.x0, box.x1);
1037 w = x1 - x0;
1038 maxw = fz_max (w, maxw);
1039 zoom = state.w / maxw;
1041 break;
1043 case FitPage:
1044 maxw = state.w;
1045 break;
1047 case FitWidth:
1048 break;
1050 default:
1051 ARSERT (0 && state.fitmodel);
1054 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1055 fz_rect rect;
1056 fz_matrix tm, sm;
1058 p = &state.pagedims[pindex];
1059 fz_rotate (&ctm, state.rotate);
1060 fz_rotate (&rm, p->rotate + state.rotate);
1061 box = p->mediabox;
1062 fz_transform_rect (&box, &rm);
1063 w = box.x1 - box.x0;
1064 switch (state.fitmodel) {
1065 case FitProportional:
1066 p->left = (int) (((maxw - w) * zoom) / 2.f);
1067 break;
1068 case FitPage:
1070 float zh, h;
1071 zw = maxw / w;
1072 h = box.y1 - box.y0;
1073 zh = state.h / h;
1074 zoom = fz_min (zw, zh);
1075 p->left = (int) ((maxw - (w * zoom)) / 2.f);
1077 break;
1078 case FitWidth:
1079 p->left = 0;
1080 zoom = state.w / w;
1081 break;
1084 fz_scale (&p->zoomctm, zoom, zoom);
1085 fz_concat (&ctm, &p->zoomctm, &ctm);
1087 fz_rotate (&rm, p->rotate);
1088 p->pagebox = p->mediabox;
1089 fz_transform_rect (&p->pagebox, &rm);
1090 p->pagebox.x1 -= p->pagebox.x0;
1091 p->pagebox.y1 -= p->pagebox.y0;
1092 p->pagebox.x0 = 0;
1093 p->pagebox.y0 = 0;
1094 rect = p->pagebox;
1095 fz_transform_rect (&rect, &ctm);
1096 fz_round_rect (&p->bounds, &rect);
1097 p->ctm = ctm;
1099 fz_translate (&tm, 0, -p->mediabox.y1);
1100 fz_scale (&sm, zoom, -zoom);
1101 fz_concat (&ctm, &tm, &sm);
1103 p->tctmready = 0;
1106 do {
1107 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1108 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1109 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1110 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1111 int boundw = x1 - x0;
1112 int boundh = y1 - y0;
1114 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1115 } while (p-- != state.pagedims);
1118 struct pagedim *pdimofpageno (int pageno)
1120 struct pagedim *pdim = state.pagedims;
1122 for (int i = 0; i < state.pagedimcount; ++i) {
1123 if (state.pagedims[i].pageno > pageno)
1124 break;
1125 pdim = &state.pagedims[i];
1127 return pdim;
1130 static void recurse_outline (fz_outline *outline, int level)
1132 while (outline) {
1133 if (outline->page >= 0) {
1134 fz_point p = {.x = outline->x, .y = outline->y};
1135 struct pagedim *pdim = pdimofpageno (outline->page);
1136 int h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1137 fz_transform_point (&p, &pdim->ctm);
1138 printd ("o %d %d %d %d %s",
1139 level, outline->page, (int) p.y, h, outline->title);
1141 else {
1142 printd ("on %d %s", level, outline->title);
1144 if (outline->down) {
1145 recurse_outline (outline->down, level + 1);
1147 outline = outline->next;
1151 static void process_outline (void)
1153 fz_outline *outline;
1155 if (!state.needoutline || !state.pagedimcount) return;
1157 state.needoutline = 0;
1158 outline = fz_load_outline (state.ctx, state.doc);
1159 if (outline) {
1160 recurse_outline (outline, 0);
1161 fz_drop_outline (state.ctx, outline);
1165 static char *strofline (fz_stext_line *line)
1167 char *p;
1168 char utf8[10];
1169 fz_stext_char *ch;
1170 size_t size = 0, cap = 80;
1172 p = malloc (cap + 1);
1173 if (!p) return NULL;
1175 for (ch = line->first_char; ch; ch = ch->next) {
1176 int n = fz_runetochar (utf8, ch->c);
1177 if (size + n > cap) {
1178 cap *= 2;
1179 p = realloc (p, cap + 1);
1180 if (!p) return NULL;
1183 memcpy (p + size, utf8, n);
1184 size += n;
1186 p[size] = 0;
1187 return p;
1190 static int matchline (regex_t *re, fz_stext_line *line,
1191 int stop, int pageno, double start)
1193 int ret;
1194 char *p;
1195 regmatch_t rm;
1197 p = strofline (line);
1198 if (!p) return -1;
1200 ret = regexec (re, p, 1, &rm, 0);
1201 if (ret) {
1202 free (p);
1203 if (ret != REG_NOMATCH) {
1204 size_t size;
1205 char errbuf[80];
1206 size = regerror (ret, re, errbuf, sizeof (errbuf));
1207 printd ("msg regexec error `%.*s'",
1208 (int) size, errbuf);
1209 return -1;
1211 return 0;
1213 else {
1214 fz_point p1, p2, p3, p4;
1215 fz_rect s = {0,0,0,0}, e;
1216 fz_stext_char *ch;
1217 int o = 0;
1219 for (ch = line->first_char; ch; ch = ch->next) {
1220 o += fz_runelen (ch->c);
1221 if (o > rm.rm_so) {
1222 s = ch->bbox;
1223 break;
1226 for (;ch; ch = ch->next) {
1227 o += fz_runelen (ch->c);
1228 if (o > rm.rm_eo) break;
1230 e = ch->bbox;
1232 p1.x = s.x0;
1233 p1.y = s.y0;
1234 p2.x = e.x1;
1235 p2.y = s.y0;
1236 p3.x = e.x1;
1237 p3.y = e.y1;
1238 p4.x = s.x0;
1239 p4.y = e.y1;
1241 #pragma GCC diagnostic ignored "-Wdouble-promotion"
1242 if (!stop) {
1243 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1244 pageno, 1,
1245 p1.x, p1.y,
1246 p2.x, p2.y,
1247 p3.x, p3.y,
1248 p4.x, p4.y);
1250 printd ("progress 1 found at %d `%.*s' in %f sec",
1251 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1252 now () - start);
1254 else {
1255 printd ("match %d %d %f %f %f %f %f %f %f %f",
1256 pageno, 2,
1257 p1.x, p1.y,
1258 p2.x, p2.y,
1259 p3.x, p3.y,
1260 p4.x, p4.y);
1262 #pragma GCC diagnostic error "-Wdouble-promotion"
1263 free (p);
1264 return 1;
1268 /* wishful thinking function */
1269 static void search (regex_t *re, int pageno, int y, int forward)
1271 fz_device *tdev;
1272 fz_stext_page *text;
1273 struct pagedim *pdim;
1274 int stop = 0, niters = 0;
1275 double start, end;
1276 fz_page *page;
1277 fz_stext_block *block;
1279 start = now ();
1280 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1281 if (niters++ == 5) {
1282 niters = 0;
1283 if (hasdata ()) {
1284 printd ("progress 1 attention requested aborting search at %d",
1285 pageno);
1286 stop = 1;
1288 else {
1289 printd ("progress %f searching in page %d",
1290 (double) (pageno + 1) / state.pagecount,
1291 pageno);
1294 pdim = pdimofpageno (pageno);
1295 text = fz_new_stext_page (state.ctx, &pdim->mediabox);
1296 tdev = fz_new_stext_device (state.ctx, text, 0);
1298 page = fz_load_page (state.ctx, state.doc, pageno);
1300 fz_matrix ctm = pagectm1 (page, pdim);
1301 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1304 fz_close_device (state.ctx, tdev);
1305 fz_drop_device (state.ctx, tdev);
1307 if (forward) {
1308 for (block = text->first_block; block; block = block->next) {
1309 fz_stext_line *line;
1311 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1312 for (line = block->u.t.first_line; line; line = line->next) {
1313 if (line->bbox.y0 < y + 1) continue;
1315 switch (matchline (re, line, stop, pageno, start)) {
1316 case 0: break;
1317 case 1: stop = 1; break;
1318 case -1: stop = 1; goto endloop;
1323 else {
1324 for (block = text->last_block; block; block = block->prev) {
1325 fz_stext_line *line;
1327 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1328 for (line = block->u.t.last_line; line; line = line->prev) {
1329 if (line->bbox.y0 < y + 1) continue;
1331 switch (matchline (re, line, stop, pageno, start)) {
1332 case 0: break;
1333 case 1: stop = 1; break;
1334 case -1: stop = 1; goto endloop;
1340 if (forward) {
1341 pageno += 1;
1342 y = 0;
1344 else {
1345 pageno -= 1;
1346 y = INT_MAX;
1348 endloop:
1349 fz_drop_stext_page (state.ctx, text);
1350 fz_drop_page (state.ctx, page);
1352 end = now ();
1353 if (!stop) {
1354 printd ("progress 1 no matches %f sec", end - start);
1356 printd ("clearrects");
1359 static void set_tex_params (int colorspace)
1361 switch (colorspace) {
1362 case 0:
1363 state.texiform = GL_RGBA8;
1364 state.texform = GL_RGBA;
1365 state.texty = GL_UNSIGNED_BYTE;
1366 state.colorspace = fz_device_rgb (state.ctx);
1367 break;
1368 case 1:
1369 state.texiform = GL_RGBA8;
1370 state.texform = GL_BGRA;
1371 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1372 state.texty = GL_UNSIGNED_INT_8_8_8_8_REV;
1373 #else
1374 state.texty = GL_UNSIGNED_INT_8_8_8_8;
1375 #endif
1376 state.colorspace = fz_device_bgr (state.ctx);
1377 break;
1378 case 2:
1379 state.texiform = GL_LUMINANCE_ALPHA;
1380 state.texform = GL_LUMINANCE_ALPHA;
1381 state.texty = GL_UNSIGNED_BYTE;
1382 state.colorspace = fz_device_gray (state.ctx);
1383 break;
1384 default:
1385 errx (1, "invalid colorspce %d", colorspace);
1389 static void realloctexts (int texcount)
1391 size_t size;
1393 if (texcount == state.texcount) return;
1395 if (texcount < state.texcount) {
1396 glDeleteTextures (state.texcount - texcount,
1397 state.texids + texcount);
1400 size = texcount * (sizeof (*state.texids) + sizeof (*state.texowners));
1401 state.texids = realloc (state.texids, size);
1402 if (!state.texids) {
1403 err (1, "realloc texs %zu", size);
1406 state.texowners = (void *) (state.texids + texcount);
1407 if (texcount > state.texcount) {
1408 glGenTextures (texcount - state.texcount,
1409 state.texids + state.texcount);
1410 for (int i = state.texcount; i < texcount; ++i) {
1411 state.texowners[i].w = -1;
1412 state.texowners[i].slice = NULL;
1415 state.texcount = texcount;
1416 state.texindex = 0;
1419 static char *mbtoutf8 (char *s)
1421 char *p, *r;
1422 wchar_t *tmp;
1423 size_t i, ret, len;
1425 if (state.utf8cs) {
1426 return s;
1429 len = mbstowcs (NULL, s, strlen (s));
1430 if (len == 0) {
1431 return s;
1433 else {
1434 if (len == (size_t) -1) {
1435 printd ("emsg mbtoutf8: mbstowcs: %d:%s", errno, strerror (errno));
1436 return s;
1440 tmp = calloc (len, sizeof (wchar_t));
1441 if (!tmp) {
1442 printd ("emsg mbtoutf8: calloc(%zu, %zu): %d:%s",
1443 len, sizeof (wchar_t), errno, strerror (errno));
1444 return s;
1447 ret = mbstowcs (tmp, s, len);
1448 if (ret == (size_t) -1) {
1449 printd ("emsg mbtoutf8: mbswcs %zu characters failed: %d:%s",
1450 len, errno, strerror (errno));
1451 free (tmp);
1452 return s;
1455 len = 0;
1456 for (i = 0; i < ret; ++i) {
1457 len += fz_runelen (tmp[i]);
1460 p = r = malloc (len + 1);
1461 if (!r) {
1462 printd ("emsg mbtoutf8: malloc(%zu)", len);
1463 free (tmp);
1464 return s;
1467 for (i = 0; i < ret; ++i) {
1468 p += fz_runetochar (p, tmp[i]);
1470 *p = 0;
1471 free (tmp);
1472 return r;
1475 CAMLprim value ml_mbtoutf8 (value s_v)
1477 CAMLparam1 (s_v);
1478 CAMLlocal1 (ret_v);
1479 char *s, *r;
1481 s = String_val (s_v);
1482 r = mbtoutf8 (s);
1483 if (r == s) {
1484 ret_v = s_v;
1486 else {
1487 ret_v = caml_copy_string (r);
1488 free (r);
1490 CAMLreturn (ret_v);
1493 static void * mainloop (void UNUSED_ATTR *unused)
1495 char *p = NULL;
1496 int len, ret, oldlen = 0;
1498 fz_var (p);
1499 fz_var (oldlen);
1500 for (;;) {
1501 len = readlen (state.csock);
1502 if (len == 0) {
1503 errx (1, "readlen returned 0");
1506 if (oldlen < len + 1) {
1507 p = realloc (p, len + 1);
1508 if (!p) {
1509 err (1, "realloc %d failed", len + 1);
1511 oldlen = len + 1;
1513 readdata (state.csock, p, len);
1514 p[len] = 0;
1516 if (!strncmp ("open", p, 4)) {
1517 int off, usedoccss, ok = 0, layouth;
1518 char *password;
1519 char *filename;
1520 char *utf8filename;
1521 size_t filenamelen;
1523 fz_var (ok);
1524 ret = sscanf (p + 5, " %d %d %n", &usedoccss, &layouth, &off);
1525 if (ret != 2) {
1526 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1529 filename = p + 5 + off;
1530 filenamelen = strlen (filename);
1531 password = filename + filenamelen + 1;
1533 if (password[strlen (password) + 1]) {
1534 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1537 lock ("open");
1538 fz_set_use_document_css (state.ctx, usedoccss);
1539 fz_try (state.ctx) {
1540 ok = openxref (filename, password, layouth);
1542 fz_catch (state.ctx) {
1543 utf8filename = mbtoutf8 (filename);
1544 printd ("msg Could not open %s", utf8filename);
1545 if (utf8filename != filename) {
1546 free (utf8filename);
1549 if (ok) {
1550 docinfo ();
1551 initpdims ();
1553 unlock ("open");
1555 if (ok) {
1556 utf8filename = mbtoutf8 (filename);
1557 printd ("msg Opened %s (press h/F1 to get help)", utf8filename);
1558 if (utf8filename != filename) {
1559 free (utf8filename);
1561 state.needoutline = 1;
1564 else if (!strncmp ("cs", p, 2)) {
1565 int i, colorspace;
1567 ret = sscanf (p + 2, " %d", &colorspace);
1568 if (ret != 1) {
1569 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1571 lock ("cs");
1572 set_tex_params (colorspace);
1573 for (i = 0; i < state.texcount; ++i) {
1574 state.texowners[i].w = -1;
1575 state.texowners[i].slice = NULL;
1577 unlock ("cs");
1579 else if (!strncmp ("freepage", p, 8)) {
1580 void *ptr;
1582 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1583 if (ret != 1) {
1584 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1586 lock ("freepage");
1587 freepage (ptr);
1588 unlock ("freepage");
1590 else if (!strncmp ("freetile", p, 8)) {
1591 void *ptr;
1593 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1594 if (ret != 1) {
1595 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1597 lock ("freetile");
1598 freetile (ptr);
1599 unlock ("freetile");
1601 else if (!strncmp ("search", p, 6)) {
1602 int icase, pageno, y, len2, forward;
1603 char *pattern;
1604 regex_t re;
1606 ret = sscanf (p + 6, " %d %d %d %d,%n",
1607 &icase, &pageno, &y, &forward, &len2);
1608 if (ret != 4) {
1609 errx (1, "malformed search `%s' ret=%d", p, ret);
1612 pattern = p + 6 + len2;
1613 ret = regcomp (&re, pattern,
1614 REG_EXTENDED | (icase ? REG_ICASE : 0));
1615 if (ret) {
1616 char errbuf[80];
1617 size_t size;
1619 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1620 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1622 else {
1623 search (&re, pageno, y, forward);
1624 regfree (&re);
1627 else if (!strncmp ("geometry", p, 8)) {
1628 int w, h, fitmodel;
1630 printd ("clear");
1631 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1632 if (ret != 3) {
1633 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1636 lock ("geometry");
1637 state.h = h;
1638 if (w != state.w) {
1639 state.w = w;
1640 for (int i = 0; i < state.texcount; ++i) {
1641 state.texowners[i].slice = NULL;
1644 state.fitmodel = fitmodel;
1645 layout ();
1646 process_outline ();
1648 state.gen++;
1649 unlock ("geometry");
1650 printd ("continue %d", state.pagecount);
1652 else if (!strncmp ("reqlayout", p, 9)) {
1653 char *nameddest;
1654 int rotate, off, h;
1655 int fitmodel;
1656 pdf_document *pdf;
1658 printd ("clear");
1659 ret = sscanf (p + 9, " %d %d %d %n",
1660 &rotate, &fitmodel, &h, &off);
1661 if (ret != 3) {
1662 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1664 lock ("reqlayout");
1665 pdf = pdf_specifics (state.ctx, state.doc);
1666 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1667 state.gen += 1;
1669 state.rotate = rotate;
1670 state.fitmodel = fitmodel;
1671 state.h = h;
1672 layout ();
1673 process_outline ();
1675 nameddest = p + 9 + off;
1676 if (pdf && nameddest && *nameddest) {
1677 fz_point xy;
1678 struct pagedim *pdim;
1679 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1680 &xy.x, &xy.y);
1681 pdim = pdimofpageno (pageno);
1682 fz_transform_point (&xy, &pdim->ctm);
1683 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1686 state.gen++;
1687 unlock ("reqlayout");
1688 printd ("continue %d", state.pagecount);
1690 else if (!strncmp ("page", p, 4)) {
1691 double a, b;
1692 struct page *page;
1693 int pageno, pindex;
1695 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1696 if (ret != 2) {
1697 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1700 lock ("page");
1701 a = now ();
1702 page = loadpage (pageno, pindex);
1703 b = now ();
1704 unlock ("page");
1706 printd ("page %" PRIxPTR " %f", (uintptr_t) page, b - a);
1708 else if (!strncmp ("tile", p, 4)) {
1709 int x, y, w, h;
1710 struct page *page;
1711 struct tile *tile;
1712 double a, b;
1713 void *data;
1715 ret = sscanf (p + 4, " %" SCNxPTR " %d %d %d %d %" SCNxPTR,
1716 (uintptr_t *) &page, &x, &y, &w, &h,
1717 (uintptr_t *) &data);
1718 if (ret != 6) {
1719 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1722 lock ("tile");
1723 a = now ();
1724 tile = rendertile (page, x, y, w, h, data);
1725 b = now ();
1726 unlock ("tile");
1728 printd ("tile %d %d %" PRIxPTR " %u %f",
1729 x, y, (uintptr_t) (tile),
1730 tile->w * tile->h * tile->pixmap->n,
1731 b - a);
1733 else if (!strncmp ("trimset", p, 7)) {
1734 fz_irect fuzz;
1735 int trimmargins;
1737 ret = sscanf (p + 7, " %d %d %d %d %d",
1738 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1739 if (ret != 5) {
1740 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1742 lock ("trimset");
1743 state.trimmargins = trimmargins;
1744 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1745 state.trimanew = 1;
1746 state.trimfuzz = fuzz;
1748 unlock ("trimset");
1750 else if (!strncmp ("settrim", p, 7)) {
1751 fz_irect fuzz;
1752 int trimmargins;
1754 ret = sscanf (p + 7, " %d %d %d %d %d",
1755 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1756 if (ret != 5) {
1757 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1759 printd ("clear");
1760 lock ("settrim");
1761 state.trimmargins = trimmargins;
1762 state.needoutline = 1;
1763 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1764 state.trimanew = 1;
1765 state.trimfuzz = fuzz;
1767 state.pagedimcount = 0;
1768 free (state.pagedims);
1769 state.pagedims = NULL;
1770 initpdims ();
1771 layout ();
1772 process_outline ();
1773 unlock ("settrim");
1774 printd ("continue %d", state.pagecount);
1776 else if (!strncmp ("sliceh", p, 6)) {
1777 int h;
1779 ret = sscanf (p + 6, " %d", &h);
1780 if (ret != 1) {
1781 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1783 if (h != state.sliceheight) {
1784 state.sliceheight = h;
1785 for (int i = 0; i < state.texcount; ++i) {
1786 state.texowners[i].w = -1;
1787 state.texowners[i].h = -1;
1788 state.texowners[i].slice = NULL;
1792 else if (!strncmp ("interrupt", p, 9)) {
1793 printd ("vmsg interrupted");
1795 else {
1796 errx (1, "unknown command %.*s", len, p);
1799 return 0;
1802 CAMLprim value ml_isexternallink (value uri_v)
1804 CAMLparam1 (uri_v);
1805 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1806 CAMLreturn (Val_bool (ext));
1809 CAMLprim value ml_uritolocation (value uri_v)
1811 CAMLparam1 (uri_v);
1812 CAMLlocal1 (ret_v);
1813 int pageno;
1814 fz_point xy;
1815 struct pagedim *pdim;
1817 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1818 &xy.x, &xy.y);
1819 pdim = pdimofpageno (pageno);
1820 fz_transform_point (&xy, &pdim->ctm);
1821 ret_v = caml_alloc_tuple (3);
1822 Field (ret_v, 0) = Val_int (pageno);
1823 Field (ret_v, 1) = caml_copy_double ((double) xy.x);
1824 Field (ret_v, 2) = caml_copy_double ((double) xy.y);
1825 CAMLreturn (ret_v);
1828 CAMLprim value ml_realloctexts (value texcount_v)
1830 CAMLparam1 (texcount_v);
1831 int ok;
1833 if (trylock (__func__)) {
1834 ok = 0;
1835 goto done;
1837 realloctexts (Int_val (texcount_v));
1838 ok = 1;
1839 unlock (__func__);
1841 done:
1842 CAMLreturn (Val_bool (ok));
1845 static void recti (int x0, int y0, int x1, int y1)
1847 GLfloat *v = state.vertices;
1849 glVertexPointer (2, GL_FLOAT, 0, v);
1850 v[0] = x0; v[1] = y0;
1851 v[2] = x1; v[3] = y0;
1852 v[4] = x0; v[5] = y1;
1853 v[6] = x1; v[7] = y1;
1854 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1857 static void showsel (struct page *page, int ox, int oy)
1859 fz_irect bbox;
1860 fz_rect rect;
1861 fz_stext_block *block;
1862 int seen = 0;
1863 unsigned char selcolor[] = {15,15,15,140};
1865 if (!page->fmark || !page->lmark) return;
1867 glEnable (GL_BLEND);
1868 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1869 glColor4ubv (selcolor);
1871 ox += state.pagedims[page->pdimno].bounds.x0;
1872 oy += state.pagedims[page->pdimno].bounds.y0;
1874 for (block = page->text->first_block; block; block = block->next) {
1875 fz_stext_line *line;
1877 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1878 for (line = block->u.t.first_line; line; line = line->next) {
1879 fz_stext_char *ch;
1881 rect = fz_empty_rect;
1882 for (ch = line->first_char; ch; ch = ch->next) {
1883 if (ch == page->fmark) seen = 1;
1884 if (seen) fz_union_rect (&rect, &ch->bbox);
1885 if (ch == page->lmark) {
1886 fz_round_rect (&bbox, &rect);
1887 recti (bbox.x0 + ox, bbox.y0 + oy,
1888 bbox.x1 + ox, bbox.y1 + oy);
1889 goto done;
1892 fz_round_rect (&bbox, &rect);
1893 recti (bbox.x0 + ox, bbox.y0 + oy,
1894 bbox.x1 + ox, bbox.y1 + oy);
1897 done:
1898 glDisable (GL_BLEND);
1901 #pragma GCC diagnostic push
1902 #pragma GCC diagnostic ignored "-Wdouble-promotion"
1903 #pragma GCC diagnostic ignored "-Wconversion"
1904 #include "glfont.c"
1905 #pragma GCC diagnostic pop
1907 static void stipplerect (fz_matrix *m,
1908 fz_point *p1,
1909 fz_point *p2,
1910 fz_point *p3,
1911 fz_point *p4,
1912 GLfloat *texcoords,
1913 GLfloat *vertices)
1915 fz_transform_point (p1, m);
1916 fz_transform_point (p2, m);
1917 fz_transform_point (p3, m);
1918 fz_transform_point (p4, m);
1920 float w, h, s, t;
1922 w = p2->x - p1->x;
1923 h = p2->y - p1->y;
1924 t = hypotf (w, h) * .25f;
1926 w = p3->x - p2->x;
1927 h = p3->y - p2->y;
1928 s = hypotf (w, h) * .25f;
1930 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
1931 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
1933 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
1934 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
1936 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
1937 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
1939 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
1940 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
1942 glDrawArrays (GL_LINES, 0, 8);
1945 static void solidrect (fz_matrix *m,
1946 fz_point *p1,
1947 fz_point *p2,
1948 fz_point *p3,
1949 fz_point *p4,
1950 GLfloat *vertices)
1952 fz_transform_point (p1, m);
1953 fz_transform_point (p2, m);
1954 fz_transform_point (p3, m);
1955 fz_transform_point (p4, m);
1956 vertices[0] = p1->x; vertices[1] = p1->y;
1957 vertices[2] = p2->x; vertices[3] = p2->y;
1959 vertices[4] = p3->x; vertices[5] = p3->y;
1960 vertices[6] = p4->x; vertices[7] = p4->y;
1961 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
1964 static void ensurelinks (struct page *page)
1966 if (!page->links)
1967 page->links = fz_load_links (state.ctx, page->fzpage);
1970 static void highlightlinks (struct page *page, int xoff, int yoff)
1972 fz_matrix ctm, tm, pm;
1973 fz_link *link;
1974 GLfloat *texcoords = state.texcoords;
1975 GLfloat *vertices = state.vertices;
1977 ensurelinks (page);
1979 glEnable (GL_TEXTURE_1D);
1980 glEnable (GL_BLEND);
1981 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1982 glBindTexture (GL_TEXTURE_1D, state.stid);
1984 xoff -= state.pagedims[page->pdimno].bounds.x0;
1985 yoff -= state.pagedims[page->pdimno].bounds.y0;
1986 fz_translate (&tm, xoff, yoff);
1987 pm = pagectm (page);
1988 fz_concat (&ctm, &pm, &tm);
1990 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
1991 glVertexPointer (2, GL_FLOAT, 0, vertices);
1993 for (link = page->links; link; link = link->next) {
1994 fz_point p1, p2, p3, p4;
1996 p1.x = link->rect.x0;
1997 p1.y = link->rect.y0;
1999 p2.x = link->rect.x1;
2000 p2.y = link->rect.y0;
2002 p3.x = link->rect.x1;
2003 p3.y = link->rect.y1;
2005 p4.x = link->rect.x0;
2006 p4.y = link->rect.y1;
2008 /* TODO: different colours for different schemes */
2009 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
2010 else glColor3ub (255, 0, 0);
2012 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2015 for (int i = 0; i < page->annotcount; ++i) {
2016 fz_point p1, p2, p3, p4;
2017 struct annot *annot = &page->annots[i];
2019 p1.x = annot->bbox.x0;
2020 p1.y = annot->bbox.y0;
2022 p2.x = annot->bbox.x1;
2023 p2.y = annot->bbox.y0;
2025 p3.x = annot->bbox.x1;
2026 p3.y = annot->bbox.y1;
2028 p4.x = annot->bbox.x0;
2029 p4.y = annot->bbox.y1;
2031 glColor3ub (0, 0, 128);
2032 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2035 glDisable (GL_BLEND);
2036 glDisable (GL_TEXTURE_1D);
2039 static int compareslinks (const void *l, const void *r)
2041 struct slink const *ls = l;
2042 struct slink const *rs = r;
2043 if (ls->bbox.y0 == rs->bbox.y0) {
2044 return rs->bbox.x0 - rs->bbox.x0;
2046 return ls->bbox.y0 - rs->bbox.y0;
2049 static void droptext (struct page *page)
2051 if (page->text) {
2052 fz_drop_stext_page (state.ctx, page->text);
2053 page->fmark = NULL;
2054 page->lmark = NULL;
2055 page->text = NULL;
2059 static void dropannots (struct page *page)
2061 if (page->annots) {
2062 free (page->annots);
2063 page->annots = NULL;
2064 page->annotcount = 0;
2068 static void ensureannots (struct page *page)
2070 int i, count = 0;
2071 size_t annotsize = sizeof (*page->annots);
2072 fz_annot *annot;
2074 if (state.gen != page->agen) {
2075 dropannots (page);
2076 page->agen = state.gen;
2078 if (page->annots) return;
2080 for (annot = fz_first_annot (state.ctx, page->fzpage);
2081 annot;
2082 annot = fz_next_annot (state.ctx, annot)) {
2083 count++;
2086 if (count > 0) {
2087 page->annotcount = count;
2088 page->annots = calloc (count, annotsize);
2089 if (!page->annots) {
2090 err (1, "calloc annots %d", count);
2093 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2094 annot;
2095 annot = fz_next_annot (state.ctx, annot), i++) {
2096 fz_rect rect;
2098 fz_bound_annot (state.ctx, annot, &rect);
2099 page->annots[i].annot = annot;
2100 fz_round_rect (&page->annots[i].bbox, &rect);
2105 static void dropslinks (struct page *page)
2107 if (page->slinks) {
2108 free (page->slinks);
2109 page->slinks = NULL;
2110 page->slinkcount = 0;
2112 if (page->links) {
2113 fz_drop_link (state.ctx, page->links);
2114 page->links = NULL;
2118 static void ensureslinks (struct page *page)
2120 fz_matrix ctm;
2121 int i, count;
2122 size_t slinksize = sizeof (*page->slinks);
2123 fz_link *link;
2125 ensureannots (page);
2126 if (state.gen != page->sgen) {
2127 dropslinks (page);
2128 page->sgen = state.gen;
2130 if (page->slinks) return;
2132 ensurelinks (page);
2133 ctm = pagectm (page);
2135 count = page->annotcount;
2136 for (link = page->links; link; link = link->next) {
2137 count++;
2139 if (count > 0) {
2140 int j;
2142 page->slinkcount = count;
2143 page->slinks = calloc (count, slinksize);
2144 if (!page->slinks) {
2145 err (1, "calloc slinks %d", count);
2148 for (i = 0, link = page->links; link; ++i, link = link->next) {
2149 fz_rect rect;
2151 rect = link->rect;
2152 fz_transform_rect (&rect, &ctm);
2153 page->slinks[i].tag = SLINK;
2154 page->slinks[i].u.link = link;
2155 fz_round_rect (&page->slinks[i].bbox, &rect);
2157 for (j = 0; j < page->annotcount; ++j, ++i) {
2158 fz_rect rect;
2159 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2160 fz_transform_rect (&rect, &ctm);
2161 fz_round_rect (&page->slinks[i].bbox, &rect);
2163 page->slinks[i].tag = SANNOT;
2164 page->slinks[i].u.annot = page->annots[j].annot;
2166 qsort (page->slinks, count, slinksize, compareslinks);
2170 static void highlightslinks (struct page *page, int xoff, int yoff,
2171 int noff, char *targ, mlsize_t tlen, int hfsize)
2173 char buf[40];
2174 struct slink *slink;
2175 float x0, y0, x1, y1, w;
2177 ensureslinks (page);
2178 glColor3ub (0xc3, 0xb0, 0x91);
2179 for (int i = 0; i < page->slinkcount; ++i) {
2180 fmt_linkn (buf, i + noff);
2181 if (!tlen || !strncmp (targ, buf, tlen)) {
2182 slink = &page->slinks[i];
2184 x0 = slink->bbox.x0 + xoff - 5;
2185 y1 = slink->bbox.y0 + yoff - 5;
2186 y0 = y1 + 10 + hfsize;
2187 w = measure_string (state.face, hfsize, buf);
2188 x1 = x0 + w + 10;
2189 recti ((int) x0, (int) y0, (int) x1, (int) y1);
2193 glEnable (GL_BLEND);
2194 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2195 glEnable (GL_TEXTURE_2D);
2196 glColor3ub (0, 0, 0);
2197 for (int i = 0; i < page->slinkcount; ++i) {
2198 fmt_linkn (buf, i + noff);
2199 if (!tlen || !strncmp (targ, buf, tlen)) {
2200 slink = &page->slinks[i];
2202 x0 = slink->bbox.x0 + xoff;
2203 y0 = slink->bbox.y0 + yoff + hfsize;
2204 draw_string (state.face, hfsize, x0, y0, buf);
2207 glDisable (GL_TEXTURE_2D);
2208 glDisable (GL_BLEND);
2211 static void uploadslice (struct tile *tile, struct slice *slice)
2213 int offset;
2214 struct slice *slice1;
2215 unsigned char *texdata;
2217 offset = 0;
2218 for (slice1 = tile->slices; slice != slice1; slice1++) {
2219 offset += slice1->h * tile->w * tile->pixmap->n;
2221 if (slice->texindex != -1 && slice->texindex < state.texcount
2222 && state.texowners[slice->texindex].slice == slice) {
2223 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2225 else {
2226 int subimage = 0;
2227 int texindex = state.texindex++ % state.texcount;
2229 if (state.texowners[texindex].w == tile->w) {
2230 if (state.texowners[texindex].h >= slice->h) {
2231 subimage = 1;
2233 else {
2234 state.texowners[texindex].h = slice->h;
2237 else {
2238 state.texowners[texindex].h = slice->h;
2241 state.texowners[texindex].w = tile->w;
2242 state.texowners[texindex].slice = slice;
2243 slice->texindex = texindex;
2245 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2246 #if TEXT_TYPE == GL_TEXTURE_2D
2247 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2248 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2249 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2250 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2251 #endif
2252 if (tile->pbo) {
2253 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2254 texdata = 0;
2256 else {
2257 texdata = tile->pixmap->samples;
2259 if (subimage) {
2260 glTexSubImage2D (TEXT_TYPE,
2264 tile->w,
2265 slice->h,
2266 state.texform,
2267 state.texty,
2268 texdata+offset
2271 else {
2272 glTexImage2D (TEXT_TYPE,
2274 state.texiform,
2275 tile->w,
2276 slice->h,
2278 state.texform,
2279 state.texty,
2280 texdata+offset
2283 if (tile->pbo) {
2284 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2289 CAMLprim void ml_begintiles (value unit_v)
2291 CAMLparam1 (unit_v);
2292 glEnable (TEXT_TYPE);
2293 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2294 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2295 CAMLreturn0;
2298 CAMLprim void ml_endtiles (value unit_v)
2300 CAMLparam1 (unit_v);
2301 glDisable (TEXT_TYPE);
2302 CAMLreturn0;
2305 CAMLprim void ml_drawtile (value args_v, value ptr_v)
2307 CAMLparam2 (args_v, ptr_v);
2308 int dispx = Int_val (Field (args_v, 0));
2309 int dispy = Int_val (Field (args_v, 1));
2310 int dispw = Int_val (Field (args_v, 2));
2311 int disph = Int_val (Field (args_v, 3));
2312 int tilex = Int_val (Field (args_v, 4));
2313 int tiley = Int_val (Field (args_v, 5));
2314 char *s = String_val (ptr_v);
2315 struct tile *tile = parse_pointer (__func__, s);
2316 int slicey, firstslice;
2317 struct slice *slice;
2318 GLfloat *texcoords = state.texcoords;
2319 GLfloat *vertices = state.vertices;
2321 firstslice = tiley / tile->sliceheight;
2322 slice = &tile->slices[firstslice];
2323 slicey = tiley % tile->sliceheight;
2325 while (disph > 0) {
2326 int dh;
2328 dh = slice->h - slicey;
2329 dh = fz_mini (disph, dh);
2330 uploadslice (tile, slice);
2332 texcoords[0] = tilex; texcoords[1] = slicey;
2333 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2334 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2335 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2337 vertices[0] = dispx; vertices[1] = dispy;
2338 vertices[2] = dispx+dispw; vertices[3] = dispy;
2339 vertices[4] = dispx; vertices[5] = dispy+dh;
2340 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2342 #if TEXT_TYPE == GL_TEXTURE_2D
2343 for (int i = 0; i < 8; ++i) {
2344 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2346 #endif
2348 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2349 dispy += dh;
2350 disph -= dh;
2351 slice++;
2352 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2353 slicey = 0;
2355 CAMLreturn0;
2358 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2360 fz_matrix ctm, tm, pm;
2361 fz_point p1, p2, p3, p4;
2362 GLfloat *vertices = state.vertices;
2363 double *v = (double *) rects_v;
2365 xoff -= state.pagedims[page->pdimno].bounds.x0;
2366 yoff -= state.pagedims[page->pdimno].bounds.y0;
2367 fz_translate (&tm, xoff, yoff);
2368 pm = pagectm (page);
2369 fz_concat (&ctm, &pm, &tm);
2371 glEnable (GL_BLEND);
2372 glVertexPointer (2, GL_FLOAT, 0, vertices);
2374 glColor4dv (v);
2375 p1.x = (float) v[4];
2376 p1.y = (float) v[5];
2378 p2.x = (float) v[6];
2379 p2.y = (float) v[5];
2381 p3.x = (float) v[6];
2382 p3.y = (float) v[7];
2384 p4.x = (float) v[4];
2385 p4.y = (float) v[7];
2386 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2387 glDisable (GL_BLEND);
2390 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2391 value xoff_v, value yoff_v,
2392 value li_v)
2394 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2395 int xoff = Int_val (xoff_v);
2396 int yoff = Int_val (yoff_v);
2397 int noff = Int_val (Field (li_v, 0));
2398 char *targ = String_val (Field (li_v, 1));
2399 mlsize_t tlen = caml_string_length (Field (li_v, 1));
2400 int hfsize = Int_val (Field (li_v, 2));
2401 char *s = String_val (ptr_v);
2402 int hlmask = Int_val (hlinks_v);
2403 struct page *page = parse_pointer (__func__, s);
2405 if (!page->fzpage) {
2406 /* deal with loadpage failed pages */
2407 goto done;
2410 if (trylock (__func__)) {
2411 noff = -1;
2412 goto done;
2415 ensureannots (page);
2416 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2417 if (hlmask & 2) {
2418 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2419 noff = page->slinkcount;
2421 if (page->tgen == state.gen) {
2422 showsel (page, xoff, yoff);
2424 unlock (__func__);
2426 done:
2427 CAMLreturn (Val_int (noff));
2430 CAMLprim void ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2431 value rects_v)
2433 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2434 int xoff = Int_val (xoff_v);
2435 int yoff = Int_val (yoff_v);
2436 char *s = String_val (ptr_v);
2437 struct page *page = parse_pointer (__func__, s);
2439 drawprect (page, xoff, yoff, rects_v);
2440 CAMLreturn0;
2443 static struct annot *getannot (struct page *page, int x, int y)
2445 fz_point p;
2446 fz_matrix ctm;
2447 const fz_matrix *tctm;
2448 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2450 if (!page->annots) return NULL;
2452 if (pdf) {
2453 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2454 tctm = &state.pagedims[page->pdimno].tctm;
2456 else {
2457 tctm = &fz_identity;
2460 p.x = x;
2461 p.y = y;
2463 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2464 fz_invert_matrix (&ctm, &ctm);
2465 fz_transform_point (&p, &ctm);
2467 if (pdf) {
2468 for (int i = 0; i < page->annotcount; ++i) {
2469 struct annot *a = &page->annots[i];
2470 fz_rect rect;
2472 fz_bound_annot (state.ctx, a->annot, &rect);
2473 if (p.x >= rect.x0 && p.x <= rect.x1) {
2474 if (p.y >= rect.y0 && p.y <= rect.y1)
2475 return a;
2479 return NULL;
2482 static fz_link *getlink (struct page *page, int x, int y)
2484 fz_point p;
2485 fz_matrix ctm;
2486 fz_link *link;
2488 ensureslinks (page);
2490 p.x = x;
2491 p.y = y;
2493 ctm = pagectm (page);
2494 fz_invert_matrix (&ctm, &ctm);
2495 fz_transform_point (&p, &ctm);
2497 for (link = page->links; link; link = link->next) {
2498 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2499 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2500 return link;
2504 return NULL;
2507 static void ensuretext (struct page *page)
2509 if (state.gen != page->tgen) {
2510 droptext (page);
2511 page->tgen = state.gen;
2513 if (!page->text) {
2514 fz_matrix ctm;
2515 fz_device *tdev;
2517 page->text = fz_new_stext_page (state.ctx,
2518 &state.pagedims[page->pdimno].mediabox);
2519 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2520 ctm = pagectm (page);
2521 fz_run_display_list (state.ctx, page->dlist,
2522 tdev, &ctm, &fz_infinite_rect, NULL);
2523 fz_close_device (state.ctx, tdev);
2524 fz_drop_device (state.ctx, tdev);
2528 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2530 CAMLparam2 (start_page_v, dir_v);
2531 CAMLlocal1 (ret_v);
2532 int i, dir = Int_val (dir_v);
2533 int start_page = Int_val (start_page_v);
2534 int end_page = dir > 0 ? state.pagecount : -1;
2535 pdf_document *pdf;
2537 fz_var (end_page);
2538 ret_v = Val_int (0);
2539 lock (__func__);
2540 pdf = pdf_specifics (state.ctx, state.doc);
2541 for (i = start_page + dir; i != end_page; i += dir) {
2542 int found;
2544 fz_var (found);
2545 if (pdf) {
2546 pdf_page *page = NULL;
2548 fz_var (page);
2549 fz_try (state.ctx) {
2550 page = pdf_load_page (state.ctx, pdf, i);
2551 found = !!page->links || !!page->annots;
2553 fz_catch (state.ctx) {
2554 found = 0;
2556 if (page) {
2557 fz_drop_page (state.ctx, &page->super);
2560 else {
2561 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2562 fz_link *link = fz_load_links (state.ctx, page);
2563 found = !!link;
2564 fz_drop_link (state.ctx, link);
2565 fz_drop_page (state.ctx, page);
2568 if (found) {
2569 ret_v = caml_alloc_small (1, 1);
2570 Field (ret_v, 0) = Val_int (i);
2571 goto unlock;
2574 unlock:
2575 unlock (__func__);
2576 CAMLreturn (ret_v);
2579 enum { dir_first, dir_last };
2580 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2582 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2584 CAMLparam2 (ptr_v, dir_v);
2585 CAMLlocal2 (ret_v, pos_v);
2586 struct page *page;
2587 int dirtag, i, slinkindex;
2588 struct slink *found = NULL ,*slink;
2589 char *s = String_val (ptr_v);
2591 page = parse_pointer (__func__, s);
2592 ret_v = Val_int (0);
2593 lock (__func__);
2594 ensureslinks (page);
2596 if (Is_block (dir_v)) {
2597 dirtag = Tag_val (dir_v);
2598 switch (dirtag) {
2599 case dir_first_visible:
2601 int x0, y0, dir, first_index, last_index;
2603 pos_v = Field (dir_v, 0);
2604 x0 = Int_val (Field (pos_v, 0));
2605 y0 = Int_val (Field (pos_v, 1));
2606 dir = Int_val (Field (pos_v, 2));
2608 if (dir >= 0) {
2609 dir = 1;
2610 first_index = 0;
2611 last_index = page->slinkcount;
2613 else {
2614 first_index = page->slinkcount - 1;
2615 last_index = -1;
2618 for (i = first_index; i != last_index; i += dir) {
2619 slink = &page->slinks[i];
2620 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2621 found = slink;
2622 break;
2626 break;
2628 case dir_left:
2629 slinkindex = Int_val (Field (dir_v, 0));
2630 found = &page->slinks[slinkindex];
2631 for (i = slinkindex - 1; i >= 0; --i) {
2632 slink = &page->slinks[i];
2633 if (slink->bbox.x0 < found->bbox.x0) {
2634 found = slink;
2635 break;
2638 break;
2640 case dir_right:
2641 slinkindex = Int_val (Field (dir_v, 0));
2642 found = &page->slinks[slinkindex];
2643 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2644 slink = &page->slinks[i];
2645 if (slink->bbox.x0 > found->bbox.x0) {
2646 found = slink;
2647 break;
2650 break;
2652 case dir_down:
2653 slinkindex = Int_val (Field (dir_v, 0));
2654 found = &page->slinks[slinkindex];
2655 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2656 slink = &page->slinks[i];
2657 if (slink->bbox.y0 >= found->bbox.y0) {
2658 found = slink;
2659 break;
2662 break;
2664 case dir_up:
2665 slinkindex = Int_val (Field (dir_v, 0));
2666 found = &page->slinks[slinkindex];
2667 for (i = slinkindex - 1; i >= 0; --i) {
2668 slink = &page->slinks[i];
2669 if (slink->bbox.y0 <= found->bbox.y0) {
2670 found = slink;
2671 break;
2674 break;
2677 else {
2678 dirtag = Int_val (dir_v);
2679 switch (dirtag) {
2680 case dir_first:
2681 found = page->slinks;
2682 break;
2684 case dir_last:
2685 if (page->slinks) {
2686 found = page->slinks + (page->slinkcount - 1);
2688 break;
2691 if (found) {
2692 ret_v = caml_alloc_small (2, 1);
2693 Field (ret_v, 0) = Val_int (found - page->slinks);
2696 unlock (__func__);
2697 CAMLreturn (ret_v);
2700 enum { uuri, utext, uannot };
2702 CAMLprim value ml_getlink (value ptr_v, value n_v)
2704 CAMLparam2 (ptr_v, n_v);
2705 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2706 fz_link *link;
2707 struct page *page;
2708 char *s = String_val (ptr_v);
2709 struct slink *slink;
2711 ret_v = Val_int (0);
2712 page = parse_pointer (__func__, s);
2714 lock (__func__);
2715 ensureslinks (page);
2716 slink = &page->slinks[Int_val (n_v)];
2717 if (slink->tag == SLINK) {
2718 link = slink->u.link;
2719 str_v = caml_copy_string (link->uri);
2720 ret_v = caml_alloc_small (1, uuri);
2721 Field (ret_v, 0) = str_v;
2723 else {
2724 ret_v = caml_alloc_small (1, uannot);
2725 tup_v = caml_alloc_tuple (2);
2726 Field (ret_v, 0) = tup_v;
2727 Field (tup_v, 0) = ptr_v;
2728 Field (tup_v, 1) = n_v;
2730 unlock (__func__);
2732 CAMLreturn (ret_v);
2735 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2737 CAMLparam2 (ptr_v, n_v);
2738 CAMLlocal1 (ret_v);
2739 pdf_document *pdf;
2740 char *contents = NULL;
2742 lock (__func__);
2743 pdf = pdf_specifics (state.ctx, state.doc);
2744 if (pdf) {
2745 char *s = String_val (ptr_v);
2746 struct page *page;
2747 struct slink *slink;
2749 page = parse_pointer (__func__, s);
2750 slink = &page->slinks[Int_val (n_v)];
2751 contents = pdf_copy_annot_contents (state.ctx,
2752 (pdf_annot *) slink->u.annot);
2754 unlock (__func__);
2755 if (contents) {
2756 ret_v = caml_copy_string (contents);
2757 fz_free (state.ctx, contents);
2759 else {
2760 ret_v = caml_copy_string ("");
2762 CAMLreturn (ret_v);
2765 CAMLprim value ml_getlinkcount (value ptr_v)
2767 CAMLparam1 (ptr_v);
2768 struct page *page;
2769 char *s = String_val (ptr_v);
2771 page = parse_pointer (__func__, s);
2772 CAMLreturn (Val_int (page->slinkcount));
2775 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2777 CAMLparam2 (ptr_v, n_v);
2778 CAMLlocal1 (ret_v);
2779 struct page *page;
2780 struct slink *slink;
2781 char *s = String_val (ptr_v);
2783 page = parse_pointer (__func__, s);
2784 ret_v = caml_alloc_tuple (4);
2785 lock (__func__);
2786 ensureslinks (page);
2788 slink = &page->slinks[Int_val (n_v)];
2789 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2790 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2791 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2792 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2793 unlock (__func__);
2794 CAMLreturn (ret_v);
2797 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2799 CAMLparam3 (ptr_v, x_v, y_v);
2800 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2801 fz_link *link;
2802 struct annot *annot;
2803 struct page *page;
2804 char *ptr = String_val (ptr_v);
2805 int x = Int_val (x_v), y = Int_val (y_v);
2806 struct pagedim *pdim;
2808 ret_v = Val_int (0);
2809 if (trylock (__func__)) {
2810 goto done;
2813 page = parse_pointer (__func__, ptr);
2814 pdim = &state.pagedims[page->pdimno];
2815 x += pdim->bounds.x0;
2816 y += pdim->bounds.y0;
2819 annot = getannot (page, x, y);
2820 if (annot) {
2821 int i, n = -1;
2823 ensureslinks (page);
2824 for (i = 0; i < page->slinkcount; ++i) {
2825 if (page->slinks[i].tag == SANNOT
2826 && page->slinks[i].u.annot == annot->annot) {
2827 n = i;
2828 break;
2831 ret_v = caml_alloc_small (1, uannot);
2832 tup_v = caml_alloc_tuple (2);
2833 Field (ret_v, 0) = tup_v;
2834 Field (tup_v, 0) = ptr_v;
2835 Field (tup_v, 1) = Val_int (n);
2836 goto unlock;
2840 link = getlink (page, x, y);
2841 if (link) {
2842 str_v = caml_copy_string (link->uri);
2843 ret_v = caml_alloc_small (1, uuri);
2844 Field (ret_v, 0) = str_v;
2846 else {
2847 fz_rect *b;
2848 fz_stext_block *block;
2850 ensuretext (page);
2852 for (block = page->text->first_block; block; block = block->next) {
2853 fz_stext_line *line;
2855 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2856 b = &block->bbox;
2857 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2858 continue;
2860 for (line = block->u.t.first_line; line; line = line->next) {
2861 fz_stext_char *ch;
2863 b = &line->bbox;
2864 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2865 continue;
2867 for (ch = line->first_char; ch; ch = ch->next) {
2868 b = &ch->bbox;
2870 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
2871 const char *n2 = fz_font_name (state.ctx, ch->font);
2872 FT_FaceRec *face = fz_font_ft_face (state.ctx,
2873 ch->font);
2875 if (!n2) n2 = "<unknown font>";
2877 if (face && face->family_name) {
2878 char *s;
2879 char *n1 = face->family_name;
2880 size_t l1 = strlen (n1);
2881 size_t l2 = strlen (n2);
2883 if (l1 != l2 || memcmp (n1, n2, l1)) {
2884 s = malloc (l1 + l2 + 2);
2885 if (s) {
2886 memcpy (s, n2, l2);
2887 s[l2] = '=';
2888 memcpy (s + l2 + 1, n1, l1 + 1);
2889 str_v = caml_copy_string (s);
2890 free (s);
2894 if (str_v == Val_unit) {
2895 str_v = caml_copy_string (n2);
2897 ret_v = caml_alloc_small (1, utext);
2898 Field (ret_v, 0) = str_v;
2899 goto unlock;
2905 unlock:
2906 unlock (__func__);
2908 done:
2909 CAMLreturn (ret_v);
2912 enum { mark_page, mark_block, mark_line, mark_word };
2914 CAMLprim void ml_clearmark (value ptr_v)
2916 CAMLparam1 (ptr_v);
2917 char *s = String_val (ptr_v);
2918 struct page *page;
2920 if (trylock (__func__)) {
2921 goto done;
2924 page = parse_pointer (__func__, s);
2925 page->fmark = NULL;
2926 page->lmark = NULL;
2928 unlock (__func__);
2929 done:
2930 CAMLreturn0;
2933 static int uninteresting (int c)
2935 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
2936 || ispunct (c);
2939 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
2941 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
2942 CAMLlocal1 (ret_v);
2943 fz_rect *b;
2944 struct page *page;
2945 fz_stext_line *line;
2946 fz_stext_block *block;
2947 struct pagedim *pdim;
2948 int mark = Int_val (mark_v);
2949 char *s = String_val (ptr_v);
2950 int x = Int_val (x_v), y = Int_val (y_v);
2952 ret_v = Val_bool (0);
2953 if (trylock (__func__)) {
2954 goto done;
2957 page = parse_pointer (__func__, s);
2958 pdim = &state.pagedims[page->pdimno];
2960 ensuretext (page);
2962 if (mark == mark_page) {
2963 page->fmark = page->text->first_block->u.t.first_line->first_char;
2964 page->lmark = page->text->last_block->u.t.last_line->last_char;
2965 ret_v = Val_bool (1);
2966 goto unlock;
2969 x += pdim->bounds.x0;
2970 y += pdim->bounds.y0;
2972 for (block = page->text->first_block; block; block = block->next) {
2973 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2974 b = &block->bbox;
2975 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2976 continue;
2978 if (mark == mark_block) {
2979 page->fmark = block->u.t.first_line->first_char;
2980 page->lmark = block->u.t.last_line->last_char;
2981 ret_v = Val_bool (1);
2982 goto unlock;
2985 for (line = block->u.t.first_line; line; line = line->next) {
2986 fz_stext_char *ch;
2988 b = &line->bbox;
2989 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2990 continue;
2992 if (mark == mark_line) {
2993 page->fmark = line->first_char;
2994 page->lmark = line->last_char;
2995 ret_v = Val_bool (1);
2996 goto unlock;
2999 for (ch = line->first_char; ch; ch = ch->next) {
3000 fz_stext_char *ch2, *first = NULL, *last = NULL;
3001 b = &ch->bbox;
3002 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3003 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
3004 if (uninteresting (ch2->c)) first = NULL;
3005 else if (!first) first = ch2;
3007 for (ch2 = ch; ch2; ch2 = ch2->next) {
3008 if (uninteresting (ch2->c)) break;
3009 last = ch2;
3012 page->fmark = first;
3013 page->lmark = last;
3014 ret_v = Val_bool (1);
3015 goto unlock;
3020 unlock:
3021 if (!Bool_val (ret_v)) {
3022 page->fmark = NULL;
3023 page->lmark = NULL;
3025 unlock (__func__);
3027 done:
3028 CAMLreturn (ret_v);
3031 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3033 CAMLparam3 (ptr_v, x_v, y_v);
3034 CAMLlocal2 (ret_v, res_v);
3035 fz_rect *b = NULL;
3036 struct page *page;
3037 struct pagedim *pdim;
3038 fz_stext_block *block;
3039 char *s = String_val (ptr_v);
3040 int x = Int_val (x_v), y = Int_val (y_v);
3042 ret_v = Val_int (0);
3043 if (trylock (__func__)) {
3044 goto done;
3047 page = parse_pointer (__func__, s);
3048 pdim = &state.pagedims[page->pdimno];
3049 x += pdim->bounds.x0;
3050 y += pdim->bounds.y0;
3052 ensuretext (page);
3054 for (block = page->text->first_block; block; block = block->next) {
3055 switch (block->type) {
3056 case FZ_STEXT_BLOCK_TEXT:
3057 b = &block->bbox;
3058 break;
3060 case FZ_STEXT_BLOCK_IMAGE:
3061 b = &block->bbox;
3062 break;
3064 default:
3065 continue;
3068 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3069 break;
3070 b = NULL;
3072 if (b) {
3073 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3074 ret_v = caml_alloc_small (1, 1);
3075 Store_double_field (res_v, 0, (double) b->x0);
3076 Store_double_field (res_v, 1, (double) b->x1);
3077 Store_double_field (res_v, 2, (double) b->y0);
3078 Store_double_field (res_v, 3, (double) b->y1);
3079 Field (ret_v, 0) = res_v;
3081 unlock (__func__);
3083 done:
3084 CAMLreturn (ret_v);
3087 CAMLprim void ml_seltext (value ptr_v, value rect_v)
3089 CAMLparam2 (ptr_v, rect_v);
3090 fz_rect b;
3091 struct page *page;
3092 struct pagedim *pdim;
3093 char *s = String_val (ptr_v);
3094 int x0, x1, y0, y1;
3095 fz_stext_char *ch;
3096 fz_stext_line *line;
3097 fz_stext_block *block;
3098 fz_stext_char *fc, *lc;
3100 if (trylock (__func__)) {
3101 goto done;
3104 page = parse_pointer (__func__, s);
3105 ensuretext (page);
3107 pdim = &state.pagedims[page->pdimno];
3108 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3109 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3110 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3111 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3113 if (y0 > y1) {
3114 int t = y0;
3115 y0 = y1;
3116 y1 = t;
3117 x0 = x1;
3118 x1 = t;
3121 fc = page->fmark;
3122 lc = page->lmark;
3124 for (block = page->text->first_block; block; block = block->next) {
3125 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3126 for (line = block->u.t.first_line; line; line = line->next) {
3127 for (ch = line->first_char; ch; ch = ch->next) {
3128 b = ch->bbox;
3129 if (x0 >= b.x0 && x0 <= b.x1 && y0 >= b.y0 && y0 <= b.y1) {
3130 fc = ch;
3132 if (x1 >= b.x0 && x1 <= b.x1 && y1 >= b.y0 && y1 <= b.y1) {
3133 lc = ch;
3138 if (x1 < x0 && fc == lc) {
3139 fz_stext_char *t;
3141 t = fc;
3142 fc = lc;
3143 lc = t;
3146 page->fmark = fc;
3147 page->lmark = lc;
3149 unlock (__func__);
3151 done:
3152 CAMLreturn0;
3155 static int pipechar (FILE *f, fz_stext_char *ch)
3157 char buf[4];
3158 int len;
3159 size_t ret;
3161 len = fz_runetochar (buf, ch->c);
3162 ret = fwrite (buf, len, 1, f);
3163 if (ret != 1) {
3164 printd ("emsg failed to write %d bytes ret=%zu: %d:%s",
3165 len, ret, errno, strerror (errno));
3166 return -1;
3168 return 0;
3171 CAMLprim value ml_spawn (value command_v, value fds_v)
3173 CAMLparam2 (command_v, fds_v);
3174 CAMLlocal2 (l_v, tup_v);
3175 int ret, ret1;
3176 pid_t pid = (pid_t) -1;
3177 char *msg = NULL;
3178 value earg_v = Nothing;
3179 posix_spawnattr_t attr;
3180 posix_spawn_file_actions_t fa;
3181 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3183 argv[2] = String_val (command_v);
3185 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3186 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3189 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3190 msg = "posix_spawnattr_init";
3191 goto fail1;
3194 #ifdef POSIX_SPAWN_USEVFORK
3195 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3196 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3197 goto fail;
3199 #endif
3201 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3202 int fd1, fd2;
3204 tup_v = Field (l_v, 0);
3205 fd1 = Int_val (Field (tup_v, 0));
3206 fd2 = Int_val (Field (tup_v, 1));
3207 if (fd2 < 0) {
3208 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3209 msg = "posix_spawn_file_actions_addclose";
3210 earg_v = tup_v;
3211 goto fail;
3214 else {
3215 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3216 msg = "posix_spawn_file_actions_adddup2";
3217 earg_v = tup_v;
3218 goto fail;
3223 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3224 msg = "posix_spawn";
3225 goto fail;
3228 fail:
3229 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3230 printd ("emsg posix_spawnattr_destroy: %d:%s", ret1, strerror (ret1));
3233 fail1:
3234 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3235 printd ("emsg posix_spawn_file_actions_destroy: %d:%s",
3236 ret1, strerror (ret1));
3239 if (msg)
3240 unix_error (ret, msg, earg_v);
3242 CAMLreturn (Val_int (pid));
3245 CAMLprim value ml_hassel (value ptr_v)
3247 CAMLparam1 (ptr_v);
3248 CAMLlocal1 (ret_v);
3249 struct page *page;
3250 char *s = String_val (ptr_v);
3252 ret_v = Val_bool (0);
3253 if (trylock (__func__)) {
3254 goto done;
3257 page = parse_pointer (__func__, s);
3258 ret_v = Val_bool (page->fmark && page->lmark);
3259 unlock (__func__);
3260 done:
3261 CAMLreturn (ret_v);
3264 CAMLprim void ml_copysel (value fd_v, value ptr_v)
3266 CAMLparam2 (fd_v, ptr_v);
3267 FILE *f;
3268 int seen = 0;
3269 struct page *page;
3270 fz_stext_line *line;
3271 fz_stext_block *block;
3272 int fd = Int_val (fd_v);
3273 char *s = String_val (ptr_v);
3275 if (trylock (__func__)) {
3276 goto done;
3279 page = parse_pointer (__func__, s);
3281 if (!page->fmark || !page->lmark) {
3282 printd ("emsg nothing to copy on page %d", page->pageno);
3283 goto unlock;
3286 f = fdopen (fd, "w");
3287 if (!f) {
3288 printd ("emsg failed to fdopen sel pipe (from fd %d): %d:%s",
3289 fd, errno, strerror (errno));
3290 f = stdout;
3293 for (block = page->text->first_block; block; block = block->next) {
3294 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3295 for (line = block->u.t.first_line; line; line = line->next) {
3296 fz_stext_char *ch;
3297 for (ch = line->first_char; ch; ch = ch->next) {
3298 if (seen || ch == page->fmark) {
3299 do {
3300 pipechar (f, ch);
3301 if (ch == page->lmark) goto close;
3302 } while ((ch = ch->next));
3303 seen = 1;
3304 break;
3307 if (seen) fputc ('\n', f);
3310 close:
3311 if (f != stdout) {
3312 int ret = fclose (f);
3313 fd = -1;
3314 if (ret == -1) {
3315 if (errno != ECHILD) {
3316 printd ("emsg failed to close sel pipe: %d:%s",
3317 errno, strerror (errno));
3321 unlock:
3322 unlock (__func__);
3324 done:
3325 if (fd >= 0) {
3326 if (close (fd)) {
3327 printd ("emsg failed to close sel pipe: %d:%s",
3328 errno, strerror (errno));
3331 CAMLreturn0;
3334 CAMLprim value ml_getpdimrect (value pagedimno_v)
3336 CAMLparam1 (pagedimno_v);
3337 CAMLlocal1 (ret_v);
3338 int pagedimno = Int_val (pagedimno_v);
3339 fz_rect box;
3341 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3342 if (trylock (__func__)) {
3343 box = fz_empty_rect;
3345 else {
3346 box = state.pagedims[pagedimno].mediabox;
3347 unlock (__func__);
3350 Store_double_field (ret_v, 0, (double) box.x0);
3351 Store_double_field (ret_v, 1, (double) box.x1);
3352 Store_double_field (ret_v, 2, (double) box.y0);
3353 Store_double_field (ret_v, 3, (double) box.y1);
3355 CAMLreturn (ret_v);
3358 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3359 value dw_v, value cols_v)
3361 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3362 CAMLlocal1 (ret_v);
3363 int i;
3364 float zoom = -1.;
3365 float maxh = 0.0;
3366 struct pagedim *p;
3367 float winw = Int_val (winw_v);
3368 float winh = Int_val (winh_v);
3369 float dw = Int_val (dw_v);
3370 float cols = Int_val (cols_v);
3371 float pw = 1.0, ph = 1.0;
3373 if (trylock (__func__)) {
3374 goto done;
3377 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3378 float w = p->pagebox.x1 / cols;
3379 float h = p->pagebox.y1;
3380 if (h > maxh) {
3381 maxh = h;
3382 ph = h;
3383 if (state.fitmodel != FitProportional) pw = w;
3385 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3388 zoom = (((winh / ph) * pw) + dw) / winw;
3389 unlock (__func__);
3390 done:
3391 ret_v = caml_copy_double ((double) zoom);
3392 CAMLreturn (ret_v);
3395 CAMLprim value ml_getmaxw (value unit_v)
3397 CAMLparam1 (unit_v);
3398 CAMLlocal1 (ret_v);
3399 int i;
3400 float maxw = -1.;
3401 struct pagedim *p;
3403 if (trylock (__func__)) {
3404 goto done;
3407 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3408 float w = p->pagebox.x1;
3409 maxw = fz_max (maxw, w);
3412 unlock (__func__);
3413 done:
3414 ret_v = caml_copy_double ((double) maxw);
3415 CAMLreturn (ret_v);
3418 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3420 CAMLparam4 (pt_v, x_v, y_v, string_v);
3421 CAMLlocal1 (ret_v);
3422 int pt = Int_val(pt_v);
3423 int x = Int_val (x_v);
3424 int y = Int_val (y_v);
3425 double w;
3427 w = (double) draw_string (state.face, pt, x, y, String_val (string_v));
3428 ret_v = caml_copy_double (w);
3429 CAMLreturn (ret_v);
3432 CAMLprim value ml_measure_string (value pt_v, value string_v)
3434 CAMLparam2 (pt_v, string_v);
3435 CAMLlocal1 (ret_v);
3436 int pt = Int_val (pt_v);
3437 double w;
3439 w = (double) measure_string (state.face, pt, String_val (string_v));
3440 ret_v = caml_copy_double (w);
3441 CAMLreturn (ret_v);
3444 CAMLprim value ml_getpagebox (value opaque_v)
3446 CAMLparam1 (opaque_v);
3447 CAMLlocal1 (ret_v);
3448 fz_rect rect;
3449 fz_irect bbox;
3450 fz_matrix ctm;
3451 fz_device *dev;
3452 char *s = String_val (opaque_v);
3453 struct page *page = parse_pointer (__func__, s);
3455 ret_v = caml_alloc_tuple (4);
3456 dev = fz_new_bbox_device (state.ctx, &rect);
3458 ctm = pagectm (page);
3459 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3461 fz_close_device (state.ctx, dev);
3462 fz_drop_device (state.ctx, dev);
3463 fz_round_rect (&bbox, &rect);
3464 Field (ret_v, 0) = Val_int (bbox.x0);
3465 Field (ret_v, 1) = Val_int (bbox.y0);
3466 Field (ret_v, 2) = Val_int (bbox.x1);
3467 Field (ret_v, 3) = Val_int (bbox.y1);
3469 CAMLreturn (ret_v);
3472 CAMLprim void ml_setaalevel (value level_v)
3474 CAMLparam1 (level_v);
3476 state.aalevel = Int_val (level_v);
3477 CAMLreturn0;
3480 #ifndef __COCOA__
3481 #pragma GCC diagnostic push
3482 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3483 #include <X11/Xlib.h>
3484 #include <X11/cursorfont.h>
3485 #pragma GCC diagnostic pop
3487 #include <GL/glx.h>
3489 static const int shapes[] = {
3490 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3493 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3495 static struct {
3496 Window wid;
3497 Display *dpy;
3498 GLXContext ctx;
3499 XVisualInfo *visual;
3500 Cursor curs[CURS_COUNT];
3501 } glx;
3504 static void initcurs (void)
3506 for (size_t n = 0; n < CURS_COUNT; ++n) {
3507 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3511 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3513 CAMLparam3 (display_v, wid_v, screen_v);
3515 glx.dpy = XOpenDisplay (String_val (display_v));
3516 if (!glx.dpy) {
3517 caml_failwith ("XOpenDisplay");
3520 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3521 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
3522 if (!glx.visual) {
3523 XCloseDisplay (glx.dpy);
3524 caml_failwith ("glXChooseVisual");
3527 initcurs ();
3529 glx.wid = Int_val (wid_v);
3530 CAMLreturn (Val_int (glx.visual->visualid));
3533 CAMLprim void ml_glxcompleteinit (value unit_v)
3535 CAMLparam1 (unit_v);
3537 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
3538 if (!glx.ctx) {
3539 caml_failwith ("glXCreateContext");
3542 XFree (glx.visual);
3543 glx.visual = NULL;
3545 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
3546 glXDestroyContext (glx.dpy, glx.ctx);
3547 glx.ctx = NULL;
3548 caml_failwith ("glXMakeCurrent");
3550 CAMLreturn0;
3553 CAMLprim void ml_setcursor (value cursor_v)
3555 CAMLparam1 (cursor_v);
3556 size_t cursn = Int_val (cursor_v);
3558 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
3559 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
3560 XFlush (glx.dpy);
3561 CAMLreturn0;
3564 CAMLprim void ml_swapb (value unit_v)
3566 CAMLparam1 (unit_v);
3567 glXSwapBuffers (glx.dpy, glx.wid);
3568 CAMLreturn0;
3571 long keysym2ucs (KeySym);
3572 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3574 CAMLparam1 (keysym_v);
3575 CAMLlocal1 (str_v);
3576 KeySym keysym = Int_val (keysym_v);
3577 Rune rune;
3578 int len;
3579 char buf[5];
3581 rune = (Rune) keysym2ucs (keysym);
3582 len = fz_runetochar (buf, rune);
3583 buf[len] = 0;
3584 str_v = caml_copy_string (buf);
3585 CAMLreturn (str_v);
3587 #else
3588 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3590 CAMLparam1 (keysym_v);
3591 CAMLlocal1 (str_v);
3592 long ucs_v = Long_val (keysym_v);
3593 int len;
3594 char buf[5];
3596 len = fz_runetochar (buf, (int) ucs_v);
3597 buf[len] = 0;
3598 str_v = caml_copy_string (buf);
3599 CAMLreturn (str_v);
3601 #endif
3603 enum { piunknown, pilinux, piosx, pisun, pibsd };
3605 CAMLprim value ml_platform (value unit_v)
3607 CAMLparam1 (unit_v);
3608 CAMLlocal2 (tup_v, arr_v);
3609 int platid = piunknown;
3610 struct utsname buf;
3612 #if defined __linux__
3613 platid = pilinux;
3614 #elif defined __DragonFly__ || defined __FreeBSD__
3615 || defined __OpenBSD__ || defined __NetBSD__
3616 platid = pibsd;
3617 #elif defined __sun__
3618 platid = pisun;
3619 #elif defined __APPLE__
3620 platid = piosx;
3621 #endif
3622 if (uname (&buf)) err (1, "uname");
3624 tup_v = caml_alloc_tuple (2);
3626 char const *sar[] = {
3627 buf.sysname,
3628 buf.release,
3629 buf.version,
3630 buf.machine,
3631 NULL
3633 arr_v = caml_copy_string_array (sar);
3635 Field (tup_v, 0) = Val_int (platid);
3636 Field (tup_v, 1) = arr_v;
3637 CAMLreturn (tup_v);
3640 CAMLprim void ml_cloexec (value fd_v)
3642 CAMLparam1 (fd_v);
3643 int fd = Int_val (fd_v);
3645 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3646 uerror ("fcntl", Nothing);
3648 CAMLreturn0;
3651 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
3653 CAMLparam2 (w_v, h_v);
3654 CAMLlocal1 (ret_v);
3655 struct bo *pbo;
3656 int w = Int_val (w_v);
3657 int h = Int_val (h_v);
3658 int cs = Int_val (cs_v);
3660 if (state.bo_usable) {
3661 pbo = calloc (sizeof (*pbo), 1);
3662 if (!pbo) {
3663 err (1, "calloc pbo");
3666 switch (cs) {
3667 case 0:
3668 case 1:
3669 pbo->size = w*h*4;
3670 break;
3671 case 2:
3672 pbo->size = w*h*2;
3673 break;
3674 default:
3675 errx (1, "%s: invalid colorspace %d", __func__, cs);
3678 state.glGenBuffersARB (1, &pbo->id);
3679 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3680 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, (GLsizei) pbo->size,
3681 NULL, GL_STREAM_DRAW);
3682 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3683 GL_READ_WRITE);
3684 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3685 if (!pbo->ptr) {
3686 printd ("emsg glMapBufferARB failed: %#x", glGetError ());
3687 state.glDeleteBuffersARB (1, &pbo->id);
3688 free (pbo);
3689 ret_v = caml_copy_string ("0");
3691 else {
3692 int res;
3693 char *s;
3695 res = snprintf (NULL, 0, "%" PRIxPTR, (uintptr_t) pbo);
3696 if (res < 0) {
3697 err (1, "snprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3699 s = malloc (res+1);
3700 if (!s) {
3701 err (1, "malloc %d bytes failed", res+1);
3703 res = sprintf (s, "%" PRIxPTR, (uintptr_t) pbo);
3704 if (res < 0) {
3705 err (1, "sprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3707 ret_v = caml_copy_string (s);
3708 free (s);
3711 else {
3712 ret_v = caml_copy_string ("0");
3714 CAMLreturn (ret_v);
3717 CAMLprim void ml_freepbo (value s_v)
3719 CAMLparam1 (s_v);
3720 char *s = String_val (s_v);
3721 struct tile *tile = parse_pointer (__func__, s);
3723 if (tile->pbo) {
3724 state.glDeleteBuffersARB (1, &tile->pbo->id);
3725 tile->pbo->id = -1;
3726 tile->pbo->ptr = NULL;
3727 tile->pbo->size = -1;
3729 CAMLreturn0;
3732 CAMLprim void ml_unmappbo (value s_v)
3734 CAMLparam1 (s_v);
3735 char *s = String_val (s_v);
3736 struct tile *tile = parse_pointer (__func__, s);
3738 if (tile->pbo) {
3739 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3740 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3741 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3743 tile->pbo->ptr = NULL;
3744 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3746 CAMLreturn0;
3749 static void setuppbo (void)
3751 #ifdef __clang__
3752 #pragma GCC diagnostic ignored "-Wunused-macros"
3753 #endif
3754 #ifdef __COCOA__
3755 static CFBundleRef framework = NULL;
3756 if (framework == NULL)
3757 framework = CFBundleGetBundleWithIdentifier (CFSTR ("com.apple.opengl"));
3758 #define GGPA(n) \
3759 (&state.n = CFBundleGetFunctionPointerForName (framework, CFSTR (#n)))
3760 #else
3761 #define GGPA(n) \
3762 (*(void (**) (void)) &state.n = glXGetProcAddress ((GLubyte *) #n))
3763 #endif
3764 state.bo_usable = GGPA (glBindBufferARB)
3765 && GGPA (glUnmapBufferARB)
3766 && GGPA (glMapBufferARB)
3767 && GGPA (glBufferDataARB)
3768 && GGPA (glGenBuffersARB)
3769 && GGPA (glDeleteBuffersARB);
3770 #undef GGPA
3773 CAMLprim value ml_bo_usable (value unit_v)
3775 CAMLparam1 (unit_v);
3776 CAMLreturn (Val_bool (state.bo_usable));
3779 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
3781 CAMLparam3 (ptr_v, x_v, y_v);
3782 CAMLlocal2 (ret_v, tup_v);
3783 struct page *page;
3784 char *s = String_val (ptr_v);
3785 int x = Int_val (x_v), y = Int_val (y_v);
3786 struct pagedim *pdim;
3787 fz_point p;
3788 fz_matrix ctm;
3790 page = parse_pointer (__func__, s);
3791 pdim = &state.pagedims[page->pdimno];
3793 ret_v = Val_int (0);
3794 if (trylock (__func__)) {
3795 goto done;
3798 if (pdf_specifics (state.ctx, state.doc)) {
3799 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
3800 ctm = state.pagedims[page->pdimno].tctm;
3802 else {
3803 ctm = fz_identity;
3805 p.x = x + pdim->bounds.x0;
3806 p.y = y + pdim->bounds.y0;
3808 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
3809 fz_invert_matrix (&ctm, &ctm);
3810 fz_transform_point (&p, &ctm);
3812 tup_v = caml_alloc_tuple (2);
3813 ret_v = caml_alloc_small (1, 1);
3814 Field (tup_v, 0) = Val_int (p.x);
3815 Field (tup_v, 1) = Val_int (p.y);
3816 Field (ret_v, 0) = tup_v;
3818 unlock (__func__);
3819 done:
3820 CAMLreturn (ret_v);
3823 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
3824 value x_v, value y_v)
3826 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
3827 CAMLlocal1 (ret_v);
3828 struct page *page;
3829 char *s = String_val (ptr_v);
3830 int pageno = Int_val (pageno_v);
3831 int pdimno = Int_val (pdimno_v);
3832 float x = (float) Double_val (x_v), y = (float) Double_val (y_v);
3833 struct pagedim *pdim;
3834 fz_point p;
3835 fz_matrix ctm;
3837 ret_v = Val_int (0);
3838 lock (__func__);
3840 if (!*s) {
3841 page = loadpage (pageno, pdimno);
3843 else {
3844 page = parse_pointer (__func__, s);
3846 pdim = &state.pagedims[pdimno];
3848 if (pdf_specifics (state.ctx, state.doc)) {
3849 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
3850 ctm = state.pagedims[page->pdimno].tctm;
3852 else {
3853 ctm = fz_identity;
3855 p.x = x + pdim->bounds.x0;
3856 p.y = y + pdim->bounds.y0;
3858 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
3859 fz_transform_point (&p, &ctm);
3861 ret_v = caml_alloc_tuple (2);
3862 Field (ret_v, 0) = caml_copy_double ((double) p.x);
3863 Field (ret_v, 1) = caml_copy_double ((double) p.y);
3865 if (!*s) {
3866 freepage (page);
3868 unlock (__func__);
3869 CAMLreturn (ret_v);
3872 CAMLprim void ml_addannot (value ptr_v, value x_v, value y_v,
3873 value contents_v)
3875 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
3876 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3878 if (pdf) {
3879 pdf_annot *annot;
3880 struct page *page;
3881 fz_point p;
3882 char *s = String_val (ptr_v);
3884 page = parse_pointer (__func__, s);
3885 annot = pdf_create_annot (state.ctx,
3886 pdf_page_from_fz_page (state.ctx,
3887 page->fzpage),
3888 PDF_ANNOT_TEXT);
3889 p.x = Int_val (x_v);
3890 p.y = Int_val (y_v);
3891 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
3892 pdf_set_text_annot_position (state.ctx, annot, p);
3893 state.dirty = 1;
3895 CAMLreturn0;
3898 CAMLprim void ml_delannot (value ptr_v, value n_v)
3900 CAMLparam2 (ptr_v, n_v);
3901 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3903 if (pdf) {
3904 struct page *page;
3905 char *s = String_val (ptr_v);
3906 struct slink *slink;
3908 page = parse_pointer (__func__, s);
3909 slink = &page->slinks[Int_val (n_v)];
3910 pdf_delete_annot (state.ctx,
3911 pdf_page_from_fz_page (state.ctx, page->fzpage),
3912 (pdf_annot *) slink->u.annot);
3913 state.dirty = 1;
3915 CAMLreturn0;
3918 CAMLprim void ml_modannot (value ptr_v, value n_v, value str_v)
3920 CAMLparam3 (ptr_v, n_v, str_v);
3921 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3923 if (pdf) {
3924 struct page *page;
3925 char *s = String_val (ptr_v);
3926 struct slink *slink;
3928 page = parse_pointer (__func__, s);
3929 slink = &page->slinks[Int_val (n_v)];
3930 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
3931 String_val (str_v));
3932 state.dirty = 1;
3934 CAMLreturn0;
3937 CAMLprim value ml_hasunsavedchanges (value unit_v)
3939 CAMLparam1 (unit_v);
3940 CAMLreturn (Val_bool (state.dirty));
3943 CAMLprim void ml_savedoc (value path_v)
3945 CAMLparam1 (path_v);
3946 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3948 if (pdf) {
3949 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
3951 CAMLreturn0;
3954 static void makestippletex (void)
3956 const char pixels[] = "\xff\xff\0\0";
3957 glGenTextures (1, &state.stid);
3958 glBindTexture (GL_TEXTURE_1D, state.stid);
3959 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
3960 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
3961 glTexImage1D (
3962 GL_TEXTURE_1D,
3964 GL_ALPHA,
3967 GL_ALPHA,
3968 GL_UNSIGNED_BYTE,
3969 pixels
3973 CAMLprim value ml_fz_version (void)
3975 return caml_copy_string (FZ_VERSION);
3978 CAMLprim value ml_llpp_version (void)
3980 extern char llpp_version[];
3981 return caml_copy_string (llpp_version);
3984 CAMLprim void ml_init (value csock_v, value params_v)
3986 CAMLparam2 (csock_v, params_v);
3987 CAMLlocal2 (trim_v, fuzz_v);
3988 int ret;
3989 int texcount;
3990 char *fontpath;
3991 int colorspace;
3992 int mustoresize;
3993 int haspboext;
3995 state.csock = Int_val (csock_v);
3996 state.rotate = Int_val (Field (params_v, 0));
3997 state.fitmodel = Int_val (Field (params_v, 1));
3998 trim_v = Field (params_v, 2);
3999 texcount = Int_val (Field (params_v, 3));
4000 state.sliceheight = Int_val (Field (params_v, 4));
4001 mustoresize = Int_val (Field (params_v, 5));
4002 colorspace = Int_val (Field (params_v, 6));
4003 fontpath = String_val (Field (params_v, 7));
4005 #ifdef __COCOA__
4006 state.utf8cs = 1;
4007 #else
4008 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html */
4009 if (setlocale (LC_CTYPE, "")) {
4010 const char *cset = nl_langinfo (CODESET);
4011 state.utf8cs = !strcmp (cset, "UTF-8");
4013 else {
4014 printd ("emsg setlocale: %d:%s", errno, strerror (errno));
4016 #endif
4018 if (caml_string_length (Field (params_v, 8)) > 0) {
4019 state.trimcachepath = ystrdup (String_val (Field (params_v, 8)));
4021 if (!state.trimcachepath) {
4022 printd ("emsg failed to strdup trimcachepath: %d:%s",
4023 errno, strerror (errno));
4027 haspboext = Bool_val (Field (params_v, 9));
4029 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4030 fz_register_document_handlers (state.ctx);
4032 state.trimmargins = Bool_val (Field (trim_v, 0));
4033 fuzz_v = Field (trim_v, 1);
4034 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4035 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4036 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4037 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4039 set_tex_params (colorspace);
4041 if (*fontpath) {
4042 state.face = load_font (fontpath);
4044 else {
4045 int len;
4046 const unsigned char *data;
4048 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
4049 state.face = load_builtin_font (data, len);
4051 if (!state.face) _exit (1);
4053 realloctexts (texcount);
4055 if (haspboext) {
4056 setuppbo ();
4059 makestippletex ();
4061 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4062 if (ret) {
4063 errx (1, "pthread_create: %s", strerror (ret));
4066 CAMLreturn0;
4069 #if FIXME || !FIXME
4070 static void UNUSED_ATTR NO_OPTIMIZE_ATTR refmacs (void) {}
4071 #endif