More ash fun
[llpp.git] / link.c
blobb8037c9bc08d8da70b232a99773630d51cbe0f34
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 #ifdef OBSCURED_OPT
714 struct obs {
715 fz_device super;
716 int cured;
717 fz_irect b;
720 static void obs_fill_image (fz_context *ctx, fz_device *dev,
721 fz_image UNUSED_ATTR *image,
722 const fz_matrix *ctm, float alpha)
724 struct obs *obs = (struct obs *) dev;
725 (void) ctx;
727 if (!obs->cured && fabs (1.0 - alpha) < 1e6) {
728 fz_irect b;
729 fz_rect rect = fz_unit_rect;
731 fz_transform_rect (&rect, ctm);
732 fz_round_rect (&b, &rect);
733 fz_intersect_irect (&b, &obs->b);
734 obs->cured = b.x0 == obs->b.x0
735 && b.x1 == obs->b.x1
736 && b.y0 == obs->b.y0
737 && b.y1 == obs->b.y1;
741 static int obscured (struct page *page, fz_irect bbox)
743 fz_rect rect;
744 fz_matrix ctm;
745 struct obs obs;
747 memset (&obs, 0, sizeof (obs));
748 obs.super.hints = 0;
749 obs.super.flags = 0;
750 obs.super.fill_image = obs_fill_image;
751 obs.b = bbox;
752 fz_rect_from_irect (&rect, &bbox);
753 ctm = pagectm (page);
754 fz_run_display_list (state.ctx, page->dlist, &obs.super, &ctm, &rect, NULL);
755 return obs.cured;
757 #define OBSCURED obscured
758 #else
759 #define OBSCURED(a, b) 0
760 #endif
762 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
763 struct pbo *pbo)
765 fz_rect rect;
766 fz_irect bbox;
767 fz_matrix ctm;
768 fz_device *dev;
769 struct tile *tile;
770 struct pagedim *pdim;
772 tile = alloctile (h);
773 pdim = &state.pagedims[page->pdimno];
775 bbox = pdim->bounds;
776 bbox.x0 += x;
777 bbox.y0 += y;
778 bbox.x1 = bbox.x0 + w;
779 bbox.y1 = bbox.y0 + h;
781 if (state.pig) {
782 if (state.pig->w == w
783 && state.pig->h == h
784 && state.pig->colorspace == state.colorspace) {
785 tile->pixmap = state.pig;
786 tile->pixmap->x = bbox.x0;
787 tile->pixmap->y = bbox.y0;
789 else {
790 fz_drop_pixmap (state.ctx, state.pig);
792 state.pig = NULL;
794 if (!tile->pixmap) {
795 if (pbo) {
796 tile->pixmap =
797 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
798 &bbox, pbo->ptr);
799 tile->pbo = pbo;
801 else {
802 tile->pixmap =
803 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox);
807 tile->w = w;
808 tile->h = h;
809 if (!page->fzpage || ((w < 128 && h < 128) || !OBSCURED (page, bbox))) {
810 clearpixmap (tile->pixmap);
812 dev = fz_new_draw_device (state.ctx, tile->pixmap);
813 ctm = pagectm (page);
814 fz_rect_from_irect (&rect, &bbox);
815 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
816 fz_drop_device (state.ctx, dev);
818 return tile;
821 #ifdef CACHE_PAGEREFS
822 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
823 thanks to Robin Watts */
824 static void
825 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
827 fz_context *ctx = state.ctx; /* doc->ctx; */
828 pdf_obj *kids;
829 int i, len;
831 if (state.pdflut.idx == state.pagecount) return;
833 kids = pdf_dict_gets (ctx, node, "Kids");
834 len = pdf_array_len (ctx, kids);
836 if (len == 0)
837 fz_throw (ctx, FZ_ERROR_GENERIC, "Malformed pages tree");
839 if (pdf_mark_obj (ctx, node))
840 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
841 for (i = 0; i < len; i++) {
842 pdf_obj *kid = pdf_array_get (ctx, kids, i);
843 char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
844 if (*type
845 ? !strcmp (type, "Pages")
846 : pdf_dict_gets (ctx, kid, "Kids")
847 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
848 pdf_collect_pages (doc, kid);
850 else {
851 if (*type
852 ? strcmp (type, "Page") != 0
853 : !pdf_dict_gets (ctx, kid, "MediaBox"))
854 fz_warn (ctx, "non-page object in page tree (%s)", type);
855 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
858 pdf_unmark_obj (ctx, node);
861 static void
862 pdf_load_page_objs (pdf_document *doc)
864 pdf_obj *root = pdf_dict_gets (state.ctx,
865 pdf_trailer (state.ctx, doc), "Root");
866 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
868 if (!node)
869 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
871 state.pdflut.idx = 0;
872 pdf_collect_pages (doc, node);
874 #endif
876 static void initpdims (void)
878 double start, end;
879 FILE *trimf = NULL;
880 fz_rect rootmediabox;
881 int pageno, trim, show;
882 int trimw = 0, cxcount;
883 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
885 start = now ();
887 if (state.trimmargins && state.trimcachepath) {
888 trimf = fopen (state.trimcachepath, "rb");
889 if (!trimf) {
890 trimf = fopen (state.trimcachepath, "wb");
891 trimw = 1;
895 if (state.trimmargins || pdf || !state.cxack)
896 cxcount = state.pagecount;
897 else
898 cxcount = MIN (state.pagecount, 1);
900 if (pdf) {
901 pdf_obj *obj;
902 obj = pdf_dict_getp (state.ctx, pdf_trailer (state.ctx, pdf),
903 "Root/Pages/MediaBox");
904 pdf_to_rect (state.ctx, obj, &rootmediabox);
907 #ifdef CACHE_PAGEREFS
908 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
909 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
910 if (!state.pdflut.objs) {
911 err (1, "malloc pageobjs %zu %d %zu failed",
912 sizeof (*state.pdflut.objs), cxcount,
913 sizeof (*state.pdflut.objs) * cxcount);
915 state.pdflut.count = cxcount;
916 pdf_load_page_objs (pdf);
917 state.pdflut.pdf = pdf;
919 #endif
921 for (pageno = 0; pageno < cxcount; ++pageno) {
922 int rotate = 0;
923 struct pagedim *p;
924 fz_rect mediabox;
926 if (pdf) {
927 pdf_obj *pageref, *pageobj;
929 #ifdef CACHE_PAGEREFS
930 pageref = state.pdflut.objs[pageno];
931 #else
932 pageref = pdf_lookup_page_obj (state.ctx, pdf, pageno);
933 #endif
934 pageobj = pdf_resolve_indirect (state.ctx, pageref);
936 if (state.trimmargins) {
937 fz_context *ctx = state.ctx;
938 pdf_obj *obj;
939 pdf_page *page;
941 fz_try (state.ctx) {
942 page = pdf_load_page (ctx, pdf, pageno);
943 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
944 trim = state.trimanew || !obj;
945 if (trim) {
946 fz_rect rect;
947 fz_matrix ctm;
948 fz_device *dev;
950 dev = fz_new_bbox_device (ctx, &rect);
951 dev->hints |= FZ_IGNORE_SHADE;
952 fz_invert_matrix (&ctm, &page->ctm);
953 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
954 fz_drop_device (ctx, dev);
956 rect.x0 += state.trimfuzz.x0;
957 rect.x1 += state.trimfuzz.x1;
958 rect.y0 += state.trimfuzz.y0;
959 rect.y1 += state.trimfuzz.y1;
960 fz_transform_rect (&rect, &ctm);
961 fz_intersect_rect (&rect, &page->mediabox);
963 if (fz_is_empty_rect (&rect)) {
964 mediabox = page->mediabox;
966 else {
967 mediabox = rect;
970 obj = pdf_new_array (ctx, pdf, 4);
971 pdf_array_push (ctx, obj, pdf_new_real (state.ctx, pdf,
972 mediabox.x0));
973 pdf_array_push (ctx, obj, pdf_new_real (state.ctx, pdf,
974 mediabox.y0));
975 pdf_array_push (ctx, obj, pdf_new_real (state.ctx, pdf,
976 mediabox.x1));
977 pdf_array_push (ctx, obj, pdf_new_real (state.ctx, pdf,
978 mediabox.y1));
979 pdf_dict_puts (state.ctx, pageobj, "llpp.TrimBox", obj);
981 else {
982 mediabox.x0 = pdf_to_real (ctx,
983 pdf_array_get (ctx, obj, 0));
984 mediabox.y0 = pdf_to_real (ctx,
985 pdf_array_get (ctx, obj, 1));
986 mediabox.x1 = pdf_to_real (ctx,
987 pdf_array_get (ctx, obj, 2));
988 mediabox.y1 = pdf_to_real (ctx,
989 pdf_array_get (ctx, obj, 3));
992 rotate = page->rotate;
993 fz_drop_page (ctx, &page->super);
995 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
996 if (show) {
997 printd ("progress %f Trimming %d",
998 (double) (pageno + 1) / state.pagecount,
999 pageno + 1);
1002 fz_catch (state.ctx) {
1003 fprintf (stderr, "failed to load page %d\n", pageno+1);
1006 else {
1007 int empty = 0;
1008 fz_rect cropbox;
1010 pdf_to_rect (state.ctx,
1011 pdf_dict_gets (state.ctx, pageobj, "MediaBox"),
1012 &mediabox);
1013 if (fz_is_empty_rect (&mediabox)) {
1014 mediabox.x0 = 0;
1015 mediabox.y0 = 0;
1016 mediabox.x1 = 612;
1017 mediabox.y1 = 792;
1018 empty = 1;
1021 pdf_to_rect (state.ctx,
1022 pdf_dict_gets (state.ctx, pageobj, "CropBox"),
1023 &cropbox);
1024 if (!fz_is_empty_rect (&cropbox)) {
1025 if (empty) {
1026 mediabox = cropbox;
1028 else {
1029 fz_intersect_rect (&mediabox, &cropbox);
1032 else {
1033 if (empty) {
1034 if (fz_is_empty_rect (&rootmediabox)) {
1035 fprintf (stderr,
1036 "cannot find page size for page %d\n",
1037 pageno+1);
1039 else {
1040 mediabox = rootmediabox;
1044 rotate = pdf_to_int (state.ctx,
1045 pdf_dict_gets (state.ctx,
1046 pageobj, "Rotate"));
1049 else {
1050 if (state.trimmargins && trimw) {
1051 fz_page *page;
1053 fz_try (state.ctx) {
1054 page = fz_load_page (state.ctx, state.doc, pageno);
1055 fz_bound_page (state.ctx, page, &mediabox);
1056 rotate = 0;
1057 if (state.trimmargins) {
1058 fz_rect rect;
1059 fz_device *dev;
1061 dev = fz_new_bbox_device (state.ctx, &rect);
1062 dev->hints |= FZ_IGNORE_SHADE;
1063 fz_run_page (state.ctx, page, dev,
1064 &fz_identity, NULL);
1065 fz_drop_device (state.ctx, dev);
1067 rect.x0 += state.trimfuzz.x0;
1068 rect.x1 += state.trimfuzz.x1;
1069 rect.y0 += state.trimfuzz.y0;
1070 rect.y1 += state.trimfuzz.y1;
1071 fz_intersect_rect (&rect, &mediabox);
1073 if (!fz_is_empty_rect (&rect)) {
1074 mediabox = rect;
1077 fz_drop_page (state.ctx, page);
1078 if (!state.cxack) {
1079 printd ("progress %f loading %d",
1080 (double) (pageno + 1) / state.pagecount,
1081 pageno + 1);
1084 fz_catch (state.ctx) {
1086 if (trimf) {
1087 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1088 if (n - 1) {
1089 err (1, "fwrite trim mediabox");
1093 else {
1094 if (trimf) {
1095 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1096 if (n - 1) {
1097 err (1, "fread trim mediabox %d", pageno);
1100 else {
1101 fz_page *page;
1102 fz_try (state.ctx) {
1103 page = fz_load_page (state.ctx,
1104 state.doc, pageno);
1105 fz_bound_page (state.ctx, page, &mediabox);
1106 fz_drop_page (state.ctx, page);
1108 show = !state.trimmargins && pageno % 20 == 0;
1109 if (show) {
1110 printd ("progress %f Gathering dimensions %d",
1111 (double) (pageno) / state.pagecount,
1112 pageno);
1115 fz_catch (state.ctx) {
1116 fprintf (stderr, "failed to load page %d\n", pageno);
1122 if (state.pagedimcount == 0
1123 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1124 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1125 size_t size;
1127 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1128 state.pagedims = realloc (state.pagedims, size);
1129 if (!state.pagedims) {
1130 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1131 size, state.pagedimcount + 1);
1134 p = &state.pagedims[state.pagedimcount++];
1135 p->rotate = rotate;
1136 p->mediabox = mediabox;
1137 p->pageno = pageno;
1140 end = now ();
1141 if (state.trimmargins) {
1142 printd ("progress 1 Trimmed %d pages in %f seconds",
1143 state.pagecount, end - start);
1145 else {
1146 printd ("progress 1 Processed %d pages in %f seconds\n",
1147 state.pagecount, end - start);
1149 state.trimanew = 0;
1150 if (trimf) {
1151 if (fclose (trimf)) {
1152 err (1, "fclose");
1157 static void layout (void)
1159 int pindex;
1160 fz_rect box;
1161 fz_matrix ctm, rm;
1162 struct pagedim *p = p;
1163 double zw, w, maxw = 0.0, zoom = zoom;
1165 if (state.pagedimcount == 0) return;
1167 switch (state.fitmodel) {
1168 case FitProportional:
1169 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1170 double x0, x1;
1172 p = &state.pagedims[pindex];
1173 fz_rotate (&rm, p->rotate + state.rotate);
1174 box = p->mediabox;
1175 fz_transform_rect (&box, &rm);
1177 x0 = MIN (box.x0, box.x1);
1178 x1 = MAX (box.x0, box.x1);
1180 w = x1 - x0;
1181 maxw = MAX (w, maxw);
1182 zoom = state.w / maxw;
1184 break;
1186 case FitPage:
1187 maxw = state.w;
1188 break;
1190 case FitWidth:
1191 break;
1193 default:
1194 ARSERT (0 && state.fitmodel);
1197 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1198 fz_rect rect;
1199 fz_matrix tm, sm;
1201 p = &state.pagedims[pindex];
1202 fz_rotate (&ctm, state.rotate);
1203 fz_rotate (&rm, p->rotate + state.rotate);
1204 box = p->mediabox;
1205 fz_transform_rect (&box, &rm);
1206 w = box.x1 - box.x0;
1207 switch (state.fitmodel) {
1208 case FitProportional:
1209 p->left = ((maxw - w) * zoom) / 2.0;
1210 break;
1211 case FitPage:
1213 double zh, h;
1214 zw = maxw / w;
1215 h = box.y1 - box.y0;
1216 zh = state.h / h;
1217 zoom = MIN (zw, zh);
1218 p->left = (maxw - (w * zoom)) / 2.0;
1220 break;
1221 case FitWidth:
1222 p->left = 0;
1223 zoom = state.w / w;
1224 break;
1227 fz_scale (&p->zoomctm, zoom, zoom);
1228 fz_concat (&ctm, &p->zoomctm, &ctm);
1230 fz_rotate (&rm, p->rotate);
1231 p->pagebox = p->mediabox;
1232 fz_transform_rect (&p->pagebox, &rm);
1233 p->pagebox.x1 -= p->pagebox.x0;
1234 p->pagebox.y1 -= p->pagebox.y0;
1235 p->pagebox.x0 = 0;
1236 p->pagebox.y0 = 0;
1237 rect = p->pagebox;
1238 fz_transform_rect (&rect, &ctm);
1239 fz_round_rect (&p->bounds, &rect);
1240 p->ctm = ctm;
1242 fz_translate (&tm, 0, -p->mediabox.y1);
1243 fz_scale (&sm, zoom, -zoom);
1244 fz_concat (&ctm, &tm, &sm);
1245 fz_concat (&p->lctm, &ctm, &rm);
1247 p->tctmready = 0;
1250 do {
1251 int x0 = MIN (p->bounds.x0, p->bounds.x1);
1252 int y0 = MIN (p->bounds.y0, p->bounds.y1);
1253 int x1 = MAX (p->bounds.x0, p->bounds.x1);
1254 int y1 = MAX (p->bounds.y0, p->bounds.y1);
1255 int boundw = x1 - x0;
1256 int boundh = y1 - y0;
1258 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1259 } while (p-- != state.pagedims);
1262 static
1263 struct anchor { int n; int x; int y; int w; int h; }
1264 desttoanchor (fz_link_dest *dest)
1266 int i;
1267 struct anchor a;
1268 struct pagedim *pdim = state.pagedims;
1270 a.n = -1;
1271 a.x = 0;
1272 a.y = 0;
1273 for (i = 0; i < state.pagedimcount; ++i) {
1274 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1275 break;
1276 pdim = &state.pagedims[i];
1278 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1279 fz_point p;
1280 if (dest->ld.gotor.flags & fz_link_flag_l_valid)
1281 p.x = dest->ld.gotor.lt.x;
1282 else
1283 p.x = 0.0;
1284 p.y = dest->ld.gotor.lt.y;
1285 fz_transform_point (&p, &pdim->lctm);
1286 a.x = p.x;
1287 a.y = p.y;
1289 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1290 double x0, x1, y0, y1;
1292 x0 = MIN (pdim->bounds.x0, pdim->bounds.x1);
1293 x1 = MAX (pdim->bounds.x0, pdim->bounds.x1);
1294 a.w = x1 - x0;
1295 y0 = MIN (pdim->bounds.y0, pdim->bounds.y1);
1296 y1 = MAX (pdim->bounds.y0, pdim->bounds.y1);
1297 a.h = y1 - y0;
1298 a.n = dest->ld.gotor.page;
1300 return a;
1303 static void recurse_outline (fz_outline *outline, int level)
1305 while (outline) {
1306 switch (outline->dest.kind) {
1307 case FZ_LINK_GOTO:
1309 struct anchor a = desttoanchor (&outline->dest);
1311 if (a.n >= 0) {
1312 printd ("o %d %d %d %d %s",
1313 level, a.n, a.y, a.h, outline->title);
1316 break;
1318 case FZ_LINK_URI:
1319 printd ("ou %d %" FMT_s " %s %s", level,
1320 strlen (outline->title), outline->title,
1321 outline->dest.ld.uri.uri);
1322 break;
1324 case FZ_LINK_NONE:
1325 printd ("on %d %s", level, outline->title);
1326 break;
1328 default:
1329 printd ("emsg Unhandled outline kind %d for %s\n",
1330 outline->dest.kind, outline->title);
1331 break;
1333 if (outline->down) {
1334 recurse_outline (outline->down, level + 1);
1336 outline = outline->next;
1340 static void process_outline (void)
1342 fz_outline *outline;
1344 if (!state.needoutline || !state.pagedimcount) return;
1346 state.needoutline = 0;
1347 outline = fz_load_outline (state.ctx, state.doc);
1348 if (outline) {
1349 recurse_outline (outline, 0);
1350 fz_drop_outline (state.ctx, outline);
1354 static char *strofspan (fz_text_span *span)
1356 char *p;
1357 char utf8[10];
1358 fz_text_char *ch;
1359 size_t size = 0, cap = 80;
1361 p = malloc (cap + 1);
1362 if (!p) return NULL;
1364 for (ch = span->text; ch < span->text + span->len; ++ch) {
1365 int n = fz_runetochar (utf8, ch->c);
1366 if (size + n > cap) {
1367 cap *= 2;
1368 p = realloc (p, cap + 1);
1369 if (!p) return NULL;
1372 memcpy (p + size, utf8, n);
1373 size += n;
1375 p[size] = 0;
1376 return p;
1379 static int matchspan (regex_t *re, fz_text_span *span,
1380 int stop, int pageno, double start)
1382 int ret;
1383 char *p;
1384 regmatch_t rm;
1385 int a, b, c;
1386 fz_rect sb, eb;
1387 fz_point p1, p2, p3, p4;
1389 p = strofspan (span);
1390 if (!p) return -1;
1392 ret = regexec (re, p, 1, &rm, 0);
1393 if (ret) {
1394 free (p);
1395 if (ret != REG_NOMATCH) {
1396 size_t size;
1397 char errbuf[80];
1398 size = regerror (ret, re, errbuf, sizeof (errbuf));
1399 printd ("msg regexec error `%.*s'",
1400 (int) size, errbuf);
1401 return -1;
1403 return 0;
1405 else {
1406 int l = span->len;
1408 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1409 c += fz_runelen (span->text[a].c);
1411 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1412 c += fz_runelen (span->text[b].c);
1415 if (fz_runelen (span->text[b].c) > 1) {
1416 b = MAX (0, b-1);
1419 fz_text_char_bbox (state.ctx, &sb, span, a);
1420 fz_text_char_bbox (state.ctx, &eb, span, b);
1422 p1.x = sb.x0;
1423 p1.y = sb.y0;
1424 p2.x = eb.x1;
1425 p2.y = sb.y0;
1426 p3.x = eb.x1;
1427 p3.y = eb.y1;
1428 p4.x = sb.x0;
1429 p4.y = eb.y1;
1431 if (!stop) {
1432 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1433 pageno, 1,
1434 p1.x, p1.y,
1435 p2.x, p2.y,
1436 p3.x, p3.y,
1437 p4.x, p4.y);
1439 printd ("progress 1 found at %d `%.*s' in %f sec",
1440 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1441 now () - start);
1443 else {
1444 printd ("match %d %d %f %f %f %f %f %f %f %f",
1445 pageno, 2,
1446 p1.x, p1.y,
1447 p2.x, p2.y,
1448 p3.x, p3.y,
1449 p4.x, p4.y);
1451 free (p);
1452 return 1;
1456 static int compareblocks (const void *l, const void *r)
1458 fz_text_block const *ls = l;
1459 fz_text_block const* rs = r;
1460 return ls->bbox.y0 - rs->bbox.y0;
1463 /* wishful thinking function */
1464 static void search (regex_t *re, int pageno, int y, int forward)
1466 int i, j;
1467 fz_device *tdev;
1468 fz_text_page *text;
1469 fz_text_sheet *sheet;
1470 struct pagedim *pdim, *pdimprev;
1471 int stop = 0, niters = 0;
1472 double start, end;
1473 fz_page *page;
1475 start = now ();
1476 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1477 if (niters++ == 5) {
1478 niters = 0;
1479 if (hasdata ()) {
1480 printd ("progress 1 attention requested aborting search at %d",
1481 pageno);
1482 stop = 1;
1484 else {
1485 printd ("progress %f searching in page %d",
1486 (double) (pageno + 1) / state.pagecount,
1487 pageno);
1490 pdimprev = NULL;
1491 for (i = 0; i < state.pagedimcount; ++i) {
1492 pdim = &state.pagedims[i];
1493 if (pdim->pageno == pageno) {
1494 goto found;
1496 if (pdim->pageno > pageno) {
1497 pdim = pdimprev;
1498 goto found;
1500 pdimprev = pdim;
1502 pdim = pdimprev;
1503 found:
1505 sheet = fz_new_text_sheet (state.ctx);
1506 text = fz_new_text_page (state.ctx);
1507 tdev = fz_new_text_device (state.ctx, sheet, text);
1509 page = fz_load_page (state.ctx, state.doc, pageno);
1511 fz_matrix ctm = pagectm1 (page, pdim);
1512 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1515 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1516 fz_drop_device (state.ctx, tdev);
1518 for (j = 0; j < text->len; ++j) {
1519 int k;
1520 fz_page_block *pb;
1521 fz_text_block *block;
1523 pb = &text->blocks[forward ? j : text->len - 1 - j];
1524 if (pb->type != FZ_PAGE_BLOCK_TEXT) continue;
1525 block = pb->u.text;
1527 for (k = 0; k < block->len; ++k) {
1528 fz_text_line *line;
1529 fz_text_span *span;
1531 if (forward) {
1532 line = &block->lines[k];
1533 if (line->bbox.y0 < y + 1) continue;
1535 else {
1536 line = &block->lines[block->len - 1 - k];
1537 if (line->bbox.y0 > y - 1) continue;
1540 for (span = line->first_span; span; span = span->next) {
1541 switch (matchspan (re, span, stop, pageno, start)) {
1542 case 0: break;
1543 case 1: stop = 1; break;
1544 case -1: stop = 1; goto endloop;
1549 if (forward) {
1550 pageno += 1;
1551 y = 0;
1553 else {
1554 pageno -= 1;
1555 y = INT_MAX;
1557 endloop:
1558 fz_drop_text_page (state.ctx, text);
1559 fz_drop_text_sheet (state.ctx, sheet);
1560 fz_drop_page (state.ctx, page);
1562 end = now ();
1563 if (!stop) {
1564 printd ("progress 1 no matches %f sec", end - start);
1566 printd ("clearrects");
1569 static void set_tex_params (int colorspace)
1571 union {
1572 unsigned char b;
1573 unsigned int s;
1574 } endianness = {1};
1576 switch (colorspace) {
1577 case 0:
1578 state.texiform = GL_RGBA8;
1579 state.texform = GL_RGBA;
1580 state.texty = GL_UNSIGNED_BYTE;
1581 state.colorspace = fz_device_rgb (state.ctx);
1582 break;
1583 case 1:
1584 state.texiform = GL_RGBA8;
1585 state.texform = GL_BGRA;
1586 state.texty = endianness.s > 1
1587 ? GL_UNSIGNED_INT_8_8_8_8
1588 : GL_UNSIGNED_INT_8_8_8_8_REV;
1589 state.colorspace = fz_device_bgr (state.ctx);
1590 break;
1591 case 2:
1592 state.texiform = GL_LUMINANCE_ALPHA;
1593 state.texform = GL_LUMINANCE_ALPHA;
1594 state.texty = GL_UNSIGNED_BYTE;
1595 state.colorspace = fz_device_gray (state.ctx);
1596 break;
1597 default:
1598 errx (1, "invalid colorspce %d", colorspace);
1602 static void realloctexts (int texcount)
1604 size_t size;
1606 if (texcount == state.texcount) return;
1608 if (texcount < state.texcount) {
1609 glDeleteTextures (state.texcount - texcount,
1610 state.texids + texcount);
1613 size = texcount * sizeof (*state.texids);
1614 state.texids = realloc (state.texids, size);
1615 if (!state.texids) {
1616 err (1, "realloc texids %" FMT_s, size);
1619 size = texcount * sizeof (*state.texowners);
1620 state.texowners = realloc (state.texowners, size);
1621 if (!state.texowners) {
1622 err (1, "realloc texowners %" FMT_s, size);
1624 if (texcount > state.texcount) {
1625 int i;
1627 glGenTextures (texcount - state.texcount,
1628 state.texids + state.texcount);
1629 for (i = state.texcount; i < texcount; ++i) {
1630 state.texowners[i].w = -1;
1631 state.texowners[i].slice = NULL;
1634 state.texcount = texcount;
1635 state.texindex = 0;
1638 static char *mbtoutf8 (char *s)
1640 char *p, *r;
1641 wchar_t *tmp;
1642 size_t i, ret, len;
1644 len = mbstowcs (NULL, s, strlen (s));
1645 if (len == 0) {
1646 return s;
1648 else {
1649 if (len == (size_t) -1) {
1650 return s;
1654 tmp = malloc (len * sizeof (wchar_t));
1655 if (!tmp) {
1656 return s;
1659 ret = mbstowcs (tmp, s, len);
1660 if (ret == (size_t) -1) {
1661 free (tmp);
1662 return s;
1665 len = 0;
1666 for (i = 0; i < ret; ++i) {
1667 len += fz_runelen (tmp[i]);
1670 p = r = malloc (len + 1);
1671 if (!r) {
1672 free (tmp);
1673 return s;
1676 for (i = 0; i < ret; ++i) {
1677 p += fz_runetochar (p, tmp[i]);
1679 *p = 0;
1680 free (tmp);
1681 return r;
1684 CAMLprim value ml_mbtoutf8 (value s_v)
1686 CAMLparam1 (s_v);
1687 CAMLlocal1 (ret_v);
1688 char *s, *r;
1690 s = String_val (s_v);
1691 r = mbtoutf8 (s);
1692 if (r == s) {
1693 ret_v = s_v;
1695 else {
1696 ret_v = caml_copy_string (r);
1697 free (r);
1699 CAMLreturn (ret_v);
1702 static void * mainloop (void UNUSED_ATTR *unused)
1704 char *p = NULL;
1705 int len, ret, oldlen = 0;
1707 for (;;) {
1708 len = readlen ();
1709 if (len == 0) {
1710 errx (1, "readlen returned 0");
1713 if (oldlen < len + 1) {
1714 p = realloc (p, len + 1);
1715 if (!p) {
1716 err (1, "realloc %d failed", len + 1);
1718 oldlen = len + 1;
1720 readdata (p, len);
1721 p[len] = 0;
1723 if (!strncmp ("open", p, 4)) {
1724 int wthack, off, ok = 0;
1725 char *password;
1726 char *filename;
1727 char *utf8filename;
1728 size_t filenamelen;
1730 ret = sscanf (p + 5, " %d %d %n", &wthack, &state.cxack, &off);
1731 if (ret != 2) {
1732 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1735 filename = p + 5 + off;
1736 filenamelen = strlen (filename);
1737 password = filename + filenamelen + 1;
1739 lock ("open");
1740 fz_try (state.ctx) {
1741 ok = openxref (filename, password);
1743 fz_catch (state.ctx) {
1744 utf8filename = mbtoutf8 (filename);
1745 printd ("msg Could not open %s", utf8filename);
1747 if (ok) {
1748 pdfinfo ();
1749 initpdims ();
1751 unlock ("open");
1753 if (ok) {
1754 if (!wthack) {
1755 utf8filename = mbtoutf8 (filename);
1756 printd ("msg Opened %s (press h/F1 to get help)",
1757 utf8filename);
1758 if (utf8filename != filename) {
1759 free (utf8filename);
1762 state.needoutline = 1;
1765 else if (!strncmp ("cs", p, 2)) {
1766 int i, colorspace;
1768 ret = sscanf (p + 2, " %d", &colorspace);
1769 if (ret != 1) {
1770 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1772 lock ("cs");
1773 set_tex_params (colorspace);
1774 for (i = 0; i < state.texcount; ++i) {
1775 state.texowners[i].w = -1;
1776 state.texowners[i].slice = NULL;
1778 unlock ("cs");
1780 else if (!strncmp ("freepage", p, 8)) {
1781 void *ptr;
1783 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1784 if (ret != 1) {
1785 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1787 freepage (ptr);
1789 else if (!strncmp ("freetile", p, 8)) {
1790 void *ptr;
1792 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1793 if (ret != 1) {
1794 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1796 freetile (ptr);
1798 else if (!strncmp ("search", p, 6)) {
1799 int icase, pageno, y, len2, forward;
1800 char *pattern;
1801 regex_t re;
1803 ret = sscanf (p + 6, " %d %d %d %d,%n",
1804 &icase, &pageno, &y, &forward, &len2);
1805 if (ret != 4) {
1806 errx (1, "malformed search `%s' ret=%d", p, ret);
1809 pattern = p + 6 + len2;
1810 ret = regcomp (&re, pattern,
1811 REG_EXTENDED | (icase ? REG_ICASE : 0));
1812 if (ret) {
1813 char errbuf[80];
1814 size_t size;
1816 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1817 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1819 else {
1820 search (&re, pageno, y, forward);
1821 regfree (&re);
1824 else if (!strncmp ("geometry", p, 8)) {
1825 int w, h, fitmodel;
1827 printd ("clear");
1828 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1829 if (ret != 3) {
1830 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1833 lock ("geometry");
1834 state.h = h;
1835 if (w != state.w) {
1836 int i;
1837 state.w = w;
1838 for (i = 0; i < state.texcount; ++i) {
1839 state.texowners[i].slice = NULL;
1842 state.fitmodel = fitmodel;
1843 layout ();
1844 process_outline ();
1846 state.gen++;
1847 unlock ("geometry");
1848 printd ("continue %d", state.pagecount);
1850 else if (!strncmp ("reqlayout", p, 9)) {
1851 char *nameddest;
1852 int rotate, off, h;
1853 unsigned int fitmodel;
1854 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
1856 printd ("clear");
1857 ret = sscanf (p + 9, " %d %u %d %n",
1858 &rotate, &fitmodel, &h, &off);
1859 if (ret != 3) {
1860 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1862 lock ("reqlayout");
1863 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1864 state.gen += 1;
1866 state.rotate = rotate;
1867 state.fitmodel = fitmodel;
1868 state.h = h;
1869 layout ();
1870 process_outline ();
1872 nameddest = p + 9 + off;
1873 if (pdf && nameddest && *nameddest) {
1874 struct anchor a;
1875 fz_link_dest dest;
1876 pdf_obj *needle, *obj;
1878 needle = pdf_new_string (state.ctx, pdf, nameddest,
1879 strlen (nameddest));
1880 obj = pdf_lookup_dest (state.ctx, pdf, needle);
1881 if (obj) {
1882 dest = pdf_parse_link_dest (state.ctx, pdf,
1883 FZ_LINK_GOTO, obj);
1885 a = desttoanchor (&dest);
1886 if (a.n >= 0) {
1887 printd ("a %d %d %d", a.n, a.x, a.y);
1889 else {
1890 printd ("emsg failed to parse destination `%s'\n",
1891 nameddest);
1894 else {
1895 printd ("emsg destination `%s' not found\n",
1896 nameddest);
1898 pdf_drop_obj (state.ctx, needle);
1901 state.gen++;
1902 unlock ("reqlayout");
1903 printd ("continue %d", state.pagecount);
1905 else if (!strncmp ("page", p, 4)) {
1906 double a, b;
1907 struct page *page;
1908 int pageno, pindex;
1910 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1911 if (ret != 2) {
1912 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1915 lock ("page");
1916 a = now ();
1917 page = loadpage (pageno, pindex);
1918 b = now ();
1919 unlock ("page");
1921 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1923 else if (!strncmp ("tile", p, 4)) {
1924 int x, y, w, h;
1925 struct page *page;
1926 struct tile *tile;
1927 double a, b;
1928 void *data;
1930 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1931 SCN_ptr_cast (&page), &x, &y, &w, &h,
1932 SCN_ptr_cast (&data));
1933 if (ret != 6) {
1934 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1937 lock ("tile");
1938 a = now ();
1939 tile = rendertile (page, x, y, w, h, data);
1940 b = now ();
1941 unlock ("tile");
1943 printd ("tile %d %d %" FMT_ptr " %u %f",
1944 x, y,
1945 FMT_ptr_cast (tile),
1946 tile->w * tile->h * tile->pixmap->n,
1947 b - a);
1949 else if (!strncmp ("trimset", p, 7)) {
1950 fz_irect fuzz;
1951 int trimmargins;
1953 ret = sscanf (p + 7, " %d %d %d %d %d",
1954 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1955 if (ret != 5) {
1956 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1958 lock ("trimset");
1959 state.trimmargins = trimmargins;
1960 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1961 state.trimanew = 1;
1962 state.trimfuzz = fuzz;
1964 unlock ("trimset");
1966 else if (!strncmp ("settrim", p, 7)) {
1967 fz_irect fuzz;
1968 int trimmargins;
1970 ret = sscanf (p + 7, " %d %d %d %d %d",
1971 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1972 if (ret != 5) {
1973 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1975 printd ("clear");
1976 lock ("settrim");
1977 state.trimmargins = trimmargins;
1978 state.needoutline = 1;
1979 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1980 state.trimanew = 1;
1981 state.trimfuzz = fuzz;
1983 state.pagedimcount = 0;
1984 free (state.pagedims);
1985 state.pagedims = NULL;
1986 initpdims ();
1987 layout ();
1988 process_outline ();
1989 unlock ("settrim");
1990 printd ("continue %d", state.pagecount);
1992 else if (!strncmp ("sliceh", p, 6)) {
1993 int h;
1995 ret = sscanf (p + 6, " %d", &h);
1996 if (ret != 1) {
1997 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1999 if (h != state.sliceheight) {
2000 int i;
2002 state.sliceheight = h;
2003 for (i = 0; i < state.texcount; ++i) {
2004 state.texowners[i].w = -1;
2005 state.texowners[i].h = -1;
2006 state.texowners[i].slice = NULL;
2010 else if (!strncmp ("interrupt", p, 9)) {
2011 printd ("vmsg interrupted");
2013 else {
2014 errx (1, "unknown command %.*s", len, p);
2017 return 0;
2020 CAMLprim value ml_realloctexts (value texcount_v)
2022 CAMLparam1 (texcount_v);
2023 int ok;
2025 if (trylock ("ml_realloctexts")) {
2026 ok = 0;
2027 goto done;
2029 realloctexts (Int_val (texcount_v));
2030 ok = 1;
2031 unlock ("ml_realloctexts");
2033 done:
2034 CAMLreturn (Val_bool (ok));
2037 static void recti (int x0, int y0, int x1, int y1)
2039 GLfloat *v = state.vertices;
2041 glVertexPointer (2, GL_FLOAT, 0, v);
2042 v[0] = x0; v[1] = y0;
2043 v[2] = x1; v[3] = y0;
2044 v[4] = x0; v[5] = y1;
2045 v[6] = x1; v[7] = y1;
2046 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2049 static void showsel (struct page *page, int ox, int oy)
2051 int seen = 0;
2052 fz_irect bbox;
2053 fz_rect rect;
2054 fz_text_line *line;
2055 fz_page_block *pageb;
2056 fz_text_block *block;
2057 struct mark first, last;
2058 unsigned char selcolor[] = {15,15,15,140};
2060 first = page->fmark;
2061 last = page->lmark;
2063 if (!first.span || !last.span) return;
2065 glEnable (GL_BLEND);
2066 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2067 glColor4ubv (selcolor);
2069 ox += state.pagedims[page->pdimno].bounds.x0;
2070 oy += state.pagedims[page->pdimno].bounds.y0;
2071 for (pageb = page->text->blocks;
2072 pageb < page->text->blocks + page->text->len;
2073 ++pageb) {
2074 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2075 block = pageb->u.text;
2077 for (line = block->lines;
2078 line < block->lines + block->len;
2079 ++line) {
2080 fz_text_span *span;
2081 rect = fz_empty_rect;
2083 for (span = line->first_span; span; span = span->next) {
2084 int i, j, k;
2085 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2087 j = 0;
2088 k = span->len - 1;
2090 if (span == page->fmark.span && span == page->lmark.span) {
2091 seen = 1;
2092 j = MIN (first.i, last.i);
2093 k = MAX (first.i, last.i);
2095 else {
2096 if (span == first.span) {
2097 seen = 1;
2098 j = first.i;
2100 else if (span == last.span) {
2101 seen = 1;
2102 k = last.i;
2106 if (seen) {
2107 for (i = j; i <= k; ++i) {
2108 fz_rect bbox1;
2109 fz_union_rect (&rect,
2110 fz_text_char_bbox (state.ctx, &bbox1,
2111 span, i));
2113 fz_round_rect (&bbox, &rect);
2114 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2115 bbox.x0,
2116 bbox.y0,
2117 bbox.x1,
2118 bbox.y1,
2119 oy, ox);
2121 recti (bbox.x0 + ox, bbox.y0 + oy,
2122 bbox.x1 + ox, bbox.y1 + oy);
2123 if (span == last.span) {
2124 goto done;
2126 rect = fz_empty_rect;
2131 done:
2132 glDisable (GL_BLEND);
2135 #include "glfont.c"
2137 static void stipplerect (fz_matrix *m,
2138 fz_point *p1,
2139 fz_point *p2,
2140 fz_point *p3,
2141 fz_point *p4,
2142 GLfloat *texcoords,
2143 GLfloat *vertices)
2145 fz_transform_point (p1, m);
2146 fz_transform_point (p2, m);
2147 fz_transform_point (p3, m);
2148 fz_transform_point (p4, m);
2150 float w, h, s, t;
2152 w = p2->x - p1->x;
2153 h = p2->y - p1->y;
2154 t = sqrtf (w*w + h*h) * .25f;
2156 w = p3->x - p2->x;
2157 h = p3->y - p2->y;
2158 s = sqrtf (w*w + h*h) * .25f;
2160 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2161 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2163 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2164 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2166 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2167 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2169 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2170 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2172 glDrawArrays (GL_LINES, 0, 8);
2175 static void highlightlinks (struct page *page, int xoff, int yoff)
2177 int i;
2178 fz_matrix ctm, tm, pm;
2179 fz_link *link, *links;
2180 GLfloat *texcoords = state.texcoords;
2181 GLfloat *vertices = state.vertices;
2183 links = fz_load_links (state.ctx, page->fzpage);
2185 glEnable (GL_TEXTURE_1D);
2186 glEnable (GL_BLEND);
2187 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2188 glBindTexture (GL_TEXTURE_1D, state.stid);
2190 xoff -= state.pagedims[page->pdimno].bounds.x0;
2191 yoff -= state.pagedims[page->pdimno].bounds.y0;
2192 fz_translate (&tm, xoff, yoff);
2193 pm = pagectm (page);
2194 fz_concat (&ctm, &pm, &tm);
2196 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2197 glVertexPointer (2, GL_FLOAT, 0, vertices);
2199 for (link = links; link; link = link->next) {
2200 fz_point p1, p2, p3, p4;
2202 p1.x = link->rect.x0;
2203 p1.y = link->rect.y0;
2205 p2.x = link->rect.x1;
2206 p2.y = link->rect.y0;
2208 p3.x = link->rect.x1;
2209 p3.y = link->rect.y1;
2211 p4.x = link->rect.x0;
2212 p4.y = link->rect.y1;
2214 switch (link->dest.kind) {
2215 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
2216 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
2217 case FZ_LINK_LAUNCH: glColor3ub (0, 255, 0); break;
2218 default: glColor3ub (0, 0, 0); break;
2220 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2223 for (i = 0; i < page->annotcount; ++i) {
2224 fz_point p1, p2, p3, p4;
2225 struct annot *annot = &page->annots[i];
2227 p1.x = annot->bbox.x0;
2228 p1.y = annot->bbox.y0;
2230 p2.x = annot->bbox.x1;
2231 p2.y = annot->bbox.y0;
2233 p3.x = annot->bbox.x1;
2234 p3.y = annot->bbox.y1;
2236 p4.x = annot->bbox.x0;
2237 p4.y = annot->bbox.y1;
2239 glColor3ub (0, 0, 128);
2240 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2243 glDisable (GL_BLEND);
2244 glDisable (GL_TEXTURE_1D);
2247 static int compareslinks (const void *l, const void *r)
2249 struct slink const *ls = l;
2250 struct slink const *rs = r;
2251 if (ls->bbox.y0 == rs->bbox.y0) {
2252 return rs->bbox.x0 - rs->bbox.x0;
2254 return ls->bbox.y0 - rs->bbox.y0;
2257 static void droptext (struct page *page)
2259 if (page->text) {
2260 fz_drop_text_page (state.ctx, page->text);
2261 page->fmark.i = -1;
2262 page->lmark.i = -1;
2263 page->fmark.span = NULL;
2264 page->lmark.span = NULL;
2265 page->text = NULL;
2267 if (page->sheet) {
2268 fz_drop_text_sheet (state.ctx, page->sheet);
2269 page->sheet = NULL;
2273 static void dropanots (struct page *page)
2275 if (page->annots) {
2276 free (page->annots);
2277 page->annots = NULL;
2278 page->annotcount = 0;
2282 static void ensureanots (struct page *page)
2284 int i, count = 0;
2285 size_t anotsize = sizeof (*page->annots);
2286 fz_annot *annot;
2288 if (state.gen != page->agen) {
2289 dropanots (page);
2290 page->agen = state.gen;
2292 if (page->annots) return;
2294 for (annot = fz_first_annot (state.ctx, page->fzpage);
2295 annot;
2296 annot = fz_next_annot (state.ctx, page->fzpage, annot)) {
2297 count++;
2300 if (count > 0) {
2301 page->annotcount = count;
2302 page->annots = calloc (count, anotsize);
2303 if (!page->annots) {
2304 err (1, "calloc annots %d", count);
2307 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2308 annot;
2309 annot = fz_next_annot (state.ctx, page->fzpage, annot), i++) {
2310 fz_rect rect;
2312 fz_bound_annot (state.ctx, page->fzpage, annot, &rect);
2313 page->annots[i].annot = annot;
2314 fz_round_rect (&page->annots[i].bbox, &rect);
2319 static void dropslinks (struct page *page)
2321 if (page->slinks) {
2322 free (page->slinks);
2323 page->slinks = NULL;
2324 page->slinkcount = 0;
2328 static void ensureslinks (struct page *page)
2330 fz_matrix ctm;
2331 int i, count;
2332 size_t slinksize = sizeof (*page->slinks);
2333 fz_link *link, *links;
2335 ensureanots (page);
2336 if (state.gen != page->sgen) {
2337 dropslinks (page);
2338 page->sgen = state.gen;
2340 if (page->slinks) return;
2342 links = fz_load_links (state.ctx, page->fzpage);
2343 ctm = state.pagedims[page->pdimno].ctm;
2345 count = page->annotcount;
2346 for (link = links; link; link = link->next) {
2347 count++;
2349 if (count > 0) {
2350 int j;
2352 page->slinkcount = count;
2353 page->slinks = calloc (count, slinksize);
2354 if (!page->slinks) {
2355 err (1, "calloc slinks %d", count);
2358 for (i = 0, link = links; link; ++i, link = link->next) {
2359 fz_rect rect;
2361 rect = link->rect;
2362 fz_transform_rect (&rect, &ctm);
2363 page->slinks[i].tag = SLINK;
2364 page->slinks[i].u.link = link;
2365 fz_round_rect (&page->slinks[i].bbox, &rect);
2367 for (j = 0; j < page->annotcount; ++j, ++i) {
2368 fz_rect rect;
2369 fz_bound_annot (state.ctx,
2370 page->fzpage,
2371 page->annots[j].annot,
2372 &rect);
2373 fz_transform_rect (&rect, &ctm);
2374 fz_round_rect (&page->slinks[i].bbox, &rect);
2376 page->slinks[i].tag = SANNOT;
2377 page->slinks[i].u.annot = page->annots[j].annot;
2379 qsort (page->slinks, count, slinksize, compareslinks);
2383 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2384 static void fmt_linkn (char *s, unsigned int u)
2386 unsigned int len; unsigned int q;
2387 unsigned int zma = 'z' - 'a' + 1;
2388 len = 1; q = u;
2389 while (q > zma - 1) { ++len; q /= zma; }
2390 if (s) {
2391 s += len;
2392 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2393 /* handles u == 0 */
2395 s[len] = 0;
2398 static void highlightslinks (struct page *page, int xoff, int yoff,
2399 int noff, char *targ, int tlen, int hfsize)
2401 int i;
2402 char buf[40];
2403 struct slink *slink;
2404 double x0, y0, x1, y1, w;
2406 ensureslinks (page);
2407 glColor3ub (0xc3, 0xb0, 0x91);
2408 for (i = 0; i < page->slinkcount; ++i) {
2409 fmt_linkn (buf, i + noff);
2410 if (!tlen || !strncmp (targ, buf, tlen)) {
2411 slink = &page->slinks[i];
2413 x0 = slink->bbox.x0 + xoff - 5;
2414 y1 = slink->bbox.y0 + yoff - 5;
2415 y0 = y1 + 10 + hfsize;
2416 w = measure_string (state.face, hfsize, buf);
2417 x1 = x0 + w + 10;
2418 recti (x0, y0, x1, y1);
2422 glEnable (GL_BLEND);
2423 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2424 glEnable (GL_TEXTURE_2D);
2425 glColor3ub (0, 0, 0);
2426 for (i = 0; i < page->slinkcount; ++i) {
2427 fmt_linkn (buf, i + noff);
2428 if (!tlen || !strncmp (targ, buf, tlen)) {
2429 slink = &page->slinks[i];
2431 x0 = slink->bbox.x0 + xoff;
2432 y0 = slink->bbox.y0 + yoff + hfsize;
2433 draw_string (state.face, hfsize, x0, y0, buf);
2436 glDisable (GL_TEXTURE_2D);
2437 glDisable (GL_BLEND);
2440 static void uploadslice (struct tile *tile, struct slice *slice)
2442 int offset;
2443 struct slice *slice1;
2444 unsigned char *texdata;
2446 offset = 0;
2447 for (slice1 = tile->slices; slice != slice1; slice1++) {
2448 offset += slice1->h * tile->w * tile->pixmap->n;
2450 if (slice->texindex != -1 && slice->texindex < state.texcount
2451 && state.texowners[slice->texindex].slice == slice) {
2452 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[slice->texindex]);
2454 else {
2455 int subimage = 0;
2456 int texindex = state.texindex++ % state.texcount;
2458 if (state.texowners[texindex].w == tile->w) {
2459 if (state.texowners[texindex].h >= slice->h) {
2460 subimage = 1;
2462 else {
2463 state.texowners[texindex].h = slice->h;
2466 else {
2467 state.texowners[texindex].h = slice->h;
2470 state.texowners[texindex].w = tile->w;
2471 state.texowners[texindex].slice = slice;
2472 slice->texindex = texindex;
2474 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[texindex]);
2475 if (tile->pbo) {
2476 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2477 texdata = 0;
2479 else {
2480 texdata = tile->pixmap->samples;
2482 if (subimage) {
2483 glTexSubImage2D (GL_TEXTURE_RECTANGLE_ARB,
2487 tile->w,
2488 slice->h,
2489 state.texform,
2490 state.texty,
2491 texdata+offset
2494 else {
2495 glTexImage2D (GL_TEXTURE_RECTANGLE_ARB,
2497 state.texiform,
2498 tile->w,
2499 slice->h,
2501 state.texform,
2502 state.texty,
2503 texdata+offset
2506 if (tile->pbo) {
2507 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2512 CAMLprim value ml_begintiles (value unit_v)
2514 CAMLparam1 (unit_v);
2515 glEnable (GL_TEXTURE_RECTANGLE_ARB);
2516 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2517 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2518 CAMLreturn (unit_v);
2521 CAMLprim value ml_endtiles (value unit_v)
2523 CAMLparam1 (unit_v);
2524 glDisable (GL_TEXTURE_RECTANGLE_ARB);
2525 CAMLreturn (unit_v);
2528 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2530 CAMLparam2 (args_v, ptr_v);
2531 int dispx = Int_val (Field (args_v, 0));
2532 int dispy = Int_val (Field (args_v, 1));
2533 int dispw = Int_val (Field (args_v, 2));
2534 int disph = Int_val (Field (args_v, 3));
2535 int tilex = Int_val (Field (args_v, 4));
2536 int tiley = Int_val (Field (args_v, 5));
2537 char *s = String_val (ptr_v);
2538 struct tile *tile = parse_pointer ("ml_drawtile", s);
2539 int slicey, firstslice;
2540 struct slice *slice;
2541 GLfloat *texcoords = state.texcoords;
2542 GLfloat *vertices = state.vertices;
2544 firstslice = tiley / tile->sliceheight;
2545 slice = &tile->slices[firstslice];
2546 slicey = tiley % tile->sliceheight;
2548 while (disph > 0) {
2549 int dh;
2551 dh = slice->h - slicey;
2552 dh = MIN (disph, dh);
2553 uploadslice (tile, slice);
2555 texcoords[0] = tilex; texcoords[1] = slicey;
2556 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2557 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2558 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2560 vertices[0] = dispx; vertices[1] = dispy;
2561 vertices[2] = dispx+dispw; vertices[3] = dispy;
2562 vertices[4] = dispx; vertices[5] = dispy+dh;
2563 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2565 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2566 dispy += dh;
2567 disph -= dh;
2568 slice++;
2569 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2570 slicey = 0;
2572 CAMLreturn (Val_unit);
2575 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2576 value xoff_v, value yoff_v,
2577 value li_v)
2579 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2580 int xoff = Int_val (xoff_v);
2581 int yoff = Int_val (yoff_v);
2582 int noff = Int_val (Field (li_v, 0));
2583 char *targ = String_val (Field (li_v, 1));
2584 int tlen = caml_string_length (Field (li_v, 1));
2585 int hfsize = Int_val (Field (li_v, 2));
2586 char *s = String_val (ptr_v);
2587 int hlmask = Int_val (hlinks_v);
2588 struct page *page = parse_pointer ("ml_postprocess", s);
2590 if (!page->fzpage) {
2591 /* deal with loadpage failed pages */
2592 goto done;
2595 ensureanots (page);
2597 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2598 if (trylock ("ml_postprocess")) {
2599 noff = 0;
2600 goto done;
2602 if (hlmask & 2) {
2603 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2604 noff = page->slinkcount;
2606 if (page->tgen == state.gen) {
2607 showsel (page, xoff, yoff);
2609 unlock ("ml_postprocess");
2611 done:
2612 CAMLreturn (Val_int (noff));
2615 static struct annot *getannot (struct page *page, int x, int y)
2617 int i;
2618 fz_point p;
2619 fz_matrix ctm;
2620 const fz_matrix *tctm;
2621 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2623 if (!page->annots) return NULL;
2625 if (pdf) {
2626 trimctm ((pdf_page *) page->fzpage, page->pdimno);
2627 tctm = &state.pagedims[page->pdimno].tctm;
2629 else {
2630 tctm = &fz_identity;
2633 p.x = x;
2634 p.y = y;
2636 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2637 fz_invert_matrix (&ctm, &ctm);
2638 fz_transform_point (&p, &ctm);
2640 if (pdf) {
2641 for (i = 0; i < page->annotcount; ++i) {
2642 struct annot *a = &page->annots[i];
2643 pdf_annot *annot = (pdf_annot *) a->annot;
2644 if (p.x >= annot->pagerect.x0 && p.x <= annot->pagerect.x1) {
2645 if (p.y >= annot->pagerect.y0 && p.y <= annot->pagerect.y1) {
2646 return a;
2651 return NULL;
2654 static fz_link *getlink (struct page *page, int x, int y)
2656 fz_point p;
2657 fz_matrix ctm;
2658 const fz_matrix *tctm;
2659 fz_link *link, *links;
2661 tctm = &fz_identity;
2662 links = fz_load_links (state.ctx, page->fzpage);
2664 p.x = x;
2665 p.y = y;
2667 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2668 fz_invert_matrix (&ctm, &ctm);
2669 fz_transform_point (&p, &ctm);
2671 for (link = links; link; link = link->next) {
2672 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2673 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2674 return link;
2678 return NULL;
2681 static void ensuretext (struct page *page)
2683 if (state.gen != page->tgen) {
2684 droptext (page);
2685 page->tgen = state.gen;
2687 if (!page->text) {
2688 fz_matrix ctm;
2689 fz_device *tdev;
2691 page->text = fz_new_text_page (state.ctx);
2692 page->sheet = fz_new_text_sheet (state.ctx);
2693 tdev = fz_new_text_device (state.ctx, page->sheet, page->text);
2694 ctm = pagectm (page);
2695 fz_begin_page (state.ctx, tdev, &fz_infinite_rect, &ctm);
2696 fz_run_display_list (state.ctx, page->dlist,
2697 tdev, &ctm, &fz_infinite_rect, NULL);
2698 qsort (page->text->blocks, page->text->len,
2699 sizeof (*page->text->blocks), compareblocks);
2700 fz_end_page (state.ctx, tdev);
2701 fz_drop_device (state.ctx, tdev);
2705 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2707 CAMLparam2 (start_page_v, dir_v);
2708 CAMLlocal1 (ret_v);
2709 int i, dir = Int_val (dir_v);
2710 int start_page = Int_val (start_page_v);
2711 int end_page = dir > 0 ? state.pagecount : -1;
2712 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2714 ret_v = Val_int (0);
2715 lock ("ml_findpage_with_links");
2716 for (i = start_page + dir; i != end_page; i += dir) {
2717 int found;
2719 if (pdf) {
2720 pdf_page *page = NULL;
2722 fz_try (state.ctx) {
2723 page = pdf_load_page (state.ctx, pdf, i);
2724 found = !!page->links || !!page->annots;
2726 fz_catch (state.ctx) {
2727 found = 0;
2729 if (page) {
2730 fz_drop_page (state.ctx, &page->super);
2733 else {
2734 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2735 found = !!fz_load_links (state.ctx, page);
2736 fz_drop_page (state.ctx, page);
2739 if (found) {
2740 ret_v = caml_alloc_small (1, 1);
2741 Field (ret_v, 0) = Val_int (i);
2742 goto unlock;
2745 unlock:
2746 unlock ("ml_findpage_with_links");
2747 CAMLreturn (ret_v);
2750 enum { dir_first, dir_last };
2751 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2753 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2755 CAMLparam2 (ptr_v, dir_v);
2756 CAMLlocal2 (ret_v, pos_v);
2757 struct page *page;
2758 int dirtag, i, slinkindex;
2759 struct slink *found = NULL ,*slink;
2760 char *s = String_val (ptr_v);
2762 page = parse_pointer ("ml_findlink", s);
2763 ret_v = Val_int (0);
2764 /* This is scary we are not taking locks here ensureslinks does
2765 not modify state and given that we obtained the page it can not
2766 disappear under us either */
2767 lock ("ml_findlink");
2768 ensureslinks (page);
2770 if (Is_block (dir_v)) {
2771 dirtag = Tag_val (dir_v);
2772 switch (dirtag) {
2773 case dir_first_visible:
2775 int x0, y0, dir, first_index, last_index;
2777 pos_v = Field (dir_v, 0);
2778 x0 = Int_val (Field (pos_v, 0));
2779 y0 = Int_val (Field (pos_v, 1));
2780 dir = Int_val (Field (pos_v, 2));
2782 if (dir >= 0) {
2783 dir = 1;
2784 first_index = 0;
2785 last_index = page->slinkcount;
2787 else {
2788 first_index = page->slinkcount - 1;
2789 last_index = -1;
2792 for (i = first_index; i != last_index; i += dir) {
2793 slink = &page->slinks[i];
2794 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2795 found = slink;
2796 break;
2800 break;
2802 case dir_left:
2803 slinkindex = Int_val (Field (dir_v, 0));
2804 found = &page->slinks[slinkindex];
2805 for (i = slinkindex - 1; i >= 0; --i) {
2806 slink = &page->slinks[i];
2807 if (slink->bbox.x0 < found->bbox.x0) {
2808 found = slink;
2809 break;
2812 break;
2814 case dir_right:
2815 slinkindex = Int_val (Field (dir_v, 0));
2816 found = &page->slinks[slinkindex];
2817 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2818 slink = &page->slinks[i];
2819 if (slink->bbox.x0 > found->bbox.x0) {
2820 found = slink;
2821 break;
2824 break;
2826 case dir_down:
2827 slinkindex = Int_val (Field (dir_v, 0));
2828 found = &page->slinks[slinkindex];
2829 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2830 slink = &page->slinks[i];
2831 if (slink->bbox.y0 >= found->bbox.y0) {
2832 found = slink;
2833 break;
2836 break;
2838 case dir_up:
2839 slinkindex = Int_val (Field (dir_v, 0));
2840 found = &page->slinks[slinkindex];
2841 for (i = slinkindex - 1; i >= 0; --i) {
2842 slink = &page->slinks[i];
2843 if (slink->bbox.y0 <= found->bbox.y0) {
2844 found = slink;
2845 break;
2848 break;
2851 else {
2852 dirtag = Int_val (dir_v);
2853 switch (dirtag) {
2854 case dir_first:
2855 found = page->slinks;
2856 break;
2858 case dir_last:
2859 if (page->slinks) {
2860 found = page->slinks + (page->slinkcount - 1);
2862 break;
2865 if (found) {
2866 ret_v = caml_alloc_small (2, 1);
2867 Field (ret_v, 0) = Val_int (found - page->slinks);
2870 unlock ("ml_findlink");
2871 CAMLreturn (ret_v);
2874 enum { uuri, ugoto, utext, uunexpected, ulaunch,
2875 unamed, uremote, uremotedest, uannot };
2877 #define LINKTOVAL \
2879 int pageno; \
2881 switch (link->dest.kind) { \
2882 case FZ_LINK_GOTO: \
2884 fz_point p; \
2886 pageno = link->dest.ld.gotor.page; \
2887 p.x = 0; \
2888 p.y = 0; \
2890 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2891 p.y = link->dest.ld.gotor.lt.y; \
2892 fz_transform_point (&p, &pdim->lctm); \
2893 if (p.y < 0) p.y = 0; \
2895 tup_v = caml_alloc_tuple (2); \
2896 ret_v = caml_alloc_small (1, ugoto); \
2897 Field (tup_v, 0) = Val_int (pageno); \
2898 Field (tup_v, 1) = Val_int (p.y); \
2899 Field (ret_v, 0) = tup_v; \
2901 break; \
2903 case FZ_LINK_URI: \
2904 str_v = caml_copy_string (link->dest.ld.uri.uri); \
2905 ret_v = caml_alloc_small (1, uuri); \
2906 Field (ret_v, 0) = str_v; \
2907 break; \
2909 case FZ_LINK_LAUNCH: \
2910 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
2911 ret_v = caml_alloc_small (1, ulaunch); \
2912 Field (ret_v, 0) = str_v; \
2913 break; \
2915 case FZ_LINK_NAMED: \
2916 str_v = caml_copy_string (link->dest.ld.named.named); \
2917 ret_v = caml_alloc_small (1, unamed); \
2918 Field (ret_v, 0) = str_v; \
2919 break; \
2921 case FZ_LINK_GOTOR: \
2923 int rty; \
2925 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
2926 pageno = link->dest.ld.gotor.page; \
2927 if (pageno == -1) { \
2928 gr_v = caml_copy_string (link->dest.ld.gotor.dest); \
2929 rty = uremotedest; \
2931 else { \
2932 gr_v = Val_int (pageno); \
2933 rty = uremote; \
2935 tup_v = caml_alloc_tuple (2); \
2936 ret_v = caml_alloc_small (1, rty); \
2937 Field (tup_v, 0) = str_v; \
2938 Field (tup_v, 1) = gr_v; \
2939 Field (ret_v, 0) = tup_v; \
2941 break; \
2943 default: \
2945 char buf[80]; \
2947 snprintf (buf, sizeof (buf), \
2948 "unhandled link kind %d", link->dest.kind); \
2949 str_v = caml_copy_string (buf); \
2950 ret_v = caml_alloc_small (1, uunexpected); \
2951 Field (ret_v, 0) = str_v; \
2953 break; \
2957 CAMLprim value ml_getlink (value ptr_v, value n_v)
2959 CAMLparam2 (ptr_v, n_v);
2960 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2961 fz_link *link;
2962 struct page *page;
2963 struct pagedim *pdim;
2964 char *s = String_val (ptr_v);
2965 struct slink *slink;
2967 /* See ml_findlink for caveat */
2969 ret_v = Val_int (0);
2970 page = parse_pointer ("ml_getlink", s);
2971 ensureslinks (page);
2972 pdim = &state.pagedims[page->pdimno];
2973 slink = &page->slinks[Int_val (n_v)];
2974 if (slink->tag == SLINK) {
2975 link = slink->u.link;
2976 LINKTOVAL;
2978 else {
2979 ret_v = caml_alloc_small (1, uannot);
2980 tup_v = caml_alloc_tuple (2);
2981 Field (ret_v, 0) = tup_v;
2982 Field (tup_v, 0) = ptr_v;
2983 Field (tup_v, 1) = n_v;
2986 unlock ("ml_getlink");
2987 CAMLreturn (ret_v);
2990 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2992 CAMLparam2 (ptr_v, n_v);
2993 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2994 if (pdf) {
2995 char *s = String_val (ptr_v);
2996 struct page *page;
2997 struct slink *slink;
2999 page = parse_pointer ("ml_getannotcontent", s);
3000 slink = &page->slinks[Int_val (n_v)];
3001 CAMLreturn (caml_copy_string (
3002 pdf_annot_contents (state.ctx, pdf,
3003 (pdf_annot *) slink->u.annot)));
3005 else {
3006 CAMLreturn (caml_copy_string (""));
3010 CAMLprim value ml_getlinkcount (value ptr_v)
3012 CAMLparam1 (ptr_v);
3013 struct page *page;
3014 char *s = String_val (ptr_v);
3016 page = parse_pointer ("ml_getlinkcount", s);
3017 CAMLreturn (Val_int (page->slinkcount));
3020 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
3022 CAMLparam2 (ptr_v, n_v);
3023 CAMLlocal1 (ret_v);
3024 struct page *page;
3025 struct slink *slink;
3026 char *s = String_val (ptr_v);
3027 /* See ml_findlink for caveat */
3029 page = parse_pointer ("ml_getlinkrect", s);
3030 ret_v = caml_alloc_tuple (4);
3031 ensureslinks (page);
3033 slink = &page->slinks[Int_val (n_v)];
3034 Field (ret_v, 0) = Val_int (slink->bbox.x0);
3035 Field (ret_v, 1) = Val_int (slink->bbox.y0);
3036 Field (ret_v, 2) = Val_int (slink->bbox.x1);
3037 Field (ret_v, 3) = Val_int (slink->bbox.y1);
3038 unlock ("ml_getlinkrect");
3039 CAMLreturn (ret_v);
3042 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
3044 CAMLparam3 (ptr_v, x_v, y_v);
3045 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3046 fz_link *link;
3047 struct annot *annot;
3048 struct page *page;
3049 char *ptr = String_val (ptr_v);
3050 int x = Int_val (x_v), y = Int_val (y_v);
3051 struct pagedim *pdim;
3053 ret_v = Val_int (0);
3054 if (trylock ("ml_whatsunder")) {
3055 goto done;
3058 page = parse_pointer ("ml_whatsunder", ptr);
3059 pdim = &state.pagedims[page->pdimno];
3060 x += pdim->bounds.x0;
3061 y += pdim->bounds.y0;
3064 annot = getannot (page, x, y);
3065 if (annot) {
3066 int i, n = -1;
3068 ensureslinks (page);
3069 for (i = 0; i < page->slinkcount; ++i) {
3070 if (page->slinks[i].tag == SANNOT
3071 && page->slinks[i].u.annot == annot->annot) {
3072 n = i;
3073 break;
3076 ret_v = caml_alloc_small (1, uannot);
3077 tup_v = caml_alloc_tuple (2);
3078 Field (ret_v, 0) = tup_v;
3079 Field (tup_v, 0) = ptr_v;
3080 Field (tup_v, 1) = Val_int (n);
3081 goto unlock;
3085 link = getlink (page, x, y);
3086 if (link) {
3087 LINKTOVAL;
3089 else {
3090 fz_rect *b;
3091 fz_page_block *pageb;
3092 fz_text_block *block;
3094 ensuretext (page);
3095 for (pageb = page->text->blocks;
3096 pageb < page->text->blocks + page->text->len;
3097 ++pageb) {
3098 fz_text_line *line;
3099 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3100 block = pageb->u.text;
3102 b = &block->bbox;
3103 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3104 continue;
3106 for (line = block->lines;
3107 line < block->lines + block->len;
3108 ++line) {
3109 fz_text_span *span;
3111 b = &line->bbox;
3112 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3113 continue;
3115 for (span = line->first_span; span; span = span->next) {
3116 int charnum;
3118 b = &span->bbox;
3119 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3120 continue;
3122 for (charnum = 0; charnum < span->len; ++charnum) {
3123 fz_rect bbox;
3124 fz_text_char_bbox (state.ctx, &bbox, span, charnum);
3125 b = &bbox;
3127 if (x >= b->x0 && x <= b->x1
3128 && y >= b->y0 && y <= b->y1) {
3129 fz_text_style *style = span->text->style;
3130 const char *n2 =
3131 style->font && style->font->name
3132 ? style->font->name
3133 : "Span has no font name"
3135 FT_FaceRec *face = style->font->ft_face;
3136 if (face && face->family_name) {
3137 char *s;
3138 char *n1 = face->family_name;
3139 size_t l1 = strlen (n1);
3140 size_t l2 = strlen (n2);
3142 if (l1 != l2 || memcmp (n1, n2, l1)) {
3143 s = malloc (l1 + l2 + 2);
3144 if (s) {
3145 memcpy (s, n2, l2);
3146 s[l2] = '=';
3147 memcpy (s + l2 + 1, n1, l1 + 1);
3148 str_v = caml_copy_string (s);
3149 free (s);
3153 if (str_v == Val_unit) {
3154 str_v = caml_copy_string (n2);
3156 ret_v = caml_alloc_small (1, utext);
3157 Field (ret_v, 0) = str_v;
3158 goto unlock;
3165 unlock:
3166 unlock ("ml_whatsunder");
3168 done:
3169 CAMLreturn (ret_v);
3172 enum { mark_page, mark_block, mark_line, mark_word };
3174 static int uninteresting (int c)
3176 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3177 || ispunct (c);
3180 CAMLprim value ml_clearmark (value ptr_v)
3182 CAMLparam1 (ptr_v);
3183 char *s = String_val (ptr_v);
3184 struct page *page;
3186 if (trylock ("ml_clearmark")) {
3187 goto done;
3190 page = parse_pointer ("ml_clearmark", s);
3191 page->fmark.span = NULL;
3192 page->lmark.span = NULL;
3193 page->fmark.i = 0;
3194 page->lmark.i = 0;
3196 unlock ("ml_clearmark");
3197 done:
3198 CAMLreturn (Val_unit);
3201 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3203 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3204 CAMLlocal1 (ret_v);
3205 fz_rect *b;
3206 struct page *page;
3207 fz_text_line *line;
3208 fz_page_block *pageb;
3209 fz_text_block *block;
3210 struct pagedim *pdim;
3211 int mark = Int_val (mark_v);
3212 char *s = String_val (ptr_v);
3213 int x = Int_val (x_v), y = Int_val (y_v);
3215 ret_v = Val_bool (0);
3216 if (trylock ("ml_markunder")) {
3217 goto done;
3220 page = parse_pointer ("ml_markunder", s);
3221 pdim = &state.pagedims[page->pdimno];
3223 ensuretext (page);
3225 if (mark == mark_page) {
3226 int i;
3227 fz_page_block *pb1 = NULL, *pb2 = NULL;
3229 for (i = 0; i < page->text->len; ++i) {
3230 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3231 pb1 = &page->text->blocks[i];
3232 break;
3235 if (!pb1) goto unlock;
3237 for (i = page->text->len - 1; i >= 0; --i) {
3238 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3239 pb2 = &page->text->blocks[i];
3240 break;
3243 if (!pb2) goto unlock;
3245 block = pb1->u.text;
3247 page->fmark.i = 0;
3248 page->fmark.span = block->lines->first_span;
3250 block = pb2->u.text;
3251 line = &block->lines[block->len - 1];
3252 page->lmark.i = line->last_span->len - 1;
3253 page->lmark.span = line->last_span;
3254 ret_v = Val_bool (1);
3255 goto unlock;
3258 x += pdim->bounds.x0;
3259 y += pdim->bounds.y0;
3261 for (pageb = page->text->blocks;
3262 pageb < page->text->blocks + page->text->len;
3263 ++pageb) {
3264 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3265 block = pageb->u.text;
3267 b = &block->bbox;
3268 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3269 continue;
3271 if (mark == mark_block) {
3272 page->fmark.i = 0;
3273 page->fmark.span = block->lines->first_span;
3275 line = &block->lines[block->len - 1];
3276 page->lmark.i = line->last_span->len - 1;
3277 page->lmark.span = line->last_span;
3278 ret_v = Val_bool (1);
3279 goto unlock;
3282 for (line = block->lines;
3283 line < block->lines + block->len;
3284 ++line) {
3285 fz_text_span *span;
3287 b = &line->bbox;
3288 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3289 continue;
3291 if (mark == mark_line) {
3292 page->fmark.i = 0;
3293 page->fmark.span = line->first_span;
3295 page->lmark.i = line->last_span->len - 1;
3296 page->lmark.span = line->last_span;
3297 ret_v = Val_bool (1);
3298 goto unlock;
3301 for (span = line->first_span; span; span = span->next) {
3302 int charnum;
3304 b = &span->bbox;
3305 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3306 continue;
3308 for (charnum = 0; charnum < span->len; ++charnum) {
3309 fz_rect bbox;
3310 fz_text_char_bbox (state.ctx, &bbox, span, charnum);
3311 b = &bbox;
3313 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3314 /* unicode ftw */
3315 int charnum2, charnum3 = -1, charnum4 = -1;
3317 if (uninteresting (span->text[charnum].c)) goto unlock;
3319 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3320 if (uninteresting (span->text[charnum2].c)) {
3321 charnum3 = charnum2 + 1;
3322 break;
3325 if (charnum3 == -1) charnum3 = 0;
3327 for (charnum2 = charnum + 1;
3328 charnum2 < span->len;
3329 ++charnum2) {
3330 if (uninteresting (span->text[charnum2].c)) break;
3331 charnum4 = charnum2;
3333 if (charnum4 == -1) goto unlock;
3335 page->fmark.i = charnum3;
3336 page->fmark.span = span;
3338 page->lmark.i = charnum4;
3339 page->lmark.span = span;
3340 ret_v = Val_bool (1);
3341 goto unlock;
3347 unlock:
3348 if (!Bool_val (ret_v)) {
3349 page->fmark.span = NULL;
3350 page->lmark.span = NULL;
3351 page->fmark.i = 0;
3352 page->lmark.i = 0;
3354 unlock ("ml_markunder");
3356 done:
3357 CAMLreturn (ret_v);
3360 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3362 CAMLparam3 (ptr_v, x_v, y_v);
3363 CAMLlocal2 (ret_v, res_v);
3364 fz_rect *b = NULL;
3365 struct page *page;
3366 fz_page_block *pageb;
3367 struct pagedim *pdim;
3368 char *s = String_val (ptr_v);
3369 int x = Int_val (x_v), y = Int_val (y_v);
3371 ret_v = Val_int (0);
3372 if (trylock ("ml_rectofblock")) {
3373 goto done;
3376 page = parse_pointer ("ml_rectofblock", s);
3377 pdim = &state.pagedims[page->pdimno];
3378 x += pdim->bounds.x0;
3379 y += pdim->bounds.y0;
3381 ensuretext (page);
3383 for (pageb = page->text->blocks;
3384 pageb < page->text->blocks + page->text->len;
3385 ++pageb) {
3386 switch (pageb->type) {
3387 case FZ_PAGE_BLOCK_TEXT:
3388 b = &pageb->u.text->bbox;
3389 break;
3391 case FZ_PAGE_BLOCK_IMAGE:
3392 b = &pageb->u.image->bbox;
3393 break;
3395 default:
3396 continue;
3399 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3400 break;
3401 b = NULL;
3403 if (b) {
3404 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3405 ret_v = caml_alloc_small (1, 1);
3406 Store_double_field (res_v, 0, b->x0);
3407 Store_double_field (res_v, 1, b->x1);
3408 Store_double_field (res_v, 2, b->y0);
3409 Store_double_field (res_v, 3, b->y1);
3410 Field (ret_v, 0) = res_v;
3412 unlock ("ml_rectofblock");
3414 done:
3415 CAMLreturn (ret_v);
3418 CAMLprim value ml_seltext (value ptr_v, value rect_v)
3420 CAMLparam2 (ptr_v, rect_v);
3421 fz_rect b;
3422 struct page *page;
3423 struct pagedim *pdim;
3424 char *s = String_val (ptr_v);
3425 int i, x0, x1, y0, y1, fi, li;
3426 fz_text_line *line;
3427 fz_page_block *pageb;
3428 fz_text_block *block;
3429 fz_text_span *span, *fspan, *lspan;
3431 if (trylock ("ml_seltext")) {
3432 goto done;
3435 page = parse_pointer ("ml_seltext", s);
3436 ensuretext (page);
3438 pdim = &state.pagedims[page->pdimno];
3439 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3440 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3441 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3442 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3444 if (y0 > y1) {
3445 int t = y0;
3446 y0 = y1;
3447 y1 = t;
3448 x0 = x1;
3449 x1 = t;
3452 if (0) {
3453 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
3454 glColor3ub (128, 128, 128);
3455 recti (x0, y0, x1, y1);
3456 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
3459 fi = page->fmark.i;
3460 fspan = page->fmark.span;
3462 li = page->lmark.i;
3463 lspan = page->lmark.span;
3465 for (pageb = page->text->blocks;
3466 pageb < page->text->blocks + page->text->len;
3467 ++pageb) {
3468 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3469 block = pageb->u.text;
3470 for (line = block->lines;
3471 line < block->lines + block->len;
3472 ++line) {
3474 for (span = line->first_span; span; span = span->next) {
3475 for (i = 0; i < span->len; ++i) {
3476 int selected = 0;
3478 fz_text_char_bbox (state.ctx, &b, span, i);
3480 if (x0 >= b.x0 && x0 <= b.x1
3481 && y0 >= b.y0 && y0 <= b.y1) {
3482 fspan = span;
3483 fi = i;
3484 selected = 1;
3486 if (x1 >= b.x0 && x1 <= b.x1
3487 && y1 >= b.y0 && y1 <= b.y1) {
3488 lspan = span;
3489 li = i;
3490 selected = 1;
3492 if (0 && selected) {
3493 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
3494 glColor3ub (128, 128, 128);
3495 recti (b.x0, b.y0, b.x1, b.y1);
3496 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
3502 if (x1 < x0 && fspan == lspan) {
3503 i = fi;
3504 span = fspan;
3506 fi = li;
3507 fspan = lspan;
3509 li = i;
3510 lspan = span;
3513 page->fmark.i = fi;
3514 page->fmark.span = fspan;
3516 page->lmark.i = li;
3517 page->lmark.span = lspan;
3519 unlock ("ml_seltext");
3521 done:
3522 CAMLreturn (Val_unit);
3525 static int UNUSED_ATTR pipespan (FILE *f, fz_text_span *span, int a, int b)
3527 char buf[4];
3528 int i, len, ret;
3530 for (i = a; i <= b; ++i) {
3531 len = fz_runetochar (buf, span->text[i].c);
3532 ret = fwrite (buf, len, 1, f);
3534 if (ret != 1) {
3535 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3536 len, ret, strerror (errno));
3537 return -1;
3540 return 0;
3543 #ifdef __CYGWIN__
3544 CAMLprim value ml_popen (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3546 caml_failwith ("ml_popen not implemented under Cygwin");
3548 #else
3549 CAMLprim value ml_popen (value command_v, value fds_v)
3551 CAMLparam2 (command_v, fds_v);
3552 CAMLlocal2 (l_v, tup_v);
3553 int ret;
3554 pid_t pid;
3555 char *msg = NULL;
3556 value earg_v = Nothing;
3557 posix_spawnattr_t attr;
3558 posix_spawn_file_actions_t fa;
3559 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3561 argv[2] = String_val (command_v);
3563 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3564 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3567 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3568 msg = "posix_spawnattr_init";
3569 goto fail1;
3572 #ifdef POSIX_SPAWN_USEVFORK
3573 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3574 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3575 goto fail;
3577 #endif
3579 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3580 int fd1, fd2;
3582 tup_v = Field (l_v, 0);
3583 fd1 = Int_val (Field (tup_v, 0));
3584 fd2 = Int_val (Field (tup_v, 1));
3585 if (fd2 < 0) {
3586 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3587 msg = "posix_spawn_file_actions_addclose";
3588 earg_v = tup_v;
3589 goto fail;
3592 else {
3593 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3594 msg = "posix_spawn_file_actions_adddup2";
3595 earg_v = tup_v;
3596 goto fail;
3601 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3602 msg = "posix_spawn";
3603 goto fail;
3606 fail:
3607 if ((ret = posix_spawnattr_destroy (&attr)) != 0) {
3608 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret));
3611 fail1:
3612 if ((ret = posix_spawn_file_actions_destroy (&fa)) != 0) {
3613 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3614 strerror (ret));
3617 if (msg)
3618 unix_error (ret, msg, earg_v);
3620 CAMLreturn (Val_int (pid));
3622 #endif
3624 CAMLprim value ml_hassel (value ptr_v)
3626 CAMLparam1 (ptr_v);
3627 CAMLlocal1 (ret_v);
3628 struct page *page;
3629 char *s = String_val (ptr_v);
3631 ret_v = Val_bool (0);
3632 if (trylock ("ml_hassel")) {
3633 goto done;
3636 page = parse_pointer ("ml_hassel", s);
3637 ret_v = Val_bool (page->fmark.span && page->lmark.span);
3638 unlock ("ml_hassel");
3639 done:
3640 CAMLreturn (ret_v);
3643 CAMLprim value ml_copysel (value fd_v, value ptr_v)
3645 CAMLparam2 (fd_v, ptr_v);
3646 FILE *f;
3647 int seen = 0;
3648 struct page *page;
3649 fz_text_line *line;
3650 fz_page_block *pageb;
3651 fz_text_block *block;
3652 int fd = Int_val (fd_v);
3653 char *s = String_val (ptr_v);
3655 if (trylock ("ml_copysel")) {
3656 goto done;
3659 page = parse_pointer ("ml_copysel", s);
3661 if (!page->fmark.span || !page->lmark.span) {
3662 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3663 goto unlock;
3666 f = fdopen (fd, "w");
3667 if (!f) {
3668 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3669 fd, strerror (errno));
3670 f = stdout;
3673 for (pageb = page->text->blocks;
3674 pageb < page->text->blocks + page->text->len;
3675 ++pageb) {
3676 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3677 block = pageb->u.text;
3678 for (line = block->lines;
3679 line < block->lines + block->len;
3680 ++line) {
3681 fz_text_span *span;
3683 for (span = line->first_span; span; span = span->next) {
3684 int a, b;
3686 seen |= span == page->fmark.span || span == page->lmark.span;
3687 a = span == page->fmark.span ? page->fmark.i : 0;
3688 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3690 if (seen) {
3691 if (pipespan (f, span, a, b)) {
3692 goto close;
3694 if (span == page->lmark.span) {
3695 goto close;
3697 if (span == line->last_span) {
3698 if (putc ('\n', f) == EOF) {
3699 fprintf (stderr,
3700 "failed break line on sel pipe: %s\n",
3701 strerror (errno));
3702 goto close;
3709 close:
3710 if (f != stdout) {
3711 int ret = fclose (f);
3712 fd = -1;
3713 if (ret == -1) {
3714 if (errno != ECHILD) {
3715 fprintf (stderr, "failed to close sel pipe: %s\n",
3716 strerror (errno));
3720 unlock:
3721 unlock ("ml_copysel");
3723 done:
3724 if (fd >= 0) {
3725 if (close (fd)) {
3726 fprintf (stderr, "failed to close sel pipe: %s\n",
3727 strerror (errno));
3730 CAMLreturn (Val_unit);
3733 CAMLprim value ml_getpdimrect (value pagedimno_v)
3735 CAMLparam1 (pagedimno_v);
3736 CAMLlocal1 (ret_v);
3737 int pagedimno = Int_val (pagedimno_v);
3738 fz_rect box;
3740 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3741 if (trylock ("ml_getpdimrect")) {
3742 box = fz_empty_rect;
3744 else {
3745 box = state.pagedims[pagedimno].mediabox;
3746 unlock ("ml_getpdimrect");
3749 Store_double_field (ret_v, 0, box.x0);
3750 Store_double_field (ret_v, 1, box.x1);
3751 Store_double_field (ret_v, 2, box.y0);
3752 Store_double_field (ret_v, 3, box.y1);
3754 CAMLreturn (ret_v);
3757 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3758 value dw_v, value cols_v)
3760 CAMLparam3 (winw_v, winh_v, dw_v);
3761 CAMLlocal1 (ret_v);
3762 int i;
3763 double zoom = -1.;
3764 double maxh = 0.0;
3765 struct pagedim *p;
3766 double winw = Int_val (winw_v);
3767 double winh = Int_val (winh_v);
3768 double dw = Int_val (dw_v);
3769 double cols = Int_val (cols_v);
3770 double pw = 1.0, ph = 1.0;
3772 if (trylock ("ml_zoom_for_height")) {
3773 goto done;
3776 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3777 double w = p->pagebox.x1 / cols;
3778 double h = p->pagebox.y1;
3779 if (h > maxh) {
3780 maxh = h;
3781 ph = h;
3782 if (state.fitmodel != FitProportional) pw = w;
3784 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3787 zoom = (((winh / ph) * pw) + dw) / winw;
3788 unlock ("ml_zoom_for_height");
3789 done:
3790 ret_v = caml_copy_double (zoom);
3791 CAMLreturn (ret_v);
3794 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3796 CAMLparam4 (pt_v, x_v, y_v, string_v);
3797 CAMLlocal1 (ret_v);
3798 int pt = Int_val(pt_v);
3799 int x = Int_val (x_v);
3800 int y = Int_val (y_v);
3801 double w;
3803 w = draw_string (state.face, pt, x, y, String_val (string_v));
3804 ret_v = caml_copy_double (w);
3805 CAMLreturn (ret_v);
3808 CAMLprim value ml_measure_string (value pt_v, value string_v)
3810 CAMLparam2 (pt_v, string_v);
3811 CAMLlocal1 (ret_v);
3812 int pt = Int_val (pt_v);
3813 double w;
3815 w = measure_string (state.face, pt, String_val (string_v));
3816 ret_v = caml_copy_double (w);
3817 CAMLreturn (ret_v);
3820 CAMLprim value ml_getpagebox (value opaque_v)
3822 CAMLparam1 (opaque_v);
3823 CAMLlocal1 (ret_v);
3824 fz_rect rect;
3825 fz_irect bbox;
3826 fz_matrix ctm;
3827 fz_device *dev;
3828 char *s = String_val (opaque_v);
3829 struct page *page = parse_pointer ("ml_getpagebox", s);
3831 ret_v = caml_alloc_tuple (4);
3832 dev = fz_new_bbox_device (state.ctx, &rect);
3833 dev->hints |= FZ_IGNORE_SHADE;
3835 ctm = pagectm (page);
3836 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3838 fz_drop_device (state.ctx, dev);
3839 fz_round_rect (&bbox, &rect);
3840 Field (ret_v, 0) = Val_int (bbox.x0);
3841 Field (ret_v, 1) = Val_int (bbox.y0);
3842 Field (ret_v, 2) = Val_int (bbox.x1);
3843 Field (ret_v, 3) = Val_int (bbox.y1);
3845 CAMLreturn (ret_v);
3848 CAMLprim value ml_setaalevel (value level_v)
3850 CAMLparam1 (level_v);
3852 state.aalevel = Int_val (level_v);
3853 CAMLreturn (Val_unit);
3856 #pragma GCC diagnostic push
3857 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3858 #include <X11/Xlib.h>
3859 #pragma GCC diagnostic pop
3861 #include <GL/glx.h>
3863 static struct {
3864 Window wid;
3865 Display *dpy;
3866 GLXContext ctx;
3867 XVisualInfo *visual;
3868 } glx;
3870 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3872 CAMLparam3 (display_v, wid_v, screen_v);
3873 int attribs[] = {GLX_RGBA, GLX_DOUBLEBUFFER, None};
3875 glx.dpy = XOpenDisplay (String_val (display_v));
3876 if (!glx.dpy) {
3877 caml_failwith ("XOpenDisplay");
3880 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
3881 if (!glx.visual) {
3882 XCloseDisplay (glx.dpy);
3883 caml_failwith ("glXChooseVisual");
3886 glx.wid = Int_val (wid_v);
3887 CAMLreturn (Val_int (glx.visual->visualid));
3890 CAMLprim value ml_glxcompleteinit (value unit_v)
3892 CAMLparam1 (unit_v);
3894 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
3895 if (!glx.ctx) {
3896 caml_failwith ("glXCreateContext");
3899 XFree (glx.visual);
3900 glx.visual = NULL;
3902 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
3903 glXDestroyContext (glx.dpy, glx.ctx);
3904 glx.ctx = NULL;
3905 caml_failwith ("glXMakeCurrent");
3907 CAMLreturn (Val_unit);
3910 CAMLprim value ml_swapb (value unit_v)
3912 CAMLparam1 (unit_v);
3913 glXSwapBuffers (glx.dpy, glx.wid);
3914 CAMLreturn (Val_unit);
3917 #include "keysym2ucs.c"
3919 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3921 CAMLparam1 (keysym_v);
3922 CAMLlocal1 (str_v);
3923 KeySym keysym = Int_val (keysym_v);
3924 Rune rune;
3925 int len;
3926 char buf[5];
3928 rune = keysym2ucs (keysym);
3929 len = fz_runetochar (buf, rune);
3930 buf[len] = 0;
3931 str_v = caml_copy_string (buf);
3932 CAMLreturn (str_v);
3935 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
3937 CAMLprim value ml_platform (value unit_v)
3939 CAMLparam1 (unit_v);
3940 CAMLlocal2 (tup_v, arr_v);
3941 int platid = piunknown;
3942 struct utsname buf;
3944 #if defined __linux__
3945 platid = pilinux;
3946 #elif defined __CYGWIN__
3947 platid = picygwin;
3948 #elif defined __DragonFly__ || defined __FreeBSD__
3949 || defined __OpenBSD__ || defined __NetBSD__
3950 platid = pibsd;
3951 #elif defined __sun__
3952 platid = pisun;
3953 #elif defined __APPLE__
3954 platid = piosx;
3955 #endif
3956 if (uname (&buf)) err (1, "uname");
3958 tup_v = caml_alloc_tuple (2);
3960 char const *sar[] = {
3961 buf.sysname,
3962 buf.release,
3963 buf.version,
3964 buf.machine,
3965 NULL
3967 arr_v = caml_copy_string_array (sar);
3969 Field (tup_v, 0) = Val_int (platid);
3970 Field (tup_v, 1) = arr_v;
3971 CAMLreturn (tup_v);
3974 CAMLprim value ml_cloexec (value fd_v)
3976 CAMLparam1 (fd_v);
3977 int fd = Int_val (fd_v);
3979 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3980 uerror ("fcntl", Nothing);
3982 CAMLreturn (Val_unit);
3985 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
3987 CAMLparam2 (w_v, h_v);
3988 CAMLlocal1 (ret_v);
3989 struct pbo *pbo;
3990 int w = Int_val (w_v);
3991 int h = Int_val (h_v);
3992 int cs = Int_val (cs_v);
3994 if (state.pbo_usable) {
3995 pbo = calloc (sizeof (*pbo), 1);
3996 if (!pbo) {
3997 err (1, "calloc pbo");
4000 switch (cs) {
4001 case 0:
4002 case 1:
4003 pbo->size = w*h*4;
4004 break;
4005 case 2:
4006 pbo->size = w*h*2;
4007 break;
4008 default:
4009 errx (1, "ml_getpbo: invalid colorspace %d", cs);
4012 state.glGenBuffersARB (1, &pbo->id);
4013 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
4014 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
4015 NULL, GL_STREAM_DRAW);
4016 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
4017 GL_READ_WRITE);
4018 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4019 if (!pbo->ptr) {
4020 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
4021 state.glDeleteBuffersARB (1, &pbo->id);
4022 free (pbo);
4023 ret_v = caml_copy_string ("0");
4025 else {
4026 int res;
4027 char *s;
4029 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
4030 if (res < 0) {
4031 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4033 s = malloc (res+1);
4034 if (!s) {
4035 err (1, "malloc %d bytes failed", res+1);
4037 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
4038 if (res < 0) {
4039 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4041 ret_v = caml_copy_string (s);
4042 free (s);
4045 else {
4046 ret_v = caml_copy_string ("0");
4048 CAMLreturn (ret_v);
4051 CAMLprim value ml_freepbo (value s_v)
4053 CAMLparam1 (s_v);
4054 char *s = String_val (s_v);
4055 struct tile *tile = parse_pointer ("ml_freepbo", s);
4057 if (tile->pbo) {
4058 state.glDeleteBuffersARB (1, &tile->pbo->id);
4059 tile->pbo->id = -1;
4060 tile->pbo->ptr = NULL;
4061 tile->pbo->size = -1;
4063 CAMLreturn (Val_unit);
4066 CAMLprim value ml_unmappbo (value s_v)
4068 CAMLparam1 (s_v);
4069 char *s = String_val (s_v);
4070 struct tile *tile = parse_pointer ("ml_unmappbo", s);
4072 if (tile->pbo) {
4073 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4074 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4075 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4077 tile->pbo->ptr = NULL;
4078 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4080 CAMLreturn (Val_unit);
4083 static void setuppbo (void)
4085 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4086 state.pbo_usable = GGPA (glBindBufferARB)
4087 && GGPA (glUnmapBufferARB)
4088 && GGPA (glMapBufferARB)
4089 && GGPA (glBufferDataARB)
4090 && GGPA (glGenBuffersARB)
4091 && GGPA (glDeleteBuffersARB);
4092 #undef GGPA
4095 CAMLprim value ml_pbo_usable (value unit_v)
4097 CAMLparam1 (unit_v);
4098 CAMLreturn (Val_bool (state.pbo_usable));
4101 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4103 CAMLparam3 (ptr_v, x_v, y_v);
4104 CAMLlocal2 (ret_v, tup_v);
4105 struct page *page;
4106 char *s = String_val (ptr_v);
4107 int x = Int_val (x_v), y = Int_val (y_v);
4108 struct pagedim *pdim;
4109 fz_point p;
4110 fz_matrix ctm;
4112 page = parse_pointer ("ml_unproject", s);
4113 pdim = &state.pagedims[page->pdimno];
4115 ret_v = Val_int (0);
4116 if (trylock ("ml_unproject")) {
4117 goto done;
4120 if (pdf_specifics (state.ctx, state.doc)) {
4121 trimctm ((pdf_page *) page->fzpage, page->pdimno);
4122 ctm = state.pagedims[page->pdimno].tctm;
4124 else {
4125 ctm = fz_identity;
4127 p.x = x + pdim->bounds.x0;
4128 p.y = y + pdim->bounds.y0;
4130 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4131 fz_invert_matrix (&ctm, &ctm);
4132 fz_transform_point (&p, &ctm);
4134 tup_v = caml_alloc_tuple (2);
4135 ret_v = caml_alloc_small (1, 1);
4136 Field (tup_v, 0) = Val_int (p.x);
4137 Field (tup_v, 1) = Val_int (p.y);
4138 Field (ret_v, 0) = tup_v;
4140 unlock ("ml_unproject");
4141 done:
4142 CAMLreturn (ret_v);
4145 CAMLprim value ml_addannot (value ptr_v, value x_v, value y_v,
4146 value contents_v)
4148 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4149 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4151 if (pdf) {
4152 pdf_annot *annot;
4153 struct page *page;
4154 fz_point p;
4155 char *s = String_val (ptr_v);
4157 page = parse_pointer ("ml_addannot", s);
4158 annot = pdf_create_annot (state.ctx, pdf,
4159 (pdf_page *) page->fzpage, FZ_ANNOT_TEXT);
4160 p.x = Int_val (x_v);
4161 p.y = Int_val (y_v);
4162 pdf_set_annot_contents (state.ctx, pdf, annot, String_val (contents_v));
4163 pdf_set_text_annot_position (state.ctx, pdf, annot, p);
4164 state.dirty = 1;
4166 CAMLreturn (Val_unit);
4169 CAMLprim value ml_delannot (value ptr_v, value n_v)
4171 CAMLparam2 (ptr_v, n_v);
4172 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4174 if (pdf) {
4175 struct page *page;
4176 char *s = String_val (ptr_v);
4177 struct slink *slink;
4179 page = parse_pointer ("ml_delannot", s);
4180 slink = &page->slinks[Int_val (n_v)];
4181 pdf_delete_annot (state.ctx, pdf,
4182 (pdf_page *) page->fzpage,
4183 (pdf_annot *) slink->u.annot);
4184 state.dirty = 1;
4186 CAMLreturn (Val_unit);
4189 CAMLprim value ml_modannot (value ptr_v, value n_v, value str_v)
4191 CAMLparam3 (ptr_v, n_v, str_v);
4192 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4194 if (pdf) {
4195 struct page *page;
4196 char *s = String_val (ptr_v);
4197 struct slink *slink;
4199 page = parse_pointer ("ml_modannot", s);
4200 slink = &page->slinks[Int_val (n_v)];
4201 pdf_set_annot_contents (state.ctx, pdf, (pdf_annot *) slink->u.annot,
4202 String_val (str_v));
4203 state.dirty = 1;
4205 CAMLreturn (Val_unit);
4208 CAMLprim value ml_hasunsavedchanges (value unit_v)
4210 CAMLparam1 (unit_v);
4211 CAMLreturn (Val_bool (state.dirty));
4214 CAMLprim value ml_savedoc (value path_v)
4216 CAMLparam1 (path_v);
4217 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4219 if (pdf) {
4220 pdf_write_document (state.ctx, pdf, String_val (path_v), NULL);
4222 CAMLreturn (Val_unit);
4225 static void makestippletex (void)
4227 const char pixels[] = "\xff\xff\0\0";
4228 glGenTextures (1, &state.stid);
4229 glBindTexture (GL_TEXTURE_1D, state.stid);
4230 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4231 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4232 glTexImage1D (
4233 GL_TEXTURE_1D,
4235 GL_ALPHA,
4238 GL_ALPHA,
4239 GL_UNSIGNED_BYTE,
4240 pixels
4244 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4246 return caml_copy_string (FZ_VERSION);
4249 #ifdef USE_FONTCONFIG
4250 static struct {
4251 int inited;
4252 FcConfig *config;
4253 } fc;
4255 static fz_font *fc_load_system_font_func (fz_context *ctx,
4256 const char *name,
4257 int bold,
4258 int italic,
4259 int UNUSED_ATTR needs_exact_metrics)
4261 char *buf;
4262 size_t i, size;
4263 fz_font *font;
4264 FcChar8 *path;
4265 FcResult result;
4266 FcPattern *pat, *pat1;
4268 lprintf ("looking up %s bold:%d italic:%d needs_exact_metrics:%d\n",
4269 name, bold, italic, needs_exact_metrics);
4270 if (!fc.inited) {
4271 fc.inited = 1;
4272 fc.config = FcInitLoadConfigAndFonts ();
4273 if (!fc.config) {
4274 lprintf ("FcInitLoadConfigAndFonts failed\n");
4275 return NULL;
4278 if (!fc.config) return NULL;
4280 size = strlen (name);
4281 if (bold) size += sizeof (":bold") - 1;
4282 if (italic) size += sizeof (":italic") - 1;
4283 size += 1;
4285 buf = malloc (size);
4286 if (!buf) {
4287 err (1, "malloc %zu failed", size);
4290 strcpy (buf, name);
4291 if (bold && italic) {
4292 strcat (buf, ":bold:italic");
4294 else {
4295 if (bold) strcat (buf, ":bold");
4296 if (italic) strcat (buf, ":italic");
4298 for (i = 0; i < size; ++i) {
4299 if (buf[i] == ',' || buf[i] == '-') buf[i] = ':';
4302 lprintf ("fcbuf=%s\n", buf);
4303 pat = FcNameParse ((FcChar8 *) buf);
4304 if (!pat) {
4305 printd ("emsg FcNameParse failed\n");
4306 free (buf);
4307 return NULL;
4310 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4311 printd ("emsg FcConfigSubstitute failed\n");
4312 free (buf);
4313 return NULL;
4315 FcDefaultSubstitute (pat);
4317 pat1 = FcFontMatch (fc.config, pat, &result);
4318 if (!pat1) {
4319 printd ("emsg FcFontMatch failed\n");
4320 FcPatternDestroy (pat);
4321 free (buf);
4322 return NULL;
4325 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4326 printd ("emsg FcPatternGetString failed\n");
4327 FcPatternDestroy (pat);
4328 FcPatternDestroy (pat1);
4329 free (buf);
4330 return NULL;
4333 #if 0
4334 printd ("emsg name=%s path=%s\n", name, path);
4335 #endif
4336 font = fz_new_font_from_file (ctx, name, (char *) path, 0, 0);
4337 FcPatternDestroy (pat);
4338 FcPatternDestroy (pat1);
4339 free (buf);
4340 return font;
4342 #endif
4344 CAMLprim value ml_init (value csock_v, value params_v)
4346 CAMLparam2 (csock_v, params_v);
4347 CAMLlocal2 (trim_v, fuzz_v);
4348 int ret;
4349 int texcount;
4350 char *fontpath;
4351 int colorspace;
4352 int mustoresize;
4353 int haspboext;
4355 state.csock = Int_val (csock_v);
4356 state.rotate = Int_val (Field (params_v, 0));
4357 state.fitmodel = Int_val (Field (params_v, 1));
4358 trim_v = Field (params_v, 2);
4359 texcount = Int_val (Field (params_v, 3));
4360 state.sliceheight = Int_val (Field (params_v, 4));
4361 mustoresize = Int_val (Field (params_v, 5));
4362 colorspace = Int_val (Field (params_v, 6));
4363 fontpath = String_val (Field (params_v, 7));
4365 if (caml_string_length (Field (params_v, 8)) > 0) {
4366 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4368 if (!state.trimcachepath) {
4369 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4370 strerror (errno));
4373 haspboext = Bool_val (Field (params_v, 9));
4375 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4376 fz_register_document_handlers (state.ctx);
4378 #ifdef USE_FONTCONFIG
4379 if (Bool_val (Field (params_v, 10))) {
4380 fz_install_load_system_font_funcs (
4381 state.ctx, fc_load_system_font_func, NULL
4384 #endif
4386 state.trimmargins = Bool_val (Field (trim_v, 0));
4387 fuzz_v = Field (trim_v, 1);
4388 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4389 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4390 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4391 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4393 set_tex_params (colorspace);
4395 if (*fontpath) {
4396 #ifndef USE_FONTCONFIG
4397 state.face = load_font (fontpath);
4398 #else
4399 FcChar8 *path;
4400 FcResult result;
4401 char *buf = fontpath;
4402 FcPattern *pat, *pat1;
4404 fc.inited = 1;
4405 fc.config = FcInitLoadConfigAndFonts ();
4406 if (!fc.config) {
4407 errx (1, "FcInitLoadConfigAndFonts failed");
4410 pat = FcNameParse ((FcChar8 *) buf);
4411 if (!pat) {
4412 errx (1, "FcNameParse failed");
4415 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4416 errx (1, "FcConfigSubstitute failed");
4418 FcDefaultSubstitute (pat);
4420 pat1 = FcFontMatch (fc.config, pat, &result);
4421 if (!pat1) {
4422 errx (1, "FcFontMatch failed");
4425 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4426 errx (1, "FcPatternGetString failed");
4429 state.face = load_font ((char *) path);
4430 FcPatternDestroy (pat);
4431 FcPatternDestroy (pat1);
4432 #endif
4434 else {
4435 unsigned int len;
4436 void *base = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
4438 state.face = load_builtin_font (base, len);
4440 if (!state.face) _exit (1);
4442 realloctexts (texcount);
4444 if (haspboext) {
4445 setuppbo ();
4448 makestippletex ();
4450 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4451 if (ret) {
4452 errx (1, "pthread_create: %s", strerror (ret));
4455 CAMLreturn (Val_unit);