Kill code made completely useless by Oaction removal
[llpp.git] / link.c
blobab0f43c9b766c12d66c8790d95600420c08ec272
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, "cannot allocate tile (%" FMT_s " bytes)", tilesize);
702 for (i = 0; i < slicecount; ++i) {
703 int sh = MIN (h, state.sliceheight);
704 tile->slices[i].h = sh;
705 tile->slices[i].texindex = -1;
706 h -= sh;
708 tile->slicecount = slicecount;
709 tile->sliceheight = state.sliceheight;
710 return tile;
713 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
714 struct pbo *pbo)
716 fz_rect rect;
717 fz_irect bbox;
718 fz_matrix ctm;
719 fz_device *dev;
720 struct tile *tile;
721 struct pagedim *pdim;
723 tile = alloctile (h);
724 pdim = &state.pagedims[page->pdimno];
726 bbox = pdim->bounds;
727 bbox.x0 += x;
728 bbox.y0 += y;
729 bbox.x1 = bbox.x0 + w;
730 bbox.y1 = bbox.y0 + h;
732 if (state.pig) {
733 if (state.pig->w == w
734 && state.pig->h == h
735 && state.pig->colorspace == state.colorspace) {
736 tile->pixmap = state.pig;
737 tile->pixmap->x = bbox.x0;
738 tile->pixmap->y = bbox.y0;
740 else {
741 fz_drop_pixmap (state.ctx, state.pig);
743 state.pig = NULL;
745 if (!tile->pixmap) {
746 if (pbo) {
747 tile->pixmap =
748 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
749 &bbox, pbo->ptr);
750 tile->pbo = pbo;
752 else {
753 tile->pixmap =
754 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox);
758 tile->w = w;
759 tile->h = h;
760 clearpixmap (tile->pixmap);
762 dev = fz_new_draw_device (state.ctx, tile->pixmap);
763 ctm = pagectm (page);
764 fz_rect_from_irect (&rect, &bbox);
765 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
766 fz_drop_device (state.ctx, dev);
768 return tile;
771 #ifdef CACHE_PAGEREFS
772 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
773 thanks to Robin Watts */
774 static void
775 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
777 fz_context *ctx = state.ctx; /* doc->ctx; */
778 pdf_obj *kids;
779 int i, len;
781 if (state.pdflut.idx == state.pagecount) return;
783 kids = pdf_dict_gets (ctx, node, "Kids");
784 len = pdf_array_len (ctx, kids);
786 if (len == 0)
787 fz_throw (ctx, FZ_ERROR_GENERIC, "Malformed pages tree");
789 if (pdf_mark_obj (ctx, node))
790 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
791 for (i = 0; i < len; i++) {
792 pdf_obj *kid = pdf_array_get (ctx, kids, i);
793 char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
794 if (*type
795 ? !strcmp (type, "Pages")
796 : pdf_dict_gets (ctx, kid, "Kids")
797 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
798 pdf_collect_pages (doc, kid);
800 else {
801 if (*type
802 ? strcmp (type, "Page") != 0
803 : !pdf_dict_gets (ctx, kid, "MediaBox"))
804 fz_warn (ctx, "non-page object in page tree (%s)", type);
805 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
808 pdf_unmark_obj (ctx, node);
811 static void
812 pdf_load_page_objs (pdf_document *doc)
814 pdf_obj *root = pdf_dict_gets (state.ctx,
815 pdf_trailer (state.ctx, doc), "Root");
816 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
818 if (!node)
819 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
821 state.pdflut.idx = 0;
822 pdf_collect_pages (doc, node);
824 #endif
826 static void initpdims (void)
828 double start, end;
829 FILE *trimf = NULL;
830 fz_rect rootmediabox;
831 int pageno, trim, show;
832 int trimw = 0, cxcount;
833 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
835 fz_var (trimw);
836 fz_var (cxcount);
837 start = now ();
839 if (state.trimmargins && state.trimcachepath) {
840 trimf = fopen (state.trimcachepath, "rb");
841 if (!trimf) {
842 trimf = fopen (state.trimcachepath, "wb");
843 trimw = 1;
847 if (state.trimmargins || pdf || !state.cxack)
848 cxcount = state.pagecount;
849 else
850 cxcount = MIN (state.pagecount, 1);
852 if (pdf) {
853 pdf_obj *obj;
854 obj = pdf_dict_getp (state.ctx, pdf_trailer (state.ctx, pdf),
855 "Root/Pages/MediaBox");
856 pdf_to_rect (state.ctx, obj, &rootmediabox);
859 #ifdef CACHE_PAGEREFS
860 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
861 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
862 if (!state.pdflut.objs) {
863 err (1, "malloc pageobjs %zu %d %zu failed",
864 sizeof (*state.pdflut.objs), cxcount,
865 sizeof (*state.pdflut.objs) * cxcount);
867 state.pdflut.count = cxcount;
868 pdf_load_page_objs (pdf);
869 state.pdflut.pdf = pdf;
871 #endif
873 for (pageno = 0; pageno < cxcount; ++pageno) {
874 int rotate = 0;
875 struct pagedim *p;
876 fz_rect mediabox;
878 if (pdf) {
879 pdf_obj *pageref, *pageobj;
881 #ifdef CACHE_PAGEREFS
882 pageref = state.pdflut.objs[pageno];
883 #else
884 pageref = pdf_lookup_page_obj (state.ctx, pdf, pageno);
885 #endif
886 pageobj = pdf_resolve_indirect (state.ctx, pageref);
888 if (state.trimmargins) {
889 fz_context *ctx = state.ctx;
890 pdf_obj *obj;
891 pdf_page *page;
893 fz_try (state.ctx) {
894 page = pdf_load_page (ctx, pdf, pageno);
895 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
896 trim = state.trimanew || !obj;
897 if (trim) {
898 fz_rect rect;
899 fz_matrix ctm;
900 fz_device *dev;
902 dev = fz_new_bbox_device (ctx, &rect);
903 dev->hints |= FZ_IGNORE_SHADE;
904 fz_invert_matrix (&ctm, &page->ctm);
905 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
906 fz_drop_device (ctx, dev);
908 rect.x0 += state.trimfuzz.x0;
909 rect.x1 += state.trimfuzz.x1;
910 rect.y0 += state.trimfuzz.y0;
911 rect.y1 += state.trimfuzz.y1;
912 fz_transform_rect (&rect, &ctm);
913 fz_intersect_rect (&rect, &page->mediabox);
915 if (fz_is_empty_rect (&rect)) {
916 mediabox = page->mediabox;
918 else {
919 mediabox = rect;
922 obj = pdf_new_array (ctx, pdf, 4);
923 pdf_array_push (ctx, obj, pdf_new_real (state.ctx, pdf,
924 mediabox.x0));
925 pdf_array_push (ctx, obj, pdf_new_real (state.ctx, pdf,
926 mediabox.y0));
927 pdf_array_push (ctx, obj, pdf_new_real (state.ctx, pdf,
928 mediabox.x1));
929 pdf_array_push (ctx, obj, pdf_new_real (state.ctx, pdf,
930 mediabox.y1));
931 pdf_dict_puts (state.ctx, pageobj, "llpp.TrimBox", obj);
933 else {
934 mediabox.x0 = pdf_to_real (ctx,
935 pdf_array_get (ctx, obj, 0));
936 mediabox.y0 = pdf_to_real (ctx,
937 pdf_array_get (ctx, obj, 1));
938 mediabox.x1 = pdf_to_real (ctx,
939 pdf_array_get (ctx, obj, 2));
940 mediabox.y1 = pdf_to_real (ctx,
941 pdf_array_get (ctx, obj, 3));
944 rotate = page->rotate;
945 fz_drop_page (ctx, &page->super);
947 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
948 if (show) {
949 printd ("progress %f Trimming %d",
950 (double) (pageno + 1) / state.pagecount,
951 pageno + 1);
954 fz_catch (state.ctx) {
955 fprintf (stderr, "failed to load page %d\n", pageno+1);
958 else {
959 int empty = 0;
960 fz_rect cropbox;
962 pdf_to_rect (state.ctx,
963 pdf_dict_gets (state.ctx, pageobj, "MediaBox"),
964 &mediabox);
965 if (fz_is_empty_rect (&mediabox)) {
966 mediabox.x0 = 0;
967 mediabox.y0 = 0;
968 mediabox.x1 = 612;
969 mediabox.y1 = 792;
970 empty = 1;
973 pdf_to_rect (state.ctx,
974 pdf_dict_gets (state.ctx, pageobj, "CropBox"),
975 &cropbox);
976 if (!fz_is_empty_rect (&cropbox)) {
977 if (empty) {
978 mediabox = cropbox;
980 else {
981 fz_intersect_rect (&mediabox, &cropbox);
984 else {
985 if (empty) {
986 if (fz_is_empty_rect (&rootmediabox)) {
987 fprintf (stderr,
988 "cannot find page size for page %d\n",
989 pageno+1);
991 else {
992 mediabox = rootmediabox;
996 rotate = pdf_to_int (state.ctx,
997 pdf_dict_gets (state.ctx,
998 pageobj, "Rotate"));
1001 else {
1002 if (state.trimmargins && trimw) {
1003 fz_page *page;
1005 fz_try (state.ctx) {
1006 page = fz_load_page (state.ctx, state.doc, pageno);
1007 fz_bound_page (state.ctx, page, &mediabox);
1008 rotate = 0;
1009 if (state.trimmargins) {
1010 fz_rect rect;
1011 fz_device *dev;
1013 dev = fz_new_bbox_device (state.ctx, &rect);
1014 dev->hints |= FZ_IGNORE_SHADE;
1015 fz_run_page (state.ctx, page, dev,
1016 &fz_identity, NULL);
1017 fz_drop_device (state.ctx, dev);
1019 rect.x0 += state.trimfuzz.x0;
1020 rect.x1 += state.trimfuzz.x1;
1021 rect.y0 += state.trimfuzz.y0;
1022 rect.y1 += state.trimfuzz.y1;
1023 fz_intersect_rect (&rect, &mediabox);
1025 if (!fz_is_empty_rect (&rect)) {
1026 mediabox = rect;
1029 fz_drop_page (state.ctx, page);
1030 if (!state.cxack) {
1031 printd ("progress %f loading %d",
1032 (double) (pageno + 1) / state.pagecount,
1033 pageno + 1);
1036 fz_catch (state.ctx) {
1038 if (trimf) {
1039 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1040 if (n - 1) {
1041 err (1, "fwrite trim mediabox");
1045 else {
1046 if (trimf) {
1047 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1048 if (n - 1) {
1049 err (1, "fread trim mediabox %d", pageno);
1052 else {
1053 fz_page *page;
1054 fz_try (state.ctx) {
1055 page = fz_load_page (state.ctx,
1056 state.doc, pageno);
1057 fz_bound_page (state.ctx, page, &mediabox);
1058 fz_drop_page (state.ctx, page);
1060 show = !state.trimmargins && pageno % 20 == 0;
1061 if (show) {
1062 printd ("progress %f Gathering dimensions %d",
1063 (double) (pageno) / state.pagecount,
1064 pageno);
1067 fz_catch (state.ctx) {
1068 fprintf (stderr, "failed to load page %d\n", pageno);
1074 if (state.pagedimcount == 0
1075 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1076 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1077 size_t size;
1079 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1080 state.pagedims = realloc (state.pagedims, size);
1081 if (!state.pagedims) {
1082 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1083 size, state.pagedimcount + 1);
1086 p = &state.pagedims[state.pagedimcount++];
1087 p->rotate = rotate;
1088 p->mediabox = mediabox;
1089 p->pageno = pageno;
1092 end = now ();
1093 printd ("progress 1 %s %d pages in %f seconds",
1094 state.trimmargins ? "Trimmed" : "Processed",
1095 state.pagecount, end - start);
1096 state.trimanew = 0;
1097 if (trimf) {
1098 if (fclose (trimf)) {
1099 err (1, "fclose");
1104 static void layout (void)
1106 int pindex;
1107 fz_rect box;
1108 fz_matrix ctm, rm;
1109 struct pagedim *p = p;
1110 double zw, w, maxw = 0.0, zoom = zoom;
1112 if (state.pagedimcount == 0) return;
1114 switch (state.fitmodel) {
1115 case FitProportional:
1116 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1117 double x0, x1;
1119 p = &state.pagedims[pindex];
1120 fz_rotate (&rm, p->rotate + state.rotate);
1121 box = p->mediabox;
1122 fz_transform_rect (&box, &rm);
1124 x0 = MIN (box.x0, box.x1);
1125 x1 = MAX (box.x0, box.x1);
1127 w = x1 - x0;
1128 maxw = MAX (w, maxw);
1129 zoom = state.w / maxw;
1131 break;
1133 case FitPage:
1134 maxw = state.w;
1135 break;
1137 case FitWidth:
1138 break;
1140 default:
1141 ARSERT (0 && state.fitmodel);
1144 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1145 fz_rect rect;
1146 fz_matrix tm, sm;
1148 p = &state.pagedims[pindex];
1149 fz_rotate (&ctm, state.rotate);
1150 fz_rotate (&rm, p->rotate + state.rotate);
1151 box = p->mediabox;
1152 fz_transform_rect (&box, &rm);
1153 w = box.x1 - box.x0;
1154 switch (state.fitmodel) {
1155 case FitProportional:
1156 p->left = ((maxw - w) * zoom) / 2.0;
1157 break;
1158 case FitPage:
1160 double zh, h;
1161 zw = maxw / w;
1162 h = box.y1 - box.y0;
1163 zh = state.h / h;
1164 zoom = MIN (zw, zh);
1165 p->left = (maxw - (w * zoom)) / 2.0;
1167 break;
1168 case FitWidth:
1169 p->left = 0;
1170 zoom = state.w / w;
1171 break;
1174 fz_scale (&p->zoomctm, zoom, zoom);
1175 fz_concat (&ctm, &p->zoomctm, &ctm);
1177 fz_rotate (&rm, p->rotate);
1178 p->pagebox = p->mediabox;
1179 fz_transform_rect (&p->pagebox, &rm);
1180 p->pagebox.x1 -= p->pagebox.x0;
1181 p->pagebox.y1 -= p->pagebox.y0;
1182 p->pagebox.x0 = 0;
1183 p->pagebox.y0 = 0;
1184 rect = p->pagebox;
1185 fz_transform_rect (&rect, &ctm);
1186 fz_round_rect (&p->bounds, &rect);
1187 p->ctm = ctm;
1189 fz_translate (&tm, 0, -p->mediabox.y1);
1190 fz_scale (&sm, zoom, -zoom);
1191 fz_concat (&ctm, &tm, &sm);
1192 fz_concat (&p->lctm, &ctm, &rm);
1194 p->tctmready = 0;
1197 do {
1198 int x0 = MIN (p->bounds.x0, p->bounds.x1);
1199 int y0 = MIN (p->bounds.y0, p->bounds.y1);
1200 int x1 = MAX (p->bounds.x0, p->bounds.x1);
1201 int y1 = MAX (p->bounds.y0, p->bounds.y1);
1202 int boundw = x1 - x0;
1203 int boundh = y1 - y0;
1205 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1206 } while (p-- != state.pagedims);
1209 static
1210 struct anchor { int n; int x; int y; int w; int h; }
1211 desttoanchor (fz_link_dest *dest)
1213 int i;
1214 struct anchor a;
1215 struct pagedim *pdim = state.pagedims;
1217 a.n = -1;
1218 a.x = 0;
1219 a.y = 0;
1220 for (i = 0; i < state.pagedimcount; ++i) {
1221 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1222 break;
1223 pdim = &state.pagedims[i];
1225 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1226 fz_point p;
1227 if (dest->ld.gotor.flags & fz_link_flag_l_valid)
1228 p.x = dest->ld.gotor.lt.x;
1229 else
1230 p.x = 0.0;
1231 p.y = dest->ld.gotor.lt.y;
1232 fz_transform_point (&p, &pdim->lctm);
1233 a.x = p.x;
1234 a.y = p.y;
1236 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1237 double x0, x1, y0, y1;
1239 x0 = MIN (pdim->bounds.x0, pdim->bounds.x1);
1240 x1 = MAX (pdim->bounds.x0, pdim->bounds.x1);
1241 a.w = x1 - x0;
1242 y0 = MIN (pdim->bounds.y0, pdim->bounds.y1);
1243 y1 = MAX (pdim->bounds.y0, pdim->bounds.y1);
1244 a.h = y1 - y0;
1245 a.n = dest->ld.gotor.page;
1247 return a;
1250 static void recurse_outline (fz_outline *outline, int level)
1252 while (outline) {
1253 switch (outline->dest.kind) {
1254 case FZ_LINK_GOTO:
1256 struct anchor a = desttoanchor (&outline->dest);
1258 if (a.n >= 0) {
1259 printd ("o %d %d %d %d %s",
1260 level, a.n, a.y, a.h, outline->title);
1263 break;
1265 case FZ_LINK_URI:
1266 printd ("ou %d %" FMT_s " %s %s", level,
1267 strlen (outline->title), outline->title,
1268 outline->dest.ld.uri.uri);
1269 break;
1271 case FZ_LINK_NONE:
1272 printd ("on %d %s", level, outline->title);
1273 break;
1275 default:
1276 printd ("emsg Unhandled outline kind %d for %s\n",
1277 outline->dest.kind, outline->title);
1278 break;
1280 if (outline->down) {
1281 recurse_outline (outline->down, level + 1);
1283 outline = outline->next;
1287 static void process_outline (void)
1289 fz_outline *outline;
1291 if (!state.needoutline || !state.pagedimcount) return;
1293 state.needoutline = 0;
1294 outline = fz_load_outline (state.ctx, state.doc);
1295 if (outline) {
1296 recurse_outline (outline, 0);
1297 fz_drop_outline (state.ctx, outline);
1301 static char *strofspan (fz_text_span *span)
1303 char *p;
1304 char utf8[10];
1305 fz_text_char *ch;
1306 size_t size = 0, cap = 80;
1308 p = malloc (cap + 1);
1309 if (!p) return NULL;
1311 for (ch = span->text; ch < span->text + span->len; ++ch) {
1312 int n = fz_runetochar (utf8, ch->c);
1313 if (size + n > cap) {
1314 cap *= 2;
1315 p = realloc (p, cap + 1);
1316 if (!p) return NULL;
1319 memcpy (p + size, utf8, n);
1320 size += n;
1322 p[size] = 0;
1323 return p;
1326 static int matchspan (regex_t *re, fz_text_span *span,
1327 int stop, int pageno, double start)
1329 int ret;
1330 char *p;
1331 regmatch_t rm;
1332 int a, b, c;
1333 fz_rect sb, eb;
1334 fz_point p1, p2, p3, p4;
1336 p = strofspan (span);
1337 if (!p) return -1;
1339 ret = regexec (re, p, 1, &rm, 0);
1340 if (ret) {
1341 free (p);
1342 if (ret != REG_NOMATCH) {
1343 size_t size;
1344 char errbuf[80];
1345 size = regerror (ret, re, errbuf, sizeof (errbuf));
1346 printd ("msg regexec error `%.*s'",
1347 (int) size, errbuf);
1348 return -1;
1350 return 0;
1352 else {
1353 int l = span->len;
1355 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1356 c += fz_runelen (span->text[a].c);
1358 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1359 c += fz_runelen (span->text[b].c);
1362 if (fz_runelen (span->text[b].c) > 1) {
1363 b = MAX (0, b-1);
1366 fz_text_char_bbox (state.ctx, &sb, span, a);
1367 fz_text_char_bbox (state.ctx, &eb, span, b);
1369 p1.x = sb.x0;
1370 p1.y = sb.y0;
1371 p2.x = eb.x1;
1372 p2.y = sb.y0;
1373 p3.x = eb.x1;
1374 p3.y = eb.y1;
1375 p4.x = sb.x0;
1376 p4.y = eb.y1;
1378 if (!stop) {
1379 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1380 pageno, 1,
1381 p1.x, p1.y,
1382 p2.x, p2.y,
1383 p3.x, p3.y,
1384 p4.x, p4.y);
1386 printd ("progress 1 found at %d `%.*s' in %f sec",
1387 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1388 now () - start);
1390 else {
1391 printd ("match %d %d %f %f %f %f %f %f %f %f",
1392 pageno, 2,
1393 p1.x, p1.y,
1394 p2.x, p2.y,
1395 p3.x, p3.y,
1396 p4.x, p4.y);
1398 free (p);
1399 return 1;
1403 static int compareblocks (const void *l, const void *r)
1405 fz_text_block const *ls = l;
1406 fz_text_block const *rs = r;
1407 return ls->bbox.y0 - rs->bbox.y0;
1410 /* wishful thinking function */
1411 static void search (regex_t *re, int pageno, int y, int forward)
1413 int i, j;
1414 fz_device *tdev;
1415 fz_text_page *text;
1416 fz_text_sheet *sheet;
1417 struct pagedim *pdim, *pdimprev;
1418 int stop = 0, niters = 0;
1419 double start, end;
1420 fz_page *page;
1422 start = now ();
1423 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1424 if (niters++ == 5) {
1425 niters = 0;
1426 if (hasdata ()) {
1427 printd ("progress 1 attention requested aborting search at %d",
1428 pageno);
1429 stop = 1;
1431 else {
1432 printd ("progress %f searching in page %d",
1433 (double) (pageno + 1) / state.pagecount,
1434 pageno);
1437 pdimprev = NULL;
1438 for (i = 0; i < state.pagedimcount; ++i) {
1439 pdim = &state.pagedims[i];
1440 if (pdim->pageno == pageno) {
1441 goto found;
1443 if (pdim->pageno > pageno) {
1444 pdim = pdimprev;
1445 goto found;
1447 pdimprev = pdim;
1449 pdim = pdimprev;
1450 found:
1452 sheet = fz_new_text_sheet (state.ctx);
1453 text = fz_new_text_page (state.ctx);
1454 tdev = fz_new_text_device (state.ctx, sheet, text);
1456 page = fz_load_page (state.ctx, state.doc, pageno);
1458 fz_matrix ctm = pagectm1 (page, pdim);
1459 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1462 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1463 fz_drop_device (state.ctx, tdev);
1465 for (j = 0; j < text->len; ++j) {
1466 int k;
1467 fz_page_block *pb;
1468 fz_text_block *block;
1470 pb = &text->blocks[forward ? j : text->len - 1 - j];
1471 if (pb->type != FZ_PAGE_BLOCK_TEXT) continue;
1472 block = pb->u.text;
1474 for (k = 0; k < block->len; ++k) {
1475 fz_text_line *line;
1476 fz_text_span *span;
1478 if (forward) {
1479 line = &block->lines[k];
1480 if (line->bbox.y0 < y + 1) continue;
1482 else {
1483 line = &block->lines[block->len - 1 - k];
1484 if (line->bbox.y0 > y - 1) continue;
1487 for (span = line->first_span; span; span = span->next) {
1488 switch (matchspan (re, span, stop, pageno, start)) {
1489 case 0: break;
1490 case 1: stop = 1; break;
1491 case -1: stop = 1; goto endloop;
1496 if (forward) {
1497 pageno += 1;
1498 y = 0;
1500 else {
1501 pageno -= 1;
1502 y = INT_MAX;
1504 endloop:
1505 fz_drop_text_page (state.ctx, text);
1506 fz_drop_text_sheet (state.ctx, sheet);
1507 fz_drop_page (state.ctx, page);
1509 end = now ();
1510 if (!stop) {
1511 printd ("progress 1 no matches %f sec", end - start);
1513 printd ("clearrects");
1516 static void set_tex_params (int colorspace)
1518 union {
1519 unsigned char b;
1520 unsigned int s;
1521 } endianness = {1};
1523 switch (colorspace) {
1524 case 0:
1525 state.texiform = GL_RGBA8;
1526 state.texform = GL_RGBA;
1527 state.texty = GL_UNSIGNED_BYTE;
1528 state.colorspace = fz_device_rgb (state.ctx);
1529 break;
1530 case 1:
1531 state.texiform = GL_RGBA8;
1532 state.texform = GL_BGRA;
1533 state.texty = endianness.s > 1
1534 ? GL_UNSIGNED_INT_8_8_8_8
1535 : GL_UNSIGNED_INT_8_8_8_8_REV;
1536 state.colorspace = fz_device_bgr (state.ctx);
1537 break;
1538 case 2:
1539 state.texiform = GL_LUMINANCE_ALPHA;
1540 state.texform = GL_LUMINANCE_ALPHA;
1541 state.texty = GL_UNSIGNED_BYTE;
1542 state.colorspace = fz_device_gray (state.ctx);
1543 break;
1544 default:
1545 errx (1, "invalid colorspce %d", colorspace);
1549 static void realloctexts (int texcount)
1551 size_t size;
1553 if (texcount == state.texcount) return;
1555 if (texcount < state.texcount) {
1556 glDeleteTextures (state.texcount - texcount,
1557 state.texids + texcount);
1560 size = texcount * sizeof (*state.texids);
1561 state.texids = realloc (state.texids, size);
1562 if (!state.texids) {
1563 err (1, "realloc texids %" FMT_s, size);
1566 size = texcount * sizeof (*state.texowners);
1567 state.texowners = realloc (state.texowners, size);
1568 if (!state.texowners) {
1569 err (1, "realloc texowners %" FMT_s, size);
1571 if (texcount > state.texcount) {
1572 int i;
1574 glGenTextures (texcount - state.texcount,
1575 state.texids + state.texcount);
1576 for (i = state.texcount; i < texcount; ++i) {
1577 state.texowners[i].w = -1;
1578 state.texowners[i].slice = NULL;
1581 state.texcount = texcount;
1582 state.texindex = 0;
1585 static char *mbtoutf8 (char *s)
1587 char *p, *r;
1588 wchar_t *tmp;
1589 size_t i, ret, len;
1591 len = mbstowcs (NULL, s, strlen (s));
1592 if (len == 0) {
1593 return s;
1595 else {
1596 if (len == (size_t) -1) {
1597 return s;
1601 tmp = malloc (len * sizeof (wchar_t));
1602 if (!tmp) {
1603 return s;
1606 ret = mbstowcs (tmp, s, len);
1607 if (ret == (size_t) -1) {
1608 free (tmp);
1609 return s;
1612 len = 0;
1613 for (i = 0; i < ret; ++i) {
1614 len += fz_runelen (tmp[i]);
1617 p = r = malloc (len + 1);
1618 if (!r) {
1619 free (tmp);
1620 return s;
1623 for (i = 0; i < ret; ++i) {
1624 p += fz_runetochar (p, tmp[i]);
1626 *p = 0;
1627 free (tmp);
1628 return r;
1631 CAMLprim value ml_mbtoutf8 (value s_v)
1633 CAMLparam1 (s_v);
1634 CAMLlocal1 (ret_v);
1635 char *s, *r;
1637 s = String_val (s_v);
1638 r = mbtoutf8 (s);
1639 if (r == s) {
1640 ret_v = s_v;
1642 else {
1643 ret_v = caml_copy_string (r);
1644 free (r);
1646 CAMLreturn (ret_v);
1649 static void * mainloop (void UNUSED_ATTR *unused)
1651 char *p = NULL;
1652 int len, ret, oldlen = 0;
1654 fz_var (p);
1655 fz_var (oldlen);
1656 for (;;) {
1657 len = readlen ();
1658 if (len == 0) {
1659 errx (1, "readlen returned 0");
1662 if (oldlen < len + 1) {
1663 p = realloc (p, len + 1);
1664 if (!p) {
1665 err (1, "realloc %d failed", len + 1);
1667 oldlen = len + 1;
1669 readdata (p, len);
1670 p[len] = 0;
1672 if (!strncmp ("open", p, 4)) {
1673 int wthack, off, ok = 0;
1674 char *password;
1675 char *filename;
1676 char *utf8filename;
1677 size_t filenamelen;
1679 fz_var (ok);
1680 ret = sscanf (p + 5, " %d %d %n", &wthack, &state.cxack, &off);
1681 if (ret != 2) {
1682 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1685 filename = p + 5 + off;
1686 filenamelen = strlen (filename);
1687 password = filename + filenamelen + 1;
1689 lock ("open");
1690 fz_try (state.ctx) {
1691 ok = openxref (filename, password);
1693 fz_catch (state.ctx) {
1694 utf8filename = mbtoutf8 (filename);
1695 printd ("msg Could not open %s", utf8filename);
1697 if (ok) {
1698 pdfinfo ();
1699 initpdims ();
1701 unlock ("open");
1703 if (ok) {
1704 if (!wthack) {
1705 utf8filename = mbtoutf8 (filename);
1706 printd ("msg Opened %s (press h/F1 to get help)",
1707 utf8filename);
1708 if (utf8filename != filename) {
1709 free (utf8filename);
1712 state.needoutline = 1;
1715 else if (!strncmp ("cs", p, 2)) {
1716 int i, colorspace;
1718 ret = sscanf (p + 2, " %d", &colorspace);
1719 if (ret != 1) {
1720 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1722 lock ("cs");
1723 set_tex_params (colorspace);
1724 for (i = 0; i < state.texcount; ++i) {
1725 state.texowners[i].w = -1;
1726 state.texowners[i].slice = NULL;
1728 unlock ("cs");
1730 else if (!strncmp ("freepage", p, 8)) {
1731 void *ptr;
1733 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1734 if (ret != 1) {
1735 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1737 freepage (ptr);
1739 else if (!strncmp ("freetile", p, 8)) {
1740 void *ptr;
1742 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1743 if (ret != 1) {
1744 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1746 freetile (ptr);
1748 else if (!strncmp ("search", p, 6)) {
1749 int icase, pageno, y, len2, forward;
1750 char *pattern;
1751 regex_t re;
1753 ret = sscanf (p + 6, " %d %d %d %d,%n",
1754 &icase, &pageno, &y, &forward, &len2);
1755 if (ret != 4) {
1756 errx (1, "malformed search `%s' ret=%d", p, ret);
1759 pattern = p + 6 + len2;
1760 ret = regcomp (&re, pattern,
1761 REG_EXTENDED | (icase ? REG_ICASE : 0));
1762 if (ret) {
1763 char errbuf[80];
1764 size_t size;
1766 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1767 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1769 else {
1770 search (&re, pageno, y, forward);
1771 regfree (&re);
1774 else if (!strncmp ("geometry", p, 8)) {
1775 int w, h, fitmodel;
1777 printd ("clear");
1778 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1779 if (ret != 3) {
1780 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1783 lock ("geometry");
1784 state.h = h;
1785 if (w != state.w) {
1786 int i;
1787 state.w = w;
1788 for (i = 0; i < state.texcount; ++i) {
1789 state.texowners[i].slice = NULL;
1792 state.fitmodel = fitmodel;
1793 layout ();
1794 process_outline ();
1796 state.gen++;
1797 unlock ("geometry");
1798 printd ("continue %d", state.pagecount);
1800 else if (!strncmp ("reqlayout", p, 9)) {
1801 char *nameddest;
1802 int rotate, off, h;
1803 unsigned int fitmodel;
1804 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
1806 printd ("clear");
1807 ret = sscanf (p + 9, " %d %u %d %n",
1808 &rotate, &fitmodel, &h, &off);
1809 if (ret != 3) {
1810 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1812 lock ("reqlayout");
1813 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1814 state.gen += 1;
1816 state.rotate = rotate;
1817 state.fitmodel = fitmodel;
1818 state.h = h;
1819 layout ();
1820 process_outline ();
1822 nameddest = p + 9 + off;
1823 if (pdf && nameddest && *nameddest) {
1824 struct anchor a;
1825 fz_link_dest dest;
1826 pdf_obj *needle, *obj;
1828 needle = pdf_new_string (state.ctx, pdf, nameddest,
1829 strlen (nameddest));
1830 obj = pdf_lookup_dest (state.ctx, pdf, needle);
1831 if (obj) {
1832 dest = pdf_parse_link_dest (state.ctx, pdf,
1833 FZ_LINK_GOTO, obj);
1835 a = desttoanchor (&dest);
1836 if (a.n >= 0) {
1837 printd ("a %d %d %d", a.n, a.x, a.y);
1839 else {
1840 printd ("emsg failed to parse destination `%s'\n",
1841 nameddest);
1844 else {
1845 printd ("emsg destination `%s' not found\n",
1846 nameddest);
1848 pdf_drop_obj (state.ctx, needle);
1851 state.gen++;
1852 unlock ("reqlayout");
1853 printd ("continue %d", state.pagecount);
1855 else if (!strncmp ("page", p, 4)) {
1856 double a, b;
1857 struct page *page;
1858 int pageno, pindex;
1860 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1861 if (ret != 2) {
1862 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1865 lock ("page");
1866 a = now ();
1867 page = loadpage (pageno, pindex);
1868 b = now ();
1869 unlock ("page");
1871 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1873 else if (!strncmp ("tile", p, 4)) {
1874 int x, y, w, h;
1875 struct page *page;
1876 struct tile *tile;
1877 double a, b;
1878 void *data;
1880 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1881 SCN_ptr_cast (&page), &x, &y, &w, &h,
1882 SCN_ptr_cast (&data));
1883 if (ret != 6) {
1884 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1887 lock ("tile");
1888 a = now ();
1889 tile = rendertile (page, x, y, w, h, data);
1890 b = now ();
1891 unlock ("tile");
1893 printd ("tile %d %d %" FMT_ptr " %u %f",
1894 x, y,
1895 FMT_ptr_cast (tile),
1896 tile->w * tile->h * tile->pixmap->n,
1897 b - a);
1899 else if (!strncmp ("trimset", p, 7)) {
1900 fz_irect fuzz;
1901 int trimmargins;
1903 ret = sscanf (p + 7, " %d %d %d %d %d",
1904 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1905 if (ret != 5) {
1906 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1908 lock ("trimset");
1909 state.trimmargins = trimmargins;
1910 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1911 state.trimanew = 1;
1912 state.trimfuzz = fuzz;
1914 unlock ("trimset");
1916 else if (!strncmp ("settrim", p, 7)) {
1917 fz_irect fuzz;
1918 int trimmargins;
1920 ret = sscanf (p + 7, " %d %d %d %d %d",
1921 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1922 if (ret != 5) {
1923 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1925 printd ("clear");
1926 lock ("settrim");
1927 state.trimmargins = trimmargins;
1928 state.needoutline = 1;
1929 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1930 state.trimanew = 1;
1931 state.trimfuzz = fuzz;
1933 state.pagedimcount = 0;
1934 free (state.pagedims);
1935 state.pagedims = NULL;
1936 initpdims ();
1937 layout ();
1938 process_outline ();
1939 unlock ("settrim");
1940 printd ("continue %d", state.pagecount);
1942 else if (!strncmp ("sliceh", p, 6)) {
1943 int h;
1945 ret = sscanf (p + 6, " %d", &h);
1946 if (ret != 1) {
1947 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1949 if (h != state.sliceheight) {
1950 int i;
1952 state.sliceheight = h;
1953 for (i = 0; i < state.texcount; ++i) {
1954 state.texowners[i].w = -1;
1955 state.texowners[i].h = -1;
1956 state.texowners[i].slice = NULL;
1960 else if (!strncmp ("interrupt", p, 9)) {
1961 printd ("vmsg interrupted");
1963 else {
1964 errx (1, "unknown command %.*s", len, p);
1967 return 0;
1970 CAMLprim value ml_realloctexts (value texcount_v)
1972 CAMLparam1 (texcount_v);
1973 int ok;
1975 if (trylock ("ml_realloctexts")) {
1976 ok = 0;
1977 goto done;
1979 realloctexts (Int_val (texcount_v));
1980 ok = 1;
1981 unlock ("ml_realloctexts");
1983 done:
1984 CAMLreturn (Val_bool (ok));
1987 static void recti (int x0, int y0, int x1, int y1)
1989 GLfloat *v = state.vertices;
1991 glVertexPointer (2, GL_FLOAT, 0, v);
1992 v[0] = x0; v[1] = y0;
1993 v[2] = x1; v[3] = y0;
1994 v[4] = x0; v[5] = y1;
1995 v[6] = x1; v[7] = y1;
1996 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1999 static void showsel (struct page *page, int ox, int oy)
2001 int seen = 0;
2002 fz_irect bbox;
2003 fz_rect rect;
2004 fz_text_line *line;
2005 fz_page_block *pageb;
2006 fz_text_block *block;
2007 struct mark first, last;
2008 unsigned char selcolor[] = {15,15,15,140};
2010 first = page->fmark;
2011 last = page->lmark;
2013 if (!first.span || !last.span) return;
2015 glEnable (GL_BLEND);
2016 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2017 glColor4ubv (selcolor);
2019 ox += state.pagedims[page->pdimno].bounds.x0;
2020 oy += state.pagedims[page->pdimno].bounds.y0;
2021 for (pageb = page->text->blocks;
2022 pageb < page->text->blocks + page->text->len;
2023 ++pageb) {
2024 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2025 block = pageb->u.text;
2027 for (line = block->lines;
2028 line < block->lines + block->len;
2029 ++line) {
2030 fz_text_span *span;
2031 rect = fz_empty_rect;
2033 for (span = line->first_span; span; span = span->next) {
2034 int i, j, k;
2035 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2037 j = 0;
2038 k = span->len - 1;
2040 if (span == page->fmark.span && span == page->lmark.span) {
2041 seen = 1;
2042 j = MIN (first.i, last.i);
2043 k = MAX (first.i, last.i);
2045 else {
2046 if (span == first.span) {
2047 seen = 1;
2048 j = first.i;
2050 else if (span == last.span) {
2051 seen = 1;
2052 k = last.i;
2056 if (seen) {
2057 for (i = j; i <= k; ++i) {
2058 fz_rect bbox1;
2059 fz_union_rect (&rect,
2060 fz_text_char_bbox (state.ctx, &bbox1,
2061 span, i));
2063 fz_round_rect (&bbox, &rect);
2064 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2065 bbox.x0,
2066 bbox.y0,
2067 bbox.x1,
2068 bbox.y1,
2069 oy, ox);
2071 recti (bbox.x0 + ox, bbox.y0 + oy,
2072 bbox.x1 + ox, bbox.y1 + oy);
2073 if (span == last.span) {
2074 goto done;
2076 rect = fz_empty_rect;
2081 done:
2082 glDisable (GL_BLEND);
2085 #include "glfont.c"
2087 static void stipplerect (fz_matrix *m,
2088 fz_point *p1,
2089 fz_point *p2,
2090 fz_point *p3,
2091 fz_point *p4,
2092 GLfloat *texcoords,
2093 GLfloat *vertices)
2095 fz_transform_point (p1, m);
2096 fz_transform_point (p2, m);
2097 fz_transform_point (p3, m);
2098 fz_transform_point (p4, m);
2100 float w, h, s, t;
2102 w = p2->x - p1->x;
2103 h = p2->y - p1->y;
2104 t = sqrtf (w*w + h*h) * .25f;
2106 w = p3->x - p2->x;
2107 h = p3->y - p2->y;
2108 s = sqrtf (w*w + h*h) * .25f;
2110 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2111 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2113 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2114 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2116 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2117 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2119 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2120 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2122 glDrawArrays (GL_LINES, 0, 8);
2125 static void highlightlinks (struct page *page, int xoff, int yoff)
2127 int i;
2128 fz_matrix ctm, tm, pm;
2129 fz_link *link, *links;
2130 GLfloat *texcoords = state.texcoords;
2131 GLfloat *vertices = state.vertices;
2133 links = fz_load_links (state.ctx, page->fzpage);
2135 glEnable (GL_TEXTURE_1D);
2136 glEnable (GL_BLEND);
2137 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2138 glBindTexture (GL_TEXTURE_1D, state.stid);
2140 xoff -= state.pagedims[page->pdimno].bounds.x0;
2141 yoff -= state.pagedims[page->pdimno].bounds.y0;
2142 fz_translate (&tm, xoff, yoff);
2143 pm = pagectm (page);
2144 fz_concat (&ctm, &pm, &tm);
2146 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2147 glVertexPointer (2, GL_FLOAT, 0, vertices);
2149 for (link = links; link; link = link->next) {
2150 fz_point p1, p2, p3, p4;
2152 p1.x = link->rect.x0;
2153 p1.y = link->rect.y0;
2155 p2.x = link->rect.x1;
2156 p2.y = link->rect.y0;
2158 p3.x = link->rect.x1;
2159 p3.y = link->rect.y1;
2161 p4.x = link->rect.x0;
2162 p4.y = link->rect.y1;
2164 switch (link->dest.kind) {
2165 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
2166 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
2167 case FZ_LINK_LAUNCH: glColor3ub (0, 255, 0); break;
2168 default: glColor3ub (0, 0, 0); break;
2170 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2173 for (i = 0; i < page->annotcount; ++i) {
2174 fz_point p1, p2, p3, p4;
2175 struct annot *annot = &page->annots[i];
2177 p1.x = annot->bbox.x0;
2178 p1.y = annot->bbox.y0;
2180 p2.x = annot->bbox.x1;
2181 p2.y = annot->bbox.y0;
2183 p3.x = annot->bbox.x1;
2184 p3.y = annot->bbox.y1;
2186 p4.x = annot->bbox.x0;
2187 p4.y = annot->bbox.y1;
2189 glColor3ub (0, 0, 128);
2190 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2193 glDisable (GL_BLEND);
2194 glDisable (GL_TEXTURE_1D);
2197 static int compareslinks (const void *l, const void *r)
2199 struct slink const *ls = l;
2200 struct slink const *rs = r;
2201 if (ls->bbox.y0 == rs->bbox.y0) {
2202 return rs->bbox.x0 - rs->bbox.x0;
2204 return ls->bbox.y0 - rs->bbox.y0;
2207 static void droptext (struct page *page)
2209 if (page->text) {
2210 fz_drop_text_page (state.ctx, page->text);
2211 page->fmark.i = -1;
2212 page->lmark.i = -1;
2213 page->fmark.span = NULL;
2214 page->lmark.span = NULL;
2215 page->text = NULL;
2217 if (page->sheet) {
2218 fz_drop_text_sheet (state.ctx, page->sheet);
2219 page->sheet = NULL;
2223 static void dropannots (struct page *page)
2225 if (page->annots) {
2226 free (page->annots);
2227 page->annots = NULL;
2228 page->annotcount = 0;
2232 static void ensureannots (struct page *page)
2234 int i, count = 0;
2235 size_t annotsize = sizeof (*page->annots);
2236 fz_annot *annot;
2238 if (state.gen != page->agen) {
2239 dropannots (page);
2240 page->agen = state.gen;
2242 if (page->annots) return;
2244 for (annot = fz_first_annot (state.ctx, page->fzpage);
2245 annot;
2246 annot = fz_next_annot (state.ctx, page->fzpage, annot)) {
2247 count++;
2250 if (count > 0) {
2251 page->annotcount = count;
2252 page->annots = calloc (count, annotsize);
2253 if (!page->annots) {
2254 err (1, "calloc annots %d", count);
2257 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2258 annot;
2259 annot = fz_next_annot (state.ctx, page->fzpage, annot), i++) {
2260 fz_rect rect;
2262 fz_bound_annot (state.ctx, page->fzpage, annot, &rect);
2263 page->annots[i].annot = annot;
2264 fz_round_rect (&page->annots[i].bbox, &rect);
2269 static void dropslinks (struct page *page)
2271 if (page->slinks) {
2272 free (page->slinks);
2273 page->slinks = NULL;
2274 page->slinkcount = 0;
2278 static void ensureslinks (struct page *page)
2280 fz_matrix ctm;
2281 int i, count;
2282 size_t slinksize = sizeof (*page->slinks);
2283 fz_link *link, *links;
2285 ensureannots (page);
2286 if (state.gen != page->sgen) {
2287 dropslinks (page);
2288 page->sgen = state.gen;
2290 if (page->slinks) return;
2292 links = fz_load_links (state.ctx, page->fzpage);
2293 ctm = state.pagedims[page->pdimno].ctm;
2295 count = page->annotcount;
2296 for (link = links; link; link = link->next) {
2297 count++;
2299 if (count > 0) {
2300 int j;
2302 page->slinkcount = count;
2303 page->slinks = calloc (count, slinksize);
2304 if (!page->slinks) {
2305 err (1, "calloc slinks %d", count);
2308 for (i = 0, link = links; link; ++i, link = link->next) {
2309 fz_rect rect;
2311 rect = link->rect;
2312 fz_transform_rect (&rect, &ctm);
2313 page->slinks[i].tag = SLINK;
2314 page->slinks[i].u.link = link;
2315 fz_round_rect (&page->slinks[i].bbox, &rect);
2317 for (j = 0; j < page->annotcount; ++j, ++i) {
2318 fz_rect rect;
2319 fz_bound_annot (state.ctx,
2320 page->fzpage,
2321 page->annots[j].annot,
2322 &rect);
2323 fz_transform_rect (&rect, &ctm);
2324 fz_round_rect (&page->slinks[i].bbox, &rect);
2326 page->slinks[i].tag = SANNOT;
2327 page->slinks[i].u.annot = page->annots[j].annot;
2329 qsort (page->slinks, count, slinksize, compareslinks);
2333 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2334 static void fmt_linkn (char *s, unsigned int u)
2336 unsigned int len; unsigned int q;
2337 unsigned int zma = 'z' - 'a' + 1;
2338 len = 1; q = u;
2339 while (q > zma - 1) { ++len; q /= zma; }
2340 if (s) {
2341 s += len;
2342 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2343 /* handles u == 0 */
2345 s[len] = 0;
2348 static void highlightslinks (struct page *page, int xoff, int yoff,
2349 int noff, char *targ, int tlen, int hfsize)
2351 int i;
2352 char buf[40];
2353 struct slink *slink;
2354 double x0, y0, x1, y1, w;
2356 ensureslinks (page);
2357 glColor3ub (0xc3, 0xb0, 0x91);
2358 for (i = 0; i < page->slinkcount; ++i) {
2359 fmt_linkn (buf, i + noff);
2360 if (!tlen || !strncmp (targ, buf, tlen)) {
2361 slink = &page->slinks[i];
2363 x0 = slink->bbox.x0 + xoff - 5;
2364 y1 = slink->bbox.y0 + yoff - 5;
2365 y0 = y1 + 10 + hfsize;
2366 w = measure_string (state.face, hfsize, buf);
2367 x1 = x0 + w + 10;
2368 recti (x0, y0, x1, y1);
2372 glEnable (GL_BLEND);
2373 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2374 glEnable (GL_TEXTURE_2D);
2375 glColor3ub (0, 0, 0);
2376 for (i = 0; i < page->slinkcount; ++i) {
2377 fmt_linkn (buf, i + noff);
2378 if (!tlen || !strncmp (targ, buf, tlen)) {
2379 slink = &page->slinks[i];
2381 x0 = slink->bbox.x0 + xoff;
2382 y0 = slink->bbox.y0 + yoff + hfsize;
2383 draw_string (state.face, hfsize, x0, y0, buf);
2386 glDisable (GL_TEXTURE_2D);
2387 glDisable (GL_BLEND);
2390 static void uploadslice (struct tile *tile, struct slice *slice)
2392 int offset;
2393 struct slice *slice1;
2394 unsigned char *texdata;
2396 offset = 0;
2397 for (slice1 = tile->slices; slice != slice1; slice1++) {
2398 offset += slice1->h * tile->w * tile->pixmap->n;
2400 if (slice->texindex != -1 && slice->texindex < state.texcount
2401 && state.texowners[slice->texindex].slice == slice) {
2402 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[slice->texindex]);
2404 else {
2405 int subimage = 0;
2406 int texindex = state.texindex++ % state.texcount;
2408 if (state.texowners[texindex].w == tile->w) {
2409 if (state.texowners[texindex].h >= slice->h) {
2410 subimage = 1;
2412 else {
2413 state.texowners[texindex].h = slice->h;
2416 else {
2417 state.texowners[texindex].h = slice->h;
2420 state.texowners[texindex].w = tile->w;
2421 state.texowners[texindex].slice = slice;
2422 slice->texindex = texindex;
2424 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[texindex]);
2425 if (tile->pbo) {
2426 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2427 texdata = 0;
2429 else {
2430 texdata = tile->pixmap->samples;
2432 if (subimage) {
2433 glTexSubImage2D (GL_TEXTURE_RECTANGLE_ARB,
2437 tile->w,
2438 slice->h,
2439 state.texform,
2440 state.texty,
2441 texdata+offset
2444 else {
2445 glTexImage2D (GL_TEXTURE_RECTANGLE_ARB,
2447 state.texiform,
2448 tile->w,
2449 slice->h,
2451 state.texform,
2452 state.texty,
2453 texdata+offset
2456 if (tile->pbo) {
2457 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2462 CAMLprim value ml_begintiles (value unit_v)
2464 CAMLparam1 (unit_v);
2465 glEnable (GL_TEXTURE_RECTANGLE_ARB);
2466 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2467 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2468 CAMLreturn (unit_v);
2471 CAMLprim value ml_endtiles (value unit_v)
2473 CAMLparam1 (unit_v);
2474 glDisable (GL_TEXTURE_RECTANGLE_ARB);
2475 CAMLreturn (unit_v);
2478 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2480 CAMLparam2 (args_v, ptr_v);
2481 int dispx = Int_val (Field (args_v, 0));
2482 int dispy = Int_val (Field (args_v, 1));
2483 int dispw = Int_val (Field (args_v, 2));
2484 int disph = Int_val (Field (args_v, 3));
2485 int tilex = Int_val (Field (args_v, 4));
2486 int tiley = Int_val (Field (args_v, 5));
2487 char *s = String_val (ptr_v);
2488 struct tile *tile = parse_pointer ("ml_drawtile", s);
2489 int slicey, firstslice;
2490 struct slice *slice;
2491 GLfloat *texcoords = state.texcoords;
2492 GLfloat *vertices = state.vertices;
2494 firstslice = tiley / tile->sliceheight;
2495 slice = &tile->slices[firstslice];
2496 slicey = tiley % tile->sliceheight;
2498 while (disph > 0) {
2499 int dh;
2501 dh = slice->h - slicey;
2502 dh = MIN (disph, dh);
2503 uploadslice (tile, slice);
2505 texcoords[0] = tilex; texcoords[1] = slicey;
2506 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2507 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2508 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2510 vertices[0] = dispx; vertices[1] = dispy;
2511 vertices[2] = dispx+dispw; vertices[3] = dispy;
2512 vertices[4] = dispx; vertices[5] = dispy+dh;
2513 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2515 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2516 dispy += dh;
2517 disph -= dh;
2518 slice++;
2519 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2520 slicey = 0;
2522 CAMLreturn (Val_unit);
2525 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2526 value xoff_v, value yoff_v,
2527 value li_v)
2529 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2530 int xoff = Int_val (xoff_v);
2531 int yoff = Int_val (yoff_v);
2532 int noff = Int_val (Field (li_v, 0));
2533 char *targ = String_val (Field (li_v, 1));
2534 int tlen = caml_string_length (Field (li_v, 1));
2535 int hfsize = Int_val (Field (li_v, 2));
2536 char *s = String_val (ptr_v);
2537 int hlmask = Int_val (hlinks_v);
2538 struct page *page = parse_pointer ("ml_postprocess", s);
2540 if (!page->fzpage) {
2541 /* deal with loadpage failed pages */
2542 goto done;
2545 ensureannots (page);
2547 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2548 if (trylock ("ml_postprocess")) {
2549 noff = 0;
2550 goto done;
2552 if (hlmask & 2) {
2553 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2554 noff = page->slinkcount;
2556 if (page->tgen == state.gen) {
2557 showsel (page, xoff, yoff);
2559 unlock ("ml_postprocess");
2561 done:
2562 CAMLreturn (Val_int (noff));
2565 static struct annot *getannot (struct page *page, int x, int y)
2567 int i;
2568 fz_point p;
2569 fz_matrix ctm;
2570 const fz_matrix *tctm;
2571 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2573 if (!page->annots) return NULL;
2575 if (pdf) {
2576 trimctm ((pdf_page *) page->fzpage, page->pdimno);
2577 tctm = &state.pagedims[page->pdimno].tctm;
2579 else {
2580 tctm = &fz_identity;
2583 p.x = x;
2584 p.y = y;
2586 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2587 fz_invert_matrix (&ctm, &ctm);
2588 fz_transform_point (&p, &ctm);
2590 if (pdf) {
2591 for (i = 0; i < page->annotcount; ++i) {
2592 struct annot *a = &page->annots[i];
2593 pdf_annot *annot = (pdf_annot *) a->annot;
2594 if (p.x >= annot->pagerect.x0 && p.x <= annot->pagerect.x1) {
2595 if (p.y >= annot->pagerect.y0 && p.y <= annot->pagerect.y1) {
2596 return a;
2601 return NULL;
2604 static fz_link *getlink (struct page *page, int x, int y)
2606 fz_point p;
2607 fz_matrix ctm;
2608 const fz_matrix *tctm;
2609 fz_link *link, *links;
2611 tctm = &fz_identity;
2612 links = fz_load_links (state.ctx, page->fzpage);
2614 p.x = x;
2615 p.y = y;
2617 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2618 fz_invert_matrix (&ctm, &ctm);
2619 fz_transform_point (&p, &ctm);
2621 for (link = links; link; link = link->next) {
2622 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2623 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2624 return link;
2628 return NULL;
2631 static void ensuretext (struct page *page)
2633 if (state.gen != page->tgen) {
2634 droptext (page);
2635 page->tgen = state.gen;
2637 if (!page->text) {
2638 fz_matrix ctm;
2639 fz_device *tdev;
2641 page->text = fz_new_text_page (state.ctx);
2642 page->sheet = fz_new_text_sheet (state.ctx);
2643 tdev = fz_new_text_device (state.ctx, page->sheet, page->text);
2644 ctm = pagectm (page);
2645 fz_begin_page (state.ctx, tdev, &fz_infinite_rect, &ctm);
2646 fz_run_display_list (state.ctx, page->dlist,
2647 tdev, &ctm, &fz_infinite_rect, NULL);
2648 qsort (page->text->blocks, page->text->len,
2649 sizeof (*page->text->blocks), compareblocks);
2650 fz_end_page (state.ctx, tdev);
2651 fz_drop_device (state.ctx, tdev);
2655 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2657 CAMLparam2 (start_page_v, dir_v);
2658 CAMLlocal1 (ret_v);
2659 int i, dir = Int_val (dir_v);
2660 int start_page = Int_val (start_page_v);
2661 int end_page = dir > 0 ? state.pagecount : -1;
2662 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2664 fz_var (end_page);
2665 ret_v = Val_int (0);
2666 lock ("ml_findpage_with_links");
2667 for (i = start_page + dir; i != end_page; i += dir) {
2668 int found;
2670 fz_var (found);
2671 if (pdf) {
2672 pdf_page *page = NULL;
2674 fz_try (state.ctx) {
2675 page = pdf_load_page (state.ctx, pdf, i);
2676 found = !!page->links || !!page->annots;
2678 fz_catch (state.ctx) {
2679 found = 0;
2681 if (page) {
2682 fz_drop_page (state.ctx, &page->super);
2685 else {
2686 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2687 found = !!fz_load_links (state.ctx, page);
2688 fz_drop_page (state.ctx, page);
2691 if (found) {
2692 ret_v = caml_alloc_small (1, 1);
2693 Field (ret_v, 0) = Val_int (i);
2694 goto unlock;
2697 unlock:
2698 unlock ("ml_findpage_with_links");
2699 CAMLreturn (ret_v);
2702 enum { dir_first, dir_last };
2703 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2705 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2707 CAMLparam2 (ptr_v, dir_v);
2708 CAMLlocal2 (ret_v, pos_v);
2709 struct page *page;
2710 int dirtag, i, slinkindex;
2711 struct slink *found = NULL ,*slink;
2712 char *s = String_val (ptr_v);
2714 page = parse_pointer ("ml_findlink", s);
2715 ret_v = Val_int (0);
2716 /* This is scary we are not taking locks here ensureslinks does
2717 not modify state and given that we obtained the page it can not
2718 disappear under us either */
2719 lock ("ml_findlink");
2720 ensureslinks (page);
2722 if (Is_block (dir_v)) {
2723 dirtag = Tag_val (dir_v);
2724 switch (dirtag) {
2725 case dir_first_visible:
2727 int x0, y0, dir, first_index, last_index;
2729 pos_v = Field (dir_v, 0);
2730 x0 = Int_val (Field (pos_v, 0));
2731 y0 = Int_val (Field (pos_v, 1));
2732 dir = Int_val (Field (pos_v, 2));
2734 if (dir >= 0) {
2735 dir = 1;
2736 first_index = 0;
2737 last_index = page->slinkcount;
2739 else {
2740 first_index = page->slinkcount - 1;
2741 last_index = -1;
2744 for (i = first_index; i != last_index; i += dir) {
2745 slink = &page->slinks[i];
2746 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2747 found = slink;
2748 break;
2752 break;
2754 case dir_left:
2755 slinkindex = Int_val (Field (dir_v, 0));
2756 found = &page->slinks[slinkindex];
2757 for (i = slinkindex - 1; i >= 0; --i) {
2758 slink = &page->slinks[i];
2759 if (slink->bbox.x0 < found->bbox.x0) {
2760 found = slink;
2761 break;
2764 break;
2766 case dir_right:
2767 slinkindex = Int_val (Field (dir_v, 0));
2768 found = &page->slinks[slinkindex];
2769 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2770 slink = &page->slinks[i];
2771 if (slink->bbox.x0 > found->bbox.x0) {
2772 found = slink;
2773 break;
2776 break;
2778 case dir_down:
2779 slinkindex = Int_val (Field (dir_v, 0));
2780 found = &page->slinks[slinkindex];
2781 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2782 slink = &page->slinks[i];
2783 if (slink->bbox.y0 >= found->bbox.y0) {
2784 found = slink;
2785 break;
2788 break;
2790 case dir_up:
2791 slinkindex = Int_val (Field (dir_v, 0));
2792 found = &page->slinks[slinkindex];
2793 for (i = slinkindex - 1; i >= 0; --i) {
2794 slink = &page->slinks[i];
2795 if (slink->bbox.y0 <= found->bbox.y0) {
2796 found = slink;
2797 break;
2800 break;
2803 else {
2804 dirtag = Int_val (dir_v);
2805 switch (dirtag) {
2806 case dir_first:
2807 found = page->slinks;
2808 break;
2810 case dir_last:
2811 if (page->slinks) {
2812 found = page->slinks + (page->slinkcount - 1);
2814 break;
2817 if (found) {
2818 ret_v = caml_alloc_small (2, 1);
2819 Field (ret_v, 0) = Val_int (found - page->slinks);
2822 unlock ("ml_findlink");
2823 CAMLreturn (ret_v);
2826 enum { uuri, ugoto, utext, uunexpected, ulaunch,
2827 unamed, uremote, uremotedest, uannot };
2829 #define LINKTOVAL \
2831 int pageno; \
2833 switch (link->dest.kind) { \
2834 case FZ_LINK_GOTO: \
2836 fz_point p; \
2838 pageno = link->dest.ld.gotor.page; \
2839 p.x = 0; \
2840 p.y = 0; \
2842 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2843 p.y = link->dest.ld.gotor.lt.y; \
2844 fz_transform_point (&p, &pdim->lctm); \
2845 if (p.y < 0) p.y = 0; \
2847 tup_v = caml_alloc_tuple (2); \
2848 ret_v = caml_alloc_small (1, ugoto); \
2849 Field (tup_v, 0) = Val_int (pageno); \
2850 Field (tup_v, 1) = Val_int (p.y); \
2851 Field (ret_v, 0) = tup_v; \
2853 break; \
2855 case FZ_LINK_URI: \
2856 str_v = caml_copy_string (link->dest.ld.uri.uri); \
2857 ret_v = caml_alloc_small (1, uuri); \
2858 Field (ret_v, 0) = str_v; \
2859 break; \
2861 case FZ_LINK_LAUNCH: \
2862 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
2863 ret_v = caml_alloc_small (1, ulaunch); \
2864 Field (ret_v, 0) = str_v; \
2865 break; \
2867 case FZ_LINK_NAMED: \
2868 str_v = caml_copy_string (link->dest.ld.named.named); \
2869 ret_v = caml_alloc_small (1, unamed); \
2870 Field (ret_v, 0) = str_v; \
2871 break; \
2873 case FZ_LINK_GOTOR: \
2875 int rty; \
2877 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
2878 pageno = link->dest.ld.gotor.page; \
2879 if (pageno == -1) { \
2880 gr_v = caml_copy_string (link->dest.ld.gotor.dest); \
2881 rty = uremotedest; \
2883 else { \
2884 gr_v = Val_int (pageno); \
2885 rty = uremote; \
2887 tup_v = caml_alloc_tuple (2); \
2888 ret_v = caml_alloc_small (1, rty); \
2889 Field (tup_v, 0) = str_v; \
2890 Field (tup_v, 1) = gr_v; \
2891 Field (ret_v, 0) = tup_v; \
2893 break; \
2895 default: \
2897 char buf[80]; \
2899 snprintf (buf, sizeof (buf), \
2900 "unhandled link kind %d", link->dest.kind); \
2901 str_v = caml_copy_string (buf); \
2902 ret_v = caml_alloc_small (1, uunexpected); \
2903 Field (ret_v, 0) = str_v; \
2905 break; \
2909 CAMLprim value ml_getlink (value ptr_v, value n_v)
2911 CAMLparam2 (ptr_v, n_v);
2912 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2913 fz_link *link;
2914 struct page *page;
2915 struct pagedim *pdim;
2916 char *s = String_val (ptr_v);
2917 struct slink *slink;
2919 /* See ml_findlink for caveat */
2921 ret_v = Val_int (0);
2922 page = parse_pointer ("ml_getlink", s);
2923 ensureslinks (page);
2924 pdim = &state.pagedims[page->pdimno];
2925 slink = &page->slinks[Int_val (n_v)];
2926 if (slink->tag == SLINK) {
2927 link = slink->u.link;
2928 LINKTOVAL;
2930 else {
2931 ret_v = caml_alloc_small (1, uannot);
2932 tup_v = caml_alloc_tuple (2);
2933 Field (ret_v, 0) = tup_v;
2934 Field (tup_v, 0) = ptr_v;
2935 Field (tup_v, 1) = n_v;
2938 CAMLreturn (ret_v);
2941 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2943 CAMLparam2 (ptr_v, n_v);
2944 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2945 if (pdf) {
2946 char *s = String_val (ptr_v);
2947 struct page *page;
2948 struct slink *slink;
2950 page = parse_pointer ("ml_getannotcontent", s);
2951 slink = &page->slinks[Int_val (n_v)];
2952 CAMLreturn (caml_copy_string (
2953 pdf_annot_contents (state.ctx, pdf,
2954 (pdf_annot *) slink->u.annot)));
2956 else {
2957 CAMLreturn (caml_copy_string (""));
2961 CAMLprim value ml_getlinkcount (value ptr_v)
2963 CAMLparam1 (ptr_v);
2964 struct page *page;
2965 char *s = String_val (ptr_v);
2967 page = parse_pointer ("ml_getlinkcount", s);
2968 CAMLreturn (Val_int (page->slinkcount));
2971 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2973 CAMLparam2 (ptr_v, n_v);
2974 CAMLlocal1 (ret_v);
2975 struct page *page;
2976 struct slink *slink;
2977 char *s = String_val (ptr_v);
2978 /* See ml_findlink for caveat */
2980 page = parse_pointer ("ml_getlinkrect", s);
2981 ret_v = caml_alloc_tuple (4);
2982 ensureslinks (page);
2984 slink = &page->slinks[Int_val (n_v)];
2985 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2986 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2987 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2988 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2989 unlock ("ml_getlinkrect");
2990 CAMLreturn (ret_v);
2993 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2995 CAMLparam3 (ptr_v, x_v, y_v);
2996 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2997 fz_link *link;
2998 struct annot *annot;
2999 struct page *page;
3000 char *ptr = String_val (ptr_v);
3001 int x = Int_val (x_v), y = Int_val (y_v);
3002 struct pagedim *pdim;
3004 ret_v = Val_int (0);
3005 if (trylock ("ml_whatsunder")) {
3006 goto done;
3009 page = parse_pointer ("ml_whatsunder", ptr);
3010 pdim = &state.pagedims[page->pdimno];
3011 x += pdim->bounds.x0;
3012 y += pdim->bounds.y0;
3015 annot = getannot (page, x, y);
3016 if (annot) {
3017 int i, n = -1;
3019 ensureslinks (page);
3020 for (i = 0; i < page->slinkcount; ++i) {
3021 if (page->slinks[i].tag == SANNOT
3022 && page->slinks[i].u.annot == annot->annot) {
3023 n = i;
3024 break;
3027 ret_v = caml_alloc_small (1, uannot);
3028 tup_v = caml_alloc_tuple (2);
3029 Field (ret_v, 0) = tup_v;
3030 Field (tup_v, 0) = ptr_v;
3031 Field (tup_v, 1) = Val_int (n);
3032 goto unlock;
3036 link = getlink (page, x, y);
3037 if (link) {
3038 LINKTOVAL;
3040 else {
3041 fz_rect *b;
3042 fz_page_block *pageb;
3043 fz_text_block *block;
3045 ensuretext (page);
3046 for (pageb = page->text->blocks;
3047 pageb < page->text->blocks + page->text->len;
3048 ++pageb) {
3049 fz_text_line *line;
3050 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3051 block = pageb->u.text;
3053 b = &block->bbox;
3054 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3055 continue;
3057 for (line = block->lines;
3058 line < block->lines + block->len;
3059 ++line) {
3060 fz_text_span *span;
3062 b = &line->bbox;
3063 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3064 continue;
3066 for (span = line->first_span; span; span = span->next) {
3067 int charnum;
3069 b = &span->bbox;
3070 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3071 continue;
3073 for (charnum = 0; charnum < span->len; ++charnum) {
3074 fz_rect bbox;
3075 fz_text_char_bbox (state.ctx, &bbox, span, charnum);
3076 b = &bbox;
3078 if (x >= b->x0 && x <= b->x1
3079 && y >= b->y0 && y <= b->y1) {
3080 fz_text_style *style = span->text->style;
3081 const char *n2 =
3082 style->font
3083 ? style->font->name
3084 : "Span has no font name"
3086 FT_FaceRec *face = style->font->ft_face;
3087 if (face && face->family_name) {
3088 char *s;
3089 char *n1 = face->family_name;
3090 size_t l1 = strlen (n1);
3091 size_t l2 = strlen (n2);
3093 if (l1 != l2 || memcmp (n1, n2, l1)) {
3094 s = malloc (l1 + l2 + 2);
3095 if (s) {
3096 memcpy (s, n2, l2);
3097 s[l2] = '=';
3098 memcpy (s + l2 + 1, n1, l1 + 1);
3099 str_v = caml_copy_string (s);
3100 free (s);
3104 if (str_v == Val_unit) {
3105 str_v = caml_copy_string (n2);
3107 ret_v = caml_alloc_small (1, utext);
3108 Field (ret_v, 0) = str_v;
3109 goto unlock;
3116 unlock:
3117 unlock ("ml_whatsunder");
3119 done:
3120 CAMLreturn (ret_v);
3123 enum { mark_page, mark_block, mark_line, mark_word };
3125 static int uninteresting (int c)
3127 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3128 || ispunct (c);
3131 CAMLprim value ml_clearmark (value ptr_v)
3133 CAMLparam1 (ptr_v);
3134 char *s = String_val (ptr_v);
3135 struct page *page;
3137 if (trylock ("ml_clearmark")) {
3138 goto done;
3141 page = parse_pointer ("ml_clearmark", s);
3142 page->fmark.span = NULL;
3143 page->lmark.span = NULL;
3144 page->fmark.i = 0;
3145 page->lmark.i = 0;
3147 unlock ("ml_clearmark");
3148 done:
3149 CAMLreturn (Val_unit);
3152 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3154 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3155 CAMLlocal1 (ret_v);
3156 fz_rect *b;
3157 struct page *page;
3158 fz_text_line *line;
3159 fz_page_block *pageb;
3160 fz_text_block *block;
3161 struct pagedim *pdim;
3162 int mark = Int_val (mark_v);
3163 char *s = String_val (ptr_v);
3164 int x = Int_val (x_v), y = Int_val (y_v);
3166 ret_v = Val_bool (0);
3167 if (trylock ("ml_markunder")) {
3168 goto done;
3171 page = parse_pointer ("ml_markunder", s);
3172 pdim = &state.pagedims[page->pdimno];
3174 ensuretext (page);
3176 if (mark == mark_page) {
3177 int i;
3178 fz_page_block *pb1 = NULL, *pb2 = NULL;
3180 for (i = 0; i < page->text->len; ++i) {
3181 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3182 pb1 = &page->text->blocks[i];
3183 break;
3186 if (!pb1) goto unlock;
3188 for (i = page->text->len - 1; i >= 0; --i) {
3189 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3190 pb2 = &page->text->blocks[i];
3191 break;
3194 if (!pb2) goto unlock;
3196 block = pb1->u.text;
3198 page->fmark.i = 0;
3199 page->fmark.span = block->lines->first_span;
3201 block = pb2->u.text;
3202 line = &block->lines[block->len - 1];
3203 page->lmark.i = line->last_span->len - 1;
3204 page->lmark.span = line->last_span;
3205 ret_v = Val_bool (1);
3206 goto unlock;
3209 x += pdim->bounds.x0;
3210 y += pdim->bounds.y0;
3212 for (pageb = page->text->blocks;
3213 pageb < page->text->blocks + page->text->len;
3214 ++pageb) {
3215 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3216 block = pageb->u.text;
3218 b = &block->bbox;
3219 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3220 continue;
3222 if (mark == mark_block) {
3223 page->fmark.i = 0;
3224 page->fmark.span = block->lines->first_span;
3226 line = &block->lines[block->len - 1];
3227 page->lmark.i = line->last_span->len - 1;
3228 page->lmark.span = line->last_span;
3229 ret_v = Val_bool (1);
3230 goto unlock;
3233 for (line = block->lines;
3234 line < block->lines + block->len;
3235 ++line) {
3236 fz_text_span *span;
3238 b = &line->bbox;
3239 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3240 continue;
3242 if (mark == mark_line) {
3243 page->fmark.i = 0;
3244 page->fmark.span = line->first_span;
3246 page->lmark.i = line->last_span->len - 1;
3247 page->lmark.span = line->last_span;
3248 ret_v = Val_bool (1);
3249 goto unlock;
3252 for (span = line->first_span; span; span = span->next) {
3253 int charnum;
3255 b = &span->bbox;
3256 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3257 continue;
3259 for (charnum = 0; charnum < span->len; ++charnum) {
3260 fz_rect bbox;
3261 fz_text_char_bbox (state.ctx, &bbox, span, charnum);
3262 b = &bbox;
3264 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3265 /* unicode ftw */
3266 int charnum2, charnum3 = -1, charnum4 = -1;
3268 if (uninteresting (span->text[charnum].c)) goto unlock;
3270 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3271 if (uninteresting (span->text[charnum2].c)) {
3272 charnum3 = charnum2 + 1;
3273 break;
3276 if (charnum3 == -1) charnum3 = 0;
3278 for (charnum2 = charnum + 1;
3279 charnum2 < span->len;
3280 ++charnum2) {
3281 if (uninteresting (span->text[charnum2].c)) break;
3282 charnum4 = charnum2;
3284 if (charnum4 == -1) goto unlock;
3286 page->fmark.i = charnum3;
3287 page->fmark.span = span;
3289 page->lmark.i = charnum4;
3290 page->lmark.span = span;
3291 ret_v = Val_bool (1);
3292 goto unlock;
3298 unlock:
3299 if (!Bool_val (ret_v)) {
3300 page->fmark.span = NULL;
3301 page->lmark.span = NULL;
3302 page->fmark.i = 0;
3303 page->lmark.i = 0;
3305 unlock ("ml_markunder");
3307 done:
3308 CAMLreturn (ret_v);
3311 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3313 CAMLparam3 (ptr_v, x_v, y_v);
3314 CAMLlocal2 (ret_v, res_v);
3315 fz_rect *b = NULL;
3316 struct page *page;
3317 fz_page_block *pageb;
3318 struct pagedim *pdim;
3319 char *s = String_val (ptr_v);
3320 int x = Int_val (x_v), y = Int_val (y_v);
3322 ret_v = Val_int (0);
3323 if (trylock ("ml_rectofblock")) {
3324 goto done;
3327 page = parse_pointer ("ml_rectofblock", s);
3328 pdim = &state.pagedims[page->pdimno];
3329 x += pdim->bounds.x0;
3330 y += pdim->bounds.y0;
3332 ensuretext (page);
3334 for (pageb = page->text->blocks;
3335 pageb < page->text->blocks + page->text->len;
3336 ++pageb) {
3337 switch (pageb->type) {
3338 case FZ_PAGE_BLOCK_TEXT:
3339 b = &pageb->u.text->bbox;
3340 break;
3342 case FZ_PAGE_BLOCK_IMAGE:
3343 b = &pageb->u.image->bbox;
3344 break;
3346 default:
3347 continue;
3350 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3351 break;
3352 b = NULL;
3354 if (b) {
3355 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3356 ret_v = caml_alloc_small (1, 1);
3357 Store_double_field (res_v, 0, b->x0);
3358 Store_double_field (res_v, 1, b->x1);
3359 Store_double_field (res_v, 2, b->y0);
3360 Store_double_field (res_v, 3, b->y1);
3361 Field (ret_v, 0) = res_v;
3363 unlock ("ml_rectofblock");
3365 done:
3366 CAMLreturn (ret_v);
3369 CAMLprim value ml_seltext (value ptr_v, value rect_v)
3371 CAMLparam2 (ptr_v, rect_v);
3372 fz_rect b;
3373 struct page *page;
3374 struct pagedim *pdim;
3375 char *s = String_val (ptr_v);
3376 int i, x0, x1, y0, y1, fi, li;
3377 fz_text_line *line;
3378 fz_page_block *pageb;
3379 fz_text_block *block;
3380 fz_text_span *span, *fspan, *lspan;
3382 if (trylock ("ml_seltext")) {
3383 goto done;
3386 page = parse_pointer ("ml_seltext", s);
3387 ensuretext (page);
3389 pdim = &state.pagedims[page->pdimno];
3390 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3391 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3392 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3393 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3395 if (y0 > y1) {
3396 int t = y0;
3397 y0 = y1;
3398 y1 = t;
3399 x0 = x1;
3400 x1 = t;
3403 if (0) {
3404 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
3405 glColor3ub (128, 128, 128);
3406 recti (x0, y0, x1, y1);
3407 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
3410 fi = page->fmark.i;
3411 fspan = page->fmark.span;
3413 li = page->lmark.i;
3414 lspan = page->lmark.span;
3416 for (pageb = page->text->blocks;
3417 pageb < page->text->blocks + page->text->len;
3418 ++pageb) {
3419 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3420 block = pageb->u.text;
3421 for (line = block->lines;
3422 line < block->lines + block->len;
3423 ++line) {
3425 for (span = line->first_span; span; span = span->next) {
3426 for (i = 0; i < span->len; ++i) {
3427 int selected = 0;
3429 fz_text_char_bbox (state.ctx, &b, span, i);
3431 if (x0 >= b.x0 && x0 <= b.x1
3432 && y0 >= b.y0 && y0 <= b.y1) {
3433 fspan = span;
3434 fi = i;
3435 selected = 1;
3437 if (x1 >= b.x0 && x1 <= b.x1
3438 && y1 >= b.y0 && y1 <= b.y1) {
3439 lspan = span;
3440 li = i;
3441 selected = 1;
3443 if (0 && selected) {
3444 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
3445 glColor3ub (128, 128, 128);
3446 recti (b.x0, b.y0, b.x1, b.y1);
3447 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
3453 if (x1 < x0 && fspan == lspan) {
3454 i = fi;
3455 span = fspan;
3457 fi = li;
3458 fspan = lspan;
3460 li = i;
3461 lspan = span;
3464 page->fmark.i = fi;
3465 page->fmark.span = fspan;
3467 page->lmark.i = li;
3468 page->lmark.span = lspan;
3470 unlock ("ml_seltext");
3472 done:
3473 CAMLreturn (Val_unit);
3476 static int UNUSED_ATTR pipespan (FILE *f, fz_text_span *span, int a, int b)
3478 char buf[4];
3479 int i, len, ret;
3481 for (i = a; i <= b; ++i) {
3482 len = fz_runetochar (buf, span->text[i].c);
3483 ret = fwrite (buf, len, 1, f);
3485 if (ret != 1) {
3486 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3487 len, ret, strerror (errno));
3488 return -1;
3491 return 0;
3494 #ifdef __CYGWIN__
3495 CAMLprim value ml_spawn (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3497 caml_failwith ("ml_popen not implemented under Cygwin");
3499 #else
3500 CAMLprim value ml_spawn (value command_v, value fds_v)
3502 CAMLparam2 (command_v, fds_v);
3503 CAMLlocal2 (l_v, tup_v);
3504 int ret, ret1;
3505 pid_t pid;
3506 char *msg = NULL;
3507 value earg_v = Nothing;
3508 posix_spawnattr_t attr;
3509 posix_spawn_file_actions_t fa;
3510 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3512 argv[2] = String_val (command_v);
3514 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3515 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3518 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3519 msg = "posix_spawnattr_init";
3520 goto fail1;
3523 #ifdef POSIX_SPAWN_USEVFORK
3524 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3525 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3526 goto fail;
3528 #endif
3530 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3531 int fd1, fd2;
3533 tup_v = Field (l_v, 0);
3534 fd1 = Int_val (Field (tup_v, 0));
3535 fd2 = Int_val (Field (tup_v, 1));
3536 if (fd2 < 0) {
3537 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3538 msg = "posix_spawn_file_actions_addclose";
3539 earg_v = tup_v;
3540 goto fail;
3543 else {
3544 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3545 msg = "posix_spawn_file_actions_adddup2";
3546 earg_v = tup_v;
3547 goto fail;
3552 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3553 msg = "posix_spawn";
3554 goto fail;
3557 fail:
3558 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3559 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret1));
3562 fail1:
3563 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3564 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3565 strerror (ret1));
3568 if (msg)
3569 unix_error (ret, msg, earg_v);
3571 CAMLreturn (Val_int (pid));
3573 #endif
3575 CAMLprim value ml_hassel (value ptr_v)
3577 CAMLparam1 (ptr_v);
3578 CAMLlocal1 (ret_v);
3579 struct page *page;
3580 char *s = String_val (ptr_v);
3582 ret_v = Val_bool (0);
3583 if (trylock ("ml_hassel")) {
3584 goto done;
3587 page = parse_pointer ("ml_hassel", s);
3588 ret_v = Val_bool (page->fmark.span && page->lmark.span);
3589 unlock ("ml_hassel");
3590 done:
3591 CAMLreturn (ret_v);
3594 CAMLprim value ml_copysel (value fd_v, value ptr_v)
3596 CAMLparam2 (fd_v, ptr_v);
3597 FILE *f;
3598 int seen = 0;
3599 struct page *page;
3600 fz_text_line *line;
3601 fz_page_block *pageb;
3602 fz_text_block *block;
3603 int fd = Int_val (fd_v);
3604 char *s = String_val (ptr_v);
3606 if (trylock ("ml_copysel")) {
3607 goto done;
3610 page = parse_pointer ("ml_copysel", s);
3612 if (!page->fmark.span || !page->lmark.span) {
3613 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3614 goto unlock;
3617 f = fdopen (fd, "w");
3618 if (!f) {
3619 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3620 fd, strerror (errno));
3621 f = stdout;
3624 for (pageb = page->text->blocks;
3625 pageb < page->text->blocks + page->text->len;
3626 ++pageb) {
3627 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3628 block = pageb->u.text;
3629 for (line = block->lines;
3630 line < block->lines + block->len;
3631 ++line) {
3632 fz_text_span *span;
3634 for (span = line->first_span; span; span = span->next) {
3635 int a, b;
3637 seen |= span == page->fmark.span || span == page->lmark.span;
3638 a = span == page->fmark.span ? page->fmark.i : 0;
3639 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3641 if (seen) {
3642 if (pipespan (f, span, a, b)) {
3643 goto close;
3645 if (span == page->lmark.span) {
3646 goto close;
3648 if (span == line->last_span) {
3649 if (putc ('\n', f) == EOF) {
3650 fprintf (stderr,
3651 "failed break line on sel pipe: %s\n",
3652 strerror (errno));
3653 goto close;
3660 close:
3661 if (f != stdout) {
3662 int ret = fclose (f);
3663 fd = -1;
3664 if (ret == -1) {
3665 if (errno != ECHILD) {
3666 fprintf (stderr, "failed to close sel pipe: %s\n",
3667 strerror (errno));
3671 unlock:
3672 unlock ("ml_copysel");
3674 done:
3675 if (fd >= 0) {
3676 if (close (fd)) {
3677 fprintf (stderr, "failed to close sel pipe: %s\n",
3678 strerror (errno));
3681 CAMLreturn (Val_unit);
3684 CAMLprim value ml_getpdimrect (value pagedimno_v)
3686 CAMLparam1 (pagedimno_v);
3687 CAMLlocal1 (ret_v);
3688 int pagedimno = Int_val (pagedimno_v);
3689 fz_rect box;
3691 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3692 if (trylock ("ml_getpdimrect")) {
3693 box = fz_empty_rect;
3695 else {
3696 box = state.pagedims[pagedimno].mediabox;
3697 unlock ("ml_getpdimrect");
3700 Store_double_field (ret_v, 0, box.x0);
3701 Store_double_field (ret_v, 1, box.x1);
3702 Store_double_field (ret_v, 2, box.y0);
3703 Store_double_field (ret_v, 3, box.y1);
3705 CAMLreturn (ret_v);
3708 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3709 value dw_v, value cols_v)
3711 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3712 CAMLlocal1 (ret_v);
3713 int i;
3714 double zoom = -1.;
3715 double maxh = 0.0;
3716 struct pagedim *p;
3717 double winw = Int_val (winw_v);
3718 double winh = Int_val (winh_v);
3719 double dw = Int_val (dw_v);
3720 double cols = Int_val (cols_v);
3721 double pw = 1.0, ph = 1.0;
3723 if (trylock ("ml_zoom_for_height")) {
3724 goto done;
3727 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3728 double w = p->pagebox.x1 / cols;
3729 double h = p->pagebox.y1;
3730 if (h > maxh) {
3731 maxh = h;
3732 ph = h;
3733 if (state.fitmodel != FitProportional) pw = w;
3735 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3738 zoom = (((winh / ph) * pw) + dw) / winw;
3739 unlock ("ml_zoom_for_height");
3740 done:
3741 ret_v = caml_copy_double (zoom);
3742 CAMLreturn (ret_v);
3745 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3747 CAMLparam4 (pt_v, x_v, y_v, string_v);
3748 CAMLlocal1 (ret_v);
3749 int pt = Int_val(pt_v);
3750 int x = Int_val (x_v);
3751 int y = Int_val (y_v);
3752 double w;
3754 w = draw_string (state.face, pt, x, y, String_val (string_v));
3755 ret_v = caml_copy_double (w);
3756 CAMLreturn (ret_v);
3759 CAMLprim value ml_measure_string (value pt_v, value string_v)
3761 CAMLparam2 (pt_v, string_v);
3762 CAMLlocal1 (ret_v);
3763 int pt = Int_val (pt_v);
3764 double w;
3766 w = measure_string (state.face, pt, String_val (string_v));
3767 ret_v = caml_copy_double (w);
3768 CAMLreturn (ret_v);
3771 CAMLprim value ml_getpagebox (value opaque_v)
3773 CAMLparam1 (opaque_v);
3774 CAMLlocal1 (ret_v);
3775 fz_rect rect;
3776 fz_irect bbox;
3777 fz_matrix ctm;
3778 fz_device *dev;
3779 char *s = String_val (opaque_v);
3780 struct page *page = parse_pointer ("ml_getpagebox", s);
3782 ret_v = caml_alloc_tuple (4);
3783 dev = fz_new_bbox_device (state.ctx, &rect);
3784 dev->hints |= FZ_IGNORE_SHADE;
3786 ctm = pagectm (page);
3787 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3789 fz_drop_device (state.ctx, dev);
3790 fz_round_rect (&bbox, &rect);
3791 Field (ret_v, 0) = Val_int (bbox.x0);
3792 Field (ret_v, 1) = Val_int (bbox.y0);
3793 Field (ret_v, 2) = Val_int (bbox.x1);
3794 Field (ret_v, 3) = Val_int (bbox.y1);
3796 CAMLreturn (ret_v);
3799 CAMLprim value ml_setaalevel (value level_v)
3801 CAMLparam1 (level_v);
3803 state.aalevel = Int_val (level_v);
3804 CAMLreturn (Val_unit);
3807 #pragma GCC diagnostic push
3808 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3809 #include <X11/Xlib.h>
3810 #include <X11/cursorfont.h>
3811 #pragma GCC diagnostic pop
3813 #include <GL/glx.h>
3815 static const int shapes[] = {
3816 XC_arrow, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3819 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3821 static struct {
3822 Window wid;
3823 Display *dpy;
3824 GLXContext ctx;
3825 XVisualInfo *visual;
3826 Cursor curs[CURS_COUNT];
3827 } glx;
3829 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3831 CAMLparam3 (display_v, wid_v, screen_v);
3832 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3834 glx.dpy = XOpenDisplay (String_val (display_v));
3835 if (!glx.dpy) {
3836 caml_failwith ("XOpenDisplay");
3839 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
3840 if (!glx.visual) {
3841 XCloseDisplay (glx.dpy);
3842 caml_failwith ("glXChooseVisual");
3845 for (size_t n = 0; n < CURS_COUNT; ++n) {
3846 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3849 glx.wid = Int_val (wid_v);
3850 CAMLreturn (Val_int (glx.visual->visualid));
3853 CAMLprim value ml_glxcompleteinit (value unit_v)
3855 CAMLparam1 (unit_v);
3857 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
3858 if (!glx.ctx) {
3859 caml_failwith ("glXCreateContext");
3862 XFree (glx.visual);
3863 glx.visual = NULL;
3865 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
3866 glXDestroyContext (glx.dpy, glx.ctx);
3867 glx.ctx = NULL;
3868 caml_failwith ("glXMakeCurrent");
3870 CAMLreturn (Val_unit);
3873 CAMLprim value ml_setcursor (value cursor_v)
3875 CAMLparam1 (cursor_v);
3876 size_t cursn = Int_val (cursor_v);
3877 XSetWindowAttributes wa;
3879 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
3880 wa.cursor = glx.curs[cursn];
3881 XChangeWindowAttributes (glx.dpy, glx.wid, CWCursor, &wa);
3882 XFlush (glx.dpy);
3883 CAMLreturn (Val_unit);
3886 CAMLprim value ml_swapb (value unit_v)
3888 CAMLparam1 (unit_v);
3889 glXSwapBuffers (glx.dpy, glx.wid);
3890 CAMLreturn (Val_unit);
3893 #include "keysym2ucs.c"
3895 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3897 CAMLparam1 (keysym_v);
3898 CAMLlocal1 (str_v);
3899 KeySym keysym = Int_val (keysym_v);
3900 Rune rune;
3901 int len;
3902 char buf[5];
3904 rune = keysym2ucs (keysym);
3905 len = fz_runetochar (buf, rune);
3906 buf[len] = 0;
3907 str_v = caml_copy_string (buf);
3908 CAMLreturn (str_v);
3911 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
3913 CAMLprim value ml_platform (value unit_v)
3915 CAMLparam1 (unit_v);
3916 CAMLlocal2 (tup_v, arr_v);
3917 int platid = piunknown;
3918 struct utsname buf;
3920 #if defined __linux__
3921 platid = pilinux;
3922 #elif defined __CYGWIN__
3923 platid = picygwin;
3924 #elif defined __DragonFly__ || defined __FreeBSD__
3925 || defined __OpenBSD__ || defined __NetBSD__
3926 platid = pibsd;
3927 #elif defined __sun__
3928 platid = pisun;
3929 #elif defined __APPLE__
3930 platid = piosx;
3931 #endif
3932 if (uname (&buf)) err (1, "uname");
3934 tup_v = caml_alloc_tuple (2);
3936 char const *sar[] = {
3937 buf.sysname,
3938 buf.release,
3939 buf.version,
3940 buf.machine,
3941 NULL
3943 arr_v = caml_copy_string_array (sar);
3945 Field (tup_v, 0) = Val_int (platid);
3946 Field (tup_v, 1) = arr_v;
3947 CAMLreturn (tup_v);
3950 CAMLprim value ml_cloexec (value fd_v)
3952 CAMLparam1 (fd_v);
3953 int fd = Int_val (fd_v);
3955 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3956 uerror ("fcntl", Nothing);
3958 CAMLreturn (Val_unit);
3961 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
3963 CAMLparam2 (w_v, h_v);
3964 CAMLlocal1 (ret_v);
3965 struct pbo *pbo;
3966 int w = Int_val (w_v);
3967 int h = Int_val (h_v);
3968 int cs = Int_val (cs_v);
3970 if (state.pbo_usable) {
3971 pbo = calloc (sizeof (*pbo), 1);
3972 if (!pbo) {
3973 err (1, "calloc pbo");
3976 switch (cs) {
3977 case 0:
3978 case 1:
3979 pbo->size = w*h*4;
3980 break;
3981 case 2:
3982 pbo->size = w*h*2;
3983 break;
3984 default:
3985 errx (1, "ml_getpbo: invalid colorspace %d", cs);
3988 state.glGenBuffersARB (1, &pbo->id);
3989 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3990 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
3991 NULL, GL_STREAM_DRAW);
3992 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3993 GL_READ_WRITE);
3994 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3995 if (!pbo->ptr) {
3996 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
3997 state.glDeleteBuffersARB (1, &pbo->id);
3998 free (pbo);
3999 ret_v = caml_copy_string ("0");
4001 else {
4002 int res;
4003 char *s;
4005 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
4006 if (res < 0) {
4007 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4009 s = malloc (res+1);
4010 if (!s) {
4011 err (1, "malloc %d bytes failed", res+1);
4013 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
4014 if (res < 0) {
4015 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4017 ret_v = caml_copy_string (s);
4018 free (s);
4021 else {
4022 ret_v = caml_copy_string ("0");
4024 CAMLreturn (ret_v);
4027 CAMLprim value ml_freepbo (value s_v)
4029 CAMLparam1 (s_v);
4030 char *s = String_val (s_v);
4031 struct tile *tile = parse_pointer ("ml_freepbo", s);
4033 if (tile->pbo) {
4034 state.glDeleteBuffersARB (1, &tile->pbo->id);
4035 tile->pbo->id = -1;
4036 tile->pbo->ptr = NULL;
4037 tile->pbo->size = -1;
4039 CAMLreturn (Val_unit);
4042 CAMLprim value ml_unmappbo (value s_v)
4044 CAMLparam1 (s_v);
4045 char *s = String_val (s_v);
4046 struct tile *tile = parse_pointer ("ml_unmappbo", s);
4048 if (tile->pbo) {
4049 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4050 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4051 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4053 tile->pbo->ptr = NULL;
4054 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4056 CAMLreturn (Val_unit);
4059 static void setuppbo (void)
4061 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4062 state.pbo_usable = GGPA (glBindBufferARB)
4063 && GGPA (glUnmapBufferARB)
4064 && GGPA (glMapBufferARB)
4065 && GGPA (glBufferDataARB)
4066 && GGPA (glGenBuffersARB)
4067 && GGPA (glDeleteBuffersARB);
4068 #undef GGPA
4071 CAMLprim value ml_pbo_usable (value unit_v)
4073 CAMLparam1 (unit_v);
4074 CAMLreturn (Val_bool (state.pbo_usable));
4077 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4079 CAMLparam3 (ptr_v, x_v, y_v);
4080 CAMLlocal2 (ret_v, tup_v);
4081 struct page *page;
4082 char *s = String_val (ptr_v);
4083 int x = Int_val (x_v), y = Int_val (y_v);
4084 struct pagedim *pdim;
4085 fz_point p;
4086 fz_matrix ctm;
4088 page = parse_pointer ("ml_unproject", s);
4089 pdim = &state.pagedims[page->pdimno];
4091 ret_v = Val_int (0);
4092 if (trylock ("ml_unproject")) {
4093 goto done;
4096 if (pdf_specifics (state.ctx, state.doc)) {
4097 trimctm ((pdf_page *) page->fzpage, page->pdimno);
4098 ctm = state.pagedims[page->pdimno].tctm;
4100 else {
4101 ctm = fz_identity;
4103 p.x = x + pdim->bounds.x0;
4104 p.y = y + pdim->bounds.y0;
4106 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4107 fz_invert_matrix (&ctm, &ctm);
4108 fz_transform_point (&p, &ctm);
4110 tup_v = caml_alloc_tuple (2);
4111 ret_v = caml_alloc_small (1, 1);
4112 Field (tup_v, 0) = Val_int (p.x);
4113 Field (tup_v, 1) = Val_int (p.y);
4114 Field (ret_v, 0) = tup_v;
4116 unlock ("ml_unproject");
4117 done:
4118 CAMLreturn (ret_v);
4121 CAMLprim value ml_addannot (value ptr_v, value x_v, value y_v,
4122 value contents_v)
4124 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4125 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4127 if (pdf) {
4128 pdf_annot *annot;
4129 struct page *page;
4130 fz_point p;
4131 char *s = String_val (ptr_v);
4133 page = parse_pointer ("ml_addannot", s);
4134 annot = pdf_create_annot (state.ctx, pdf,
4135 (pdf_page *) page->fzpage, FZ_ANNOT_TEXT);
4136 p.x = Int_val (x_v);
4137 p.y = Int_val (y_v);
4138 pdf_set_annot_contents (state.ctx, pdf, annot, String_val (contents_v));
4139 pdf_set_text_annot_position (state.ctx, pdf, annot, p);
4140 state.dirty = 1;
4142 CAMLreturn (Val_unit);
4145 CAMLprim value ml_delannot (value ptr_v, value n_v)
4147 CAMLparam2 (ptr_v, n_v);
4148 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4150 if (pdf) {
4151 struct page *page;
4152 char *s = String_val (ptr_v);
4153 struct slink *slink;
4155 page = parse_pointer ("ml_delannot", s);
4156 slink = &page->slinks[Int_val (n_v)];
4157 pdf_delete_annot (state.ctx, pdf,
4158 (pdf_page *) page->fzpage,
4159 (pdf_annot *) slink->u.annot);
4160 state.dirty = 1;
4162 CAMLreturn (Val_unit);
4165 CAMLprim value ml_modannot (value ptr_v, value n_v, value str_v)
4167 CAMLparam3 (ptr_v, n_v, str_v);
4168 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4170 if (pdf) {
4171 struct page *page;
4172 char *s = String_val (ptr_v);
4173 struct slink *slink;
4175 page = parse_pointer ("ml_modannot", s);
4176 slink = &page->slinks[Int_val (n_v)];
4177 pdf_set_annot_contents (state.ctx, pdf, (pdf_annot *) slink->u.annot,
4178 String_val (str_v));
4179 state.dirty = 1;
4181 CAMLreturn (Val_unit);
4184 CAMLprim value ml_hasunsavedchanges (value unit_v)
4186 CAMLparam1 (unit_v);
4187 CAMLreturn (Val_bool (state.dirty));
4190 CAMLprim value ml_savedoc (value path_v)
4192 CAMLparam1 (path_v);
4193 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4195 if (pdf) {
4196 pdf_write_document (state.ctx, pdf, String_val (path_v), NULL);
4198 CAMLreturn (Val_unit);
4201 static void makestippletex (void)
4203 const char pixels[] = "\xff\xff\0\0";
4204 glGenTextures (1, &state.stid);
4205 glBindTexture (GL_TEXTURE_1D, state.stid);
4206 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4207 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4208 glTexImage1D (
4209 GL_TEXTURE_1D,
4211 GL_ALPHA,
4214 GL_ALPHA,
4215 GL_UNSIGNED_BYTE,
4216 pixels
4220 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4222 return caml_copy_string (FZ_VERSION);
4225 #ifdef USE_FONTCONFIG
4226 static struct {
4227 int inited;
4228 FcConfig *config;
4229 } fc;
4231 static fz_font *fc_load_system_font_func (fz_context *ctx,
4232 const char *name,
4233 int bold,
4234 int italic,
4235 int UNUSED_ATTR needs_exact_metrics)
4237 char *buf;
4238 size_t i, size;
4239 fz_font *font;
4240 FcChar8 *path;
4241 FcResult result;
4242 FcPattern *pat, *pat1;
4244 lprintf ("looking up %s bold:%d italic:%d needs_exact_metrics:%d\n",
4245 name, bold, italic, needs_exact_metrics);
4246 if (!fc.inited) {
4247 fc.inited = 1;
4248 fc.config = FcInitLoadConfigAndFonts ();
4249 if (!fc.config) {
4250 lprintf ("FcInitLoadConfigAndFonts failed\n");
4251 return NULL;
4254 if (!fc.config) return NULL;
4256 size = strlen (name);
4257 if (bold) size += sizeof (":bold") - 1;
4258 if (italic) size += sizeof (":italic") - 1;
4259 size += 1;
4261 buf = malloc (size);
4262 if (!buf) {
4263 err (1, "malloc %zu failed", size);
4266 strcpy (buf, name);
4267 if (bold && italic) {
4268 strcat (buf, ":bold:italic");
4270 else {
4271 if (bold) strcat (buf, ":bold");
4272 if (italic) strcat (buf, ":italic");
4274 for (i = 0; i < size; ++i) {
4275 if (buf[i] == ',' || buf[i] == '-') buf[i] = ':';
4278 lprintf ("fcbuf=%s\n", buf);
4279 pat = FcNameParse ((FcChar8 *) buf);
4280 if (!pat) {
4281 printd ("emsg FcNameParse failed\n");
4282 free (buf);
4283 return NULL;
4286 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4287 printd ("emsg FcConfigSubstitute failed\n");
4288 free (buf);
4289 return NULL;
4291 FcDefaultSubstitute (pat);
4293 pat1 = FcFontMatch (fc.config, pat, &result);
4294 if (!pat1) {
4295 printd ("emsg FcFontMatch failed\n");
4296 FcPatternDestroy (pat);
4297 free (buf);
4298 return NULL;
4301 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4302 printd ("emsg FcPatternGetString failed\n");
4303 FcPatternDestroy (pat);
4304 FcPatternDestroy (pat1);
4305 free (buf);
4306 return NULL;
4309 #if 0
4310 printd ("emsg name=%s path=%s\n", name, path);
4311 #endif
4312 font = fz_new_font_from_file (ctx, name, (char *) path, 0, 0);
4313 FcPatternDestroy (pat);
4314 FcPatternDestroy (pat1);
4315 free (buf);
4316 return font;
4318 #endif
4320 CAMLprim value ml_init (value csock_v, value params_v)
4322 CAMLparam2 (csock_v, params_v);
4323 CAMLlocal2 (trim_v, fuzz_v);
4324 int ret;
4325 int texcount;
4326 char *fontpath;
4327 int colorspace;
4328 int mustoresize;
4329 int haspboext;
4331 state.csock = Int_val (csock_v);
4332 state.rotate = Int_val (Field (params_v, 0));
4333 state.fitmodel = Int_val (Field (params_v, 1));
4334 trim_v = Field (params_v, 2);
4335 texcount = Int_val (Field (params_v, 3));
4336 state.sliceheight = Int_val (Field (params_v, 4));
4337 mustoresize = Int_val (Field (params_v, 5));
4338 colorspace = Int_val (Field (params_v, 6));
4339 fontpath = String_val (Field (params_v, 7));
4341 if (caml_string_length (Field (params_v, 8)) > 0) {
4342 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4344 if (!state.trimcachepath) {
4345 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4346 strerror (errno));
4349 haspboext = Bool_val (Field (params_v, 9));
4351 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4352 fz_register_document_handlers (state.ctx);
4354 #ifdef USE_FONTCONFIG
4355 if (Bool_val (Field (params_v, 10))) {
4356 fz_install_load_system_font_funcs (
4357 state.ctx, fc_load_system_font_func, NULL
4360 #endif
4362 state.trimmargins = Bool_val (Field (trim_v, 0));
4363 fuzz_v = Field (trim_v, 1);
4364 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4365 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4366 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4367 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4369 set_tex_params (colorspace);
4371 if (*fontpath) {
4372 #ifndef USE_FONTCONFIG
4373 state.face = load_font (fontpath);
4374 #else
4375 FcChar8 *path;
4376 FcResult result;
4377 char *buf = fontpath;
4378 FcPattern *pat, *pat1;
4380 fc.inited = 1;
4381 fc.config = FcInitLoadConfigAndFonts ();
4382 if (!fc.config) {
4383 errx (1, "FcInitLoadConfigAndFonts failed");
4386 pat = FcNameParse ((FcChar8 *) buf);
4387 if (!pat) {
4388 errx (1, "FcNameParse failed");
4391 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4392 errx (1, "FcConfigSubstitute failed");
4394 FcDefaultSubstitute (pat);
4396 pat1 = FcFontMatch (fc.config, pat, &result);
4397 if (!pat1) {
4398 errx (1, "FcFontMatch failed");
4401 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4402 errx (1, "FcPatternGetString failed");
4405 state.face = load_font ((char *) path);
4406 FcPatternDestroy (pat);
4407 FcPatternDestroy (pat1);
4408 #endif
4410 else {
4411 unsigned int len;
4412 void *base = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
4414 state.face = load_builtin_font (base, len);
4416 if (!state.face) _exit (1);
4418 realloctexts (texcount);
4420 if (haspboext) {
4421 setuppbo ();
4424 makestippletex ();
4426 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4427 if (ret) {
4428 errx (1, "pthread_create: %s", strerror (ret));
4431 CAMLreturn (Val_unit);