Cosmetics
[llpp.git] / link.c
blob4a94a831b0fef07863b37311c802d37702ab5029
1 /* lots of code c&p-ed directly from mupdf */
2 #ifdef __clang__
3 #pragma GCC diagnostic error "-Weverything"
4 #pragma GCC diagnostic ignored "-Wpadded"
5 #pragma GCC diagnostic ignored "-Wsign-conversion"
6 #pragma GCC diagnostic ignored "-Wdocumentation-unknown-command"
7 #pragma GCC diagnostic ignored "-Wdocumentation"
8 #pragma GCC diagnostic ignored "-Wmissing-prototypes"
9 #endif
11 #define CAML_NAME_SPACE
12 #define FIXME 0
14 extern char **environ;
16 #include <errno.h>
17 #include <stdio.h>
18 #include <ctype.h>
19 #include <string.h>
20 #include <stdlib.h>
21 #include <signal.h>
23 #include <math.h>
24 #include <wchar.h>
25 #include <locale.h>
26 #include <langinfo.h>
28 #include <unistd.h>
29 #include <pthread.h>
30 #include <sys/uio.h>
31 #include <sys/time.h>
32 #include <sys/stat.h>
33 #include <fcntl.h>
34 #include <sys/types.h>
35 #include <sys/ioctl.h>
36 #include <sys/utsname.h>
38 #include <spawn.h>
40 #include <regex.h>
41 #include <stdarg.h>
42 #include <limits.h>
43 #include <inttypes.h>
45 #ifdef __COCOA__
46 #include <CoreFoundation/CoreFoundation.h>
47 #endif
49 #ifdef __APPLE__
50 #include <OpenGL/gl.h>
51 #else
52 #include <GL/gl.h>
53 #endif
55 #pragma GCC diagnostic push
56 #ifdef __clang__
57 #pragma GCC diagnostic ignored "-Wreserved-id-macro"
58 #endif
59 #pragma GCC diagnostic ignored "-Wpedantic"
60 #include <caml/fail.h>
61 #include <caml/alloc.h>
62 #include <caml/memory.h>
63 #include <caml/unixsupport.h>
65 #pragma GCC diagnostic push
66 #pragma GCC diagnostic ignored "-Wfloat-equal"
67 #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 #ifdef __ALTIVEC__
533 #include <stdint.h>
534 #include <altivec.h>
536 static int cacheline32bytes;
538 static void __attribute__ ((constructor)) clcheck (void)
540 char **envp = environ;
541 unsigned long *auxv;
543 while (*envp++);
545 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
546 if (*auxv == 19) {
547 cacheline32bytes = auxv[1] == 32;
548 return;
553 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
555 size_t size = pixmap->w * pixmap->h * pixmap->n;
556 if (cacheline32bytes && size > 32) {
557 intptr_t a1, a2, diff;
558 size_t sizea, i;
559 vector unsigned char v = vec_splat_u8 (-1);
560 vector unsigned char *p;
562 a1 = a2 = (intptr_t) pixmap->samples;
563 a2 = (a1 + 31) & ~31;
564 diff = a2 - a1;
565 sizea = size - diff;
566 p = (void *) a2;
568 while (a1 != a2) *(char *) a1++ = 0xff;
569 for (i = 0; i < (sizea & ~31); i += 32) {
570 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
571 vec_st (v, i, p);
572 vec_st (v, i + 16, p);
574 while (i < sizea) *((char *) a1 + i++) = 0xff;
576 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
578 #else
579 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
580 #endif
582 static void trimctm (pdf_page *page, int pindex)
584 fz_matrix ctm;
585 struct pagedim *pdim = &state.pagedims[pindex];
587 if (!page) return;
588 if (!pdim->tctmready) {
589 fz_rect realbox, mediabox;
590 fz_matrix rm, sm, tm, im, ctm1, page_ctm;
592 fz_rotate (&rm, -pdim->rotate);
593 fz_scale (&sm, 1, -1);
594 fz_concat (&ctm, &rm, &sm);
595 realbox = pdim->mediabox;
596 fz_transform_rect (&realbox, &ctm);
597 fz_translate (&tm, -realbox.x0, -realbox.y0);
598 fz_concat (&ctm1, &ctm, &tm);
599 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
600 fz_invert_matrix (&im, &page_ctm);
601 fz_concat (&ctm, &im, &ctm1);
602 pdim->tctm = ctm;
603 pdim->tctmready = 1;
607 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
609 fz_matrix ctm, tm;
610 ptrdiff_t pdimno = pdim - state.pagedims;
612 ARSERT (pdim - state.pagedims < INT_MAX);
613 if (pdf_specifics (state.ctx, state.doc)) {
614 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), (int) pdimno);
615 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
617 else {
618 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
619 fz_concat (&ctm, &tm, &pdim->ctm);
621 return ctm;
624 static fz_matrix pagectm (struct page *page)
626 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
629 static void *loadpage (int pageno, int pindex)
631 fz_device *dev;
632 struct page *page;
634 page = calloc (sizeof (struct page), 1);
635 if (!page) {
636 err (1, "calloc page %d", pageno);
639 page->dlist = fz_new_display_list (state.ctx, NULL);
640 dev = fz_new_list_device (state.ctx, page->dlist);
641 fz_try (state.ctx) {
642 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
643 fz_run_page (state.ctx, page->fzpage, dev,
644 &fz_identity, NULL);
646 fz_catch (state.ctx) {
647 page->fzpage = NULL;
649 fz_close_device (state.ctx, dev);
650 fz_drop_device (state.ctx, dev);
652 page->pdimno = pindex;
653 page->pageno = pageno;
654 page->sgen = state.gen;
655 page->agen = state.gen;
656 page->tgen = state.gen;
657 return page;
660 static struct tile *alloctile (int h)
662 int slicecount;
663 size_t tilesize;
664 struct tile *tile;
666 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
667 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
668 tile = calloc (tilesize, 1);
669 if (!tile) {
670 err (1, "cannot allocate tile (%zu bytes)", tilesize);
672 for (int i = 0; i < slicecount; ++i) {
673 int sh = fz_mini (h, state.sliceheight);
674 tile->slices[i].h = sh;
675 tile->slices[i].texindex = -1;
676 h -= sh;
678 tile->slicecount = slicecount;
679 tile->sliceheight = state.sliceheight;
680 return tile;
683 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
684 struct bo *pbo)
686 fz_rect rect;
687 fz_irect bbox;
688 fz_matrix ctm;
689 fz_device *dev;
690 struct tile *tile;
691 struct pagedim *pdim;
693 tile = alloctile (h);
694 pdim = &state.pagedims[page->pdimno];
696 bbox = pdim->bounds;
697 bbox.x0 += x;
698 bbox.y0 += y;
699 bbox.x1 = bbox.x0 + w;
700 bbox.y1 = bbox.y0 + h;
702 if (state.pig) {
703 if (state.pig->w == w
704 && state.pig->h == h
705 && state.pig->colorspace == state.colorspace) {
706 tile->pixmap = state.pig;
707 tile->pixmap->x = bbox.x0;
708 tile->pixmap->y = bbox.y0;
710 else {
711 fz_drop_pixmap (state.ctx, state.pig);
713 state.pig = NULL;
715 if (!tile->pixmap) {
716 if (pbo) {
717 tile->pixmap =
718 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
719 &bbox, NULL, 1, pbo->ptr);
720 tile->pbo = pbo;
722 else {
723 tile->pixmap =
724 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox,
725 NULL, 1);
729 tile->w = w;
730 tile->h = h;
731 clearpixmap (tile->pixmap);
733 dev = fz_new_draw_device (state.ctx, NULL, tile->pixmap);
734 ctm = pagectm (page);
735 fz_rect_from_irect (&rect, &bbox);
736 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
737 fz_close_device (state.ctx, dev);
738 fz_drop_device (state.ctx, dev);
740 return tile;
743 #ifdef CACHE_PAGEREFS
744 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
745 thanks to Robin Watts */
746 static void
747 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
749 fz_context *ctx = state.ctx; /* doc->ctx; */
750 pdf_obj *kids;
751 int len;
753 if (state.pdflut.idx == state.pagecount) return;
755 kids = pdf_dict_gets (ctx, node, "Kids");
756 len = pdf_array_len (ctx, kids);
758 if (len == 0)
759 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
761 if (pdf_mark_obj (ctx, node))
762 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
763 for (int i = 0; i < len; i++) {
764 pdf_obj *kid = pdf_array_get (ctx, kids, i);
765 const char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
766 if (*type
767 ? !strcmp (type, "Pages")
768 : pdf_dict_gets (ctx, kid, "Kids")
769 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
770 pdf_collect_pages (doc, kid);
772 else {
773 if (*type
774 ? strcmp (type, "Page") != 0
775 : !pdf_dict_gets (ctx, kid, "MediaBox"))
776 fz_warn (ctx, "non-page object in page tree (%s)", type);
777 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
780 pdf_unmark_obj (ctx, node);
783 static void
784 pdf_load_page_objs (pdf_document *doc)
786 pdf_obj *root = pdf_dict_gets (state.ctx,
787 pdf_trailer (state.ctx, doc), "Root");
788 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
790 if (!node)
791 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
793 state.pdflut.idx = 0;
794 pdf_collect_pages (doc, node);
796 #endif
798 static void initpdims (void)
800 double start, end;
801 FILE *trimf = NULL;
802 fz_rect rootmediabox = fz_empty_rect;
803 int pageno, trim, show;
804 int trimw = 0, cxcount;
805 fz_context *ctx = state.ctx;
806 pdf_document *pdf = pdf_specifics (ctx, state.doc);
808 fz_var (trimw);
809 fz_var (trimf);
810 fz_var (cxcount);
811 start = now ();
813 if (state.trimmargins && state.trimcachepath) {
814 trimf = fopen (state.trimcachepath, "rb");
815 if (!trimf) {
816 trimf = fopen (state.trimcachepath, "wb");
817 trimw = 1;
821 if (state.trimmargins || pdf)
822 cxcount = state.pagecount;
823 else
824 cxcount = fz_mini (state.pagecount, 1);
826 if (pdf) {
827 pdf_obj *obj;
828 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
829 "Root/Pages/MediaBox");
830 pdf_to_rect (ctx, obj, &rootmediabox);
833 #ifdef CACHE_PAGEREFS
834 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
835 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
836 if (!state.pdflut.objs) {
837 err (1, "malloc pageobjs %zu %d %zu failed",
838 sizeof (*state.pdflut.objs), cxcount,
839 sizeof (*state.pdflut.objs) * cxcount);
841 state.pdflut.count = cxcount;
842 pdf_load_page_objs (pdf);
843 state.pdflut.pdf = pdf;
845 #endif
847 for (pageno = 0; pageno < cxcount; ++pageno) {
848 int rotate = 0;
849 struct pagedim *p;
850 fz_rect mediabox = fz_empty_rect;
852 fz_var (rotate);
853 if (pdf) {
854 pdf_obj *pageref, *pageobj;
856 #ifdef CACHE_PAGEREFS
857 pageref = state.pdflut.objs[pageno];
858 #else
859 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
860 #endif
861 pageobj = pdf_resolve_indirect (ctx, pageref);
862 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
864 if (state.trimmargins) {
865 pdf_obj *obj;
866 pdf_page *page;
868 fz_try (ctx) {
869 page = pdf_load_page (ctx, pdf, pageno);
870 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
871 trim = state.trimanew || !obj;
872 if (trim) {
873 fz_rect rect;
874 fz_device *dev;
875 fz_matrix ctm, page_ctm;
877 dev = fz_new_bbox_device (ctx, &rect);
878 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
879 fz_invert_matrix (&ctm, &page_ctm);
880 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
881 fz_close_device (ctx, dev);
882 fz_drop_device (ctx, dev);
884 rect.x0 += state.trimfuzz.x0;
885 rect.x1 += state.trimfuzz.x1;
886 rect.y0 += state.trimfuzz.y0;
887 rect.y1 += state.trimfuzz.y1;
888 fz_transform_rect (&rect, &ctm);
889 fz_intersect_rect (&rect, &mediabox);
891 if (!fz_is_empty_rect (&rect)) {
892 mediabox = rect;
895 obj = pdf_new_array (ctx, pdf, 4);
896 pdf_array_push (ctx, obj,
897 pdf_new_real (ctx, mediabox.x0));
898 pdf_array_push (ctx, obj,
899 pdf_new_real (ctx, mediabox.y0));
900 pdf_array_push (ctx, obj,
901 pdf_new_real (ctx, mediabox.x1));
902 pdf_array_push (ctx, obj,
903 pdf_new_real (ctx, mediabox.y1));
904 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
906 else {
907 mediabox.x0 = pdf_to_real (ctx,
908 pdf_array_get (ctx, obj, 0));
909 mediabox.y0 = pdf_to_real (ctx,
910 pdf_array_get (ctx, obj, 1));
911 mediabox.x1 = pdf_to_real (ctx,
912 pdf_array_get (ctx, obj, 2));
913 mediabox.y1 = pdf_to_real (ctx,
914 pdf_array_get (ctx, obj, 3));
917 fz_drop_page (ctx, &page->super);
918 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
919 if (show) {
920 printd ("progress %f Trimming %d",
921 (double) (pageno + 1) / state.pagecount,
922 pageno + 1);
925 fz_catch (ctx) {
926 printd ("emsg failed to load page %d", pageno);
929 else {
930 int empty = 0;
931 fz_rect cropbox;
933 pdf_to_rect (ctx,
934 pdf_dict_gets (ctx, pageobj, "MediaBox"),
935 &mediabox);
936 if (fz_is_empty_rect (&mediabox)) {
937 mediabox.x0 = 0;
938 mediabox.y0 = 0;
939 mediabox.x1 = 612;
940 mediabox.y1 = 792;
941 empty = 1;
944 pdf_to_rect (ctx,
945 pdf_dict_gets (ctx, pageobj, "CropBox"),
946 &cropbox);
947 if (!fz_is_empty_rect (&cropbox)) {
948 if (empty) {
949 mediabox = cropbox;
951 else {
952 fz_intersect_rect (&mediabox, &cropbox);
955 else {
956 if (empty) {
957 if (fz_is_empty_rect (&rootmediabox)) {
958 printd ("emsg cannot find page size for page %d",
959 pageno);
961 else {
962 mediabox = rootmediabox;
968 else {
969 if (state.trimmargins && trimw) {
970 fz_page *page;
972 fz_try (ctx) {
973 page = fz_load_page (ctx, state.doc, pageno);
974 fz_bound_page (ctx, page, &mediabox);
975 if (state.trimmargins) {
976 fz_rect rect;
977 fz_device *dev;
979 dev = fz_new_bbox_device (ctx, &rect);
980 fz_run_page (ctx, page, dev, &fz_identity, NULL);
981 fz_close_device (ctx, dev);
982 fz_drop_device (ctx, dev);
984 rect.x0 += state.trimfuzz.x0;
985 rect.x1 += state.trimfuzz.x1;
986 rect.y0 += state.trimfuzz.y0;
987 rect.y1 += state.trimfuzz.y1;
988 fz_intersect_rect (&rect, &mediabox);
990 if (!fz_is_empty_rect (&rect)) {
991 mediabox = rect;
994 fz_drop_page (ctx, page);
996 fz_catch (ctx) {
998 if (trimf) {
999 size_t n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1000 if (n - 1) {
1001 err (1, "fwrite trim mediabox");
1005 else {
1006 if (trimf) {
1007 size_t n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1008 if (n - 1) {
1009 err (1, "fread trim mediabox %d", pageno);
1012 else {
1013 fz_page *page;
1014 fz_try (ctx) {
1015 page = fz_load_page (ctx, state.doc, pageno);
1016 fz_bound_page (ctx, page, &mediabox);
1017 fz_drop_page (ctx, page);
1019 show = !state.trimmargins && pageno % 20 == 0;
1020 if (show) {
1021 printd ("progress %f Gathering dimensions %d",
1022 (double) (pageno) / state.pagecount,
1023 pageno);
1026 fz_catch (ctx) {
1027 printd ("emsg failed to load page %d", pageno);
1033 if (state.pagedimcount == 0
1034 || ((void) (p = &state.pagedims[state.pagedimcount-1])
1035 , p->rotate != rotate)
1036 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1037 size_t size;
1039 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1040 state.pagedims = realloc (state.pagedims, size);
1041 if (!state.pagedims) {
1042 err (1, "realloc pagedims to %zu (%d elems)",
1043 size, state.pagedimcount + 1);
1046 p = &state.pagedims[state.pagedimcount++];
1047 p->rotate = rotate;
1048 p->mediabox = mediabox;
1049 p->pageno = pageno;
1052 end = now ();
1053 printd ("progress 1 %s %d pages in %f seconds",
1054 state.trimmargins ? "Trimmed" : "Processed",
1055 state.pagecount, end - start);
1056 state.trimanew = 0;
1057 if (trimf) {
1058 if (fclose (trimf)) {
1059 err (1, "fclose");
1064 static void layout (void)
1066 int pindex;
1067 fz_rect box;
1068 fz_matrix ctm, rm;
1069 struct pagedim *p = NULL;
1070 float zw, w, maxw = 0.0, zoom = 1.0;
1072 if (state.pagedimcount == 0) return;
1074 switch (state.fitmodel) {
1075 case FitProportional:
1076 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1077 float x0, x1;
1079 p = &state.pagedims[pindex];
1080 fz_rotate (&rm, p->rotate + state.rotate);
1081 box = p->mediabox;
1082 fz_transform_rect (&box, &rm);
1084 x0 = fz_min (box.x0, box.x1);
1085 x1 = fz_max (box.x0, box.x1);
1087 w = x1 - x0;
1088 maxw = fz_max (w, maxw);
1089 zoom = state.w / maxw;
1091 break;
1093 case FitPage:
1094 maxw = state.w;
1095 break;
1097 case FitWidth:
1098 break;
1100 default:
1101 ARSERT (0 && state.fitmodel);
1104 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1105 fz_rect rect;
1106 fz_matrix tm, sm;
1108 p = &state.pagedims[pindex];
1109 fz_rotate (&ctm, state.rotate);
1110 fz_rotate (&rm, p->rotate + state.rotate);
1111 box = p->mediabox;
1112 fz_transform_rect (&box, &rm);
1113 w = box.x1 - box.x0;
1114 switch (state.fitmodel) {
1115 case FitProportional:
1116 p->left = (int) (((maxw - w) * zoom) / 2.f);
1117 break;
1118 case FitPage:
1120 float zh, h;
1121 zw = maxw / w;
1122 h = box.y1 - box.y0;
1123 zh = state.h / h;
1124 zoom = fz_min (zw, zh);
1125 p->left = (int) ((maxw - (w * zoom)) / 2.f);
1127 break;
1128 case FitWidth:
1129 p->left = 0;
1130 zoom = state.w / w;
1131 break;
1134 fz_scale (&p->zoomctm, zoom, zoom);
1135 fz_concat (&ctm, &p->zoomctm, &ctm);
1137 fz_rotate (&rm, p->rotate);
1138 p->pagebox = p->mediabox;
1139 fz_transform_rect (&p->pagebox, &rm);
1140 p->pagebox.x1 -= p->pagebox.x0;
1141 p->pagebox.y1 -= p->pagebox.y0;
1142 p->pagebox.x0 = 0;
1143 p->pagebox.y0 = 0;
1144 rect = p->pagebox;
1145 fz_transform_rect (&rect, &ctm);
1146 fz_round_rect (&p->bounds, &rect);
1147 p->ctm = ctm;
1149 fz_translate (&tm, 0, -p->mediabox.y1);
1150 fz_scale (&sm, zoom, -zoom);
1151 fz_concat (&ctm, &tm, &sm);
1153 p->tctmready = 0;
1156 do {
1157 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1158 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1159 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1160 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1161 int boundw = x1 - x0;
1162 int boundh = y1 - y0;
1164 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1165 } while (p-- != state.pagedims);
1168 struct pagedim *pdimofpageno (int pageno)
1170 struct pagedim *pdim = state.pagedims;
1172 for (int i = 0; i < state.pagedimcount; ++i) {
1173 if (state.pagedims[i].pageno > pageno)
1174 break;
1175 pdim = &state.pagedims[i];
1177 return pdim;
1180 static void recurse_outline (fz_outline *outline, int level)
1182 while (outline) {
1183 if (outline->page >= 0) {
1184 fz_point p = {.x = outline->x, .y = outline->y};
1185 struct pagedim *pdim = pdimofpageno (outline->page);
1186 int h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1187 fz_transform_point (&p, &pdim->ctm);
1188 printd ("o %d %d %d %d %s",
1189 level, outline->page, (int) p.y, h, outline->title);
1191 else {
1192 printd ("on %d %s", level, outline->title);
1194 if (outline->down) {
1195 recurse_outline (outline->down, level + 1);
1197 outline = outline->next;
1201 static void process_outline (void)
1203 fz_outline *outline;
1205 if (!state.needoutline || !state.pagedimcount) return;
1207 state.needoutline = 0;
1208 outline = fz_load_outline (state.ctx, state.doc);
1209 if (outline) {
1210 recurse_outline (outline, 0);
1211 fz_drop_outline (state.ctx, outline);
1215 static char *strofline (fz_stext_line *line)
1217 char *p;
1218 char utf8[10];
1219 fz_stext_char *ch;
1220 size_t size = 0, cap = 80;
1222 p = malloc (cap + 1);
1223 if (!p) return NULL;
1225 for (ch = line->first_char; ch; ch = ch->next) {
1226 int n = fz_runetochar (utf8, ch->c);
1227 if (size + n > cap) {
1228 cap *= 2;
1229 p = realloc (p, cap + 1);
1230 if (!p) return NULL;
1233 memcpy (p + size, utf8, n);
1234 size += n;
1236 p[size] = 0;
1237 return p;
1240 static int matchline (regex_t *re, fz_stext_line *line,
1241 int stop, int pageno, double start)
1243 int ret;
1244 char *p;
1245 regmatch_t rm;
1247 p = strofline (line);
1248 if (!p) return -1;
1250 ret = regexec (re, p, 1, &rm, 0);
1251 if (ret) {
1252 free (p);
1253 if (ret != REG_NOMATCH) {
1254 size_t size;
1255 char errbuf[80];
1256 size = regerror (ret, re, errbuf, sizeof (errbuf));
1257 printd ("msg regexec error `%.*s'",
1258 (int) size, errbuf);
1259 return -1;
1261 return 0;
1263 else {
1264 fz_point p1, p2, p3, p4;
1265 fz_rect s = {0,0,0,0}, e;
1266 fz_stext_char *ch;
1267 int o = 0;
1269 for (ch = line->first_char; ch; ch = ch->next) {
1270 o += fz_runelen (ch->c);
1271 if (o > rm.rm_so) {
1272 s = ch->bbox;
1273 break;
1276 for (;ch; ch = ch->next) {
1277 o += fz_runelen (ch->c);
1278 if (o > rm.rm_eo) break;
1280 e = ch->bbox;
1282 p1.x = s.x0;
1283 p1.y = s.y0;
1284 p2.x = e.x1;
1285 p2.y = s.y0;
1286 p3.x = e.x1;
1287 p3.y = e.y1;
1288 p4.x = s.x0;
1289 p4.y = e.y1;
1291 #pragma GCC diagnostic ignored "-Wdouble-promotion"
1292 if (!stop) {
1293 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1294 pageno, 1,
1295 p1.x, p1.y,
1296 p2.x, p2.y,
1297 p3.x, p3.y,
1298 p4.x, p4.y);
1300 printd ("progress 1 found at %d `%.*s' in %f sec",
1301 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1302 now () - start);
1304 else {
1305 printd ("match %d %d %f %f %f %f %f %f %f %f",
1306 pageno, 2,
1307 p1.x, p1.y,
1308 p2.x, p2.y,
1309 p3.x, p3.y,
1310 p4.x, p4.y);
1312 #pragma GCC diagnostic error "-Wdouble-promotion"
1313 free (p);
1314 return 1;
1318 /* wishful thinking function */
1319 static void search (regex_t *re, int pageno, int y, int forward)
1321 fz_device *tdev;
1322 fz_stext_page *text;
1323 struct pagedim *pdim;
1324 int stop = 0, niters = 0;
1325 double start, end;
1326 fz_page *page;
1327 fz_stext_block *block;
1329 start = now ();
1330 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1331 if (niters++ == 5) {
1332 niters = 0;
1333 if (hasdata ()) {
1334 printd ("progress 1 attention requested aborting search at %d",
1335 pageno);
1336 stop = 1;
1338 else {
1339 printd ("progress %f searching in page %d",
1340 (double) (pageno + 1) / state.pagecount,
1341 pageno);
1344 pdim = pdimofpageno (pageno);
1345 text = fz_new_stext_page (state.ctx, &pdim->mediabox);
1346 tdev = fz_new_stext_device (state.ctx, text, 0);
1348 page = fz_load_page (state.ctx, state.doc, pageno);
1350 fz_matrix ctm = pagectm1 (page, pdim);
1351 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1354 fz_close_device (state.ctx, tdev);
1355 fz_drop_device (state.ctx, tdev);
1357 if (forward) {
1358 for (block = text->first_block; block; block = block->next) {
1359 fz_stext_line *line;
1361 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1362 for (line = block->u.t.first_line; line; line = line->next) {
1363 if (line->bbox.y0 < y + 1) continue;
1365 switch (matchline (re, line, stop, pageno, start)) {
1366 case 0: break;
1367 case 1: stop = 1; break;
1368 case -1: stop = 1; goto endloop;
1373 else {
1374 for (block = text->last_block; block; block = block->prev) {
1375 fz_stext_line *line;
1377 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1378 for (line = block->u.t.last_line; line; line = line->prev) {
1379 if (line->bbox.y0 < y + 1) continue;
1381 switch (matchline (re, line, stop, pageno, start)) {
1382 case 0: break;
1383 case 1: stop = 1; break;
1384 case -1: stop = 1; goto endloop;
1390 if (forward) {
1391 pageno += 1;
1392 y = 0;
1394 else {
1395 pageno -= 1;
1396 y = INT_MAX;
1398 endloop:
1399 fz_drop_stext_page (state.ctx, text);
1400 fz_drop_page (state.ctx, page);
1402 end = now ();
1403 if (!stop) {
1404 printd ("progress 1 no matches %f sec", end - start);
1406 printd ("clearrects");
1409 static void set_tex_params (int colorspace)
1411 switch (colorspace) {
1412 case 0:
1413 state.texiform = GL_RGBA8;
1414 state.texform = GL_RGBA;
1415 state.texty = GL_UNSIGNED_BYTE;
1416 state.colorspace = fz_device_rgb (state.ctx);
1417 break;
1418 case 1:
1419 state.texiform = GL_RGBA8;
1420 state.texform = GL_BGRA;
1421 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1422 state.texty = GL_UNSIGNED_INT_8_8_8_8_REV;
1423 #else
1424 state.texty = GL_UNSIGNED_INT_8_8_8_8;
1425 #endif
1426 state.colorspace = fz_device_bgr (state.ctx);
1427 break;
1428 case 2:
1429 state.texiform = GL_LUMINANCE_ALPHA;
1430 state.texform = GL_LUMINANCE_ALPHA;
1431 state.texty = GL_UNSIGNED_BYTE;
1432 state.colorspace = fz_device_gray (state.ctx);
1433 break;
1434 default:
1435 errx (1, "invalid colorspce %d", colorspace);
1439 static void realloctexts (int texcount)
1441 size_t size;
1443 if (texcount == state.texcount) return;
1445 if (texcount < state.texcount) {
1446 glDeleteTextures (state.texcount - texcount,
1447 state.texids + texcount);
1450 size = texcount * (sizeof (*state.texids) + sizeof (*state.texowners));
1451 state.texids = realloc (state.texids, size);
1452 if (!state.texids) {
1453 err (1, "realloc texs %zu", size);
1456 state.texowners = (void *) (state.texids + texcount);
1457 if (texcount > state.texcount) {
1458 glGenTextures (texcount - state.texcount,
1459 state.texids + state.texcount);
1460 for (int i = state.texcount; i < texcount; ++i) {
1461 state.texowners[i].w = -1;
1462 state.texowners[i].slice = NULL;
1465 state.texcount = texcount;
1466 state.texindex = 0;
1469 static char *mbtoutf8 (char *s)
1471 char *p, *r;
1472 wchar_t *tmp;
1473 size_t i, ret, len;
1475 if (state.utf8cs) {
1476 return s;
1479 len = mbstowcs (NULL, s, strlen (s));
1480 if (len == 0) {
1481 return s;
1483 else {
1484 if (len == (size_t) -1) {
1485 printd ("emsg mbtoutf8: mbstowcs: %d:%s", errno, strerror (errno));
1486 return s;
1490 tmp = calloc (len, sizeof (wchar_t));
1491 if (!tmp) {
1492 printd ("emsg mbtoutf8: calloc(%zu, %zu): %d:%s",
1493 len, sizeof (wchar_t), errno, strerror (errno));
1494 return s;
1497 ret = mbstowcs (tmp, s, len);
1498 if (ret == (size_t) -1) {
1499 printd ("emsg mbtoutf8: mbswcs %zu characters failed: %d:%s",
1500 len, errno, strerror (errno));
1501 free (tmp);
1502 return s;
1505 len = 0;
1506 for (i = 0; i < ret; ++i) {
1507 len += fz_runelen (tmp[i]);
1510 p = r = malloc (len + 1);
1511 if (!r) {
1512 printd ("emsg mbtoutf8: malloc(%zu)", len);
1513 free (tmp);
1514 return s;
1517 for (i = 0; i < ret; ++i) {
1518 p += fz_runetochar (p, tmp[i]);
1520 *p = 0;
1521 free (tmp);
1522 return r;
1525 CAMLprim value ml_mbtoutf8 (value s_v)
1527 CAMLparam1 (s_v);
1528 CAMLlocal1 (ret_v);
1529 char *s, *r;
1531 s = String_val (s_v);
1532 r = mbtoutf8 (s);
1533 if (r == s) {
1534 ret_v = s_v;
1536 else {
1537 ret_v = caml_copy_string (r);
1538 free (r);
1540 CAMLreturn (ret_v);
1543 static void * mainloop (void UNUSED_ATTR *unused)
1545 char *p = NULL;
1546 int len, ret, oldlen = 0;
1548 fz_var (p);
1549 fz_var (oldlen);
1550 for (;;) {
1551 len = readlen (state.csock);
1552 if (len == 0) {
1553 errx (1, "readlen returned 0");
1556 if (oldlen < len + 1) {
1557 p = realloc (p, len + 1);
1558 if (!p) {
1559 err (1, "realloc %d failed", len + 1);
1561 oldlen = len + 1;
1563 readdata (state.csock, p, len);
1564 p[len] = 0;
1566 if (!strncmp ("open", p, 4)) {
1567 int off, usedoccss, ok = 0, layouth;
1568 char *password;
1569 char *filename;
1570 char *utf8filename;
1571 size_t filenamelen;
1573 fz_var (ok);
1574 ret = sscanf (p + 5, " %d %d %n", &usedoccss, &layouth, &off);
1575 if (ret != 2) {
1576 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1579 filename = p + 5 + off;
1580 filenamelen = strlen (filename);
1581 password = filename + filenamelen + 1;
1583 if (password[strlen (password) + 1]) {
1584 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1587 lock ("open");
1588 fz_set_use_document_css (state.ctx, usedoccss);
1589 fz_try (state.ctx) {
1590 ok = openxref (filename, password, layouth);
1592 fz_catch (state.ctx) {
1593 utf8filename = mbtoutf8 (filename);
1594 printd ("msg Could not open %s", utf8filename);
1595 if (utf8filename != filename) {
1596 free (utf8filename);
1599 if (ok) {
1600 docinfo ();
1601 initpdims ();
1603 unlock ("open");
1605 if (ok) {
1606 utf8filename = mbtoutf8 (filename);
1607 printd ("msg Opened %s (press h/F1 to get help)", utf8filename);
1608 if (utf8filename != filename) {
1609 free (utf8filename);
1611 state.needoutline = 1;
1614 else if (!strncmp ("cs", p, 2)) {
1615 int i, colorspace;
1617 ret = sscanf (p + 2, " %d", &colorspace);
1618 if (ret != 1) {
1619 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1621 lock ("cs");
1622 set_tex_params (colorspace);
1623 for (i = 0; i < state.texcount; ++i) {
1624 state.texowners[i].w = -1;
1625 state.texowners[i].slice = NULL;
1627 unlock ("cs");
1629 else if (!strncmp ("freepage", p, 8)) {
1630 void *ptr;
1632 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1633 if (ret != 1) {
1634 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1636 lock ("freepage");
1637 freepage (ptr);
1638 unlock ("freepage");
1640 else if (!strncmp ("freetile", p, 8)) {
1641 void *ptr;
1643 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1644 if (ret != 1) {
1645 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1647 lock ("freetile");
1648 freetile (ptr);
1649 unlock ("freetile");
1651 else if (!strncmp ("search", p, 6)) {
1652 int icase, pageno, y, len2, forward;
1653 char *pattern;
1654 regex_t re;
1656 ret = sscanf (p + 6, " %d %d %d %d,%n",
1657 &icase, &pageno, &y, &forward, &len2);
1658 if (ret != 4) {
1659 errx (1, "malformed search `%s' ret=%d", p, ret);
1662 pattern = p + 6 + len2;
1663 ret = regcomp (&re, pattern,
1664 REG_EXTENDED | (icase ? REG_ICASE : 0));
1665 if (ret) {
1666 char errbuf[80];
1667 size_t size;
1669 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1670 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1672 else {
1673 search (&re, pageno, y, forward);
1674 regfree (&re);
1677 else if (!strncmp ("geometry", p, 8)) {
1678 int w, h, fitmodel;
1680 printd ("clear");
1681 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1682 if (ret != 3) {
1683 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1686 lock ("geometry");
1687 state.h = h;
1688 if (w != state.w) {
1689 state.w = w;
1690 for (int i = 0; i < state.texcount; ++i) {
1691 state.texowners[i].slice = NULL;
1694 state.fitmodel = fitmodel;
1695 layout ();
1696 process_outline ();
1698 state.gen++;
1699 unlock ("geometry");
1700 printd ("continue %d", state.pagecount);
1702 else if (!strncmp ("reqlayout", p, 9)) {
1703 char *nameddest;
1704 int rotate, off, h;
1705 int fitmodel;
1706 pdf_document *pdf;
1708 printd ("clear");
1709 ret = sscanf (p + 9, " %d %d %d %n",
1710 &rotate, &fitmodel, &h, &off);
1711 if (ret != 3) {
1712 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1714 lock ("reqlayout");
1715 pdf = pdf_specifics (state.ctx, state.doc);
1716 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1717 state.gen += 1;
1719 state.rotate = rotate;
1720 state.fitmodel = fitmodel;
1721 state.h = h;
1722 layout ();
1723 process_outline ();
1725 nameddest = p + 9 + off;
1726 if (pdf && nameddest && *nameddest) {
1727 fz_point xy;
1728 struct pagedim *pdim;
1729 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1730 &xy.x, &xy.y);
1731 pdim = pdimofpageno (pageno);
1732 fz_transform_point (&xy, &pdim->ctm);
1733 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1736 state.gen++;
1737 unlock ("reqlayout");
1738 printd ("continue %d", state.pagecount);
1740 else if (!strncmp ("page", p, 4)) {
1741 double a, b;
1742 struct page *page;
1743 int pageno, pindex;
1745 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1746 if (ret != 2) {
1747 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1750 lock ("page");
1751 a = now ();
1752 page = loadpage (pageno, pindex);
1753 b = now ();
1754 unlock ("page");
1756 printd ("page %" PRIxPTR " %f", (uintptr_t) page, b - a);
1758 else if (!strncmp ("tile", p, 4)) {
1759 int x, y, w, h;
1760 struct page *page;
1761 struct tile *tile;
1762 double a, b;
1763 void *data;
1765 ret = sscanf (p + 4, " %" SCNxPTR " %d %d %d %d %" SCNxPTR,
1766 (uintptr_t *) &page, &x, &y, &w, &h,
1767 (uintptr_t *) &data);
1768 if (ret != 6) {
1769 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1772 lock ("tile");
1773 a = now ();
1774 tile = rendertile (page, x, y, w, h, data);
1775 b = now ();
1776 unlock ("tile");
1778 printd ("tile %d %d %" PRIxPTR " %u %f",
1779 x, y, (uintptr_t) (tile),
1780 tile->w * tile->h * tile->pixmap->n,
1781 b - a);
1783 else if (!strncmp ("trimset", p, 7)) {
1784 fz_irect fuzz;
1785 int trimmargins;
1787 ret = sscanf (p + 7, " %d %d %d %d %d",
1788 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1789 if (ret != 5) {
1790 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1792 lock ("trimset");
1793 state.trimmargins = trimmargins;
1794 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1795 state.trimanew = 1;
1796 state.trimfuzz = fuzz;
1798 unlock ("trimset");
1800 else if (!strncmp ("settrim", p, 7)) {
1801 fz_irect fuzz;
1802 int trimmargins;
1804 ret = sscanf (p + 7, " %d %d %d %d %d",
1805 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1806 if (ret != 5) {
1807 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1809 printd ("clear");
1810 lock ("settrim");
1811 state.trimmargins = trimmargins;
1812 state.needoutline = 1;
1813 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1814 state.trimanew = 1;
1815 state.trimfuzz = fuzz;
1817 state.pagedimcount = 0;
1818 free (state.pagedims);
1819 state.pagedims = NULL;
1820 initpdims ();
1821 layout ();
1822 process_outline ();
1823 unlock ("settrim");
1824 printd ("continue %d", state.pagecount);
1826 else if (!strncmp ("sliceh", p, 6)) {
1827 int h;
1829 ret = sscanf (p + 6, " %d", &h);
1830 if (ret != 1) {
1831 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1833 if (h != state.sliceheight) {
1834 state.sliceheight = h;
1835 for (int i = 0; i < state.texcount; ++i) {
1836 state.texowners[i].w = -1;
1837 state.texowners[i].h = -1;
1838 state.texowners[i].slice = NULL;
1842 else if (!strncmp ("interrupt", p, 9)) {
1843 printd ("vmsg interrupted");
1845 else {
1846 errx (1, "unknown command %.*s", len, p);
1849 return 0;
1852 CAMLprim value ml_isexternallink (value uri_v)
1854 CAMLparam1 (uri_v);
1855 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1856 CAMLreturn (Val_bool (ext));
1859 CAMLprim value ml_uritolocation (value uri_v)
1861 CAMLparam1 (uri_v);
1862 CAMLlocal1 (ret_v);
1863 int pageno;
1864 fz_point xy;
1865 struct pagedim *pdim;
1867 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1868 &xy.x, &xy.y);
1869 pdim = pdimofpageno (pageno);
1870 fz_transform_point (&xy, &pdim->ctm);
1871 ret_v = caml_alloc_tuple (3);
1872 Field (ret_v, 0) = Val_int (pageno);
1873 Field (ret_v, 1) = caml_copy_double ((double) xy.x);
1874 Field (ret_v, 2) = caml_copy_double ((double) xy.y);
1875 CAMLreturn (ret_v);
1878 CAMLprim value ml_realloctexts (value texcount_v)
1880 CAMLparam1 (texcount_v);
1881 int ok;
1883 if (trylock (__func__)) {
1884 ok = 0;
1885 goto done;
1887 realloctexts (Int_val (texcount_v));
1888 ok = 1;
1889 unlock (__func__);
1891 done:
1892 CAMLreturn (Val_bool (ok));
1895 static void recti (int x0, int y0, int x1, int y1)
1897 GLfloat *v = state.vertices;
1899 glVertexPointer (2, GL_FLOAT, 0, v);
1900 v[0] = x0; v[1] = y0;
1901 v[2] = x1; v[3] = y0;
1902 v[4] = x0; v[5] = y1;
1903 v[6] = x1; v[7] = y1;
1904 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1907 static void showsel (struct page *page, int ox, int oy)
1909 fz_irect bbox;
1910 fz_rect rect;
1911 fz_stext_block *block;
1912 int seen = 0;
1913 unsigned char selcolor[] = {15,15,15,140};
1915 if (!page->fmark || !page->lmark) return;
1917 glEnable (GL_BLEND);
1918 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1919 glColor4ubv (selcolor);
1921 ox += state.pagedims[page->pdimno].bounds.x0;
1922 oy += state.pagedims[page->pdimno].bounds.y0;
1924 for (block = page->text->first_block; block; block = block->next) {
1925 fz_stext_line *line;
1927 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1928 for (line = block->u.t.first_line; line; line = line->next) {
1929 fz_stext_char *ch;
1931 rect = fz_empty_rect;
1932 for (ch = line->first_char; ch; ch = ch->next) {
1933 if (ch == page->fmark) seen = 1;
1934 if (seen) fz_union_rect (&rect, &ch->bbox);
1935 if (ch == page->lmark) {
1936 fz_round_rect (&bbox, &rect);
1937 recti (bbox.x0 + ox, bbox.y0 + oy,
1938 bbox.x1 + ox, bbox.y1 + oy);
1939 goto done;
1942 fz_round_rect (&bbox, &rect);
1943 recti (bbox.x0 + ox, bbox.y0 + oy,
1944 bbox.x1 + ox, bbox.y1 + oy);
1947 done:
1948 glDisable (GL_BLEND);
1951 #pragma GCC diagnostic push
1952 #pragma GCC diagnostic ignored "-Wdouble-promotion"
1953 #pragma GCC diagnostic ignored "-Wconversion"
1954 #include "glfont.c"
1955 #pragma GCC diagnostic pop
1957 static void stipplerect (fz_matrix *m,
1958 fz_point *p1,
1959 fz_point *p2,
1960 fz_point *p3,
1961 fz_point *p4,
1962 GLfloat *texcoords,
1963 GLfloat *vertices)
1965 fz_transform_point (p1, m);
1966 fz_transform_point (p2, m);
1967 fz_transform_point (p3, m);
1968 fz_transform_point (p4, m);
1970 float w, h, s, t;
1972 w = p2->x - p1->x;
1973 h = p2->y - p1->y;
1974 t = hypotf (w, h) * .25f;
1976 w = p3->x - p2->x;
1977 h = p3->y - p2->y;
1978 s = hypotf (w, h) * .25f;
1980 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
1981 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
1983 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
1984 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
1986 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
1987 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
1989 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
1990 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
1992 glDrawArrays (GL_LINES, 0, 8);
1995 static void solidrect (fz_matrix *m,
1996 fz_point *p1,
1997 fz_point *p2,
1998 fz_point *p3,
1999 fz_point *p4,
2000 GLfloat *vertices)
2002 fz_transform_point (p1, m);
2003 fz_transform_point (p2, m);
2004 fz_transform_point (p3, m);
2005 fz_transform_point (p4, m);
2006 vertices[0] = p1->x; vertices[1] = p1->y;
2007 vertices[2] = p2->x; vertices[3] = p2->y;
2009 vertices[4] = p3->x; vertices[5] = p3->y;
2010 vertices[6] = p4->x; vertices[7] = p4->y;
2011 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2014 static void ensurelinks (struct page *page)
2016 if (!page->links)
2017 page->links = fz_load_links (state.ctx, page->fzpage);
2020 static void highlightlinks (struct page *page, int xoff, int yoff)
2022 fz_matrix ctm, tm, pm;
2023 fz_link *link;
2024 GLfloat *texcoords = state.texcoords;
2025 GLfloat *vertices = state.vertices;
2027 ensurelinks (page);
2029 glEnable (GL_TEXTURE_1D);
2030 glEnable (GL_BLEND);
2031 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2032 glBindTexture (GL_TEXTURE_1D, state.stid);
2034 xoff -= state.pagedims[page->pdimno].bounds.x0;
2035 yoff -= state.pagedims[page->pdimno].bounds.y0;
2036 fz_translate (&tm, xoff, yoff);
2037 pm = pagectm (page);
2038 fz_concat (&ctm, &pm, &tm);
2040 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2041 glVertexPointer (2, GL_FLOAT, 0, vertices);
2043 for (link = page->links; link; link = link->next) {
2044 fz_point p1, p2, p3, p4;
2046 p1.x = link->rect.x0;
2047 p1.y = link->rect.y0;
2049 p2.x = link->rect.x1;
2050 p2.y = link->rect.y0;
2052 p3.x = link->rect.x1;
2053 p3.y = link->rect.y1;
2055 p4.x = link->rect.x0;
2056 p4.y = link->rect.y1;
2058 /* TODO: different colours for different schemes */
2059 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
2060 else glColor3ub (255, 0, 0);
2062 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2065 for (int i = 0; i < page->annotcount; ++i) {
2066 fz_point p1, p2, p3, p4;
2067 struct annot *annot = &page->annots[i];
2069 p1.x = annot->bbox.x0;
2070 p1.y = annot->bbox.y0;
2072 p2.x = annot->bbox.x1;
2073 p2.y = annot->bbox.y0;
2075 p3.x = annot->bbox.x1;
2076 p3.y = annot->bbox.y1;
2078 p4.x = annot->bbox.x0;
2079 p4.y = annot->bbox.y1;
2081 glColor3ub (0, 0, 128);
2082 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2085 glDisable (GL_BLEND);
2086 glDisable (GL_TEXTURE_1D);
2089 static int compareslinks (const void *l, const void *r)
2091 struct slink const *ls = l;
2092 struct slink const *rs = r;
2093 if (ls->bbox.y0 == rs->bbox.y0) {
2094 return rs->bbox.x0 - rs->bbox.x0;
2096 return ls->bbox.y0 - rs->bbox.y0;
2099 static void droptext (struct page *page)
2101 if (page->text) {
2102 fz_drop_stext_page (state.ctx, page->text);
2103 page->fmark = NULL;
2104 page->lmark = NULL;
2105 page->text = NULL;
2109 static void dropannots (struct page *page)
2111 if (page->annots) {
2112 free (page->annots);
2113 page->annots = NULL;
2114 page->annotcount = 0;
2118 static void ensureannots (struct page *page)
2120 int i, count = 0;
2121 size_t annotsize = sizeof (*page->annots);
2122 fz_annot *annot;
2124 if (state.gen != page->agen) {
2125 dropannots (page);
2126 page->agen = state.gen;
2128 if (page->annots) return;
2130 for (annot = fz_first_annot (state.ctx, page->fzpage);
2131 annot;
2132 annot = fz_next_annot (state.ctx, annot)) {
2133 count++;
2136 if (count > 0) {
2137 page->annotcount = count;
2138 page->annots = calloc (count, annotsize);
2139 if (!page->annots) {
2140 err (1, "calloc annots %d", count);
2143 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2144 annot;
2145 annot = fz_next_annot (state.ctx, annot), i++) {
2146 fz_rect rect;
2148 fz_bound_annot (state.ctx, annot, &rect);
2149 page->annots[i].annot = annot;
2150 fz_round_rect (&page->annots[i].bbox, &rect);
2155 static void dropslinks (struct page *page)
2157 if (page->slinks) {
2158 free (page->slinks);
2159 page->slinks = NULL;
2160 page->slinkcount = 0;
2162 if (page->links) {
2163 fz_drop_link (state.ctx, page->links);
2164 page->links = NULL;
2168 static void ensureslinks (struct page *page)
2170 fz_matrix ctm;
2171 int i, count;
2172 size_t slinksize = sizeof (*page->slinks);
2173 fz_link *link;
2175 ensureannots (page);
2176 if (state.gen != page->sgen) {
2177 dropslinks (page);
2178 page->sgen = state.gen;
2180 if (page->slinks) return;
2182 ensurelinks (page);
2183 ctm = pagectm (page);
2185 count = page->annotcount;
2186 for (link = page->links; link; link = link->next) {
2187 count++;
2189 if (count > 0) {
2190 int j;
2192 page->slinkcount = count;
2193 page->slinks = calloc (count, slinksize);
2194 if (!page->slinks) {
2195 err (1, "calloc slinks %d", count);
2198 for (i = 0, link = page->links; link; ++i, link = link->next) {
2199 fz_rect rect;
2201 rect = link->rect;
2202 fz_transform_rect (&rect, &ctm);
2203 page->slinks[i].tag = SLINK;
2204 page->slinks[i].u.link = link;
2205 fz_round_rect (&page->slinks[i].bbox, &rect);
2207 for (j = 0; j < page->annotcount; ++j, ++i) {
2208 fz_rect rect;
2209 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2210 fz_transform_rect (&rect, &ctm);
2211 fz_round_rect (&page->slinks[i].bbox, &rect);
2213 page->slinks[i].tag = SANNOT;
2214 page->slinks[i].u.annot = page->annots[j].annot;
2216 qsort (page->slinks, count, slinksize, compareslinks);
2220 static void highlightslinks (struct page *page, int xoff, int yoff,
2221 int noff, char *targ, mlsize_t tlen, int hfsize)
2223 char buf[40];
2224 struct slink *slink;
2225 float x0, y0, x1, y1, w;
2227 ensureslinks (page);
2228 glColor3ub (0xc3, 0xb0, 0x91);
2229 for (int i = 0; i < page->slinkcount; ++i) {
2230 fmt_linkn (buf, i + noff);
2231 if (!tlen || !strncmp (targ, buf, tlen)) {
2232 slink = &page->slinks[i];
2234 x0 = slink->bbox.x0 + xoff - 5;
2235 y1 = slink->bbox.y0 + yoff - 5;
2236 y0 = y1 + 10 + hfsize;
2237 w = measure_string (state.face, hfsize, buf);
2238 x1 = x0 + w + 10;
2239 recti ((int) x0, (int) y0, (int) x1, (int) y1);
2243 glEnable (GL_BLEND);
2244 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2245 glEnable (GL_TEXTURE_2D);
2246 glColor3ub (0, 0, 0);
2247 for (int i = 0; i < page->slinkcount; ++i) {
2248 fmt_linkn (buf, i + noff);
2249 if (!tlen || !strncmp (targ, buf, tlen)) {
2250 slink = &page->slinks[i];
2252 x0 = slink->bbox.x0 + xoff;
2253 y0 = slink->bbox.y0 + yoff + hfsize;
2254 draw_string (state.face, hfsize, x0, y0, buf);
2257 glDisable (GL_TEXTURE_2D);
2258 glDisable (GL_BLEND);
2261 static void uploadslice (struct tile *tile, struct slice *slice)
2263 int offset;
2264 struct slice *slice1;
2265 unsigned char *texdata;
2267 offset = 0;
2268 for (slice1 = tile->slices; slice != slice1; slice1++) {
2269 offset += slice1->h * tile->w * tile->pixmap->n;
2271 if (slice->texindex != -1 && slice->texindex < state.texcount
2272 && state.texowners[slice->texindex].slice == slice) {
2273 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2275 else {
2276 int subimage = 0;
2277 int texindex = state.texindex++ % state.texcount;
2279 if (state.texowners[texindex].w == tile->w) {
2280 if (state.texowners[texindex].h >= slice->h) {
2281 subimage = 1;
2283 else {
2284 state.texowners[texindex].h = slice->h;
2287 else {
2288 state.texowners[texindex].h = slice->h;
2291 state.texowners[texindex].w = tile->w;
2292 state.texowners[texindex].slice = slice;
2293 slice->texindex = texindex;
2295 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2296 #if TEXT_TYPE == GL_TEXTURE_2D
2297 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2298 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2299 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2300 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2301 #endif
2302 if (tile->pbo) {
2303 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2304 texdata = 0;
2306 else {
2307 texdata = tile->pixmap->samples;
2309 if (subimage) {
2310 glTexSubImage2D (TEXT_TYPE,
2314 tile->w,
2315 slice->h,
2316 state.texform,
2317 state.texty,
2318 texdata+offset
2321 else {
2322 glTexImage2D (TEXT_TYPE,
2324 state.texiform,
2325 tile->w,
2326 slice->h,
2328 state.texform,
2329 state.texty,
2330 texdata+offset
2333 if (tile->pbo) {
2334 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2339 CAMLprim void ml_begintiles (value unit_v)
2341 CAMLparam1 (unit_v);
2342 glEnable (TEXT_TYPE);
2343 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2344 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2345 CAMLreturn0;
2348 CAMLprim void ml_endtiles (value unit_v)
2350 CAMLparam1 (unit_v);
2351 glDisable (TEXT_TYPE);
2352 CAMLreturn0;
2355 CAMLprim void ml_drawtile (value args_v, value ptr_v)
2357 CAMLparam2 (args_v, ptr_v);
2358 int dispx = Int_val (Field (args_v, 0));
2359 int dispy = Int_val (Field (args_v, 1));
2360 int dispw = Int_val (Field (args_v, 2));
2361 int disph = Int_val (Field (args_v, 3));
2362 int tilex = Int_val (Field (args_v, 4));
2363 int tiley = Int_val (Field (args_v, 5));
2364 char *s = String_val (ptr_v);
2365 struct tile *tile = parse_pointer (__func__, s);
2366 int slicey, firstslice;
2367 struct slice *slice;
2368 GLfloat *texcoords = state.texcoords;
2369 GLfloat *vertices = state.vertices;
2371 firstslice = tiley / tile->sliceheight;
2372 slice = &tile->slices[firstslice];
2373 slicey = tiley % tile->sliceheight;
2375 while (disph > 0) {
2376 int dh;
2378 dh = slice->h - slicey;
2379 dh = fz_mini (disph, dh);
2380 uploadslice (tile, slice);
2382 texcoords[0] = tilex; texcoords[1] = slicey;
2383 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2384 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2385 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2387 vertices[0] = dispx; vertices[1] = dispy;
2388 vertices[2] = dispx+dispw; vertices[3] = dispy;
2389 vertices[4] = dispx; vertices[5] = dispy+dh;
2390 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2392 #if TEXT_TYPE == GL_TEXTURE_2D
2393 for (int i = 0; i < 8; ++i) {
2394 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2396 #endif
2398 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2399 dispy += dh;
2400 disph -= dh;
2401 slice++;
2402 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2403 slicey = 0;
2405 CAMLreturn0;
2408 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2410 fz_matrix ctm, tm, pm;
2411 fz_point p1, p2, p3, p4;
2412 GLfloat *vertices = state.vertices;
2413 double *v = (double *) rects_v;
2415 xoff -= state.pagedims[page->pdimno].bounds.x0;
2416 yoff -= state.pagedims[page->pdimno].bounds.y0;
2417 fz_translate (&tm, xoff, yoff);
2418 pm = pagectm (page);
2419 fz_concat (&ctm, &pm, &tm);
2421 glEnable (GL_BLEND);
2422 glVertexPointer (2, GL_FLOAT, 0, vertices);
2424 glColor4dv (v);
2425 p1.x = (float) v[4];
2426 p1.y = (float) v[5];
2428 p2.x = (float) v[6];
2429 p2.y = (float) v[5];
2431 p3.x = (float) v[6];
2432 p3.y = (float) v[7];
2434 p4.x = (float) v[4];
2435 p4.y = (float) v[7];
2436 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2437 glDisable (GL_BLEND);
2440 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2441 value xoff_v, value yoff_v,
2442 value li_v)
2444 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2445 int xoff = Int_val (xoff_v);
2446 int yoff = Int_val (yoff_v);
2447 int noff = Int_val (Field (li_v, 0));
2448 char *targ = String_val (Field (li_v, 1));
2449 mlsize_t tlen = caml_string_length (Field (li_v, 1));
2450 int hfsize = Int_val (Field (li_v, 2));
2451 char *s = String_val (ptr_v);
2452 int hlmask = Int_val (hlinks_v);
2453 struct page *page = parse_pointer (__func__, s);
2455 if (!page->fzpage) {
2456 /* deal with loadpage failed pages */
2457 goto done;
2460 if (trylock (__func__)) {
2461 noff = -1;
2462 goto done;
2465 ensureannots (page);
2466 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2467 if (hlmask & 2) {
2468 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2469 noff = page->slinkcount;
2471 if (page->tgen == state.gen) {
2472 showsel (page, xoff, yoff);
2474 unlock (__func__);
2476 done:
2477 CAMLreturn (Val_int (noff));
2480 CAMLprim void ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2481 value rects_v)
2483 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2484 int xoff = Int_val (xoff_v);
2485 int yoff = Int_val (yoff_v);
2486 char *s = String_val (ptr_v);
2487 struct page *page = parse_pointer (__func__, s);
2489 drawprect (page, xoff, yoff, rects_v);
2490 CAMLreturn0;
2493 static struct annot *getannot (struct page *page, int x, int y)
2495 fz_point p;
2496 fz_matrix ctm;
2497 const fz_matrix *tctm;
2498 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2500 if (!page->annots) return NULL;
2502 if (pdf) {
2503 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2504 tctm = &state.pagedims[page->pdimno].tctm;
2506 else {
2507 tctm = &fz_identity;
2510 p.x = x;
2511 p.y = y;
2513 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2514 fz_invert_matrix (&ctm, &ctm);
2515 fz_transform_point (&p, &ctm);
2517 if (pdf) {
2518 for (int i = 0; i < page->annotcount; ++i) {
2519 struct annot *a = &page->annots[i];
2520 fz_rect rect;
2522 fz_bound_annot (state.ctx, a->annot, &rect);
2523 if (p.x >= rect.x0 && p.x <= rect.x1) {
2524 if (p.y >= rect.y0 && p.y <= rect.y1)
2525 return a;
2529 return NULL;
2532 static fz_link *getlink (struct page *page, int x, int y)
2534 fz_point p;
2535 fz_matrix ctm;
2536 fz_link *link;
2538 ensureslinks (page);
2540 p.x = x;
2541 p.y = y;
2543 ctm = pagectm (page);
2544 fz_invert_matrix (&ctm, &ctm);
2545 fz_transform_point (&p, &ctm);
2547 for (link = page->links; link; link = link->next) {
2548 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2549 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2550 return link;
2554 return NULL;
2557 static void ensuretext (struct page *page)
2559 if (state.gen != page->tgen) {
2560 droptext (page);
2561 page->tgen = state.gen;
2563 if (!page->text) {
2564 fz_matrix ctm;
2565 fz_device *tdev;
2567 page->text = fz_new_stext_page (state.ctx,
2568 &state.pagedims[page->pdimno].mediabox);
2569 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2570 ctm = pagectm (page);
2571 fz_run_display_list (state.ctx, page->dlist,
2572 tdev, &ctm, &fz_infinite_rect, NULL);
2573 fz_close_device (state.ctx, tdev);
2574 fz_drop_device (state.ctx, tdev);
2578 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2580 CAMLparam2 (start_page_v, dir_v);
2581 CAMLlocal1 (ret_v);
2582 int i, dir = Int_val (dir_v);
2583 int start_page = Int_val (start_page_v);
2584 int end_page = dir > 0 ? state.pagecount : -1;
2585 pdf_document *pdf;
2587 fz_var (end_page);
2588 ret_v = Val_int (0);
2589 lock (__func__);
2590 pdf = pdf_specifics (state.ctx, state.doc);
2591 for (i = start_page + dir; i != end_page; i += dir) {
2592 int found;
2594 fz_var (found);
2595 if (pdf) {
2596 pdf_page *page = NULL;
2598 fz_var (page);
2599 fz_try (state.ctx) {
2600 page = pdf_load_page (state.ctx, pdf, i);
2601 found = !!page->links || !!page->annots;
2603 fz_catch (state.ctx) {
2604 found = 0;
2606 if (page) {
2607 fz_drop_page (state.ctx, &page->super);
2610 else {
2611 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2612 fz_link *link = fz_load_links (state.ctx, page);
2613 found = !!link;
2614 fz_drop_link (state.ctx, link);
2615 fz_drop_page (state.ctx, page);
2618 if (found) {
2619 ret_v = caml_alloc_small (1, 1);
2620 Field (ret_v, 0) = Val_int (i);
2621 goto unlock;
2624 unlock:
2625 unlock (__func__);
2626 CAMLreturn (ret_v);
2629 enum { dir_first, dir_last };
2630 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2632 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2634 CAMLparam2 (ptr_v, dir_v);
2635 CAMLlocal2 (ret_v, pos_v);
2636 struct page *page;
2637 int dirtag, i, slinkindex;
2638 struct slink *found = NULL ,*slink;
2639 char *s = String_val (ptr_v);
2641 page = parse_pointer (__func__, s);
2642 ret_v = Val_int (0);
2643 lock (__func__);
2644 ensureslinks (page);
2646 if (Is_block (dir_v)) {
2647 dirtag = Tag_val (dir_v);
2648 switch (dirtag) {
2649 case dir_first_visible:
2651 int x0, y0, dir, first_index, last_index;
2653 pos_v = Field (dir_v, 0);
2654 x0 = Int_val (Field (pos_v, 0));
2655 y0 = Int_val (Field (pos_v, 1));
2656 dir = Int_val (Field (pos_v, 2));
2658 if (dir >= 0) {
2659 dir = 1;
2660 first_index = 0;
2661 last_index = page->slinkcount;
2663 else {
2664 first_index = page->slinkcount - 1;
2665 last_index = -1;
2668 for (i = first_index; i != last_index; i += dir) {
2669 slink = &page->slinks[i];
2670 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2671 found = slink;
2672 break;
2676 break;
2678 case dir_left:
2679 slinkindex = Int_val (Field (dir_v, 0));
2680 found = &page->slinks[slinkindex];
2681 for (i = slinkindex - 1; i >= 0; --i) {
2682 slink = &page->slinks[i];
2683 if (slink->bbox.x0 < found->bbox.x0) {
2684 found = slink;
2685 break;
2688 break;
2690 case dir_right:
2691 slinkindex = Int_val (Field (dir_v, 0));
2692 found = &page->slinks[slinkindex];
2693 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2694 slink = &page->slinks[i];
2695 if (slink->bbox.x0 > found->bbox.x0) {
2696 found = slink;
2697 break;
2700 break;
2702 case dir_down:
2703 slinkindex = Int_val (Field (dir_v, 0));
2704 found = &page->slinks[slinkindex];
2705 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2706 slink = &page->slinks[i];
2707 if (slink->bbox.y0 >= found->bbox.y0) {
2708 found = slink;
2709 break;
2712 break;
2714 case dir_up:
2715 slinkindex = Int_val (Field (dir_v, 0));
2716 found = &page->slinks[slinkindex];
2717 for (i = slinkindex - 1; i >= 0; --i) {
2718 slink = &page->slinks[i];
2719 if (slink->bbox.y0 <= found->bbox.y0) {
2720 found = slink;
2721 break;
2724 break;
2727 else {
2728 dirtag = Int_val (dir_v);
2729 switch (dirtag) {
2730 case dir_first:
2731 found = page->slinks;
2732 break;
2734 case dir_last:
2735 if (page->slinks) {
2736 found = page->slinks + (page->slinkcount - 1);
2738 break;
2741 if (found) {
2742 ret_v = caml_alloc_small (2, 1);
2743 Field (ret_v, 0) = Val_int (found - page->slinks);
2746 unlock (__func__);
2747 CAMLreturn (ret_v);
2750 enum { uuri, utext, uannot };
2752 CAMLprim value ml_getlink (value ptr_v, value n_v)
2754 CAMLparam2 (ptr_v, n_v);
2755 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2756 fz_link *link;
2757 struct page *page;
2758 char *s = String_val (ptr_v);
2759 struct slink *slink;
2761 ret_v = Val_int (0);
2762 page = parse_pointer (__func__, s);
2764 lock (__func__);
2765 ensureslinks (page);
2766 slink = &page->slinks[Int_val (n_v)];
2767 if (slink->tag == SLINK) {
2768 link = slink->u.link;
2769 str_v = caml_copy_string (link->uri);
2770 ret_v = caml_alloc_small (1, uuri);
2771 Field (ret_v, 0) = str_v;
2773 else {
2774 ret_v = caml_alloc_small (1, uannot);
2775 tup_v = caml_alloc_tuple (2);
2776 Field (ret_v, 0) = tup_v;
2777 Field (tup_v, 0) = ptr_v;
2778 Field (tup_v, 1) = n_v;
2780 unlock (__func__);
2782 CAMLreturn (ret_v);
2785 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2787 CAMLparam2 (ptr_v, n_v);
2788 CAMLlocal1 (ret_v);
2789 pdf_document *pdf;
2790 char *contents = NULL;
2792 lock (__func__);
2793 pdf = pdf_specifics (state.ctx, state.doc);
2794 if (pdf) {
2795 char *s = String_val (ptr_v);
2796 struct page *page;
2797 struct slink *slink;
2799 page = parse_pointer (__func__, s);
2800 slink = &page->slinks[Int_val (n_v)];
2801 contents = pdf_copy_annot_contents (state.ctx,
2802 (pdf_annot *) slink->u.annot);
2804 unlock (__func__);
2805 if (contents) {
2806 ret_v = caml_copy_string (contents);
2807 fz_free (state.ctx, contents);
2809 else {
2810 ret_v = caml_copy_string ("");
2812 CAMLreturn (ret_v);
2815 CAMLprim value ml_getlinkcount (value ptr_v)
2817 CAMLparam1 (ptr_v);
2818 struct page *page;
2819 char *s = String_val (ptr_v);
2821 page = parse_pointer (__func__, s);
2822 CAMLreturn (Val_int (page->slinkcount));
2825 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2827 CAMLparam2 (ptr_v, n_v);
2828 CAMLlocal1 (ret_v);
2829 struct page *page;
2830 struct slink *slink;
2831 char *s = String_val (ptr_v);
2833 page = parse_pointer (__func__, s);
2834 ret_v = caml_alloc_tuple (4);
2835 lock (__func__);
2836 ensureslinks (page);
2838 slink = &page->slinks[Int_val (n_v)];
2839 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2840 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2841 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2842 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2843 unlock (__func__);
2844 CAMLreturn (ret_v);
2847 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2849 CAMLparam3 (ptr_v, x_v, y_v);
2850 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2851 fz_link *link;
2852 struct annot *annot;
2853 struct page *page;
2854 char *ptr = String_val (ptr_v);
2855 int x = Int_val (x_v), y = Int_val (y_v);
2856 struct pagedim *pdim;
2858 ret_v = Val_int (0);
2859 if (trylock (__func__)) {
2860 goto done;
2863 page = parse_pointer (__func__, ptr);
2864 pdim = &state.pagedims[page->pdimno];
2865 x += pdim->bounds.x0;
2866 y += pdim->bounds.y0;
2869 annot = getannot (page, x, y);
2870 if (annot) {
2871 int i, n = -1;
2873 ensureslinks (page);
2874 for (i = 0; i < page->slinkcount; ++i) {
2875 if (page->slinks[i].tag == SANNOT
2876 && page->slinks[i].u.annot == annot->annot) {
2877 n = i;
2878 break;
2881 ret_v = caml_alloc_small (1, uannot);
2882 tup_v = caml_alloc_tuple (2);
2883 Field (ret_v, 0) = tup_v;
2884 Field (tup_v, 0) = ptr_v;
2885 Field (tup_v, 1) = Val_int (n);
2886 goto unlock;
2890 link = getlink (page, x, y);
2891 if (link) {
2892 str_v = caml_copy_string (link->uri);
2893 ret_v = caml_alloc_small (1, uuri);
2894 Field (ret_v, 0) = str_v;
2896 else {
2897 fz_rect *b;
2898 fz_stext_block *block;
2900 ensuretext (page);
2902 for (block = page->text->first_block; block; block = block->next) {
2903 fz_stext_line *line;
2905 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2906 b = &block->bbox;
2907 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2908 continue;
2910 for (line = block->u.t.first_line; line; line = line->next) {
2911 fz_stext_char *ch;
2913 b = &line->bbox;
2914 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2915 continue;
2917 for (ch = line->first_char; ch; ch = ch->next) {
2918 b = &ch->bbox;
2920 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
2921 const char *n2 = fz_font_name (state.ctx, ch->font);
2922 FT_FaceRec *face = fz_font_ft_face (state.ctx,
2923 ch->font);
2925 if (!n2) n2 = "<unknown font>";
2927 if (face && face->family_name) {
2928 char *s;
2929 char *n1 = face->family_name;
2930 size_t l1 = strlen (n1);
2931 size_t l2 = strlen (n2);
2933 if (l1 != l2 || memcmp (n1, n2, l1)) {
2934 s = malloc (l1 + l2 + 2);
2935 if (s) {
2936 memcpy (s, n2, l2);
2937 s[l2] = '=';
2938 memcpy (s + l2 + 1, n1, l1 + 1);
2939 str_v = caml_copy_string (s);
2940 free (s);
2944 if (str_v == Val_unit) {
2945 str_v = caml_copy_string (n2);
2947 ret_v = caml_alloc_small (1, utext);
2948 Field (ret_v, 0) = str_v;
2949 goto unlock;
2955 unlock:
2956 unlock (__func__);
2958 done:
2959 CAMLreturn (ret_v);
2962 enum { mark_page, mark_block, mark_line, mark_word };
2964 CAMLprim void ml_clearmark (value ptr_v)
2966 CAMLparam1 (ptr_v);
2967 char *s = String_val (ptr_v);
2968 struct page *page;
2970 if (trylock (__func__)) {
2971 goto done;
2974 page = parse_pointer (__func__, s);
2975 page->fmark = NULL;
2976 page->lmark = NULL;
2978 unlock (__func__);
2979 done:
2980 CAMLreturn0;
2983 static int uninteresting (int c)
2985 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
2986 || ispunct (c);
2989 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
2991 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
2992 CAMLlocal1 (ret_v);
2993 fz_rect *b;
2994 struct page *page;
2995 fz_stext_line *line;
2996 fz_stext_block *block;
2997 struct pagedim *pdim;
2998 int mark = Int_val (mark_v);
2999 char *s = String_val (ptr_v);
3000 int x = Int_val (x_v), y = Int_val (y_v);
3002 ret_v = Val_bool (0);
3003 if (trylock (__func__)) {
3004 goto done;
3007 page = parse_pointer (__func__, s);
3008 pdim = &state.pagedims[page->pdimno];
3010 ensuretext (page);
3012 if (mark == mark_page) {
3013 page->fmark = page->text->first_block->u.t.first_line->first_char;
3014 page->lmark = page->text->last_block->u.t.last_line->last_char;
3015 ret_v = Val_bool (1);
3016 goto unlock;
3019 x += pdim->bounds.x0;
3020 y += pdim->bounds.y0;
3022 for (block = page->text->first_block; block; block = block->next) {
3023 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3024 b = &block->bbox;
3025 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3026 continue;
3028 if (mark == mark_block) {
3029 page->fmark = block->u.t.first_line->first_char;
3030 page->lmark = block->u.t.last_line->last_char;
3031 ret_v = Val_bool (1);
3032 goto unlock;
3035 for (line = block->u.t.first_line; line; line = line->next) {
3036 fz_stext_char *ch;
3038 b = &line->bbox;
3039 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3040 continue;
3042 if (mark == mark_line) {
3043 page->fmark = line->first_char;
3044 page->lmark = line->last_char;
3045 ret_v = Val_bool (1);
3046 goto unlock;
3049 for (ch = line->first_char; ch; ch = ch->next) {
3050 fz_stext_char *ch2, *first = NULL, *last = NULL;
3051 b = &ch->bbox;
3052 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3053 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
3054 if (uninteresting (ch2->c)) first = NULL;
3055 else if (!first) first = ch2;
3057 for (ch2 = ch; ch2; ch2 = ch2->next) {
3058 if (uninteresting (ch2->c)) break;
3059 last = ch2;
3062 page->fmark = first;
3063 page->lmark = last;
3064 ret_v = Val_bool (1);
3065 goto unlock;
3070 unlock:
3071 if (!Bool_val (ret_v)) {
3072 page->fmark = NULL;
3073 page->lmark = NULL;
3075 unlock (__func__);
3077 done:
3078 CAMLreturn (ret_v);
3081 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3083 CAMLparam3 (ptr_v, x_v, y_v);
3084 CAMLlocal2 (ret_v, res_v);
3085 fz_rect *b = NULL;
3086 struct page *page;
3087 struct pagedim *pdim;
3088 fz_stext_block *block;
3089 char *s = String_val (ptr_v);
3090 int x = Int_val (x_v), y = Int_val (y_v);
3092 ret_v = Val_int (0);
3093 if (trylock (__func__)) {
3094 goto done;
3097 page = parse_pointer (__func__, s);
3098 pdim = &state.pagedims[page->pdimno];
3099 x += pdim->bounds.x0;
3100 y += pdim->bounds.y0;
3102 ensuretext (page);
3104 for (block = page->text->first_block; block; block = block->next) {
3105 switch (block->type) {
3106 case FZ_STEXT_BLOCK_TEXT:
3107 b = &block->bbox;
3108 break;
3110 case FZ_STEXT_BLOCK_IMAGE:
3111 b = &block->bbox;
3112 break;
3114 default:
3115 continue;
3118 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3119 break;
3120 b = NULL;
3122 if (b) {
3123 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3124 ret_v = caml_alloc_small (1, 1);
3125 Store_double_field (res_v, 0, (double) b->x0);
3126 Store_double_field (res_v, 1, (double) b->x1);
3127 Store_double_field (res_v, 2, (double) b->y0);
3128 Store_double_field (res_v, 3, (double) b->y1);
3129 Field (ret_v, 0) = res_v;
3131 unlock (__func__);
3133 done:
3134 CAMLreturn (ret_v);
3137 CAMLprim void ml_seltext (value ptr_v, value rect_v)
3139 CAMLparam2 (ptr_v, rect_v);
3140 fz_rect b;
3141 struct page *page;
3142 struct pagedim *pdim;
3143 char *s = String_val (ptr_v);
3144 int x0, x1, y0, y1;
3145 fz_stext_char *ch;
3146 fz_stext_line *line;
3147 fz_stext_block *block;
3148 fz_stext_char *fc, *lc;
3150 if (trylock (__func__)) {
3151 goto done;
3154 page = parse_pointer (__func__, s);
3155 ensuretext (page);
3157 pdim = &state.pagedims[page->pdimno];
3158 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3159 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3160 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3161 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3163 if (y0 > y1) {
3164 int t = y0;
3165 y0 = y1;
3166 y1 = t;
3167 x0 = x1;
3168 x1 = t;
3171 fc = page->fmark;
3172 lc = page->lmark;
3174 for (block = page->text->first_block; block; block = block->next) {
3175 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3176 for (line = block->u.t.first_line; line; line = line->next) {
3177 for (ch = line->first_char; ch; ch = ch->next) {
3178 b = ch->bbox;
3179 if (x0 >= b.x0 && x0 <= b.x1 && y0 >= b.y0 && y0 <= b.y1) {
3180 fc = ch;
3182 if (x1 >= b.x0 && x1 <= b.x1 && y1 >= b.y0 && y1 <= b.y1) {
3183 lc = ch;
3188 if (x1 < x0 && fc == lc) {
3189 fz_stext_char *t;
3191 t = fc;
3192 fc = lc;
3193 lc = t;
3196 page->fmark = fc;
3197 page->lmark = lc;
3199 unlock (__func__);
3201 done:
3202 CAMLreturn0;
3205 static int pipechar (FILE *f, fz_stext_char *ch)
3207 char buf[4];
3208 int len;
3209 size_t ret;
3211 len = fz_runetochar (buf, ch->c);
3212 ret = fwrite (buf, len, 1, f);
3213 if (ret != 1) {
3214 printd ("emsg failed to write %d bytes ret=%zu: %d:%s",
3215 len, ret, errno, strerror (errno));
3216 return -1;
3218 return 0;
3221 CAMLprim value ml_spawn (value command_v, value fds_v)
3223 CAMLparam2 (command_v, fds_v);
3224 CAMLlocal2 (l_v, tup_v);
3225 int ret, ret1;
3226 pid_t pid = (pid_t) -1;
3227 char *msg = NULL;
3228 value earg_v = Nothing;
3229 posix_spawnattr_t attr;
3230 posix_spawn_file_actions_t fa;
3231 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3233 argv[2] = String_val (command_v);
3235 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3236 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3239 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3240 msg = "posix_spawnattr_init";
3241 goto fail1;
3244 #ifdef POSIX_SPAWN_USEVFORK
3245 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3246 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3247 goto fail;
3249 #endif
3251 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3252 int fd1, fd2;
3254 tup_v = Field (l_v, 0);
3255 fd1 = Int_val (Field (tup_v, 0));
3256 fd2 = Int_val (Field (tup_v, 1));
3257 if (fd2 < 0) {
3258 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3259 msg = "posix_spawn_file_actions_addclose";
3260 earg_v = tup_v;
3261 goto fail;
3264 else {
3265 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3266 msg = "posix_spawn_file_actions_adddup2";
3267 earg_v = tup_v;
3268 goto fail;
3273 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3274 msg = "posix_spawn";
3275 goto fail;
3278 fail:
3279 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3280 printd ("emsg posix_spawnattr_destroy: %d:%s", ret1, strerror (ret1));
3283 fail1:
3284 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3285 printd ("emsg posix_spawn_file_actions_destroy: %d:%s",
3286 ret1, strerror (ret1));
3289 if (msg)
3290 unix_error (ret, msg, earg_v);
3292 CAMLreturn (Val_int (pid));
3295 CAMLprim value ml_hassel (value ptr_v)
3297 CAMLparam1 (ptr_v);
3298 CAMLlocal1 (ret_v);
3299 struct page *page;
3300 char *s = String_val (ptr_v);
3302 ret_v = Val_bool (0);
3303 if (trylock (__func__)) {
3304 goto done;
3307 page = parse_pointer (__func__, s);
3308 ret_v = Val_bool (page->fmark && page->lmark);
3309 unlock (__func__);
3310 done:
3311 CAMLreturn (ret_v);
3314 CAMLprim void ml_copysel (value fd_v, value ptr_v)
3316 CAMLparam2 (fd_v, ptr_v);
3317 FILE *f;
3318 int seen = 0;
3319 struct page *page;
3320 fz_stext_line *line;
3321 fz_stext_block *block;
3322 int fd = Int_val (fd_v);
3323 char *s = String_val (ptr_v);
3325 if (trylock (__func__)) {
3326 goto done;
3329 page = parse_pointer (__func__, s);
3331 if (!page->fmark || !page->lmark) {
3332 printd ("emsg nothing to copy on page %d", page->pageno);
3333 goto unlock;
3336 f = fdopen (fd, "w");
3337 if (!f) {
3338 printd ("emsg failed to fdopen sel pipe (from fd %d): %d:%s",
3339 fd, errno, strerror (errno));
3340 f = stdout;
3343 for (block = page->text->first_block; block; block = block->next) {
3344 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3345 for (line = block->u.t.first_line; line; line = line->next) {
3346 fz_stext_char *ch;
3347 for (ch = line->first_char; ch; ch = ch->next) {
3348 if (seen || ch == page->fmark) {
3349 do {
3350 pipechar (f, ch);
3351 if (ch == page->lmark) goto close;
3352 } while ((ch = ch->next));
3353 seen = 1;
3354 break;
3357 if (seen) fputc ('\n', f);
3360 close:
3361 if (f != stdout) {
3362 int ret = fclose (f);
3363 fd = -1;
3364 if (ret == -1) {
3365 if (errno != ECHILD) {
3366 printd ("emsg failed to close sel pipe: %d:%s",
3367 errno, strerror (errno));
3371 unlock:
3372 unlock (__func__);
3374 done:
3375 if (fd >= 0) {
3376 if (close (fd)) {
3377 printd ("emsg failed to close sel pipe: %d:%s",
3378 errno, strerror (errno));
3381 CAMLreturn0;
3384 CAMLprim value ml_getpdimrect (value pagedimno_v)
3386 CAMLparam1 (pagedimno_v);
3387 CAMLlocal1 (ret_v);
3388 int pagedimno = Int_val (pagedimno_v);
3389 fz_rect box;
3391 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3392 if (trylock (__func__)) {
3393 box = fz_empty_rect;
3395 else {
3396 box = state.pagedims[pagedimno].mediabox;
3397 unlock (__func__);
3400 Store_double_field (ret_v, 0, (double) box.x0);
3401 Store_double_field (ret_v, 1, (double) box.x1);
3402 Store_double_field (ret_v, 2, (double) box.y0);
3403 Store_double_field (ret_v, 3, (double) box.y1);
3405 CAMLreturn (ret_v);
3408 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3409 value dw_v, value cols_v)
3411 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3412 CAMLlocal1 (ret_v);
3413 int i;
3414 float zoom = -1.;
3415 float maxh = 0.0;
3416 struct pagedim *p;
3417 float winw = Int_val (winw_v);
3418 float winh = Int_val (winh_v);
3419 float dw = Int_val (dw_v);
3420 float cols = Int_val (cols_v);
3421 float pw = 1.0, ph = 1.0;
3423 if (trylock (__func__)) {
3424 goto done;
3427 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3428 float w = p->pagebox.x1 / cols;
3429 float h = p->pagebox.y1;
3430 if (h > maxh) {
3431 maxh = h;
3432 ph = h;
3433 if (state.fitmodel != FitProportional) pw = w;
3435 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3438 zoom = (((winh / ph) * pw) + dw) / winw;
3439 unlock (__func__);
3440 done:
3441 ret_v = caml_copy_double ((double) zoom);
3442 CAMLreturn (ret_v);
3445 CAMLprim value ml_getmaxw (value unit_v)
3447 CAMLparam1 (unit_v);
3448 CAMLlocal1 (ret_v);
3449 int i;
3450 float maxw = -1.;
3451 struct pagedim *p;
3453 if (trylock (__func__)) {
3454 goto done;
3457 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3458 float w = p->pagebox.x1;
3459 maxw = fz_max (maxw, w);
3462 unlock (__func__);
3463 done:
3464 ret_v = caml_copy_double ((double) maxw);
3465 CAMLreturn (ret_v);
3468 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3470 CAMLparam4 (pt_v, x_v, y_v, string_v);
3471 CAMLlocal1 (ret_v);
3472 int pt = Int_val(pt_v);
3473 int x = Int_val (x_v);
3474 int y = Int_val (y_v);
3475 double w;
3477 w = (double) draw_string (state.face, pt, x, y, String_val (string_v));
3478 ret_v = caml_copy_double (w);
3479 CAMLreturn (ret_v);
3482 CAMLprim value ml_measure_string (value pt_v, value string_v)
3484 CAMLparam2 (pt_v, string_v);
3485 CAMLlocal1 (ret_v);
3486 int pt = Int_val (pt_v);
3487 double w;
3489 w = (double) measure_string (state.face, pt, String_val (string_v));
3490 ret_v = caml_copy_double (w);
3491 CAMLreturn (ret_v);
3494 CAMLprim value ml_getpagebox (value opaque_v)
3496 CAMLparam1 (opaque_v);
3497 CAMLlocal1 (ret_v);
3498 fz_rect rect;
3499 fz_irect bbox;
3500 fz_matrix ctm;
3501 fz_device *dev;
3502 char *s = String_val (opaque_v);
3503 struct page *page = parse_pointer (__func__, s);
3505 ret_v = caml_alloc_tuple (4);
3506 dev = fz_new_bbox_device (state.ctx, &rect);
3508 ctm = pagectm (page);
3509 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3511 fz_close_device (state.ctx, dev);
3512 fz_drop_device (state.ctx, dev);
3513 fz_round_rect (&bbox, &rect);
3514 Field (ret_v, 0) = Val_int (bbox.x0);
3515 Field (ret_v, 1) = Val_int (bbox.y0);
3516 Field (ret_v, 2) = Val_int (bbox.x1);
3517 Field (ret_v, 3) = Val_int (bbox.y1);
3519 CAMLreturn (ret_v);
3522 CAMLprim void ml_setaalevel (value level_v)
3524 CAMLparam1 (level_v);
3526 state.aalevel = Int_val (level_v);
3527 CAMLreturn0;
3530 #ifndef __COCOA__
3531 #pragma GCC diagnostic push
3532 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3533 #include <X11/Xlib.h>
3534 #include <X11/cursorfont.h>
3535 #pragma GCC diagnostic pop
3537 #ifdef USE_EGL
3538 #include <EGL/egl.h>
3539 #else
3540 #include <GL/glx.h>
3541 #endif
3543 static const int shapes[] = {
3544 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3547 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3549 static struct {
3550 Window wid;
3551 Display *dpy;
3552 #ifdef USE_EGL
3553 EGLContext ctx;
3554 EGLConfig conf;
3555 EGLSurface win;
3556 EGLDisplay *edpy;
3557 #else
3558 GLXContext ctx;
3559 #endif
3560 XVisualInfo *visual;
3561 Cursor curs[CURS_COUNT];
3562 } glx;
3565 static void initcurs (void)
3567 for (size_t n = 0; n < CURS_COUNT; ++n) {
3568 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3572 #ifdef USE_EGL
3573 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3575 CAMLparam3 (display_v, wid_v, screen_v);
3576 int major, minor;
3577 int num_conf;
3578 EGLint visid;
3579 EGLint attribs[] = {
3580 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
3581 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
3582 EGL_NONE
3584 EGLConfig conf;
3586 glx.dpy = XOpenDisplay (String_val (display_v));
3587 if (!glx.dpy) {
3588 caml_failwith ("XOpenDisplay");
3591 eglBindAPI (EGL_OPENGL_API);
3593 glx.edpy = eglGetDisplay (glx.dpy);
3594 if (glx.edpy == EGL_NO_DISPLAY) {
3595 caml_failwith ("eglGetDisplay");
3598 if (!eglInitialize (glx.edpy, &major, &minor)) {
3599 caml_failwith ("eglInitialize");
3602 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
3603 !num_conf) {
3604 caml_failwith ("eglChooseConfig");
3607 if (!eglGetConfigAttrib (glx.edpy, conf, EGL_NATIVE_VISUAL_ID, &visid)) {
3608 caml_failwith ("eglGetConfigAttrib");
3611 glx.conf = conf;
3612 initcurs ();
3614 glx.wid = Int_val (wid_v);
3615 CAMLreturn (Val_int (visid));
3618 CAMLprim void ml_glxcompleteinit (value unit_v)
3620 CAMLparam1 (unit_v);
3622 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
3623 if (!glx.ctx) {
3624 caml_failwith ("eglCreateContext");
3627 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
3628 glx.wid, NULL);
3629 if (glx.win == EGL_NO_SURFACE) {
3630 caml_failwith ("eglCreateWindowSurface");
3633 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
3634 glx.ctx = NULL;
3635 caml_failwith ("eglMakeCurrent");
3637 CAMLreturn0;
3639 #else
3640 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3642 CAMLparam3 (display_v, wid_v, screen_v);
3644 glx.dpy = XOpenDisplay (String_val (display_v));
3645 if (!glx.dpy) {
3646 caml_failwith ("XOpenDisplay");
3649 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3650 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
3651 if (!glx.visual) {
3652 XCloseDisplay (glx.dpy);
3653 caml_failwith ("glXChooseVisual");
3656 initcurs ();
3658 glx.wid = Int_val (wid_v);
3659 CAMLreturn (Val_int (glx.visual->visualid));
3662 CAMLprim void ml_glxcompleteinit (value unit_v)
3664 CAMLparam1 (unit_v);
3666 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
3667 if (!glx.ctx) {
3668 caml_failwith ("glXCreateContext");
3671 XFree (glx.visual);
3672 glx.visual = NULL;
3674 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
3675 glXDestroyContext (glx.dpy, glx.ctx);
3676 glx.ctx = NULL;
3677 caml_failwith ("glXMakeCurrent");
3679 CAMLreturn0;
3681 #endif
3683 CAMLprim void ml_setcursor (value cursor_v)
3685 CAMLparam1 (cursor_v);
3686 size_t cursn = Int_val (cursor_v);
3688 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
3689 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
3690 XFlush (glx.dpy);
3691 CAMLreturn0;
3694 CAMLprim void ml_swapb (value unit_v)
3696 CAMLparam1 (unit_v);
3697 #ifdef USE_EGL
3698 if (!eglSwapBuffers (glx.edpy, glx.win)) {
3699 caml_failwith ("eglSwapBuffers");
3701 #else
3702 glXSwapBuffers (glx.dpy, glx.wid);
3703 #endif
3704 CAMLreturn0;
3707 long keysym2ucs (KeySym);
3708 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3710 CAMLparam1 (keysym_v);
3711 CAMLlocal1 (str_v);
3712 KeySym keysym = Int_val (keysym_v);
3713 Rune rune;
3714 int len;
3715 char buf[5];
3717 rune = (Rune) keysym2ucs (keysym);
3718 len = fz_runetochar (buf, rune);
3719 buf[len] = 0;
3720 str_v = caml_copy_string (buf);
3721 CAMLreturn (str_v);
3723 #else
3724 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3726 CAMLparam1 (keysym_v);
3727 CAMLlocal1 (str_v);
3728 long ucs_v = Long_val (keysym_v);
3729 int len;
3730 char buf[5];
3732 len = fz_runetochar (buf, (int) ucs_v);
3733 buf[len] = 0;
3734 str_v = caml_copy_string (buf);
3735 CAMLreturn (str_v);
3737 #endif
3739 enum { piunknown, pilinux, piosx, pisun, pibsd };
3741 CAMLprim value ml_platform (value unit_v)
3743 CAMLparam1 (unit_v);
3744 CAMLlocal2 (tup_v, arr_v);
3745 int platid = piunknown;
3746 struct utsname buf;
3748 #if defined __linux__
3749 platid = pilinux;
3750 #elif defined __DragonFly__ || defined __FreeBSD__
3751 || defined __OpenBSD__ || defined __NetBSD__
3752 platid = pibsd;
3753 #elif defined __sun__
3754 platid = pisun;
3755 #elif defined __APPLE__
3756 platid = piosx;
3757 #endif
3758 if (uname (&buf)) err (1, "uname");
3760 tup_v = caml_alloc_tuple (2);
3762 char const *sar[] = {
3763 buf.sysname,
3764 buf.release,
3765 buf.version,
3766 buf.machine,
3767 NULL
3769 arr_v = caml_copy_string_array (sar);
3771 Field (tup_v, 0) = Val_int (platid);
3772 Field (tup_v, 1) = arr_v;
3773 CAMLreturn (tup_v);
3776 CAMLprim void ml_cloexec (value fd_v)
3778 CAMLparam1 (fd_v);
3779 int fd = Int_val (fd_v);
3781 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3782 uerror ("fcntl", Nothing);
3784 CAMLreturn0;
3787 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
3789 CAMLparam2 (w_v, h_v);
3790 CAMLlocal1 (ret_v);
3791 struct bo *pbo;
3792 int w = Int_val (w_v);
3793 int h = Int_val (h_v);
3794 int cs = Int_val (cs_v);
3796 if (state.bo_usable) {
3797 pbo = calloc (sizeof (*pbo), 1);
3798 if (!pbo) {
3799 err (1, "calloc pbo");
3802 switch (cs) {
3803 case 0:
3804 case 1:
3805 pbo->size = w*h*4;
3806 break;
3807 case 2:
3808 pbo->size = w*h*2;
3809 break;
3810 default:
3811 errx (1, "%s: invalid colorspace %d", __func__, cs);
3814 state.glGenBuffersARB (1, &pbo->id);
3815 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3816 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, (GLsizei) pbo->size,
3817 NULL, GL_STREAM_DRAW);
3818 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3819 GL_READ_WRITE);
3820 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3821 if (!pbo->ptr) {
3822 printd ("emsg glMapBufferARB failed: %#x", glGetError ());
3823 state.glDeleteBuffersARB (1, &pbo->id);
3824 free (pbo);
3825 ret_v = caml_copy_string ("0");
3827 else {
3828 int res;
3829 char *s;
3831 res = snprintf (NULL, 0, "%" PRIxPTR, (uintptr_t) pbo);
3832 if (res < 0) {
3833 err (1, "snprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3835 s = malloc (res+1);
3836 if (!s) {
3837 err (1, "malloc %d bytes failed", res+1);
3839 res = sprintf (s, "%" PRIxPTR, (uintptr_t) pbo);
3840 if (res < 0) {
3841 err (1, "sprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3843 ret_v = caml_copy_string (s);
3844 free (s);
3847 else {
3848 ret_v = caml_copy_string ("0");
3850 CAMLreturn (ret_v);
3853 CAMLprim void ml_freepbo (value s_v)
3855 CAMLparam1 (s_v);
3856 char *s = String_val (s_v);
3857 struct tile *tile = parse_pointer (__func__, s);
3859 if (tile->pbo) {
3860 state.glDeleteBuffersARB (1, &tile->pbo->id);
3861 tile->pbo->id = -1;
3862 tile->pbo->ptr = NULL;
3863 tile->pbo->size = -1;
3865 CAMLreturn0;
3868 CAMLprim void ml_unmappbo (value s_v)
3870 CAMLparam1 (s_v);
3871 char *s = String_val (s_v);
3872 struct tile *tile = parse_pointer (__func__, s);
3874 if (tile->pbo) {
3875 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3876 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3877 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3879 tile->pbo->ptr = NULL;
3880 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3882 CAMLreturn0;
3885 static void setuppbo (void)
3887 #ifdef __clang__
3888 #pragma GCC diagnostic ignored "-Wunused-macros"
3889 #endif
3890 #ifdef __COCOA__
3891 static CFBundleRef framework = NULL;
3892 if (framework == NULL)
3893 framework = CFBundleGetBundleWithIdentifier (CFSTR ("com.apple.opengl"));
3894 #define GGPA(n) (&state.n = CFBundleGetFunctionPointerForName (framework, CFSTR (#n)))
3895 #else
3896 #ifdef USE_EGL
3897 #define GGPA(n) (*(void (**) (void)) &state.n = eglGetProcAddress (#n))
3898 #else
3899 #define GGPA(n) (*(void (**) (void)) &state.n = glXGetProcAddress ((GLubyte *) #n))
3900 #endif
3901 state.bo_usable = GGPA (glBindBufferARB)
3902 && GGPA (glUnmapBufferARB)
3903 && GGPA (glMapBufferARB)
3904 && GGPA (glBufferDataARB)
3905 && GGPA (glGenBuffersARB)
3906 && GGPA (glDeleteBuffersARB);
3907 #endif
3908 #undef GGPA
3911 CAMLprim value ml_bo_usable (value unit_v)
3913 CAMLparam1 (unit_v);
3914 CAMLreturn (Val_bool (state.bo_usable));
3917 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
3919 CAMLparam3 (ptr_v, x_v, y_v);
3920 CAMLlocal2 (ret_v, tup_v);
3921 struct page *page;
3922 char *s = String_val (ptr_v);
3923 int x = Int_val (x_v), y = Int_val (y_v);
3924 struct pagedim *pdim;
3925 fz_point p;
3926 fz_matrix ctm;
3928 page = parse_pointer (__func__, s);
3929 pdim = &state.pagedims[page->pdimno];
3931 ret_v = Val_int (0);
3932 if (trylock (__func__)) {
3933 goto done;
3936 if (pdf_specifics (state.ctx, state.doc)) {
3937 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
3938 ctm = state.pagedims[page->pdimno].tctm;
3940 else {
3941 ctm = fz_identity;
3943 p.x = x + pdim->bounds.x0;
3944 p.y = y + pdim->bounds.y0;
3946 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
3947 fz_invert_matrix (&ctm, &ctm);
3948 fz_transform_point (&p, &ctm);
3950 tup_v = caml_alloc_tuple (2);
3951 ret_v = caml_alloc_small (1, 1);
3952 Field (tup_v, 0) = Val_int (p.x);
3953 Field (tup_v, 1) = Val_int (p.y);
3954 Field (ret_v, 0) = tup_v;
3956 unlock (__func__);
3957 done:
3958 CAMLreturn (ret_v);
3961 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
3962 value x_v, value y_v)
3964 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
3965 CAMLlocal1 (ret_v);
3966 struct page *page;
3967 char *s = String_val (ptr_v);
3968 int pageno = Int_val (pageno_v);
3969 int pdimno = Int_val (pdimno_v);
3970 float x = (float) Double_val (x_v), y = (float) Double_val (y_v);
3971 struct pagedim *pdim;
3972 fz_point p;
3973 fz_matrix ctm;
3975 ret_v = Val_int (0);
3976 lock (__func__);
3978 if (!*s) {
3979 page = loadpage (pageno, pdimno);
3981 else {
3982 page = parse_pointer (__func__, s);
3984 pdim = &state.pagedims[pdimno];
3986 if (pdf_specifics (state.ctx, state.doc)) {
3987 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
3988 ctm = state.pagedims[page->pdimno].tctm;
3990 else {
3991 ctm = fz_identity;
3993 p.x = x + pdim->bounds.x0;
3994 p.y = y + pdim->bounds.y0;
3996 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
3997 fz_transform_point (&p, &ctm);
3999 ret_v = caml_alloc_tuple (2);
4000 Field (ret_v, 0) = caml_copy_double ((double) p.x);
4001 Field (ret_v, 1) = caml_copy_double ((double) p.y);
4003 if (!*s) {
4004 freepage (page);
4006 unlock (__func__);
4007 CAMLreturn (ret_v);
4010 CAMLprim void ml_addannot (value ptr_v, value x_v, value y_v,
4011 value contents_v)
4013 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4014 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4016 if (pdf) {
4017 pdf_annot *annot;
4018 struct page *page;
4019 fz_point p;
4020 char *s = String_val (ptr_v);
4022 page = parse_pointer (__func__, s);
4023 annot = pdf_create_annot (state.ctx,
4024 pdf_page_from_fz_page (state.ctx,
4025 page->fzpage),
4026 PDF_ANNOT_TEXT);
4027 p.x = Int_val (x_v);
4028 p.y = Int_val (y_v);
4029 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
4030 pdf_set_text_annot_position (state.ctx, annot, p);
4031 state.dirty = 1;
4033 CAMLreturn0;
4036 CAMLprim void ml_delannot (value ptr_v, value n_v)
4038 CAMLparam2 (ptr_v, n_v);
4039 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4041 if (pdf) {
4042 struct page *page;
4043 char *s = String_val (ptr_v);
4044 struct slink *slink;
4046 page = parse_pointer (__func__, s);
4047 slink = &page->slinks[Int_val (n_v)];
4048 pdf_delete_annot (state.ctx,
4049 pdf_page_from_fz_page (state.ctx, page->fzpage),
4050 (pdf_annot *) slink->u.annot);
4051 state.dirty = 1;
4053 CAMLreturn0;
4056 CAMLprim void ml_modannot (value ptr_v, value n_v, value str_v)
4058 CAMLparam3 (ptr_v, n_v, str_v);
4059 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4061 if (pdf) {
4062 struct page *page;
4063 char *s = String_val (ptr_v);
4064 struct slink *slink;
4066 page = parse_pointer (__func__, s);
4067 slink = &page->slinks[Int_val (n_v)];
4068 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
4069 String_val (str_v));
4070 state.dirty = 1;
4072 CAMLreturn0;
4075 CAMLprim value ml_hasunsavedchanges (value unit_v)
4077 CAMLparam1 (unit_v);
4078 CAMLreturn (Val_bool (state.dirty));
4081 CAMLprim void ml_savedoc (value path_v)
4083 CAMLparam1 (path_v);
4084 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4086 if (pdf) {
4087 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
4089 CAMLreturn0;
4092 static void makestippletex (void)
4094 const char pixels[] = "\xff\xff\0\0";
4095 glGenTextures (1, &state.stid);
4096 glBindTexture (GL_TEXTURE_1D, state.stid);
4097 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4098 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4099 glTexImage1D (
4100 GL_TEXTURE_1D,
4102 GL_ALPHA,
4105 GL_ALPHA,
4106 GL_UNSIGNED_BYTE,
4107 pixels
4111 CAMLprim value ml_fz_version (void)
4113 return caml_copy_string (FZ_VERSION);
4116 CAMLprim value ml_llpp_version (void)
4118 extern char llpp_version[];
4119 return caml_copy_string (llpp_version);
4122 CAMLprim void ml_init (value csock_v, value params_v)
4124 CAMLparam2 (csock_v, params_v);
4125 CAMLlocal2 (trim_v, fuzz_v);
4126 int ret;
4127 int texcount;
4128 char *fontpath;
4129 int colorspace;
4130 int mustoresize;
4131 int haspboext;
4133 state.csock = Int_val (csock_v);
4134 state.rotate = Int_val (Field (params_v, 0));
4135 state.fitmodel = Int_val (Field (params_v, 1));
4136 trim_v = Field (params_v, 2);
4137 texcount = Int_val (Field (params_v, 3));
4138 state.sliceheight = Int_val (Field (params_v, 4));
4139 mustoresize = Int_val (Field (params_v, 5));
4140 colorspace = Int_val (Field (params_v, 6));
4141 fontpath = String_val (Field (params_v, 7));
4143 #ifdef __COCOA__
4144 state.utf8cs = 1;
4145 #else
4146 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html */
4147 if (setlocale (LC_CTYPE, "")) {
4148 const char *cset = nl_langinfo (CODESET);
4149 state.utf8cs = !strcmp (cset, "UTF-8");
4151 else {
4152 printd ("emsg setlocale: %d:%s", errno, strerror (errno));
4154 #endif
4156 if (caml_string_length (Field (params_v, 8)) > 0) {
4157 state.trimcachepath = ystrdup (String_val (Field (params_v, 8)));
4159 if (!state.trimcachepath) {
4160 printd ("emsg failed to strdup trimcachepath: %d:%s",
4161 errno, strerror (errno));
4165 haspboext = Bool_val (Field (params_v, 9));
4167 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4168 fz_register_document_handlers (state.ctx);
4170 state.trimmargins = Bool_val (Field (trim_v, 0));
4171 fuzz_v = Field (trim_v, 1);
4172 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4173 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4174 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4175 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4177 set_tex_params (colorspace);
4179 if (*fontpath) {
4180 state.face = load_font (fontpath);
4182 else {
4183 int len;
4184 const unsigned char *data;
4186 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
4187 state.face = load_builtin_font (data, len);
4189 if (!state.face) _exit (1);
4191 realloctexts (texcount);
4193 if (haspboext) {
4194 setuppbo ();
4197 makestippletex ();
4199 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4200 if (ret) {
4201 errx (1, "pthread_create: %s", strerror (ret));
4204 CAMLreturn0;
4207 #if FIXME || !FIXME
4208 static void UNUSED_ATTR NO_OPTIMIZE_ATTR refmacs (void) {}
4209 #endif