Real constency
[llpp.git] / link.c
blobed29719af7e707026ba2710c12b5f9504e5b0d50
1 /* lots of code c&p-ed directly from mupdf */
2 #define CAML_NAME_SPACE
4 #include <errno.h>
5 #include <stdio.h>
6 #include <ctype.h>
7 #include <string.h>
8 #include <stdlib.h>
9 #include <signal.h>
10 #include <wchar.h>
12 #include <unistd.h>
13 #include <pthread.h>
14 #include <sys/time.h>
15 #include <sys/types.h>
16 #include <sys/ioctl.h>
17 #include <sys/utsname.h>
19 #ifdef __CYGWIN__
20 #include <cygwin/socket.h> /* FIONREAD */
21 #else
22 #include <spawn.h>
23 #endif
25 #include <regex.h>
26 #include <stdarg.h>
27 #include <limits.h>
28 #include <inttypes.h>
30 #include <GL/gl.h>
32 #include <caml/fail.h>
33 #include <caml/alloc.h>
34 #include <caml/memory.h>
35 #include <caml/unixsupport.h>
37 #pragma GCC diagnostic push
38 #pragma GCC diagnostic ignored "-Wunused-parameter"
39 #include <mupdf/fitz.h>
40 #pragma GCC diagnostic pop
41 #include <mupdf/pdf.h>
43 #include <ft2build.h>
44 #include FT_FREETYPE_H
46 #ifdef USE_FONTCONFIG
47 #include <fontconfig/fontconfig.h>
48 #endif
50 #define PIGGYBACK
51 #define CACHE_PAGEREFS
53 #ifndef __USE_GNU
54 extern char **environ;
55 #endif
57 #define MIN(a,b) ((a) < (b) ? (a) : (b))
58 #define MAX(a,b) ((a) > (b) ? (a) : (b))
60 #if defined __GNUC__
61 #define NORETURN_ATTR __attribute__ ((noreturn))
62 #define UNUSED_ATTR __attribute__ ((unused))
63 #if !defined __clang__
64 #define OPTIMIZE_ATTR(n) __attribute__ ((optimize ("O"#n)))
65 #else
66 #define OPTIMIZE_ATTR(n)
67 #endif
68 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
69 #else
70 #define NORETURN_ATTR
71 #define UNUSED_ATTR
72 #define OPTIMIZE_ATTR(n)
73 #define GCC_FMT_ATTR(a, b)
74 #endif
76 #define FMT_s "zu"
78 #define FMT_ptr PRIxPTR
79 #define SCN_ptr SCNxPTR
80 #define FMT_ptr_cast(p) ((uintptr_t) (p))
81 #define SCN_ptr_cast(p) ((uintptr_t *) (p))
83 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
84 err (int exitcode, const char *fmt, ...)
86 va_list ap;
87 int savederrno;
89 savederrno = errno;
90 va_start (ap, fmt);
91 vfprintf (stderr, fmt, ap);
92 va_end (ap);
93 fprintf (stderr, ": %s\n", strerror (savederrno));
94 fflush (stderr);
95 _exit (exitcode);
98 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
99 errx (int exitcode, const char *fmt, ...)
101 va_list ap;
103 va_start (ap, fmt);
104 vfprintf (stderr, fmt, ap);
105 va_end (ap);
106 fputc ('\n', stderr);
107 fflush (stderr);
108 _exit (exitcode);
111 #ifndef GL_TEXTURE_RECTANGLE_ARB
112 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
113 #endif
115 #ifndef GL_BGRA
116 #define GL_BGRA 0x80E1
117 #endif
119 #ifndef GL_UNSIGNED_INT_8_8_8_8
120 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
121 #endif
123 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
124 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
125 #endif
127 #if 0
128 #define lprintf printf
129 #else
130 #define lprintf(...)
131 #endif
133 #define ARSERT(cond) for (;;) { \
134 if (!(cond)) { \
135 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
137 break; \
140 struct slice {
141 int h;
142 int texindex;
145 struct tile {
146 int w, h;
147 int slicecount;
148 int sliceheight;
149 struct pbo *pbo;
150 fz_pixmap *pixmap;
151 struct slice slices[1];
154 struct pagedim {
155 int pageno;
156 int rotate;
157 int left;
158 int tctmready;
159 fz_irect bounds;
160 fz_rect pagebox;
161 fz_rect mediabox;
162 fz_matrix ctm, zoomctm, lctm, tctm;
165 struct slink {
166 enum { SLINK, SANNOT } tag;
167 fz_irect bbox;
168 union {
169 fz_link *link;
170 fz_annot *annot;
171 } u;
174 struct annot {
175 fz_irect bbox;
176 fz_annot *annot;
179 struct page {
180 int tgen;
181 int sgen;
182 int agen;
183 int pageno;
184 int pdimno;
185 fz_text_page *text;
186 fz_text_sheet *sheet;
187 fz_page *fzpage;
188 fz_display_list *dlist;
189 int slinkcount;
190 struct slink *slinks;
191 int annotcount;
192 struct annot *annots;
193 struct mark {
194 int i;
195 fz_text_span *span;
196 } fmark, lmark;
199 struct {
200 int sliceheight;
201 struct pagedim *pagedims;
202 int pagecount;
203 int pagedimcount;
204 fz_document *doc;
205 fz_context *ctx;
206 int w, h;
208 int texindex;
209 int texcount;
210 GLuint *texids;
212 GLenum texiform;
213 GLenum texform;
214 GLenum texty;
216 fz_colorspace *colorspace;
218 struct {
219 int w, h;
220 struct slice *slice;
221 } *texowners;
223 int rotate;
224 enum { FitWidth, FitProportional, FitPage } fitmodel;
225 int trimmargins;
226 int needoutline;
227 int gen;
228 int aalevel;
230 int trimanew;
231 fz_irect trimfuzz;
232 fz_pixmap *pig;
234 pthread_t thread;
235 int csock;
236 FT_Face face;
238 char *trimcachepath;
239 int cxack;
240 int dirty;
242 GLuint stid;
244 int pbo_usable;
245 void (*glBindBufferARB) (GLenum, GLuint);
246 GLboolean (*glUnmapBufferARB) (GLenum);
247 void *(*glMapBufferARB) (GLenum, GLenum);
248 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
249 void (*glGenBuffersARB) (GLsizei, GLuint *);
250 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
252 GLfloat texcoords[8];
253 GLfloat vertices[16];
255 #ifdef CACHE_PAGEREFS
256 struct {
257 int idx;
258 int count;
259 pdf_obj **objs;
260 pdf_document *pdf;
261 } pdflut;
262 #endif
263 } state;
265 struct pbo {
266 GLuint id;
267 void *ptr;
268 size_t size;
271 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
273 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
276 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
278 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
281 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
283 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
284 m.a, m.b, m.c, m.d, m.e, m.f);
287 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
289 static void lock (const char *cap)
291 int ret = pthread_mutex_lock (&mutex);
292 if (ret) {
293 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
297 static void unlock (const char *cap)
299 int ret = pthread_mutex_unlock (&mutex);
300 if (ret) {
301 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
305 static int trylock (const char *cap)
307 int ret = pthread_mutex_trylock (&mutex);
308 if (ret && ret != EBUSY) {
309 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
311 return ret == EBUSY;
314 static void *parse_pointer (const char *cap, const char *s)
316 int ret;
317 void *ptr;
319 ret = sscanf (s, "%" SCN_ptr, SCN_ptr_cast (&ptr));
320 if (ret != 1) {
321 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
323 return ptr;
326 static double now (void)
328 struct timeval tv;
330 if (gettimeofday (&tv, NULL)) {
331 err (1, "gettimeofday");
333 return tv.tv_sec + tv.tv_usec*1e-6;
336 static int hasdata (void)
338 int ret, avail;
339 ret = ioctl (state.csock, FIONREAD, &avail);
340 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
341 return avail > 0;
344 CAMLprim value ml_hasdata (value fd_v)
346 CAMLparam1 (fd_v);
347 int ret, avail;
349 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
350 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
351 CAMLreturn (Val_bool (avail > 0));
354 static void readdata (void *p, int size)
356 ssize_t n;
358 again:
359 n = read (state.csock, p, size);
360 if (n < 0) {
361 if (errno == EINTR) goto again;
362 err (1, "read (req %d, ret %zd)", size, n);
364 if (n - size) {
365 if (!n) errx (1, "EOF while reading");
366 errx (1, "read (req %d, ret %zd)", size, n);
370 static void writedata (char *p, int size)
372 ssize_t n;
374 p[0] = (size >> 24) & 0xff;
375 p[1] = (size >> 16) & 0xff;
376 p[2] = (size >> 8) & 0xff;
377 p[3] = (size >> 0) & 0xff;
379 n = write (state.csock, p, size + 4);
380 if (n - size - 4) {
381 if (!n) errx (1, "EOF while writing data");
382 err (1, "write (req %d, ret %zd)", size + 4, n);
386 static int readlen (void)
388 unsigned char p[4];
390 readdata (p, 4);
391 return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
394 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
396 int size = 200, len;
397 va_list ap;
398 char *buf;
400 buf = malloc (size);
401 for (;;) {
402 if (!buf) err (1, "malloc for temp buf (%d bytes) failed", size);
404 va_start (ap, fmt);
405 len = vsnprintf (buf + 4, size - 4, fmt, ap);
406 va_end (ap);
408 if (len > -1) {
409 if (len < size - 4) {
410 writedata (buf, len);
411 break;
413 else size = len + 5;
415 else {
416 err (1, "vsnprintf for `%s' failed", fmt);
418 buf = realloc (buf, size);
420 free (buf);
423 static void closedoc (void)
425 #ifdef CACHE_PAGEREFS
426 if (state.pdflut.objs) {
427 int i;
429 for (i = 0; i < state.pdflut.count; ++i) {
430 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
432 free (state.pdflut.objs);
433 state.pdflut.objs = NULL;
434 state.pdflut.idx = 0;
436 #endif
437 if (state.doc) {
438 fz_drop_document (state.ctx, state.doc);
439 state.doc = NULL;
443 static int openxref (char *filename, char *password)
445 int i;
447 for (i = 0; i < state.texcount; ++i) {
448 state.texowners[i].w = -1;
449 state.texowners[i].slice = NULL;
452 closedoc ();
454 state.dirty = 0;
455 if (state.pagedims) {
456 free (state.pagedims);
457 state.pagedims = NULL;
459 state.pagedimcount = 0;
461 fz_set_aa_level (state.ctx, state.aalevel);
462 state.doc = fz_open_document (state.ctx, filename);
463 if (fz_needs_password (state.ctx, state.doc)) {
464 if (password && !*password) {
465 printd ("pass");
466 return 0;
468 else {
469 int ok = fz_authenticate_password (state.ctx, state.doc, password);
470 if (!ok) {
471 printd ("pass fail");
472 return 0;
476 state.pagecount = fz_count_pages (state.ctx, state.doc);
477 return 1;
480 static void pdfinfo (void)
482 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
483 if (pdf) {
484 pdf_obj *infoobj;
486 printd ("info PDF version\t%d.%d",
487 pdf->version / 10, pdf->version % 10);
489 infoobj = pdf_dict_gets (state.ctx, pdf_trailer (state.ctx,
490 pdf), "Info");
491 if (infoobj) {
492 unsigned int i;
493 char *s;
494 char *items[] = { "Title", "Author", "Creator",
495 "Producer", "CreationDate" };
497 for (i = 0; i < sizeof (items) / sizeof (*items); ++i) {
498 pdf_obj *obj = pdf_dict_gets (state.ctx, infoobj, items[i]);
499 s = pdf_to_utf8 (state.ctx, pdf, obj);
500 if (*s) printd ("info %s\t%s", items[i], s);
501 fz_free (state.ctx, s);
504 printd ("infoend");
508 static void unlinktile (struct tile *tile)
510 int i;
512 for (i = 0; i < tile->slicecount; ++i) {
513 struct slice *s = &tile->slices[i];
515 if (s->texindex != -1) {
516 if (state.texowners[s->texindex].slice == s) {
517 state.texowners[s->texindex].slice = NULL;
523 static void freepage (struct page *page)
525 if (!page) return;
526 if (page->text) {
527 fz_drop_text_page (state.ctx, page->text);
529 if (page->sheet) {
530 fz_drop_text_sheet (state.ctx, page->sheet);
532 if (page->slinks) {
533 free (page->slinks);
535 fz_drop_display_list (state.ctx, page->dlist);
536 fz_drop_page (state.ctx, page->fzpage);
537 free (page);
540 static void freetile (struct tile *tile)
542 unlinktile (tile);
543 if (!tile->pbo) {
544 #ifndef PIGGYBACK
545 fz_drop_pixmap (state.ctx, tile->pixmap);
546 #else
547 if (state.pig) {
548 fz_drop_pixmap (state.ctx, state.pig);
550 state.pig = tile->pixmap;
551 #endif
553 else {
554 free (tile->pbo);
555 fz_drop_pixmap (state.ctx, tile->pixmap);
557 free (tile);
560 #ifdef __ALTIVEC__
561 #include <stdint.h>
562 #include <altivec.h>
564 static int cacheline32bytes;
566 static void __attribute__ ((constructor)) clcheck (void)
568 char **envp = environ;
569 unsigned long *auxv;
571 while (*envp++);
573 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
574 if (*auxv == 19) {
575 cacheline32bytes = auxv[1] == 32;
576 return;
581 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
583 size_t size = pixmap->w * pixmap->h * pixmap->n;
584 if (cacheline32bytes && size > 32) {
585 intptr_t a1, a2, diff;
586 size_t sizea, i;
587 vector unsigned char v = vec_splat_u8 (-1);
588 vector unsigned char *p;
590 a1 = a2 = (intptr_t) pixmap->samples;
591 a2 = (a1 + 31) & ~31;
592 diff = a2 - a1;
593 sizea = size - diff;
594 p = (void *) a2;
596 while (a1 != a2) *(char *) a1++ = 0xff;
597 for (i = 0; i < (sizea & ~31); i += 32) {
598 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
599 vec_st (v, i, p);
600 vec_st (v, i + 16, p);
602 while (i < sizea) *((char *) a1 + i++) = 0xff;
604 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
606 #else
607 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
608 #endif
610 static void trimctm (pdf_page *page, int pindex)
612 fz_matrix ctm;
613 struct pagedim *pdim = &state.pagedims[pindex];
615 if (!pdim->tctmready) {
616 if (state.trimmargins) {
617 fz_rect realbox;
618 fz_matrix rm, sm, tm, im, ctm1;
620 fz_rotate (&rm, -pdim->rotate);
621 fz_scale (&sm, 1, -1);
622 fz_concat (&ctm, &rm, &sm);
623 realbox = pdim->mediabox;
624 fz_transform_rect (&realbox, &ctm);
625 fz_translate (&tm, -realbox.x0, -realbox.y0);
626 fz_concat (&ctm1, &ctm, &tm);
627 fz_invert_matrix (&im, &page->ctm);
628 fz_concat (&ctm, &im, &ctm1);
630 else {
631 ctm = fz_identity;
633 pdim->tctm = ctm;
634 pdim->tctmready = 1;
638 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
640 fz_matrix ctm, tm;
641 int pdimno = pdim - state.pagedims;
643 if (pdf_specifics (state.ctx, state.doc)) {
644 trimctm ((pdf_page *) fzpage, pdimno);
645 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
647 else {
648 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
649 fz_concat (&ctm, &tm, &pdim->ctm);
651 return ctm;
654 static fz_matrix pagectm (struct page *page)
656 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
659 static void *loadpage (int pageno, int pindex)
661 fz_device *dev;
662 struct page *page;
664 page = calloc (sizeof (struct page), 1);
665 if (!page) {
666 err (1, "calloc page %d", pageno);
669 page->dlist = fz_new_display_list (state.ctx);
670 dev = fz_new_list_device (state.ctx, page->dlist);
671 fz_try (state.ctx) {
672 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
673 fz_run_page (state.ctx, page->fzpage, dev,
674 &fz_identity, NULL);
676 fz_catch (state.ctx) {
677 page->fzpage = NULL;
679 fz_drop_device (state.ctx, dev);
681 page->pdimno = pindex;
682 page->pageno = pageno;
683 page->sgen = state.gen;
684 page->agen = state.gen;
685 page->tgen = state.gen;
686 return page;
689 static struct tile *alloctile (int h)
691 int i;
692 int slicecount;
693 size_t tilesize;
694 struct tile *tile;
696 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
697 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
698 tile = calloc (tilesize, 1);
699 if (!tile) {
700 err (1, "can not allocate tile (%" FMT_s " bytes)", tilesize);
702 for (i = 0; i < slicecount; ++i) {
703 int sh = MIN (h, state.sliceheight);
704 tile->slices[i].h = sh;
705 tile->slices[i].texindex = -1;
706 h -= sh;
708 tile->slicecount = slicecount;
709 tile->sliceheight = state.sliceheight;
710 return tile;
713 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
714 struct pbo *pbo)
716 fz_rect rect;
717 fz_irect bbox;
718 fz_matrix ctm;
719 fz_device *dev;
720 struct tile *tile;
721 struct pagedim *pdim;
723 tile = alloctile (h);
724 pdim = &state.pagedims[page->pdimno];
726 bbox = pdim->bounds;
727 bbox.x0 += x;
728 bbox.y0 += y;
729 bbox.x1 = bbox.x0 + w;
730 bbox.y1 = bbox.y0 + h;
732 if (state.pig) {
733 if (state.pig->w == w
734 && state.pig->h == h
735 && state.pig->colorspace == state.colorspace) {
736 tile->pixmap = state.pig;
737 tile->pixmap->x = bbox.x0;
738 tile->pixmap->y = bbox.y0;
740 else {
741 fz_drop_pixmap (state.ctx, state.pig);
743 state.pig = NULL;
745 if (!tile->pixmap) {
746 if (pbo) {
747 tile->pixmap =
748 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
749 &bbox, pbo->ptr);
750 tile->pbo = pbo;
752 else {
753 tile->pixmap =
754 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox);
758 tile->w = w;
759 tile->h = h;
760 clearpixmap (tile->pixmap);
762 dev = fz_new_draw_device (state.ctx, tile->pixmap);
763 ctm = pagectm (page);
764 fz_rect_from_irect (&rect, &bbox);
765 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
766 fz_drop_device (state.ctx, dev);
768 return tile;
771 #ifdef CACHE_PAGEREFS
772 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
773 thanks to Robin Watts */
774 static void
775 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
777 fz_context *ctx = state.ctx; /* doc->ctx; */
778 pdf_obj *kids;
779 int i, len;
781 if (state.pdflut.idx == state.pagecount) return;
783 kids = pdf_dict_gets (ctx, node, "Kids");
784 len = pdf_array_len (ctx, kids);
786 if (len == 0)
787 fz_throw (ctx, FZ_ERROR_GENERIC, "Malformed pages tree");
789 if (pdf_mark_obj (ctx, node))
790 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
791 for (i = 0; i < len; i++) {
792 pdf_obj *kid = pdf_array_get (ctx, kids, i);
793 char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
794 if (*type
795 ? !strcmp (type, "Pages")
796 : pdf_dict_gets (ctx, kid, "Kids")
797 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
798 pdf_collect_pages (doc, kid);
800 else {
801 if (*type
802 ? strcmp (type, "Page") != 0
803 : !pdf_dict_gets (ctx, kid, "MediaBox"))
804 fz_warn (ctx, "non-page object in page tree (%s)", type);
805 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
808 pdf_unmark_obj (ctx, node);
811 static void
812 pdf_load_page_objs (pdf_document *doc)
814 pdf_obj *root = pdf_dict_gets (state.ctx,
815 pdf_trailer (state.ctx, doc), "Root");
816 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
818 if (!node)
819 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
821 state.pdflut.idx = 0;
822 pdf_collect_pages (doc, node);
824 #endif
826 static void initpdims (void)
828 double start, end;
829 FILE *trimf = NULL;
830 fz_rect rootmediabox;
831 int pageno, trim, show;
832 int trimw = 0, cxcount;
833 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
835 start = now ();
837 if (state.trimmargins && state.trimcachepath) {
838 trimf = fopen (state.trimcachepath, "rb");
839 if (!trimf) {
840 trimf = fopen (state.trimcachepath, "wb");
841 trimw = 1;
845 if (state.trimmargins || pdf || !state.cxack)
846 cxcount = state.pagecount;
847 else
848 cxcount = MIN (state.pagecount, 1);
850 if (pdf) {
851 pdf_obj *obj;
852 obj = pdf_dict_getp (state.ctx, pdf_trailer (state.ctx, pdf),
853 "Root/Pages/MediaBox");
854 pdf_to_rect (state.ctx, obj, &rootmediabox);
857 #ifdef CACHE_PAGEREFS
858 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
859 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
860 if (!state.pdflut.objs) {
861 err (1, "malloc pageobjs %zu %d %zu failed",
862 sizeof (*state.pdflut.objs), cxcount,
863 sizeof (*state.pdflut.objs) * cxcount);
865 state.pdflut.count = cxcount;
866 pdf_load_page_objs (pdf);
867 state.pdflut.pdf = pdf;
869 #endif
871 for (pageno = 0; pageno < cxcount; ++pageno) {
872 int rotate = 0;
873 struct pagedim *p;
874 fz_rect mediabox;
876 if (pdf) {
877 pdf_obj *pageref, *pageobj;
879 #ifdef CACHE_PAGEREFS
880 pageref = state.pdflut.objs[pageno];
881 #else
882 pageref = pdf_lookup_page_obj (state.ctx, pdf, pageno);
883 #endif
884 pageobj = pdf_resolve_indirect (state.ctx, pageref);
886 if (state.trimmargins) {
887 fz_context *ctx = state.ctx;
888 pdf_obj *obj;
889 pdf_page *page;
891 fz_try (state.ctx) {
892 page = pdf_load_page (ctx, pdf, pageno);
893 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
894 trim = state.trimanew || !obj;
895 if (trim) {
896 fz_rect rect;
897 fz_matrix ctm;
898 fz_device *dev;
900 dev = fz_new_bbox_device (ctx, &rect);
901 dev->hints |= FZ_IGNORE_SHADE;
902 fz_invert_matrix (&ctm, &page->ctm);
903 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
904 fz_drop_device (ctx, dev);
906 rect.x0 += state.trimfuzz.x0;
907 rect.x1 += state.trimfuzz.x1;
908 rect.y0 += state.trimfuzz.y0;
909 rect.y1 += state.trimfuzz.y1;
910 fz_transform_rect (&rect, &ctm);
911 fz_intersect_rect (&rect, &page->mediabox);
913 if (fz_is_empty_rect (&rect)) {
914 mediabox = page->mediabox;
916 else {
917 mediabox = rect;
920 obj = pdf_new_array (ctx, pdf, 4);
921 pdf_array_push (ctx, obj, pdf_new_real (state.ctx, pdf,
922 mediabox.x0));
923 pdf_array_push (ctx, obj, pdf_new_real (state.ctx, pdf,
924 mediabox.y0));
925 pdf_array_push (ctx, obj, pdf_new_real (state.ctx, pdf,
926 mediabox.x1));
927 pdf_array_push (ctx, obj, pdf_new_real (state.ctx, pdf,
928 mediabox.y1));
929 pdf_dict_puts (state.ctx, pageobj, "llpp.TrimBox", obj);
931 else {
932 mediabox.x0 = pdf_to_real (ctx,
933 pdf_array_get (ctx, obj, 0));
934 mediabox.y0 = pdf_to_real (ctx,
935 pdf_array_get (ctx, obj, 1));
936 mediabox.x1 = pdf_to_real (ctx,
937 pdf_array_get (ctx, obj, 2));
938 mediabox.y1 = pdf_to_real (ctx,
939 pdf_array_get (ctx, obj, 3));
942 rotate = page->rotate;
943 fz_drop_page (ctx, &page->super);
945 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
946 if (show) {
947 printd ("progress %f Trimming %d",
948 (double) (pageno + 1) / state.pagecount,
949 pageno + 1);
952 fz_catch (state.ctx) {
953 fprintf (stderr, "failed to load page %d\n", pageno+1);
956 else {
957 int empty = 0;
958 fz_rect cropbox;
960 pdf_to_rect (state.ctx,
961 pdf_dict_gets (state.ctx, pageobj, "MediaBox"),
962 &mediabox);
963 if (fz_is_empty_rect (&mediabox)) {
964 mediabox.x0 = 0;
965 mediabox.y0 = 0;
966 mediabox.x1 = 612;
967 mediabox.y1 = 792;
968 empty = 1;
971 pdf_to_rect (state.ctx,
972 pdf_dict_gets (state.ctx, pageobj, "CropBox"),
973 &cropbox);
974 if (!fz_is_empty_rect (&cropbox)) {
975 if (empty) {
976 mediabox = cropbox;
978 else {
979 fz_intersect_rect (&mediabox, &cropbox);
982 else {
983 if (empty) {
984 if (fz_is_empty_rect (&rootmediabox)) {
985 fprintf (stderr,
986 "cannot find page size for page %d\n",
987 pageno+1);
989 else {
990 mediabox = rootmediabox;
994 rotate = pdf_to_int (state.ctx,
995 pdf_dict_gets (state.ctx,
996 pageobj, "Rotate"));
999 else {
1000 if (state.trimmargins && trimw) {
1001 fz_page *page;
1003 fz_try (state.ctx) {
1004 page = fz_load_page (state.ctx, state.doc, pageno);
1005 fz_bound_page (state.ctx, page, &mediabox);
1006 rotate = 0;
1007 if (state.trimmargins) {
1008 fz_rect rect;
1009 fz_device *dev;
1011 dev = fz_new_bbox_device (state.ctx, &rect);
1012 dev->hints |= FZ_IGNORE_SHADE;
1013 fz_run_page (state.ctx, page, dev,
1014 &fz_identity, NULL);
1015 fz_drop_device (state.ctx, dev);
1017 rect.x0 += state.trimfuzz.x0;
1018 rect.x1 += state.trimfuzz.x1;
1019 rect.y0 += state.trimfuzz.y0;
1020 rect.y1 += state.trimfuzz.y1;
1021 fz_intersect_rect (&rect, &mediabox);
1023 if (!fz_is_empty_rect (&rect)) {
1024 mediabox = rect;
1027 fz_drop_page (state.ctx, page);
1028 if (!state.cxack) {
1029 printd ("progress %f loading %d",
1030 (double) (pageno + 1) / state.pagecount,
1031 pageno + 1);
1034 fz_catch (state.ctx) {
1036 if (trimf) {
1037 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1038 if (n - 1) {
1039 err (1, "fwrite trim mediabox");
1043 else {
1044 if (trimf) {
1045 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1046 if (n - 1) {
1047 err (1, "fread trim mediabox %d", pageno);
1050 else {
1051 fz_page *page;
1052 fz_try (state.ctx) {
1053 page = fz_load_page (state.ctx,
1054 state.doc, pageno);
1055 fz_bound_page (state.ctx, page, &mediabox);
1056 fz_drop_page (state.ctx, page);
1058 show = !state.trimmargins && pageno % 20 == 0;
1059 if (show) {
1060 printd ("progress %f Gathering dimensions %d",
1061 (double) (pageno) / state.pagecount,
1062 pageno);
1065 fz_catch (state.ctx) {
1066 fprintf (stderr, "failed to load page %d\n", pageno);
1072 if (state.pagedimcount == 0
1073 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1074 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1075 size_t size;
1077 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1078 state.pagedims = realloc (state.pagedims, size);
1079 if (!state.pagedims) {
1080 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1081 size, state.pagedimcount + 1);
1084 p = &state.pagedims[state.pagedimcount++];
1085 p->rotate = rotate;
1086 p->mediabox = mediabox;
1087 p->pageno = pageno;
1090 end = now ();
1091 if (state.trimmargins) {
1092 printd ("progress 1 Trimmed %d pages in %f seconds",
1093 state.pagecount, end - start);
1095 else {
1096 printd ("progress 1 Processed %d pages in %f seconds\n",
1097 state.pagecount, end - start);
1099 state.trimanew = 0;
1100 if (trimf) {
1101 if (fclose (trimf)) {
1102 err (1, "fclose");
1107 static void layout (void)
1109 int pindex;
1110 fz_rect box;
1111 fz_matrix ctm, rm;
1112 struct pagedim *p = p;
1113 double zw, w, maxw = 0.0, zoom = zoom;
1115 if (state.pagedimcount == 0) return;
1117 switch (state.fitmodel) {
1118 case FitProportional:
1119 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1120 double x0, x1;
1122 p = &state.pagedims[pindex];
1123 fz_rotate (&rm, p->rotate + state.rotate);
1124 box = p->mediabox;
1125 fz_transform_rect (&box, &rm);
1127 x0 = MIN (box.x0, box.x1);
1128 x1 = MAX (box.x0, box.x1);
1130 w = x1 - x0;
1131 maxw = MAX (w, maxw);
1132 zoom = state.w / maxw;
1134 break;
1136 case FitPage:
1137 maxw = state.w;
1138 break;
1140 case FitWidth:
1141 break;
1143 default:
1144 ARSERT (0 && state.fitmodel);
1147 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1148 fz_rect rect;
1149 fz_matrix tm, sm;
1151 p = &state.pagedims[pindex];
1152 fz_rotate (&ctm, state.rotate);
1153 fz_rotate (&rm, p->rotate + state.rotate);
1154 box = p->mediabox;
1155 fz_transform_rect (&box, &rm);
1156 w = box.x1 - box.x0;
1157 switch (state.fitmodel) {
1158 case FitProportional:
1159 p->left = ((maxw - w) * zoom) / 2.0;
1160 break;
1161 case FitPage:
1163 double zh, h;
1164 zw = maxw / w;
1165 h = box.y1 - box.y0;
1166 zh = state.h / h;
1167 zoom = MIN (zw, zh);
1168 p->left = (maxw - (w * zoom)) / 2.0;
1170 break;
1171 case FitWidth:
1172 p->left = 0;
1173 zoom = state.w / w;
1174 break;
1177 fz_scale (&p->zoomctm, zoom, zoom);
1178 fz_concat (&ctm, &p->zoomctm, &ctm);
1180 fz_rotate (&rm, p->rotate);
1181 p->pagebox = p->mediabox;
1182 fz_transform_rect (&p->pagebox, &rm);
1183 p->pagebox.x1 -= p->pagebox.x0;
1184 p->pagebox.y1 -= p->pagebox.y0;
1185 p->pagebox.x0 = 0;
1186 p->pagebox.y0 = 0;
1187 rect = p->pagebox;
1188 fz_transform_rect (&rect, &ctm);
1189 fz_round_rect (&p->bounds, &rect);
1190 p->ctm = ctm;
1192 fz_translate (&tm, 0, -p->mediabox.y1);
1193 fz_scale (&sm, zoom, -zoom);
1194 fz_concat (&ctm, &tm, &sm);
1195 fz_concat (&p->lctm, &ctm, &rm);
1197 p->tctmready = 0;
1200 do {
1201 int x0 = MIN (p->bounds.x0, p->bounds.x1);
1202 int y0 = MIN (p->bounds.y0, p->bounds.y1);
1203 int x1 = MAX (p->bounds.x0, p->bounds.x1);
1204 int y1 = MAX (p->bounds.y0, p->bounds.y1);
1205 int boundw = x1 - x0;
1206 int boundh = y1 - y0;
1208 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1209 } while (p-- != state.pagedims);
1212 static
1213 struct anchor { int n; int x; int y; int w; int h; }
1214 desttoanchor (fz_link_dest *dest)
1216 int i;
1217 struct anchor a;
1218 struct pagedim *pdim = state.pagedims;
1220 a.n = -1;
1221 a.x = 0;
1222 a.y = 0;
1223 for (i = 0; i < state.pagedimcount; ++i) {
1224 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1225 break;
1226 pdim = &state.pagedims[i];
1228 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1229 fz_point p;
1230 if (dest->ld.gotor.flags & fz_link_flag_l_valid)
1231 p.x = dest->ld.gotor.lt.x;
1232 else
1233 p.x = 0.0;
1234 p.y = dest->ld.gotor.lt.y;
1235 fz_transform_point (&p, &pdim->lctm);
1236 a.x = p.x;
1237 a.y = p.y;
1239 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1240 double x0, x1, y0, y1;
1242 x0 = MIN (pdim->bounds.x0, pdim->bounds.x1);
1243 x1 = MAX (pdim->bounds.x0, pdim->bounds.x1);
1244 a.w = x1 - x0;
1245 y0 = MIN (pdim->bounds.y0, pdim->bounds.y1);
1246 y1 = MAX (pdim->bounds.y0, pdim->bounds.y1);
1247 a.h = y1 - y0;
1248 a.n = dest->ld.gotor.page;
1250 return a;
1253 static void recurse_outline (fz_outline *outline, int level)
1255 while (outline) {
1256 switch (outline->dest.kind) {
1257 case FZ_LINK_GOTO:
1259 struct anchor a = desttoanchor (&outline->dest);
1261 if (a.n >= 0) {
1262 printd ("o %d %d %d %d %s",
1263 level, a.n, a.y, a.h, outline->title);
1266 break;
1268 case FZ_LINK_URI:
1269 printd ("ou %d %" FMT_s " %s %s", level,
1270 strlen (outline->title), outline->title,
1271 outline->dest.ld.uri.uri);
1272 break;
1274 case FZ_LINK_NONE:
1275 printd ("on %d %s", level, outline->title);
1276 break;
1278 default:
1279 printd ("emsg Unhandled outline kind %d for %s\n",
1280 outline->dest.kind, outline->title);
1281 break;
1283 if (outline->down) {
1284 recurse_outline (outline->down, level + 1);
1286 outline = outline->next;
1290 static void process_outline (void)
1292 fz_outline *outline;
1294 if (!state.needoutline || !state.pagedimcount) return;
1296 state.needoutline = 0;
1297 outline = fz_load_outline (state.ctx, state.doc);
1298 if (outline) {
1299 recurse_outline (outline, 0);
1300 fz_drop_outline (state.ctx, outline);
1304 static char *strofspan (fz_text_span *span)
1306 char *p;
1307 char utf8[10];
1308 fz_text_char *ch;
1309 size_t size = 0, cap = 80;
1311 p = malloc (cap + 1);
1312 if (!p) return NULL;
1314 for (ch = span->text; ch < span->text + span->len; ++ch) {
1315 int n = fz_runetochar (utf8, ch->c);
1316 if (size + n > cap) {
1317 cap *= 2;
1318 p = realloc (p, cap + 1);
1319 if (!p) return NULL;
1322 memcpy (p + size, utf8, n);
1323 size += n;
1325 p[size] = 0;
1326 return p;
1329 static int matchspan (regex_t *re, fz_text_span *span,
1330 int stop, int pageno, double start)
1332 int ret;
1333 char *p;
1334 regmatch_t rm;
1335 int a, b, c;
1336 fz_rect sb, eb;
1337 fz_point p1, p2, p3, p4;
1339 p = strofspan (span);
1340 if (!p) return -1;
1342 ret = regexec (re, p, 1, &rm, 0);
1343 if (ret) {
1344 free (p);
1345 if (ret != REG_NOMATCH) {
1346 size_t size;
1347 char errbuf[80];
1348 size = regerror (ret, re, errbuf, sizeof (errbuf));
1349 printd ("msg regexec error `%.*s'",
1350 (int) size, errbuf);
1351 return -1;
1353 return 0;
1355 else {
1356 int l = span->len;
1358 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1359 c += fz_runelen (span->text[a].c);
1361 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1362 c += fz_runelen (span->text[b].c);
1365 if (fz_runelen (span->text[b].c) > 1) {
1366 b = MAX (0, b-1);
1369 fz_text_char_bbox (state.ctx, &sb, span, a);
1370 fz_text_char_bbox (state.ctx, &eb, span, b);
1372 p1.x = sb.x0;
1373 p1.y = sb.y0;
1374 p2.x = eb.x1;
1375 p2.y = sb.y0;
1376 p3.x = eb.x1;
1377 p3.y = eb.y1;
1378 p4.x = sb.x0;
1379 p4.y = eb.y1;
1381 if (!stop) {
1382 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1383 pageno, 1,
1384 p1.x, p1.y,
1385 p2.x, p2.y,
1386 p3.x, p3.y,
1387 p4.x, p4.y);
1389 printd ("progress 1 found at %d `%.*s' in %f sec",
1390 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1391 now () - start);
1393 else {
1394 printd ("match %d %d %f %f %f %f %f %f %f %f",
1395 pageno, 2,
1396 p1.x, p1.y,
1397 p2.x, p2.y,
1398 p3.x, p3.y,
1399 p4.x, p4.y);
1401 free (p);
1402 return 1;
1406 static int compareblocks (const void *l, const void *r)
1408 fz_text_block const *ls = l;
1409 fz_text_block const* rs = r;
1410 return ls->bbox.y0 - rs->bbox.y0;
1413 /* wishful thinking function */
1414 static void search (regex_t *re, int pageno, int y, int forward)
1416 int i, j;
1417 fz_device *tdev;
1418 fz_text_page *text;
1419 fz_text_sheet *sheet;
1420 struct pagedim *pdim, *pdimprev;
1421 int stop = 0, niters = 0;
1422 double start, end;
1423 fz_page *page;
1425 start = now ();
1426 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1427 if (niters++ == 5) {
1428 niters = 0;
1429 if (hasdata ()) {
1430 printd ("progress 1 attention requested aborting search at %d",
1431 pageno);
1432 stop = 1;
1434 else {
1435 printd ("progress %f searching in page %d",
1436 (double) (pageno + 1) / state.pagecount,
1437 pageno);
1440 pdimprev = NULL;
1441 for (i = 0; i < state.pagedimcount; ++i) {
1442 pdim = &state.pagedims[i];
1443 if (pdim->pageno == pageno) {
1444 goto found;
1446 if (pdim->pageno > pageno) {
1447 pdim = pdimprev;
1448 goto found;
1450 pdimprev = pdim;
1452 pdim = pdimprev;
1453 found:
1455 sheet = fz_new_text_sheet (state.ctx);
1456 text = fz_new_text_page (state.ctx);
1457 tdev = fz_new_text_device (state.ctx, sheet, text);
1459 page = fz_load_page (state.ctx, state.doc, pageno);
1461 fz_matrix ctm = pagectm1 (page, pdim);
1462 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1465 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1466 fz_drop_device (state.ctx, tdev);
1468 for (j = 0; j < text->len; ++j) {
1469 int k;
1470 fz_page_block *pb;
1471 fz_text_block *block;
1473 pb = &text->blocks[forward ? j : text->len - 1 - j];
1474 if (pb->type != FZ_PAGE_BLOCK_TEXT) continue;
1475 block = pb->u.text;
1477 for (k = 0; k < block->len; ++k) {
1478 fz_text_line *line;
1479 fz_text_span *span;
1481 if (forward) {
1482 line = &block->lines[k];
1483 if (line->bbox.y0 < y + 1) continue;
1485 else {
1486 line = &block->lines[block->len - 1 - k];
1487 if (line->bbox.y0 > y - 1) continue;
1490 for (span = line->first_span; span; span = span->next) {
1491 switch (matchspan (re, span, stop, pageno, start)) {
1492 case 0: break;
1493 case 1: stop = 1; break;
1494 case -1: stop = 1; goto endloop;
1499 if (forward) {
1500 pageno += 1;
1501 y = 0;
1503 else {
1504 pageno -= 1;
1505 y = INT_MAX;
1507 endloop:
1508 fz_drop_text_page (state.ctx, text);
1509 fz_drop_text_sheet (state.ctx, sheet);
1510 fz_drop_page (state.ctx, page);
1512 end = now ();
1513 if (!stop) {
1514 printd ("progress 1 no matches %f sec", end - start);
1516 printd ("clearrects");
1519 static void set_tex_params (int colorspace)
1521 union {
1522 unsigned char b;
1523 unsigned int s;
1524 } endianness = {1};
1526 switch (colorspace) {
1527 case 0:
1528 state.texiform = GL_RGBA8;
1529 state.texform = GL_RGBA;
1530 state.texty = GL_UNSIGNED_BYTE;
1531 state.colorspace = fz_device_rgb (state.ctx);
1532 break;
1533 case 1:
1534 state.texiform = GL_RGBA8;
1535 state.texform = GL_BGRA;
1536 state.texty = endianness.s > 1
1537 ? GL_UNSIGNED_INT_8_8_8_8
1538 : GL_UNSIGNED_INT_8_8_8_8_REV;
1539 state.colorspace = fz_device_bgr (state.ctx);
1540 break;
1541 case 2:
1542 state.texiform = GL_LUMINANCE_ALPHA;
1543 state.texform = GL_LUMINANCE_ALPHA;
1544 state.texty = GL_UNSIGNED_BYTE;
1545 state.colorspace = fz_device_gray (state.ctx);
1546 break;
1547 default:
1548 errx (1, "invalid colorspce %d", colorspace);
1552 static void realloctexts (int texcount)
1554 size_t size;
1556 if (texcount == state.texcount) return;
1558 if (texcount < state.texcount) {
1559 glDeleteTextures (state.texcount - texcount,
1560 state.texids + texcount);
1563 size = texcount * sizeof (*state.texids);
1564 state.texids = realloc (state.texids, size);
1565 if (!state.texids) {
1566 err (1, "realloc texids %" FMT_s, size);
1569 size = texcount * sizeof (*state.texowners);
1570 state.texowners = realloc (state.texowners, size);
1571 if (!state.texowners) {
1572 err (1, "realloc texowners %" FMT_s, size);
1574 if (texcount > state.texcount) {
1575 int i;
1577 glGenTextures (texcount - state.texcount,
1578 state.texids + state.texcount);
1579 for (i = state.texcount; i < texcount; ++i) {
1580 state.texowners[i].w = -1;
1581 state.texowners[i].slice = NULL;
1584 state.texcount = texcount;
1585 state.texindex = 0;
1588 static char *mbtoutf8 (char *s)
1590 char *p, *r;
1591 wchar_t *tmp;
1592 size_t i, ret, len;
1594 len = mbstowcs (NULL, s, strlen (s));
1595 if (len == 0) {
1596 return s;
1598 else {
1599 if (len == (size_t) -1) {
1600 return s;
1604 tmp = malloc (len * sizeof (wchar_t));
1605 if (!tmp) {
1606 return s;
1609 ret = mbstowcs (tmp, s, len);
1610 if (ret == (size_t) -1) {
1611 free (tmp);
1612 return s;
1615 len = 0;
1616 for (i = 0; i < ret; ++i) {
1617 len += fz_runelen (tmp[i]);
1620 p = r = malloc (len + 1);
1621 if (!r) {
1622 free (tmp);
1623 return s;
1626 for (i = 0; i < ret; ++i) {
1627 p += fz_runetochar (p, tmp[i]);
1629 *p = 0;
1630 free (tmp);
1631 return r;
1634 CAMLprim value ml_mbtoutf8 (value s_v)
1636 CAMLparam1 (s_v);
1637 CAMLlocal1 (ret_v);
1638 char *s, *r;
1640 s = String_val (s_v);
1641 r = mbtoutf8 (s);
1642 if (r == s) {
1643 ret_v = s_v;
1645 else {
1646 ret_v = caml_copy_string (r);
1647 free (r);
1649 CAMLreturn (ret_v);
1652 static void * mainloop (void UNUSED_ATTR *unused)
1654 char *p = NULL;
1655 int len, ret, oldlen = 0;
1657 for (;;) {
1658 len = readlen ();
1659 if (len == 0) {
1660 errx (1, "readlen returned 0");
1663 if (oldlen < len + 1) {
1664 p = realloc (p, len + 1);
1665 if (!p) {
1666 err (1, "realloc %d failed", len + 1);
1668 oldlen = len + 1;
1670 readdata (p, len);
1671 p[len] = 0;
1673 if (!strncmp ("open", p, 4)) {
1674 int wthack, off, ok = 0;
1675 char *password;
1676 char *filename;
1677 char *utf8filename;
1678 size_t filenamelen;
1680 ret = sscanf (p + 5, " %d %d %n", &wthack, &state.cxack, &off);
1681 if (ret != 2) {
1682 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1685 filename = p + 5 + off;
1686 filenamelen = strlen (filename);
1687 password = filename + filenamelen + 1;
1689 lock ("open");
1690 fz_try (state.ctx) {
1691 ok = openxref (filename, password);
1693 fz_catch (state.ctx) {
1694 utf8filename = mbtoutf8 (filename);
1695 printd ("msg Could not open %s", utf8filename);
1697 if (ok) {
1698 pdfinfo ();
1699 initpdims ();
1701 unlock ("open");
1703 if (ok) {
1704 if (!wthack) {
1705 utf8filename = mbtoutf8 (filename);
1706 printd ("msg Opened %s (press h/F1 to get help)",
1707 utf8filename);
1708 if (utf8filename != filename) {
1709 free (utf8filename);
1712 state.needoutline = 1;
1715 else if (!strncmp ("cs", p, 2)) {
1716 int i, colorspace;
1718 ret = sscanf (p + 2, " %d", &colorspace);
1719 if (ret != 1) {
1720 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1722 lock ("cs");
1723 set_tex_params (colorspace);
1724 for (i = 0; i < state.texcount; ++i) {
1725 state.texowners[i].w = -1;
1726 state.texowners[i].slice = NULL;
1728 unlock ("cs");
1730 else if (!strncmp ("freepage", p, 8)) {
1731 void *ptr;
1733 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1734 if (ret != 1) {
1735 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1737 freepage (ptr);
1739 else if (!strncmp ("freetile", p, 8)) {
1740 void *ptr;
1742 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1743 if (ret != 1) {
1744 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1746 freetile (ptr);
1748 else if (!strncmp ("search", p, 6)) {
1749 int icase, pageno, y, len2, forward;
1750 char *pattern;
1751 regex_t re;
1753 ret = sscanf (p + 6, " %d %d %d %d,%n",
1754 &icase, &pageno, &y, &forward, &len2);
1755 if (ret != 4) {
1756 errx (1, "malformed search `%s' ret=%d", p, ret);
1759 pattern = p + 6 + len2;
1760 ret = regcomp (&re, pattern,
1761 REG_EXTENDED | (icase ? REG_ICASE : 0));
1762 if (ret) {
1763 char errbuf[80];
1764 size_t size;
1766 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1767 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1769 else {
1770 search (&re, pageno, y, forward);
1771 regfree (&re);
1774 else if (!strncmp ("geometry", p, 8)) {
1775 int w, h, fitmodel;
1777 printd ("clear");
1778 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1779 if (ret != 3) {
1780 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1783 lock ("geometry");
1784 state.h = h;
1785 if (w != state.w) {
1786 int i;
1787 state.w = w;
1788 for (i = 0; i < state.texcount; ++i) {
1789 state.texowners[i].slice = NULL;
1792 state.fitmodel = fitmodel;
1793 layout ();
1794 process_outline ();
1796 state.gen++;
1797 unlock ("geometry");
1798 printd ("continue %d", state.pagecount);
1800 else if (!strncmp ("reqlayout", p, 9)) {
1801 char *nameddest;
1802 int rotate, off, h;
1803 unsigned int fitmodel;
1804 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
1806 printd ("clear");
1807 ret = sscanf (p + 9, " %d %u %d %n",
1808 &rotate, &fitmodel, &h, &off);
1809 if (ret != 3) {
1810 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1812 lock ("reqlayout");
1813 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1814 state.gen += 1;
1816 state.rotate = rotate;
1817 state.fitmodel = fitmodel;
1818 state.h = h;
1819 layout ();
1820 process_outline ();
1822 nameddest = p + 9 + off;
1823 if (pdf && nameddest && *nameddest) {
1824 struct anchor a;
1825 fz_link_dest dest;
1826 pdf_obj *needle, *obj;
1828 needle = pdf_new_string (state.ctx, pdf, nameddest,
1829 strlen (nameddest));
1830 obj = pdf_lookup_dest (state.ctx, pdf, needle);
1831 if (obj) {
1832 dest = pdf_parse_link_dest (state.ctx, pdf,
1833 FZ_LINK_GOTO, obj);
1835 a = desttoanchor (&dest);
1836 if (a.n >= 0) {
1837 printd ("a %d %d %d", a.n, a.x, a.y);
1839 else {
1840 printd ("emsg failed to parse destination `%s'\n",
1841 nameddest);
1844 else {
1845 printd ("emsg destination `%s' not found\n",
1846 nameddest);
1848 pdf_drop_obj (state.ctx, needle);
1851 state.gen++;
1852 unlock ("reqlayout");
1853 printd ("continue %d", state.pagecount);
1855 else if (!strncmp ("page", p, 4)) {
1856 double a, b;
1857 struct page *page;
1858 int pageno, pindex;
1860 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1861 if (ret != 2) {
1862 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1865 lock ("page");
1866 a = now ();
1867 page = loadpage (pageno, pindex);
1868 b = now ();
1869 unlock ("page");
1871 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1873 else if (!strncmp ("tile", p, 4)) {
1874 int x, y, w, h;
1875 struct page *page;
1876 struct tile *tile;
1877 double a, b;
1878 void *data;
1880 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1881 SCN_ptr_cast (&page), &x, &y, &w, &h,
1882 SCN_ptr_cast (&data));
1883 if (ret != 6) {
1884 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1887 lock ("tile");
1888 a = now ();
1889 tile = rendertile (page, x, y, w, h, data);
1890 b = now ();
1891 unlock ("tile");
1893 printd ("tile %d %d %" FMT_ptr " %u %f",
1894 x, y,
1895 FMT_ptr_cast (tile),
1896 tile->w * tile->h * tile->pixmap->n,
1897 b - a);
1899 else if (!strncmp ("trimset", p, 7)) {
1900 fz_irect fuzz;
1901 int trimmargins;
1903 ret = sscanf (p + 7, " %d %d %d %d %d",
1904 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1905 if (ret != 5) {
1906 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1908 lock ("trimset");
1909 state.trimmargins = trimmargins;
1910 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1911 state.trimanew = 1;
1912 state.trimfuzz = fuzz;
1914 unlock ("trimset");
1916 else if (!strncmp ("settrim", p, 7)) {
1917 fz_irect fuzz;
1918 int trimmargins;
1920 ret = sscanf (p + 7, " %d %d %d %d %d",
1921 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1922 if (ret != 5) {
1923 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1925 printd ("clear");
1926 lock ("settrim");
1927 state.trimmargins = trimmargins;
1928 state.needoutline = 1;
1929 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1930 state.trimanew = 1;
1931 state.trimfuzz = fuzz;
1933 state.pagedimcount = 0;
1934 free (state.pagedims);
1935 state.pagedims = NULL;
1936 initpdims ();
1937 layout ();
1938 process_outline ();
1939 unlock ("settrim");
1940 printd ("continue %d", state.pagecount);
1942 else if (!strncmp ("sliceh", p, 6)) {
1943 int h;
1945 ret = sscanf (p + 6, " %d", &h);
1946 if (ret != 1) {
1947 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1949 if (h != state.sliceheight) {
1950 int i;
1952 state.sliceheight = h;
1953 for (i = 0; i < state.texcount; ++i) {
1954 state.texowners[i].w = -1;
1955 state.texowners[i].h = -1;
1956 state.texowners[i].slice = NULL;
1960 else if (!strncmp ("interrupt", p, 9)) {
1961 printd ("vmsg interrupted");
1963 else {
1964 errx (1, "unknown command %.*s", len, p);
1967 return 0;
1970 CAMLprim value ml_realloctexts (value texcount_v)
1972 CAMLparam1 (texcount_v);
1973 int ok;
1975 if (trylock ("ml_realloctexts")) {
1976 ok = 0;
1977 goto done;
1979 realloctexts (Int_val (texcount_v));
1980 ok = 1;
1981 unlock ("ml_realloctexts");
1983 done:
1984 CAMLreturn (Val_bool (ok));
1987 static void recti (int x0, int y0, int x1, int y1)
1989 GLfloat *v = state.vertices;
1991 glVertexPointer (2, GL_FLOAT, 0, v);
1992 v[0] = x0; v[1] = y0;
1993 v[2] = x1; v[3] = y0;
1994 v[4] = x0; v[5] = y1;
1995 v[6] = x1; v[7] = y1;
1996 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1999 static void showsel (struct page *page, int ox, int oy)
2001 int seen = 0;
2002 fz_irect bbox;
2003 fz_rect rect;
2004 fz_text_line *line;
2005 fz_page_block *pageb;
2006 fz_text_block *block;
2007 struct mark first, last;
2008 unsigned char selcolor[] = {15,15,15,140};
2010 first = page->fmark;
2011 last = page->lmark;
2013 if (!first.span || !last.span) return;
2015 glEnable (GL_BLEND);
2016 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2017 glColor4ubv (selcolor);
2019 ox += state.pagedims[page->pdimno].bounds.x0;
2020 oy += state.pagedims[page->pdimno].bounds.y0;
2021 for (pageb = page->text->blocks;
2022 pageb < page->text->blocks + page->text->len;
2023 ++pageb) {
2024 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2025 block = pageb->u.text;
2027 for (line = block->lines;
2028 line < block->lines + block->len;
2029 ++line) {
2030 fz_text_span *span;
2031 rect = fz_empty_rect;
2033 for (span = line->first_span; span; span = span->next) {
2034 int i, j, k;
2035 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2037 j = 0;
2038 k = span->len - 1;
2040 if (span == page->fmark.span && span == page->lmark.span) {
2041 seen = 1;
2042 j = MIN (first.i, last.i);
2043 k = MAX (first.i, last.i);
2045 else {
2046 if (span == first.span) {
2047 seen = 1;
2048 j = first.i;
2050 else if (span == last.span) {
2051 seen = 1;
2052 k = last.i;
2056 if (seen) {
2057 for (i = j; i <= k; ++i) {
2058 fz_rect bbox1;
2059 fz_union_rect (&rect,
2060 fz_text_char_bbox (state.ctx, &bbox1,
2061 span, i));
2063 fz_round_rect (&bbox, &rect);
2064 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2065 bbox.x0,
2066 bbox.y0,
2067 bbox.x1,
2068 bbox.y1,
2069 oy, ox);
2071 recti (bbox.x0 + ox, bbox.y0 + oy,
2072 bbox.x1 + ox, bbox.y1 + oy);
2073 if (span == last.span) {
2074 goto done;
2076 rect = fz_empty_rect;
2081 done:
2082 glDisable (GL_BLEND);
2085 #include "glfont.c"
2087 static void stipplerect (fz_matrix *m,
2088 fz_point *p1,
2089 fz_point *p2,
2090 fz_point *p3,
2091 fz_point *p4,
2092 GLfloat *texcoords,
2093 GLfloat *vertices)
2095 fz_transform_point (p1, m);
2096 fz_transform_point (p2, m);
2097 fz_transform_point (p3, m);
2098 fz_transform_point (p4, m);
2100 float w, h, s, t;
2102 w = p2->x - p1->x;
2103 h = p2->y - p1->y;
2104 t = sqrtf (w*w + h*h) * .25f;
2106 w = p3->x - p2->x;
2107 h = p3->y - p2->y;
2108 s = sqrtf (w*w + h*h) * .25f;
2110 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2111 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2113 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2114 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2116 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2117 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2119 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2120 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2122 glDrawArrays (GL_LINES, 0, 8);
2125 static void highlightlinks (struct page *page, int xoff, int yoff)
2127 int i;
2128 fz_matrix ctm, tm, pm;
2129 fz_link *link, *links;
2130 GLfloat *texcoords = state.texcoords;
2131 GLfloat *vertices = state.vertices;
2133 links = fz_load_links (state.ctx, page->fzpage);
2135 glEnable (GL_TEXTURE_1D);
2136 glEnable (GL_BLEND);
2137 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2138 glBindTexture (GL_TEXTURE_1D, state.stid);
2140 xoff -= state.pagedims[page->pdimno].bounds.x0;
2141 yoff -= state.pagedims[page->pdimno].bounds.y0;
2142 fz_translate (&tm, xoff, yoff);
2143 pm = pagectm (page);
2144 fz_concat (&ctm, &pm, &tm);
2146 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2147 glVertexPointer (2, GL_FLOAT, 0, vertices);
2149 for (link = links; link; link = link->next) {
2150 fz_point p1, p2, p3, p4;
2152 p1.x = link->rect.x0;
2153 p1.y = link->rect.y0;
2155 p2.x = link->rect.x1;
2156 p2.y = link->rect.y0;
2158 p3.x = link->rect.x1;
2159 p3.y = link->rect.y1;
2161 p4.x = link->rect.x0;
2162 p4.y = link->rect.y1;
2164 switch (link->dest.kind) {
2165 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
2166 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
2167 case FZ_LINK_LAUNCH: glColor3ub (0, 255, 0); break;
2168 default: glColor3ub (0, 0, 0); break;
2170 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2173 for (i = 0; i < page->annotcount; ++i) {
2174 fz_point p1, p2, p3, p4;
2175 struct annot *annot = &page->annots[i];
2177 p1.x = annot->bbox.x0;
2178 p1.y = annot->bbox.y0;
2180 p2.x = annot->bbox.x1;
2181 p2.y = annot->bbox.y0;
2183 p3.x = annot->bbox.x1;
2184 p3.y = annot->bbox.y1;
2186 p4.x = annot->bbox.x0;
2187 p4.y = annot->bbox.y1;
2189 glColor3ub (0, 0, 128);
2190 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2193 glDisable (GL_BLEND);
2194 glDisable (GL_TEXTURE_1D);
2197 static int compareslinks (const void *l, const void *r)
2199 struct slink const *ls = l;
2200 struct slink const *rs = r;
2201 if (ls->bbox.y0 == rs->bbox.y0) {
2202 return rs->bbox.x0 - rs->bbox.x0;
2204 return ls->bbox.y0 - rs->bbox.y0;
2207 static void droptext (struct page *page)
2209 if (page->text) {
2210 fz_drop_text_page (state.ctx, page->text);
2211 page->fmark.i = -1;
2212 page->lmark.i = -1;
2213 page->fmark.span = NULL;
2214 page->lmark.span = NULL;
2215 page->text = NULL;
2217 if (page->sheet) {
2218 fz_drop_text_sheet (state.ctx, page->sheet);
2219 page->sheet = NULL;
2223 static void dropannots (struct page *page)
2225 if (page->annots) {
2226 free (page->annots);
2227 page->annots = NULL;
2228 page->annotcount = 0;
2232 static void ensureannots (struct page *page)
2234 int i, count = 0;
2235 size_t annotsize = sizeof (*page->annots);
2236 fz_annot *annot;
2238 if (state.gen != page->agen) {
2239 dropannots (page);
2240 page->agen = state.gen;
2242 if (page->annots) return;
2244 for (annot = fz_first_annot (state.ctx, page->fzpage);
2245 annot;
2246 annot = fz_next_annot (state.ctx, page->fzpage, annot)) {
2247 count++;
2250 if (count > 0) {
2251 page->annotcount = count;
2252 page->annots = calloc (count, annotsize);
2253 if (!page->annots) {
2254 err (1, "calloc annots %d", count);
2257 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2258 annot;
2259 annot = fz_next_annot (state.ctx, page->fzpage, annot), i++) {
2260 fz_rect rect;
2262 fz_bound_annot (state.ctx, page->fzpage, annot, &rect);
2263 page->annots[i].annot = annot;
2264 fz_round_rect (&page->annots[i].bbox, &rect);
2269 static void dropslinks (struct page *page)
2271 if (page->slinks) {
2272 free (page->slinks);
2273 page->slinks = NULL;
2274 page->slinkcount = 0;
2278 static void ensureslinks (struct page *page)
2280 fz_matrix ctm;
2281 int i, count;
2282 size_t slinksize = sizeof (*page->slinks);
2283 fz_link *link, *links;
2285 ensureannots (page);
2286 if (state.gen != page->sgen) {
2287 dropslinks (page);
2288 page->sgen = state.gen;
2290 if (page->slinks) return;
2292 links = fz_load_links (state.ctx, page->fzpage);
2293 ctm = state.pagedims[page->pdimno].ctm;
2295 count = page->annotcount;
2296 for (link = links; link; link = link->next) {
2297 count++;
2299 if (count > 0) {
2300 int j;
2302 page->slinkcount = count;
2303 page->slinks = calloc (count, slinksize);
2304 if (!page->slinks) {
2305 err (1, "calloc slinks %d", count);
2308 for (i = 0, link = links; link; ++i, link = link->next) {
2309 fz_rect rect;
2311 rect = link->rect;
2312 fz_transform_rect (&rect, &ctm);
2313 page->slinks[i].tag = SLINK;
2314 page->slinks[i].u.link = link;
2315 fz_round_rect (&page->slinks[i].bbox, &rect);
2317 for (j = 0; j < page->annotcount; ++j, ++i) {
2318 fz_rect rect;
2319 fz_bound_annot (state.ctx,
2320 page->fzpage,
2321 page->annots[j].annot,
2322 &rect);
2323 fz_transform_rect (&rect, &ctm);
2324 fz_round_rect (&page->slinks[i].bbox, &rect);
2326 page->slinks[i].tag = SANNOT;
2327 page->slinks[i].u.annot = page->annots[j].annot;
2329 qsort (page->slinks, count, slinksize, compareslinks);
2333 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2334 static void fmt_linkn (char *s, unsigned int u)
2336 unsigned int len; unsigned int q;
2337 unsigned int zma = 'z' - 'a' + 1;
2338 len = 1; q = u;
2339 while (q > zma - 1) { ++len; q /= zma; }
2340 if (s) {
2341 s += len;
2342 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2343 /* handles u == 0 */
2345 s[len] = 0;
2348 static void highlightslinks (struct page *page, int xoff, int yoff,
2349 int noff, char *targ, int tlen, int hfsize)
2351 int i;
2352 char buf[40];
2353 struct slink *slink;
2354 double x0, y0, x1, y1, w;
2356 ensureslinks (page);
2357 glColor3ub (0xc3, 0xb0, 0x91);
2358 for (i = 0; i < page->slinkcount; ++i) {
2359 fmt_linkn (buf, i + noff);
2360 if (!tlen || !strncmp (targ, buf, tlen)) {
2361 slink = &page->slinks[i];
2363 x0 = slink->bbox.x0 + xoff - 5;
2364 y1 = slink->bbox.y0 + yoff - 5;
2365 y0 = y1 + 10 + hfsize;
2366 w = measure_string (state.face, hfsize, buf);
2367 x1 = x0 + w + 10;
2368 recti (x0, y0, x1, y1);
2372 glEnable (GL_BLEND);
2373 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2374 glEnable (GL_TEXTURE_2D);
2375 glColor3ub (0, 0, 0);
2376 for (i = 0; i < page->slinkcount; ++i) {
2377 fmt_linkn (buf, i + noff);
2378 if (!tlen || !strncmp (targ, buf, tlen)) {
2379 slink = &page->slinks[i];
2381 x0 = slink->bbox.x0 + xoff;
2382 y0 = slink->bbox.y0 + yoff + hfsize;
2383 draw_string (state.face, hfsize, x0, y0, buf);
2386 glDisable (GL_TEXTURE_2D);
2387 glDisable (GL_BLEND);
2390 static void uploadslice (struct tile *tile, struct slice *slice)
2392 int offset;
2393 struct slice *slice1;
2394 unsigned char *texdata;
2396 offset = 0;
2397 for (slice1 = tile->slices; slice != slice1; slice1++) {
2398 offset += slice1->h * tile->w * tile->pixmap->n;
2400 if (slice->texindex != -1 && slice->texindex < state.texcount
2401 && state.texowners[slice->texindex].slice == slice) {
2402 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[slice->texindex]);
2404 else {
2405 int subimage = 0;
2406 int texindex = state.texindex++ % state.texcount;
2408 if (state.texowners[texindex].w == tile->w) {
2409 if (state.texowners[texindex].h >= slice->h) {
2410 subimage = 1;
2412 else {
2413 state.texowners[texindex].h = slice->h;
2416 else {
2417 state.texowners[texindex].h = slice->h;
2420 state.texowners[texindex].w = tile->w;
2421 state.texowners[texindex].slice = slice;
2422 slice->texindex = texindex;
2424 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[texindex]);
2425 if (tile->pbo) {
2426 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2427 texdata = 0;
2429 else {
2430 texdata = tile->pixmap->samples;
2432 if (subimage) {
2433 glTexSubImage2D (GL_TEXTURE_RECTANGLE_ARB,
2437 tile->w,
2438 slice->h,
2439 state.texform,
2440 state.texty,
2441 texdata+offset
2444 else {
2445 glTexImage2D (GL_TEXTURE_RECTANGLE_ARB,
2447 state.texiform,
2448 tile->w,
2449 slice->h,
2451 state.texform,
2452 state.texty,
2453 texdata+offset
2456 if (tile->pbo) {
2457 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2462 CAMLprim value ml_begintiles (value unit_v)
2464 CAMLparam1 (unit_v);
2465 glEnable (GL_TEXTURE_RECTANGLE_ARB);
2466 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2467 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2468 CAMLreturn (unit_v);
2471 CAMLprim value ml_endtiles (value unit_v)
2473 CAMLparam1 (unit_v);
2474 glDisable (GL_TEXTURE_RECTANGLE_ARB);
2475 CAMLreturn (unit_v);
2478 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2480 CAMLparam2 (args_v, ptr_v);
2481 int dispx = Int_val (Field (args_v, 0));
2482 int dispy = Int_val (Field (args_v, 1));
2483 int dispw = Int_val (Field (args_v, 2));
2484 int disph = Int_val (Field (args_v, 3));
2485 int tilex = Int_val (Field (args_v, 4));
2486 int tiley = Int_val (Field (args_v, 5));
2487 char *s = String_val (ptr_v);
2488 struct tile *tile = parse_pointer ("ml_drawtile", s);
2489 int slicey, firstslice;
2490 struct slice *slice;
2491 GLfloat *texcoords = state.texcoords;
2492 GLfloat *vertices = state.vertices;
2494 firstslice = tiley / tile->sliceheight;
2495 slice = &tile->slices[firstslice];
2496 slicey = tiley % tile->sliceheight;
2498 while (disph > 0) {
2499 int dh;
2501 dh = slice->h - slicey;
2502 dh = MIN (disph, dh);
2503 uploadslice (tile, slice);
2505 texcoords[0] = tilex; texcoords[1] = slicey;
2506 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2507 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2508 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2510 vertices[0] = dispx; vertices[1] = dispy;
2511 vertices[2] = dispx+dispw; vertices[3] = dispy;
2512 vertices[4] = dispx; vertices[5] = dispy+dh;
2513 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2515 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2516 dispy += dh;
2517 disph -= dh;
2518 slice++;
2519 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2520 slicey = 0;
2522 CAMLreturn (Val_unit);
2525 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2526 value xoff_v, value yoff_v,
2527 value li_v)
2529 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2530 int xoff = Int_val (xoff_v);
2531 int yoff = Int_val (yoff_v);
2532 int noff = Int_val (Field (li_v, 0));
2533 char *targ = String_val (Field (li_v, 1));
2534 int tlen = caml_string_length (Field (li_v, 1));
2535 int hfsize = Int_val (Field (li_v, 2));
2536 char *s = String_val (ptr_v);
2537 int hlmask = Int_val (hlinks_v);
2538 struct page *page = parse_pointer ("ml_postprocess", s);
2540 if (!page->fzpage) {
2541 /* deal with loadpage failed pages */
2542 goto done;
2545 ensureannots (page);
2547 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2548 if (trylock ("ml_postprocess")) {
2549 noff = 0;
2550 goto done;
2552 if (hlmask & 2) {
2553 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2554 noff = page->slinkcount;
2556 if (page->tgen == state.gen) {
2557 showsel (page, xoff, yoff);
2559 unlock ("ml_postprocess");
2561 done:
2562 CAMLreturn (Val_int (noff));
2565 static struct annot *getannot (struct page *page, int x, int y)
2567 int i;
2568 fz_point p;
2569 fz_matrix ctm;
2570 const fz_matrix *tctm;
2571 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2573 if (!page->annots) return NULL;
2575 if (pdf) {
2576 trimctm ((pdf_page *) page->fzpage, page->pdimno);
2577 tctm = &state.pagedims[page->pdimno].tctm;
2579 else {
2580 tctm = &fz_identity;
2583 p.x = x;
2584 p.y = y;
2586 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2587 fz_invert_matrix (&ctm, &ctm);
2588 fz_transform_point (&p, &ctm);
2590 if (pdf) {
2591 for (i = 0; i < page->annotcount; ++i) {
2592 struct annot *a = &page->annots[i];
2593 pdf_annot *annot = (pdf_annot *) a->annot;
2594 if (p.x >= annot->pagerect.x0 && p.x <= annot->pagerect.x1) {
2595 if (p.y >= annot->pagerect.y0 && p.y <= annot->pagerect.y1) {
2596 return a;
2601 return NULL;
2604 static fz_link *getlink (struct page *page, int x, int y)
2606 fz_point p;
2607 fz_matrix ctm;
2608 const fz_matrix *tctm;
2609 fz_link *link, *links;
2611 tctm = &fz_identity;
2612 links = fz_load_links (state.ctx, page->fzpage);
2614 p.x = x;
2615 p.y = y;
2617 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2618 fz_invert_matrix (&ctm, &ctm);
2619 fz_transform_point (&p, &ctm);
2621 for (link = links; link; link = link->next) {
2622 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2623 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2624 return link;
2628 return NULL;
2631 static void ensuretext (struct page *page)
2633 if (state.gen != page->tgen) {
2634 droptext (page);
2635 page->tgen = state.gen;
2637 if (!page->text) {
2638 fz_matrix ctm;
2639 fz_device *tdev;
2641 page->text = fz_new_text_page (state.ctx);
2642 page->sheet = fz_new_text_sheet (state.ctx);
2643 tdev = fz_new_text_device (state.ctx, page->sheet, page->text);
2644 ctm = pagectm (page);
2645 fz_begin_page (state.ctx, tdev, &fz_infinite_rect, &ctm);
2646 fz_run_display_list (state.ctx, page->dlist,
2647 tdev, &ctm, &fz_infinite_rect, NULL);
2648 qsort (page->text->blocks, page->text->len,
2649 sizeof (*page->text->blocks), compareblocks);
2650 fz_end_page (state.ctx, tdev);
2651 fz_drop_device (state.ctx, tdev);
2655 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2657 CAMLparam2 (start_page_v, dir_v);
2658 CAMLlocal1 (ret_v);
2659 int i, dir = Int_val (dir_v);
2660 int start_page = Int_val (start_page_v);
2661 int end_page = dir > 0 ? state.pagecount : -1;
2662 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2664 ret_v = Val_int (0);
2665 lock ("ml_findpage_with_links");
2666 for (i = start_page + dir; i != end_page; i += dir) {
2667 int found;
2669 if (pdf) {
2670 pdf_page *page = NULL;
2672 fz_try (state.ctx) {
2673 page = pdf_load_page (state.ctx, pdf, i);
2674 found = !!page->links || !!page->annots;
2676 fz_catch (state.ctx) {
2677 found = 0;
2679 if (page) {
2680 fz_drop_page (state.ctx, &page->super);
2683 else {
2684 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2685 found = !!fz_load_links (state.ctx, page);
2686 fz_drop_page (state.ctx, page);
2689 if (found) {
2690 ret_v = caml_alloc_small (1, 1);
2691 Field (ret_v, 0) = Val_int (i);
2692 goto unlock;
2695 unlock:
2696 unlock ("ml_findpage_with_links");
2697 CAMLreturn (ret_v);
2700 enum { dir_first, dir_last };
2701 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2703 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2705 CAMLparam2 (ptr_v, dir_v);
2706 CAMLlocal2 (ret_v, pos_v);
2707 struct page *page;
2708 int dirtag, i, slinkindex;
2709 struct slink *found = NULL ,*slink;
2710 char *s = String_val (ptr_v);
2712 page = parse_pointer ("ml_findlink", s);
2713 ret_v = Val_int (0);
2714 /* This is scary we are not taking locks here ensureslinks does
2715 not modify state and given that we obtained the page it can not
2716 disappear under us either */
2717 lock ("ml_findlink");
2718 ensureslinks (page);
2720 if (Is_block (dir_v)) {
2721 dirtag = Tag_val (dir_v);
2722 switch (dirtag) {
2723 case dir_first_visible:
2725 int x0, y0, dir, first_index, last_index;
2727 pos_v = Field (dir_v, 0);
2728 x0 = Int_val (Field (pos_v, 0));
2729 y0 = Int_val (Field (pos_v, 1));
2730 dir = Int_val (Field (pos_v, 2));
2732 if (dir >= 0) {
2733 dir = 1;
2734 first_index = 0;
2735 last_index = page->slinkcount;
2737 else {
2738 first_index = page->slinkcount - 1;
2739 last_index = -1;
2742 for (i = first_index; i != last_index; i += dir) {
2743 slink = &page->slinks[i];
2744 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2745 found = slink;
2746 break;
2750 break;
2752 case dir_left:
2753 slinkindex = Int_val (Field (dir_v, 0));
2754 found = &page->slinks[slinkindex];
2755 for (i = slinkindex - 1; i >= 0; --i) {
2756 slink = &page->slinks[i];
2757 if (slink->bbox.x0 < found->bbox.x0) {
2758 found = slink;
2759 break;
2762 break;
2764 case dir_right:
2765 slinkindex = Int_val (Field (dir_v, 0));
2766 found = &page->slinks[slinkindex];
2767 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2768 slink = &page->slinks[i];
2769 if (slink->bbox.x0 > found->bbox.x0) {
2770 found = slink;
2771 break;
2774 break;
2776 case dir_down:
2777 slinkindex = Int_val (Field (dir_v, 0));
2778 found = &page->slinks[slinkindex];
2779 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2780 slink = &page->slinks[i];
2781 if (slink->bbox.y0 >= found->bbox.y0) {
2782 found = slink;
2783 break;
2786 break;
2788 case dir_up:
2789 slinkindex = Int_val (Field (dir_v, 0));
2790 found = &page->slinks[slinkindex];
2791 for (i = slinkindex - 1; i >= 0; --i) {
2792 slink = &page->slinks[i];
2793 if (slink->bbox.y0 <= found->bbox.y0) {
2794 found = slink;
2795 break;
2798 break;
2801 else {
2802 dirtag = Int_val (dir_v);
2803 switch (dirtag) {
2804 case dir_first:
2805 found = page->slinks;
2806 break;
2808 case dir_last:
2809 if (page->slinks) {
2810 found = page->slinks + (page->slinkcount - 1);
2812 break;
2815 if (found) {
2816 ret_v = caml_alloc_small (2, 1);
2817 Field (ret_v, 0) = Val_int (found - page->slinks);
2820 unlock ("ml_findlink");
2821 CAMLreturn (ret_v);
2824 enum { uuri, ugoto, utext, uunexpected, ulaunch,
2825 unamed, uremote, uremotedest, uannot };
2827 #define LINKTOVAL \
2829 int pageno; \
2831 switch (link->dest.kind) { \
2832 case FZ_LINK_GOTO: \
2834 fz_point p; \
2836 pageno = link->dest.ld.gotor.page; \
2837 p.x = 0; \
2838 p.y = 0; \
2840 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2841 p.y = link->dest.ld.gotor.lt.y; \
2842 fz_transform_point (&p, &pdim->lctm); \
2843 if (p.y < 0) p.y = 0; \
2845 tup_v = caml_alloc_tuple (2); \
2846 ret_v = caml_alloc_small (1, ugoto); \
2847 Field (tup_v, 0) = Val_int (pageno); \
2848 Field (tup_v, 1) = Val_int (p.y); \
2849 Field (ret_v, 0) = tup_v; \
2851 break; \
2853 case FZ_LINK_URI: \
2854 str_v = caml_copy_string (link->dest.ld.uri.uri); \
2855 ret_v = caml_alloc_small (1, uuri); \
2856 Field (ret_v, 0) = str_v; \
2857 break; \
2859 case FZ_LINK_LAUNCH: \
2860 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
2861 ret_v = caml_alloc_small (1, ulaunch); \
2862 Field (ret_v, 0) = str_v; \
2863 break; \
2865 case FZ_LINK_NAMED: \
2866 str_v = caml_copy_string (link->dest.ld.named.named); \
2867 ret_v = caml_alloc_small (1, unamed); \
2868 Field (ret_v, 0) = str_v; \
2869 break; \
2871 case FZ_LINK_GOTOR: \
2873 int rty; \
2875 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
2876 pageno = link->dest.ld.gotor.page; \
2877 if (pageno == -1) { \
2878 gr_v = caml_copy_string (link->dest.ld.gotor.dest); \
2879 rty = uremotedest; \
2881 else { \
2882 gr_v = Val_int (pageno); \
2883 rty = uremote; \
2885 tup_v = caml_alloc_tuple (2); \
2886 ret_v = caml_alloc_small (1, rty); \
2887 Field (tup_v, 0) = str_v; \
2888 Field (tup_v, 1) = gr_v; \
2889 Field (ret_v, 0) = tup_v; \
2891 break; \
2893 default: \
2895 char buf[80]; \
2897 snprintf (buf, sizeof (buf), \
2898 "unhandled link kind %d", link->dest.kind); \
2899 str_v = caml_copy_string (buf); \
2900 ret_v = caml_alloc_small (1, uunexpected); \
2901 Field (ret_v, 0) = str_v; \
2903 break; \
2907 CAMLprim value ml_getlink (value ptr_v, value n_v)
2909 CAMLparam2 (ptr_v, n_v);
2910 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2911 fz_link *link;
2912 struct page *page;
2913 struct pagedim *pdim;
2914 char *s = String_val (ptr_v);
2915 struct slink *slink;
2917 /* See ml_findlink for caveat */
2919 ret_v = Val_int (0);
2920 page = parse_pointer ("ml_getlink", s);
2921 ensureslinks (page);
2922 pdim = &state.pagedims[page->pdimno];
2923 slink = &page->slinks[Int_val (n_v)];
2924 if (slink->tag == SLINK) {
2925 link = slink->u.link;
2926 LINKTOVAL;
2928 else {
2929 ret_v = caml_alloc_small (1, uannot);
2930 tup_v = caml_alloc_tuple (2);
2931 Field (ret_v, 0) = tup_v;
2932 Field (tup_v, 0) = ptr_v;
2933 Field (tup_v, 1) = n_v;
2936 CAMLreturn (ret_v);
2939 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2941 CAMLparam2 (ptr_v, n_v);
2942 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2943 if (pdf) {
2944 char *s = String_val (ptr_v);
2945 struct page *page;
2946 struct slink *slink;
2948 page = parse_pointer ("ml_getannotcontent", s);
2949 slink = &page->slinks[Int_val (n_v)];
2950 CAMLreturn (caml_copy_string (
2951 pdf_annot_contents (state.ctx, pdf,
2952 (pdf_annot *) slink->u.annot)));
2954 else {
2955 CAMLreturn (caml_copy_string (""));
2959 CAMLprim value ml_getlinkcount (value ptr_v)
2961 CAMLparam1 (ptr_v);
2962 struct page *page;
2963 char *s = String_val (ptr_v);
2965 page = parse_pointer ("ml_getlinkcount", s);
2966 CAMLreturn (Val_int (page->slinkcount));
2969 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2971 CAMLparam2 (ptr_v, n_v);
2972 CAMLlocal1 (ret_v);
2973 struct page *page;
2974 struct slink *slink;
2975 char *s = String_val (ptr_v);
2976 /* See ml_findlink for caveat */
2978 page = parse_pointer ("ml_getlinkrect", s);
2979 ret_v = caml_alloc_tuple (4);
2980 ensureslinks (page);
2982 slink = &page->slinks[Int_val (n_v)];
2983 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2984 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2985 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2986 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2987 unlock ("ml_getlinkrect");
2988 CAMLreturn (ret_v);
2991 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2993 CAMLparam3 (ptr_v, x_v, y_v);
2994 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2995 fz_link *link;
2996 struct annot *annot;
2997 struct page *page;
2998 char *ptr = String_val (ptr_v);
2999 int x = Int_val (x_v), y = Int_val (y_v);
3000 struct pagedim *pdim;
3002 ret_v = Val_int (0);
3003 if (trylock ("ml_whatsunder")) {
3004 goto done;
3007 page = parse_pointer ("ml_whatsunder", ptr);
3008 pdim = &state.pagedims[page->pdimno];
3009 x += pdim->bounds.x0;
3010 y += pdim->bounds.y0;
3013 annot = getannot (page, x, y);
3014 if (annot) {
3015 int i, n = -1;
3017 ensureslinks (page);
3018 for (i = 0; i < page->slinkcount; ++i) {
3019 if (page->slinks[i].tag == SANNOT
3020 && page->slinks[i].u.annot == annot->annot) {
3021 n = i;
3022 break;
3025 ret_v = caml_alloc_small (1, uannot);
3026 tup_v = caml_alloc_tuple (2);
3027 Field (ret_v, 0) = tup_v;
3028 Field (tup_v, 0) = ptr_v;
3029 Field (tup_v, 1) = Val_int (n);
3030 goto unlock;
3034 link = getlink (page, x, y);
3035 if (link) {
3036 LINKTOVAL;
3038 else {
3039 fz_rect *b;
3040 fz_page_block *pageb;
3041 fz_text_block *block;
3043 ensuretext (page);
3044 for (pageb = page->text->blocks;
3045 pageb < page->text->blocks + page->text->len;
3046 ++pageb) {
3047 fz_text_line *line;
3048 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3049 block = pageb->u.text;
3051 b = &block->bbox;
3052 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3053 continue;
3055 for (line = block->lines;
3056 line < block->lines + block->len;
3057 ++line) {
3058 fz_text_span *span;
3060 b = &line->bbox;
3061 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3062 continue;
3064 for (span = line->first_span; span; span = span->next) {
3065 int charnum;
3067 b = &span->bbox;
3068 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3069 continue;
3071 for (charnum = 0; charnum < span->len; ++charnum) {
3072 fz_rect bbox;
3073 fz_text_char_bbox (state.ctx, &bbox, span, charnum);
3074 b = &bbox;
3076 if (x >= b->x0 && x <= b->x1
3077 && y >= b->y0 && y <= b->y1) {
3078 fz_text_style *style = span->text->style;
3079 const char *n2 =
3080 style->font && style->font->name
3081 ? style->font->name
3082 : "Span has no font name"
3084 FT_FaceRec *face = style->font->ft_face;
3085 if (face && face->family_name) {
3086 char *s;
3087 char *n1 = face->family_name;
3088 size_t l1 = strlen (n1);
3089 size_t l2 = strlen (n2);
3091 if (l1 != l2 || memcmp (n1, n2, l1)) {
3092 s = malloc (l1 + l2 + 2);
3093 if (s) {
3094 memcpy (s, n2, l2);
3095 s[l2] = '=';
3096 memcpy (s + l2 + 1, n1, l1 + 1);
3097 str_v = caml_copy_string (s);
3098 free (s);
3102 if (str_v == Val_unit) {
3103 str_v = caml_copy_string (n2);
3105 ret_v = caml_alloc_small (1, utext);
3106 Field (ret_v, 0) = str_v;
3107 goto unlock;
3114 unlock:
3115 unlock ("ml_whatsunder");
3117 done:
3118 CAMLreturn (ret_v);
3121 enum { mark_page, mark_block, mark_line, mark_word };
3123 static int uninteresting (int c)
3125 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3126 || ispunct (c);
3129 CAMLprim value ml_clearmark (value ptr_v)
3131 CAMLparam1 (ptr_v);
3132 char *s = String_val (ptr_v);
3133 struct page *page;
3135 if (trylock ("ml_clearmark")) {
3136 goto done;
3139 page = parse_pointer ("ml_clearmark", s);
3140 page->fmark.span = NULL;
3141 page->lmark.span = NULL;
3142 page->fmark.i = 0;
3143 page->lmark.i = 0;
3145 unlock ("ml_clearmark");
3146 done:
3147 CAMLreturn (Val_unit);
3150 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3152 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3153 CAMLlocal1 (ret_v);
3154 fz_rect *b;
3155 struct page *page;
3156 fz_text_line *line;
3157 fz_page_block *pageb;
3158 fz_text_block *block;
3159 struct pagedim *pdim;
3160 int mark = Int_val (mark_v);
3161 char *s = String_val (ptr_v);
3162 int x = Int_val (x_v), y = Int_val (y_v);
3164 ret_v = Val_bool (0);
3165 if (trylock ("ml_markunder")) {
3166 goto done;
3169 page = parse_pointer ("ml_markunder", s);
3170 pdim = &state.pagedims[page->pdimno];
3172 ensuretext (page);
3174 if (mark == mark_page) {
3175 int i;
3176 fz_page_block *pb1 = NULL, *pb2 = NULL;
3178 for (i = 0; i < page->text->len; ++i) {
3179 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3180 pb1 = &page->text->blocks[i];
3181 break;
3184 if (!pb1) goto unlock;
3186 for (i = page->text->len - 1; i >= 0; --i) {
3187 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3188 pb2 = &page->text->blocks[i];
3189 break;
3192 if (!pb2) goto unlock;
3194 block = pb1->u.text;
3196 page->fmark.i = 0;
3197 page->fmark.span = block->lines->first_span;
3199 block = pb2->u.text;
3200 line = &block->lines[block->len - 1];
3201 page->lmark.i = line->last_span->len - 1;
3202 page->lmark.span = line->last_span;
3203 ret_v = Val_bool (1);
3204 goto unlock;
3207 x += pdim->bounds.x0;
3208 y += pdim->bounds.y0;
3210 for (pageb = page->text->blocks;
3211 pageb < page->text->blocks + page->text->len;
3212 ++pageb) {
3213 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3214 block = pageb->u.text;
3216 b = &block->bbox;
3217 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3218 continue;
3220 if (mark == mark_block) {
3221 page->fmark.i = 0;
3222 page->fmark.span = block->lines->first_span;
3224 line = &block->lines[block->len - 1];
3225 page->lmark.i = line->last_span->len - 1;
3226 page->lmark.span = line->last_span;
3227 ret_v = Val_bool (1);
3228 goto unlock;
3231 for (line = block->lines;
3232 line < block->lines + block->len;
3233 ++line) {
3234 fz_text_span *span;
3236 b = &line->bbox;
3237 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3238 continue;
3240 if (mark == mark_line) {
3241 page->fmark.i = 0;
3242 page->fmark.span = line->first_span;
3244 page->lmark.i = line->last_span->len - 1;
3245 page->lmark.span = line->last_span;
3246 ret_v = Val_bool (1);
3247 goto unlock;
3250 for (span = line->first_span; span; span = span->next) {
3251 int charnum;
3253 b = &span->bbox;
3254 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3255 continue;
3257 for (charnum = 0; charnum < span->len; ++charnum) {
3258 fz_rect bbox;
3259 fz_text_char_bbox (state.ctx, &bbox, span, charnum);
3260 b = &bbox;
3262 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3263 /* unicode ftw */
3264 int charnum2, charnum3 = -1, charnum4 = -1;
3266 if (uninteresting (span->text[charnum].c)) goto unlock;
3268 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3269 if (uninteresting (span->text[charnum2].c)) {
3270 charnum3 = charnum2 + 1;
3271 break;
3274 if (charnum3 == -1) charnum3 = 0;
3276 for (charnum2 = charnum + 1;
3277 charnum2 < span->len;
3278 ++charnum2) {
3279 if (uninteresting (span->text[charnum2].c)) break;
3280 charnum4 = charnum2;
3282 if (charnum4 == -1) goto unlock;
3284 page->fmark.i = charnum3;
3285 page->fmark.span = span;
3287 page->lmark.i = charnum4;
3288 page->lmark.span = span;
3289 ret_v = Val_bool (1);
3290 goto unlock;
3296 unlock:
3297 if (!Bool_val (ret_v)) {
3298 page->fmark.span = NULL;
3299 page->lmark.span = NULL;
3300 page->fmark.i = 0;
3301 page->lmark.i = 0;
3303 unlock ("ml_markunder");
3305 done:
3306 CAMLreturn (ret_v);
3309 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3311 CAMLparam3 (ptr_v, x_v, y_v);
3312 CAMLlocal2 (ret_v, res_v);
3313 fz_rect *b = NULL;
3314 struct page *page;
3315 fz_page_block *pageb;
3316 struct pagedim *pdim;
3317 char *s = String_val (ptr_v);
3318 int x = Int_val (x_v), y = Int_val (y_v);
3320 ret_v = Val_int (0);
3321 if (trylock ("ml_rectofblock")) {
3322 goto done;
3325 page = parse_pointer ("ml_rectofblock", s);
3326 pdim = &state.pagedims[page->pdimno];
3327 x += pdim->bounds.x0;
3328 y += pdim->bounds.y0;
3330 ensuretext (page);
3332 for (pageb = page->text->blocks;
3333 pageb < page->text->blocks + page->text->len;
3334 ++pageb) {
3335 switch (pageb->type) {
3336 case FZ_PAGE_BLOCK_TEXT:
3337 b = &pageb->u.text->bbox;
3338 break;
3340 case FZ_PAGE_BLOCK_IMAGE:
3341 b = &pageb->u.image->bbox;
3342 break;
3344 default:
3345 continue;
3348 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3349 break;
3350 b = NULL;
3352 if (b) {
3353 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3354 ret_v = caml_alloc_small (1, 1);
3355 Store_double_field (res_v, 0, b->x0);
3356 Store_double_field (res_v, 1, b->x1);
3357 Store_double_field (res_v, 2, b->y0);
3358 Store_double_field (res_v, 3, b->y1);
3359 Field (ret_v, 0) = res_v;
3361 unlock ("ml_rectofblock");
3363 done:
3364 CAMLreturn (ret_v);
3367 CAMLprim value ml_seltext (value ptr_v, value rect_v)
3369 CAMLparam2 (ptr_v, rect_v);
3370 fz_rect b;
3371 struct page *page;
3372 struct pagedim *pdim;
3373 char *s = String_val (ptr_v);
3374 int i, x0, x1, y0, y1, fi, li;
3375 fz_text_line *line;
3376 fz_page_block *pageb;
3377 fz_text_block *block;
3378 fz_text_span *span, *fspan, *lspan;
3380 if (trylock ("ml_seltext")) {
3381 goto done;
3384 page = parse_pointer ("ml_seltext", s);
3385 ensuretext (page);
3387 pdim = &state.pagedims[page->pdimno];
3388 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3389 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3390 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3391 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3393 if (y0 > y1) {
3394 int t = y0;
3395 y0 = y1;
3396 y1 = t;
3397 x0 = x1;
3398 x1 = t;
3401 if (0) {
3402 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
3403 glColor3ub (128, 128, 128);
3404 recti (x0, y0, x1, y1);
3405 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
3408 fi = page->fmark.i;
3409 fspan = page->fmark.span;
3411 li = page->lmark.i;
3412 lspan = page->lmark.span;
3414 for (pageb = page->text->blocks;
3415 pageb < page->text->blocks + page->text->len;
3416 ++pageb) {
3417 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3418 block = pageb->u.text;
3419 for (line = block->lines;
3420 line < block->lines + block->len;
3421 ++line) {
3423 for (span = line->first_span; span; span = span->next) {
3424 for (i = 0; i < span->len; ++i) {
3425 int selected = 0;
3427 fz_text_char_bbox (state.ctx, &b, span, i);
3429 if (x0 >= b.x0 && x0 <= b.x1
3430 && y0 >= b.y0 && y0 <= b.y1) {
3431 fspan = span;
3432 fi = i;
3433 selected = 1;
3435 if (x1 >= b.x0 && x1 <= b.x1
3436 && y1 >= b.y0 && y1 <= b.y1) {
3437 lspan = span;
3438 li = i;
3439 selected = 1;
3441 if (0 && selected) {
3442 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
3443 glColor3ub (128, 128, 128);
3444 recti (b.x0, b.y0, b.x1, b.y1);
3445 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
3451 if (x1 < x0 && fspan == lspan) {
3452 i = fi;
3453 span = fspan;
3455 fi = li;
3456 fspan = lspan;
3458 li = i;
3459 lspan = span;
3462 page->fmark.i = fi;
3463 page->fmark.span = fspan;
3465 page->lmark.i = li;
3466 page->lmark.span = lspan;
3468 unlock ("ml_seltext");
3470 done:
3471 CAMLreturn (Val_unit);
3474 static int UNUSED_ATTR pipespan (FILE *f, fz_text_span *span, int a, int b)
3476 char buf[4];
3477 int i, len, ret;
3479 for (i = a; i <= b; ++i) {
3480 len = fz_runetochar (buf, span->text[i].c);
3481 ret = fwrite (buf, len, 1, f);
3483 if (ret != 1) {
3484 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3485 len, ret, strerror (errno));
3486 return -1;
3489 return 0;
3492 #ifdef __CYGWIN__
3493 CAMLprim value ml_popen (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3495 caml_failwith ("ml_popen not implemented under Cygwin");
3497 #else
3498 CAMLprim value ml_popen (value command_v, value fds_v)
3500 CAMLparam2 (command_v, fds_v);
3501 CAMLlocal2 (l_v, tup_v);
3502 int ret;
3503 pid_t pid;
3504 char *msg = NULL;
3505 value earg_v = Nothing;
3506 posix_spawnattr_t attr;
3507 posix_spawn_file_actions_t fa;
3508 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3510 argv[2] = String_val (command_v);
3512 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3513 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3516 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3517 msg = "posix_spawnattr_init";
3518 goto fail1;
3521 #ifdef POSIX_SPAWN_USEVFORK
3522 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3523 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3524 goto fail;
3526 #endif
3528 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3529 int fd1, fd2;
3531 tup_v = Field (l_v, 0);
3532 fd1 = Int_val (Field (tup_v, 0));
3533 fd2 = Int_val (Field (tup_v, 1));
3534 if (fd2 < 0) {
3535 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3536 msg = "posix_spawn_file_actions_addclose";
3537 earg_v = tup_v;
3538 goto fail;
3541 else {
3542 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3543 msg = "posix_spawn_file_actions_adddup2";
3544 earg_v = tup_v;
3545 goto fail;
3550 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3551 msg = "posix_spawn";
3552 goto fail;
3555 fail:
3556 if ((ret = posix_spawnattr_destroy (&attr)) != 0) {
3557 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret));
3560 fail1:
3561 if ((ret = posix_spawn_file_actions_destroy (&fa)) != 0) {
3562 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3563 strerror (ret));
3566 if (msg)
3567 unix_error (ret, msg, earg_v);
3569 CAMLreturn (Val_int (pid));
3571 #endif
3573 CAMLprim value ml_hassel (value ptr_v)
3575 CAMLparam1 (ptr_v);
3576 CAMLlocal1 (ret_v);
3577 struct page *page;
3578 char *s = String_val (ptr_v);
3580 ret_v = Val_bool (0);
3581 if (trylock ("ml_hassel")) {
3582 goto done;
3585 page = parse_pointer ("ml_hassel", s);
3586 ret_v = Val_bool (page->fmark.span && page->lmark.span);
3587 unlock ("ml_hassel");
3588 done:
3589 CAMLreturn (ret_v);
3592 CAMLprim value ml_copysel (value fd_v, value ptr_v)
3594 CAMLparam2 (fd_v, ptr_v);
3595 FILE *f;
3596 int seen = 0;
3597 struct page *page;
3598 fz_text_line *line;
3599 fz_page_block *pageb;
3600 fz_text_block *block;
3601 int fd = Int_val (fd_v);
3602 char *s = String_val (ptr_v);
3604 if (trylock ("ml_copysel")) {
3605 goto done;
3608 page = parse_pointer ("ml_copysel", s);
3610 if (!page->fmark.span || !page->lmark.span) {
3611 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3612 goto unlock;
3615 f = fdopen (fd, "w");
3616 if (!f) {
3617 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3618 fd, strerror (errno));
3619 f = stdout;
3622 for (pageb = page->text->blocks;
3623 pageb < page->text->blocks + page->text->len;
3624 ++pageb) {
3625 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3626 block = pageb->u.text;
3627 for (line = block->lines;
3628 line < block->lines + block->len;
3629 ++line) {
3630 fz_text_span *span;
3632 for (span = line->first_span; span; span = span->next) {
3633 int a, b;
3635 seen |= span == page->fmark.span || span == page->lmark.span;
3636 a = span == page->fmark.span ? page->fmark.i : 0;
3637 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3639 if (seen) {
3640 if (pipespan (f, span, a, b)) {
3641 goto close;
3643 if (span == page->lmark.span) {
3644 goto close;
3646 if (span == line->last_span) {
3647 if (putc ('\n', f) == EOF) {
3648 fprintf (stderr,
3649 "failed break line on sel pipe: %s\n",
3650 strerror (errno));
3651 goto close;
3658 close:
3659 if (f != stdout) {
3660 int ret = fclose (f);
3661 fd = -1;
3662 if (ret == -1) {
3663 if (errno != ECHILD) {
3664 fprintf (stderr, "failed to close sel pipe: %s\n",
3665 strerror (errno));
3669 unlock:
3670 unlock ("ml_copysel");
3672 done:
3673 if (fd >= 0) {
3674 if (close (fd)) {
3675 fprintf (stderr, "failed to close sel pipe: %s\n",
3676 strerror (errno));
3679 CAMLreturn (Val_unit);
3682 CAMLprim value ml_getpdimrect (value pagedimno_v)
3684 CAMLparam1 (pagedimno_v);
3685 CAMLlocal1 (ret_v);
3686 int pagedimno = Int_val (pagedimno_v);
3687 fz_rect box;
3689 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3690 if (trylock ("ml_getpdimrect")) {
3691 box = fz_empty_rect;
3693 else {
3694 box = state.pagedims[pagedimno].mediabox;
3695 unlock ("ml_getpdimrect");
3698 Store_double_field (ret_v, 0, box.x0);
3699 Store_double_field (ret_v, 1, box.x1);
3700 Store_double_field (ret_v, 2, box.y0);
3701 Store_double_field (ret_v, 3, box.y1);
3703 CAMLreturn (ret_v);
3706 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3707 value dw_v, value cols_v)
3709 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3710 CAMLlocal1 (ret_v);
3711 int i;
3712 double zoom = -1.;
3713 double maxh = 0.0;
3714 struct pagedim *p;
3715 double winw = Int_val (winw_v);
3716 double winh = Int_val (winh_v);
3717 double dw = Int_val (dw_v);
3718 double cols = Int_val (cols_v);
3719 double pw = 1.0, ph = 1.0;
3721 if (trylock ("ml_zoom_for_height")) {
3722 goto done;
3725 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3726 double w = p->pagebox.x1 / cols;
3727 double h = p->pagebox.y1;
3728 if (h > maxh) {
3729 maxh = h;
3730 ph = h;
3731 if (state.fitmodel != FitProportional) pw = w;
3733 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3736 zoom = (((winh / ph) * pw) + dw) / winw;
3737 unlock ("ml_zoom_for_height");
3738 done:
3739 ret_v = caml_copy_double (zoom);
3740 CAMLreturn (ret_v);
3743 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3745 CAMLparam4 (pt_v, x_v, y_v, string_v);
3746 CAMLlocal1 (ret_v);
3747 int pt = Int_val(pt_v);
3748 int x = Int_val (x_v);
3749 int y = Int_val (y_v);
3750 double w;
3752 w = draw_string (state.face, pt, x, y, String_val (string_v));
3753 ret_v = caml_copy_double (w);
3754 CAMLreturn (ret_v);
3757 CAMLprim value ml_measure_string (value pt_v, value string_v)
3759 CAMLparam2 (pt_v, string_v);
3760 CAMLlocal1 (ret_v);
3761 int pt = Int_val (pt_v);
3762 double w;
3764 w = measure_string (state.face, pt, String_val (string_v));
3765 ret_v = caml_copy_double (w);
3766 CAMLreturn (ret_v);
3769 CAMLprim value ml_getpagebox (value opaque_v)
3771 CAMLparam1 (opaque_v);
3772 CAMLlocal1 (ret_v);
3773 fz_rect rect;
3774 fz_irect bbox;
3775 fz_matrix ctm;
3776 fz_device *dev;
3777 char *s = String_val (opaque_v);
3778 struct page *page = parse_pointer ("ml_getpagebox", s);
3780 ret_v = caml_alloc_tuple (4);
3781 dev = fz_new_bbox_device (state.ctx, &rect);
3782 dev->hints |= FZ_IGNORE_SHADE;
3784 ctm = pagectm (page);
3785 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3787 fz_drop_device (state.ctx, dev);
3788 fz_round_rect (&bbox, &rect);
3789 Field (ret_v, 0) = Val_int (bbox.x0);
3790 Field (ret_v, 1) = Val_int (bbox.y0);
3791 Field (ret_v, 2) = Val_int (bbox.x1);
3792 Field (ret_v, 3) = Val_int (bbox.y1);
3794 CAMLreturn (ret_v);
3797 CAMLprim value ml_setaalevel (value level_v)
3799 CAMLparam1 (level_v);
3801 state.aalevel = Int_val (level_v);
3802 CAMLreturn (Val_unit);
3805 #pragma GCC diagnostic push
3806 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3807 #include <X11/Xlib.h>
3808 #include <X11/cursorfont.h>
3809 #pragma GCC diagnostic pop
3811 #include <GL/glx.h>
3813 static struct {
3814 Window wid;
3815 Display *dpy;
3816 GLXContext ctx;
3817 XVisualInfo *visual;
3818 Cursor curs[5];
3819 } glx;
3821 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3823 CAMLparam3 (display_v, wid_v, screen_v);
3824 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3825 int shapes[] = { XC_arrow, XC_hand2, XC_exchange, XC_crosshair, XC_xterm };
3827 glx.dpy = XOpenDisplay (String_val (display_v));
3828 if (!glx.dpy) {
3829 caml_failwith ("XOpenDisplay");
3832 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
3833 if (!glx.visual) {
3834 XCloseDisplay (glx.dpy);
3835 caml_failwith ("glXChooseVisual");
3838 for (size_t n = 0; n < sizeof (shapes) / sizeof (shapes[0]); ++n) {
3839 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3842 glx.wid = Int_val (wid_v);
3843 CAMLreturn (Val_int (glx.visual->visualid));
3846 CAMLprim value ml_glxcompleteinit (value unit_v)
3848 CAMLparam1 (unit_v);
3850 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
3851 if (!glx.ctx) {
3852 caml_failwith ("glXCreateContext");
3855 XFree (glx.visual);
3856 glx.visual = NULL;
3858 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
3859 glXDestroyContext (glx.dpy, glx.ctx);
3860 glx.ctx = NULL;
3861 caml_failwith ("glXMakeCurrent");
3863 CAMLreturn (Val_unit);
3866 CAMLprim value ml_setcursor (value cursor_v)
3868 CAMLparam1 (cursor_v);
3869 XSetWindowAttributes wa = { .cursor = glx.curs[Int_val (cursor_v)] };
3870 XChangeWindowAttributes (glx.dpy, glx.wid, CWCursor, &wa);
3871 XFlush (glx.dpy);
3872 CAMLreturn (Val_unit);
3875 CAMLprim value ml_swapb (value unit_v)
3877 CAMLparam1 (unit_v);
3878 glXSwapBuffers (glx.dpy, glx.wid);
3879 CAMLreturn (Val_unit);
3882 #include "keysym2ucs.c"
3884 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3886 CAMLparam1 (keysym_v);
3887 CAMLlocal1 (str_v);
3888 KeySym keysym = Int_val (keysym_v);
3889 Rune rune;
3890 int len;
3891 char buf[5];
3893 rune = keysym2ucs (keysym);
3894 len = fz_runetochar (buf, rune);
3895 buf[len] = 0;
3896 str_v = caml_copy_string (buf);
3897 CAMLreturn (str_v);
3900 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
3902 CAMLprim value ml_platform (value unit_v)
3904 CAMLparam1 (unit_v);
3905 CAMLlocal2 (tup_v, arr_v);
3906 int platid = piunknown;
3907 struct utsname buf;
3909 #if defined __linux__
3910 platid = pilinux;
3911 #elif defined __CYGWIN__
3912 platid = picygwin;
3913 #elif defined __DragonFly__ || defined __FreeBSD__
3914 || defined __OpenBSD__ || defined __NetBSD__
3915 platid = pibsd;
3916 #elif defined __sun__
3917 platid = pisun;
3918 #elif defined __APPLE__
3919 platid = piosx;
3920 #endif
3921 if (uname (&buf)) err (1, "uname");
3923 tup_v = caml_alloc_tuple (2);
3925 char const *sar[] = {
3926 buf.sysname,
3927 buf.release,
3928 buf.version,
3929 buf.machine,
3930 NULL
3932 arr_v = caml_copy_string_array (sar);
3934 Field (tup_v, 0) = Val_int (platid);
3935 Field (tup_v, 1) = arr_v;
3936 CAMLreturn (tup_v);
3939 CAMLprim value ml_cloexec (value fd_v)
3941 CAMLparam1 (fd_v);
3942 int fd = Int_val (fd_v);
3944 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3945 uerror ("fcntl", Nothing);
3947 CAMLreturn (Val_unit);
3950 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
3952 CAMLparam2 (w_v, h_v);
3953 CAMLlocal1 (ret_v);
3954 struct pbo *pbo;
3955 int w = Int_val (w_v);
3956 int h = Int_val (h_v);
3957 int cs = Int_val (cs_v);
3959 if (state.pbo_usable) {
3960 pbo = calloc (sizeof (*pbo), 1);
3961 if (!pbo) {
3962 err (1, "calloc pbo");
3965 switch (cs) {
3966 case 0:
3967 case 1:
3968 pbo->size = w*h*4;
3969 break;
3970 case 2:
3971 pbo->size = w*h*2;
3972 break;
3973 default:
3974 errx (1, "ml_getpbo: invalid colorspace %d", cs);
3977 state.glGenBuffersARB (1, &pbo->id);
3978 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3979 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
3980 NULL, GL_STREAM_DRAW);
3981 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3982 GL_READ_WRITE);
3983 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3984 if (!pbo->ptr) {
3985 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
3986 state.glDeleteBuffersARB (1, &pbo->id);
3987 free (pbo);
3988 ret_v = caml_copy_string ("0");
3990 else {
3991 int res;
3992 char *s;
3994 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
3995 if (res < 0) {
3996 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
3998 s = malloc (res+1);
3999 if (!s) {
4000 err (1, "malloc %d bytes failed", res+1);
4002 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
4003 if (res < 0) {
4004 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4006 ret_v = caml_copy_string (s);
4007 free (s);
4010 else {
4011 ret_v = caml_copy_string ("0");
4013 CAMLreturn (ret_v);
4016 CAMLprim value ml_freepbo (value s_v)
4018 CAMLparam1 (s_v);
4019 char *s = String_val (s_v);
4020 struct tile *tile = parse_pointer ("ml_freepbo", s);
4022 if (tile->pbo) {
4023 state.glDeleteBuffersARB (1, &tile->pbo->id);
4024 tile->pbo->id = -1;
4025 tile->pbo->ptr = NULL;
4026 tile->pbo->size = -1;
4028 CAMLreturn (Val_unit);
4031 CAMLprim value ml_unmappbo (value s_v)
4033 CAMLparam1 (s_v);
4034 char *s = String_val (s_v);
4035 struct tile *tile = parse_pointer ("ml_unmappbo", s);
4037 if (tile->pbo) {
4038 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4039 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4040 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4042 tile->pbo->ptr = NULL;
4043 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4045 CAMLreturn (Val_unit);
4048 static void setuppbo (void)
4050 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4051 state.pbo_usable = GGPA (glBindBufferARB)
4052 && GGPA (glUnmapBufferARB)
4053 && GGPA (glMapBufferARB)
4054 && GGPA (glBufferDataARB)
4055 && GGPA (glGenBuffersARB)
4056 && GGPA (glDeleteBuffersARB);
4057 #undef GGPA
4060 CAMLprim value ml_pbo_usable (value unit_v)
4062 CAMLparam1 (unit_v);
4063 CAMLreturn (Val_bool (state.pbo_usable));
4066 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4068 CAMLparam3 (ptr_v, x_v, y_v);
4069 CAMLlocal2 (ret_v, tup_v);
4070 struct page *page;
4071 char *s = String_val (ptr_v);
4072 int x = Int_val (x_v), y = Int_val (y_v);
4073 struct pagedim *pdim;
4074 fz_point p;
4075 fz_matrix ctm;
4077 page = parse_pointer ("ml_unproject", s);
4078 pdim = &state.pagedims[page->pdimno];
4080 ret_v = Val_int (0);
4081 if (trylock ("ml_unproject")) {
4082 goto done;
4085 if (pdf_specifics (state.ctx, state.doc)) {
4086 trimctm ((pdf_page *) page->fzpage, page->pdimno);
4087 ctm = state.pagedims[page->pdimno].tctm;
4089 else {
4090 ctm = fz_identity;
4092 p.x = x + pdim->bounds.x0;
4093 p.y = y + pdim->bounds.y0;
4095 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4096 fz_invert_matrix (&ctm, &ctm);
4097 fz_transform_point (&p, &ctm);
4099 tup_v = caml_alloc_tuple (2);
4100 ret_v = caml_alloc_small (1, 1);
4101 Field (tup_v, 0) = Val_int (p.x);
4102 Field (tup_v, 1) = Val_int (p.y);
4103 Field (ret_v, 0) = tup_v;
4105 unlock ("ml_unproject");
4106 done:
4107 CAMLreturn (ret_v);
4110 CAMLprim value ml_addannot (value ptr_v, value x_v, value y_v,
4111 value contents_v)
4113 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4114 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4116 if (pdf) {
4117 pdf_annot *annot;
4118 struct page *page;
4119 fz_point p;
4120 char *s = String_val (ptr_v);
4122 page = parse_pointer ("ml_addannot", s);
4123 annot = pdf_create_annot (state.ctx, pdf,
4124 (pdf_page *) page->fzpage, FZ_ANNOT_TEXT);
4125 p.x = Int_val (x_v);
4126 p.y = Int_val (y_v);
4127 pdf_set_annot_contents (state.ctx, pdf, annot, String_val (contents_v));
4128 pdf_set_text_annot_position (state.ctx, pdf, annot, p);
4129 state.dirty = 1;
4131 CAMLreturn (Val_unit);
4134 CAMLprim value ml_delannot (value ptr_v, value n_v)
4136 CAMLparam2 (ptr_v, n_v);
4137 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4139 if (pdf) {
4140 struct page *page;
4141 char *s = String_val (ptr_v);
4142 struct slink *slink;
4144 page = parse_pointer ("ml_delannot", s);
4145 slink = &page->slinks[Int_val (n_v)];
4146 pdf_delete_annot (state.ctx, pdf,
4147 (pdf_page *) page->fzpage,
4148 (pdf_annot *) slink->u.annot);
4149 state.dirty = 1;
4151 CAMLreturn (Val_unit);
4154 CAMLprim value ml_modannot (value ptr_v, value n_v, value str_v)
4156 CAMLparam3 (ptr_v, n_v, str_v);
4157 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4159 if (pdf) {
4160 struct page *page;
4161 char *s = String_val (ptr_v);
4162 struct slink *slink;
4164 page = parse_pointer ("ml_modannot", s);
4165 slink = &page->slinks[Int_val (n_v)];
4166 pdf_set_annot_contents (state.ctx, pdf, (pdf_annot *) slink->u.annot,
4167 String_val (str_v));
4168 state.dirty = 1;
4170 CAMLreturn (Val_unit);
4173 CAMLprim value ml_hasunsavedchanges (value unit_v)
4175 CAMLparam1 (unit_v);
4176 CAMLreturn (Val_bool (state.dirty));
4179 CAMLprim value ml_savedoc (value path_v)
4181 CAMLparam1 (path_v);
4182 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4184 if (pdf) {
4185 pdf_write_document (state.ctx, pdf, String_val (path_v), NULL);
4187 CAMLreturn (Val_unit);
4190 static void makestippletex (void)
4192 const char pixels[] = "\xff\xff\0\0";
4193 glGenTextures (1, &state.stid);
4194 glBindTexture (GL_TEXTURE_1D, state.stid);
4195 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4196 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4197 glTexImage1D (
4198 GL_TEXTURE_1D,
4200 GL_ALPHA,
4203 GL_ALPHA,
4204 GL_UNSIGNED_BYTE,
4205 pixels
4209 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4211 return caml_copy_string (FZ_VERSION);
4214 #ifdef USE_FONTCONFIG
4215 static struct {
4216 int inited;
4217 FcConfig *config;
4218 } fc;
4220 static fz_font *fc_load_system_font_func (fz_context *ctx,
4221 const char *name,
4222 int bold,
4223 int italic,
4224 int UNUSED_ATTR needs_exact_metrics)
4226 char *buf;
4227 size_t i, size;
4228 fz_font *font;
4229 FcChar8 *path;
4230 FcResult result;
4231 FcPattern *pat, *pat1;
4233 lprintf ("looking up %s bold:%d italic:%d needs_exact_metrics:%d\n",
4234 name, bold, italic, needs_exact_metrics);
4235 if (!fc.inited) {
4236 fc.inited = 1;
4237 fc.config = FcInitLoadConfigAndFonts ();
4238 if (!fc.config) {
4239 lprintf ("FcInitLoadConfigAndFonts failed\n");
4240 return NULL;
4243 if (!fc.config) return NULL;
4245 size = strlen (name);
4246 if (bold) size += sizeof (":bold") - 1;
4247 if (italic) size += sizeof (":italic") - 1;
4248 size += 1;
4250 buf = malloc (size);
4251 if (!buf) {
4252 err (1, "malloc %zu failed", size);
4255 strcpy (buf, name);
4256 if (bold && italic) {
4257 strcat (buf, ":bold:italic");
4259 else {
4260 if (bold) strcat (buf, ":bold");
4261 if (italic) strcat (buf, ":italic");
4263 for (i = 0; i < size; ++i) {
4264 if (buf[i] == ',' || buf[i] == '-') buf[i] = ':';
4267 lprintf ("fcbuf=%s\n", buf);
4268 pat = FcNameParse ((FcChar8 *) buf);
4269 if (!pat) {
4270 printd ("emsg FcNameParse failed\n");
4271 free (buf);
4272 return NULL;
4275 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4276 printd ("emsg FcConfigSubstitute failed\n");
4277 free (buf);
4278 return NULL;
4280 FcDefaultSubstitute (pat);
4282 pat1 = FcFontMatch (fc.config, pat, &result);
4283 if (!pat1) {
4284 printd ("emsg FcFontMatch failed\n");
4285 FcPatternDestroy (pat);
4286 free (buf);
4287 return NULL;
4290 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4291 printd ("emsg FcPatternGetString failed\n");
4292 FcPatternDestroy (pat);
4293 FcPatternDestroy (pat1);
4294 free (buf);
4295 return NULL;
4298 #if 0
4299 printd ("emsg name=%s path=%s\n", name, path);
4300 #endif
4301 font = fz_new_font_from_file (ctx, name, (char *) path, 0, 0);
4302 FcPatternDestroy (pat);
4303 FcPatternDestroy (pat1);
4304 free (buf);
4305 return font;
4307 #endif
4309 CAMLprim value ml_init (value csock_v, value params_v)
4311 CAMLparam2 (csock_v, params_v);
4312 CAMLlocal2 (trim_v, fuzz_v);
4313 int ret;
4314 int texcount;
4315 char *fontpath;
4316 int colorspace;
4317 int mustoresize;
4318 int haspboext;
4320 state.csock = Int_val (csock_v);
4321 state.rotate = Int_val (Field (params_v, 0));
4322 state.fitmodel = Int_val (Field (params_v, 1));
4323 trim_v = Field (params_v, 2);
4324 texcount = Int_val (Field (params_v, 3));
4325 state.sliceheight = Int_val (Field (params_v, 4));
4326 mustoresize = Int_val (Field (params_v, 5));
4327 colorspace = Int_val (Field (params_v, 6));
4328 fontpath = String_val (Field (params_v, 7));
4330 if (caml_string_length (Field (params_v, 8)) > 0) {
4331 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4333 if (!state.trimcachepath) {
4334 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4335 strerror (errno));
4338 haspboext = Bool_val (Field (params_v, 9));
4340 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4341 fz_register_document_handlers (state.ctx);
4343 #ifdef USE_FONTCONFIG
4344 if (Bool_val (Field (params_v, 10))) {
4345 fz_install_load_system_font_funcs (
4346 state.ctx, fc_load_system_font_func, NULL
4349 #endif
4351 state.trimmargins = Bool_val (Field (trim_v, 0));
4352 fuzz_v = Field (trim_v, 1);
4353 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4354 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4355 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4356 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4358 set_tex_params (colorspace);
4360 if (*fontpath) {
4361 #ifndef USE_FONTCONFIG
4362 state.face = load_font (fontpath);
4363 #else
4364 FcChar8 *path;
4365 FcResult result;
4366 char *buf = fontpath;
4367 FcPattern *pat, *pat1;
4369 fc.inited = 1;
4370 fc.config = FcInitLoadConfigAndFonts ();
4371 if (!fc.config) {
4372 errx (1, "FcInitLoadConfigAndFonts failed");
4375 pat = FcNameParse ((FcChar8 *) buf);
4376 if (!pat) {
4377 errx (1, "FcNameParse failed");
4380 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4381 errx (1, "FcConfigSubstitute failed");
4383 FcDefaultSubstitute (pat);
4385 pat1 = FcFontMatch (fc.config, pat, &result);
4386 if (!pat1) {
4387 errx (1, "FcFontMatch failed");
4390 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4391 errx (1, "FcPatternGetString failed");
4394 state.face = load_font ((char *) path);
4395 FcPatternDestroy (pat);
4396 FcPatternDestroy (pat1);
4397 #endif
4399 else {
4400 unsigned int len;
4401 void *base = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
4403 state.face = load_builtin_font (base, len);
4405 if (!state.face) _exit (1);
4407 realloctexts (texcount);
4409 if (haspboext) {
4410 setuppbo ();
4413 makestippletex ();
4415 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4416 if (ret) {
4417 errx (1, "pthread_create: %s", strerror (ret));
4420 CAMLreturn (Val_unit);