Make openxref static
[llpp.git] / link.c
blobc2e6f18f826dc30a7bf55da47d1510246758be8a
1 /* lot's of code c&p-ed directly from mupdf */
3 #define _GNU_SOURCE
4 #include <err.h>
5 #include <regex.h>
6 #include <errno.h>
7 #include <ctype.h>
8 #include <stdio.h>
9 #include <stdarg.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <pthread.h>
13 #include <sys/poll.h>
14 #include <sys/time.h>
16 /* fugly as hell and GCC specific but... */
17 #ifdef _BIG_ENDIAN
18 #define GL_GLEXT_PROTOTYPES
19 #endif
21 #include <GL/gl.h>
22 #include <GL/glext.h>
24 #include <caml/fail.h>
25 #include <caml/alloc.h>
26 #include <caml/memory.h>
27 #include <caml/unixsupport.h>
29 #include <fitz.h>
30 #include <mupdf.h>
32 #if 0
33 #define lprintf printf
34 #else
35 #define lprintf(...)
36 #endif
38 #define ARSERT(cond) for (;;) { \
39 if (!(cond)) { \
40 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
41 } \
42 break; \
45 struct slice {
46 int texindex;
47 int w, h;
50 struct page {
51 int pageno;
52 int slicecount;
53 fz_textspan *text;
54 fz_pixmap *pixmap;
55 pdf_page *drawpage;
56 struct pagedim *pagedim;
57 struct page *prev;
58 struct slice slices[];
61 struct pagedim {
62 int pageno;
63 int rotate;
64 fz_rect box;
65 fz_bbox bbox;
66 fz_matrix ctm;
69 struct {
70 int sock;
71 int sliceheight;
72 pthread_t thread;
73 struct page *pages;
74 struct pagedim *pagedims;
75 int pagecount;
76 int pagedimcount;
77 pdf_xref *xref;
78 fz_glyphcache *cache;
79 int w, h;
81 int useatifs;
83 int texindex;
84 int texcount;
85 GLuint *texids;
87 GLenum texform;
88 GLenum texty;
90 int lotsamemory;
92 int *pagetbl;
93 struct {
94 int w, h;
95 struct slice *slice;
96 } *texowners;
97 } state;
99 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
101 static void lock (const char *cap)
103 int ret = pthread_mutex_lock (&mutex);
104 if (ret) {
105 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
109 static void unlock (const char *cap)
111 int ret = pthread_mutex_unlock (&mutex);
112 if (ret) {
113 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
117 static int trylock (const char *cap)
119 int ret = pthread_mutex_trylock (&mutex);
121 if (ret && ret != EBUSY) {
122 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
124 return ret == EBUSY;
127 static void *parse_pointer (const char *cap, const char *s)
129 int ret;
130 void *ptr;
132 ret = sscanf (s, "%p", &ptr);
133 if (ret != 1) {
134 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
136 return ptr;
139 static int hasdata (int sock)
141 int ret;
142 struct pollfd pfd;
144 pfd.fd = sock;
145 pfd.events = POLLIN;
146 ret = poll (&pfd, 1, 0);
147 if (ret == 0) {
148 return 0;
150 if (ret != 1) {
151 err (1, "poll");
153 return pfd.revents & POLLIN;
156 static double now (void)
158 struct timeval tv;
160 if (gettimeofday (&tv, NULL)) {
161 err (1, "gettimeofday");
163 return tv.tv_sec + tv.tv_usec*1e-6;
166 static void readdata (int fd, char *p, int size)
168 ssize_t n;
170 n = read (fd, p, size);
171 if (n - size) {
172 err (1, "read (req %d, ret %zd)", size, n);
176 static void writedata (int fd, char *p, int size)
178 char buf[4];
179 ssize_t n;
181 buf[0] = (size >> 24) & 0xff;
182 buf[1] = (size >> 16) & 0xff;
183 buf[2] = (size >> 8) & 0xff;
184 buf[3] = (size >> 0) & 0xff;
186 n = write (fd, buf, 4);
187 if (n != 4) {
188 err (1, "write %zd", n);
191 n = write (fd, p, size);
192 if (n - size) {
193 err (1, "write (req %d, ret %zd)", size, n);
197 static void __attribute__ ((format (printf, 2, 3)))
198 printd (int fd, const char *fmt, ...)
200 int len;
201 va_list ap;
202 char buf[200];
204 va_start (ap, fmt);
205 len = vsnprintf (buf, sizeof (buf), fmt, ap);
206 va_end (ap);
207 writedata (fd, buf, len);
210 static void die (fz_error error)
212 fz_catch (error, "aborting");
213 if (state.xref)
214 pdf_closexref (state.xref);
215 exit (1);
218 static void openxref (char *filename)
220 int fd;
221 fz_stream *file;
223 fd = open (filename, O_BINARY | O_RDONLY, 0666);
224 if (fd < 0)
225 die (fz_throw ("cannot open file '%s'", filename));
227 file = fz_openfile (fd);
228 state.xref = pdf_openxref (file);
229 if (!state.xref)
230 die (fz_throw ("cannot open PDF file '%s'", filename));
231 fz_dropstream (file);
233 if (pdf_needspassword (state.xref)) {
234 die (fz_throw ("password protected"));
237 state.pagecount = pdf_getpagecount (state.xref);
238 state.pagetbl = stat_alloc (state.pagecount * sizeof (*state.pagetbl));
241 static int readlen (int fd)
243 ssize_t n;
244 char p[4];
246 n = read (fd, p, 4);
247 if (n != 4) {
248 err (1, "read %zd", n);
251 return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
254 static void freepage (struct page *page)
256 int i;
257 struct page *p;
259 fz_droppixmap (page->pixmap);
260 for (p = state.pages; p; p = p->prev) {
261 if (p->prev == page) {
262 p->prev = page->prev;
263 break;
266 for (i = 0; i < page->slicecount; ++i) {
267 struct slice *s = &page->slices[i];
268 if (s->texindex != -1) {
269 if (state.texowners[s->texindex].slice == s) {
270 state.texowners[s->texindex].slice = NULL;
271 ARSERT (state.texowners[s->texindex].w == s->w);
272 ARSERT (state.texowners[s->texindex].h >= s->h);
276 if (page->text) {
277 fz_freetextspan (page->text);
279 if (page->drawpage) {
280 pdf_droppage (page->drawpage);
283 free (page);
286 static void subdivide (struct page *p)
288 int i;
289 int h = p->pixmap->h;
290 int th = MIN (h, state.sliceheight);
292 for (i = 0; i < p->slicecount; ++i) {
293 struct slice *s = &p->slices[i];
294 s->texindex = -1;
295 s->h = MIN (th, h);
296 s->w = p->pixmap->w;
297 h -= th;
301 static void *render (int pageno, int pindex)
303 fz_error error;
304 int slicecount;
305 fz_obj *pageobj;
306 struct page *page;
307 double start, end;
308 pdf_page *drawpage;
309 fz_displaylist *list;
310 fz_device *idev, *mdev;
311 struct pagedim *pagedim;
313 start = now ();
314 /* printd (state.sock, "T \"rendering %d\"", pageno); */
315 pdf_flushxref (state.xref, 0);
317 pagedim = &state.pagedims[pindex];
318 slicecount = (pagedim->bbox.y1 - pagedim->bbox.y0
319 + state.sliceheight - 1) / state.sliceheight;
320 slicecount += slicecount == 0;
322 page = calloc (sizeof (*page)
323 + (slicecount * sizeof (struct slice)), 1);
324 if (!page) {
325 err (1, "calloc page %d\n", pageno);
327 page->slicecount = slicecount;
328 page->prev = state.pages;
329 state.pages = page;
331 pageobj = pdf_getpageobject (state.xref, pageno);
332 if (!pageobj)
333 die (fz_throw ("cannot retrieve info from page %d", pageno));
335 error = pdf_loadpage (&drawpage, state.xref, pageobj);
336 if (error)
337 die (error);
339 page->pixmap = fz_newpixmapwithrect (pdf_devicergb, pagedim->bbox);
340 if (error)
341 die (error);
342 fz_clearpixmap (page->pixmap, 0xFF);
344 list = fz_newdisplaylist ();
345 if (!list)
346 die (fz_throw ("fz_newdisplaylist failed"));
348 mdev = fz_newlistdevice (list);
349 error = pdf_runcontentstream (mdev, fz_identity (), state.xref,
350 drawpage->resources,
351 drawpage->contents);
352 if (error)
353 die (error);
354 fz_freedevice (mdev);
356 idev = fz_newdrawdevice (state.cache, page->pixmap);
357 if (!idev)
358 die (fz_throw ("fz_newdrawdevice failed"));
359 fz_executedisplaylist (list, idev, pagedim->ctm);
360 fz_freedevice (idev);
362 fz_freedisplaylist (list);
364 page->drawpage = drawpage;
365 page->pagedim = pagedim;
366 page->pageno = pageno;
367 subdivide (page);
368 end = now ();
370 if (!state.lotsamemory) {
371 pdf_agestoreditems (state.xref->store);
372 pdf_evictageditems (state.xref->store);
375 /* printd (state.sock, "T \"rendering %d took %f sec\"", pageno, end - start); */
376 return page;
379 /* almost verbatim copy of pdf_getpagecountimp */
380 static void
381 recurse_page (pdf_xref *xref, fz_obj *node, int *pagesp)
383 fz_obj *type;
384 fz_obj *kids;
385 fz_obj *count;
386 char *typestr;
387 int pages = 0;
388 int i;
390 if (!fz_isdict(node))
392 fz_warn("pagetree node is missing, igoring missing pages...");
393 return;
396 type = fz_dictgets(node, "Type");
397 kids = fz_dictgets(node, "Kids");
398 count = fz_dictgets(node, "Count");
400 if (fz_isname(type))
401 typestr = fz_toname(type);
402 else
404 fz_warn("pagetree node (%d %d R) lacks required type", fz_tonum(node), fz_togen(node));
406 kids = fz_dictgets(node, "Kids");
407 if (kids)
409 fz_warn("guessing it may be a pagetree node, continuing...");
410 typestr = "Pages";
412 else
414 fz_warn("guessing it may be a page, continuing...");
415 typestr = "Page";
419 if (!strcmp(typestr, "Page")) {
420 int rotate;
421 fz_obj *obj;
422 fz_rect box;
423 struct pagedim *p;
424 int pageno = *pagesp;
426 state.pagetbl[pageno] = fz_tonum (node);
427 obj = fz_dictgets (node, "CropBox");
428 if (!fz_isarray (obj)) {
429 obj = fz_dictgets (node, "MediaBox");
430 if (!fz_isarray (obj)) {
431 die (fz_throw ("cannot find page bounds %d (%d R)",
432 fz_tonum (node), fz_togen (node)));
435 box = pdf_torect (obj);
437 obj = fz_dictgets (node, "Rotate");
438 if (fz_isint (obj)) {
439 rotate = fz_toint (obj);
441 else {
442 rotate = 0;
445 p = &state.pagedims[state.pagedimcount - 1];
446 if ((state.pagedimcount == 0)
447 || (p->rotate != rotate || memcmp (&p->box, &box, sizeof (box)))) {
448 size_t size;
450 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
451 state.pagedims = realloc (state.pagedims, size);
452 if (!state.pagedims) {
453 err (1, "realloc pagedims to %zu (%d elems)",
454 size, state.pagedimcount + 1);
456 p = &state.pagedims[state.pagedimcount++];
457 p->rotate = rotate;
458 p->box = box;
459 p->pageno = *pagesp;
461 (*pagesp)++;
463 else if (!strcmp(typestr, "Pages"))
465 if (!fz_isarray(kids))
466 fz_warn("page tree node contains no pages");
468 pdf_logpage("subtree (%d %d R) {\n", fz_tonum(node), fz_togen(node));
470 for (i = 0; i < fz_arraylen(kids); i++)
472 fz_obj *obj = fz_arrayget(kids, i);
474 /* prevent infinite recursion possible in maliciously crafted PDFs */
475 if (obj == node)
477 fz_warn("cyclic page tree");
478 return;
481 recurse_page (xref, obj, &pages);
484 if (pages != fz_toint(count))
486 fz_warn("page tree node contains incorrect number of pages, continuing...");
487 count = fz_newint(pages);
488 fz_dictputs(node, "Count", count);
489 fz_dropobj(count);
492 pdf_logpage("%d pages\n", pages);
494 (*pagesp) += pages;
496 pdf_logpage("}\n");
500 static void initpdims (void)
502 fz_obj *catalog;
503 fz_obj *pages;
504 int count;
505 double start, end;
507 start = now ();
508 catalog = fz_dictgets (state.xref->trailer, "Root");
509 pages = fz_dictgets (catalog, "Pages");
511 count = 0;
512 recurse_page (state.xref, pages, &count);
513 end = now ();
514 printd (state.sock, "T \"Processed %d pages in %f seconds\"",
515 count, end - start);
518 static void layout (void)
520 int pindex;
521 fz_matrix ctm;
522 fz_rect box, box2;
523 double zoom, w;
524 struct pagedim *p = state.pagedims;
526 pindex = 0;
527 printd (state.sock, "c");
528 for (pindex = 0; pindex < state.pagedimcount; ++pindex, ++p) {
529 box.x0 = MIN (p->box.x0, p->box.x1);
530 box.y0 = MIN (p->box.y0, p->box.y1);
531 box.x1 = MAX (p->box.x0, p->box.x1);
532 box.y1 = MAX (p->box.y0, p->box.y1);
534 ctm = fz_identity ();
535 ctm = fz_concat (ctm, fz_translate (0, -box.y1));
536 ctm = fz_concat (ctm, fz_rotate (p->rotate));
537 box2 = fz_transformrect (ctm, box);
538 w = box2.x1 - box2.x0;
540 zoom = (state.w / w);
541 ctm = fz_identity ();
542 ctm = fz_concat (ctm, fz_translate (0, -box.y1));
543 ctm = fz_concat (ctm, fz_scale (zoom, -zoom));
544 ctm = fz_concat (ctm, fz_rotate (p->rotate));
545 p->bbox = fz_roundrect (fz_transformrect (ctm, box));
546 memcpy (&p->ctm, &ctm, sizeof (ctm));
549 while (p-- != state.pagedims) {
550 printd (state.sock, "l %d %d %d",
551 p->pageno, p->bbox.x1 - p->bbox.x0, p->bbox.y1 - p->bbox.y0);
554 printd (state.sock, "C %d", state.pagecount);
557 static void recurse_outline (pdf_outline *outline, int level)
559 while (outline) {
560 fz_obj *obj;
561 int top = 0;
562 int pageno = -1;
564 if (!outline->link) goto next;
566 obj = outline->link->dest;
567 if (fz_isarray (obj)) {
568 int i;
569 int num;
570 fz_obj *obj2;
571 struct pagedim *pagedim = state.pagedims;
573 obj2 = fz_arrayget (obj, 0);
574 if (fz_isint (obj2)) {
575 pageno = fz_toint (obj2);
577 else {
578 num = fz_tonum (obj2);
579 for (i = 0; i < state.pagecount; ++i) {
580 if (state.pagetbl[i] == num) {
581 pageno = i;
582 break;
587 for (i = 0; i < state.pagedimcount; ++i) {
588 if (state.pagedims[i].pageno > pageno)
589 break;
590 pagedim = &state.pagedims[i];
593 if (fz_arraylen (obj) > 3) {
594 fz_point p;
596 p.x = fz_toint (fz_arrayget (obj, 2));
597 p.y = fz_toint (fz_arrayget (obj, 3));
598 p = fz_transformpoint (pagedim->ctm, p);
599 top = p.y;
603 lprintf ("%*c%s %d\n", level, ' ', outline->title, pageno);
604 printd (state.sock, "o %d %d %d %s",
605 level, pageno, top, outline->title);
606 next:
607 if (outline->child) {
608 recurse_outline (outline->child, level + 1);
610 outline = outline->next;
614 static void process_outline (void)
616 pdf_outline *outline;
618 outline = pdf_loadoutline (state.xref);
619 if (outline) {
620 recurse_outline (outline, 0);
621 pdf_dropoutline (outline);
625 /* wishful thinking function */
626 static void search (regex_t *re, int pageno, int y, int forward)
628 int i;
629 int ret;
630 char *p;
631 char buf[256];
632 fz_error error;
633 fz_obj *pageobj;
634 fz_device *tdev;
635 pdf_page *drawpage;
636 fz_textspan *text, *span;
637 struct pagedim *pdim, *pdimprev;
638 int stop = 0;
639 int niters = 0;
640 double start, end;
642 start = now ();
643 while (pageno >= 0 && pageno < state.pagecount && !stop) {
644 if (niters++ == 5) {
645 niters = 0;
646 if (hasdata (state.sock)) {
647 printd (state.sock, "T \"attention requested aborting search at %d\"",
648 pageno);
649 stop = 1;
651 else {
652 printd (state.sock, "T \"searching in page %d\"", pageno);
655 pdimprev = NULL;
656 for (i = 0; i < state.pagedimcount; ++i) {
657 pdim = &state.pagedims[i];
658 if (pdim->pageno == pageno) {
659 goto found;
661 if (pdim->pageno > pageno) {
662 pdim = pdimprev;
663 goto found;
665 pdimprev = pdim;
667 pdim = pdimprev;
668 found:
670 pageobj = pdf_getpageobject (state.xref, pageno + 1);
671 if (!pageobj)
672 die (fz_throw ("cannot retrieve info from page %d", pageno));
674 error = pdf_loadpage (&drawpage, state.xref, pageobj);
675 if (error)
676 die (error);
678 text = fz_newtextspan ();
679 tdev = fz_newtextdevice (text);
680 error = pdf_runcontentstream (tdev, pdim->ctm, state.xref,
681 drawpage->resources,
682 drawpage->contents);
683 if (error) die (error);
684 fz_freedevice (tdev);
686 for (span = text; span; span = span->next) {
687 regmatch_t rm;
689 p = buf;
690 /* XXX: spans are not sorted "visually" */
691 for (i = 0; i < MIN (span->len, sizeof (buf) - 1); ++i) {
692 if (forward) {
693 if (span->text[i].bbox.y0 < y + 1) {
694 continue;
697 else {
698 if (span->text[i].bbox.y0 > y - 1) {
699 continue;
702 if (span->text[i].c < 256) {
703 *p++ = span->text[i].c;
705 else {
706 *p++ = '?';
709 if (p == buf) {
710 continue;
712 *p++ = 0;
714 ret = regexec (re, buf, 1, &rm, 0);
715 if (ret) {
716 if (ret != REG_NOMATCH) {
717 size_t size;
718 char errbuf[80];
719 size = regerror (ret, re, errbuf, sizeof (errbuf));
720 printd (state.sock,
721 "T \"regexec error `%.*s'\"",
722 (int) size, errbuf);
725 else {
726 fz_rect r;
728 r.x0 = span->text[rm.rm_so].bbox.x0 - pdim->bbox.x0;
729 r.y0 = span->text[rm.rm_so].bbox.y0;
730 r.x1 = span->text[rm.rm_eo - 1].bbox.x1 - pdim->bbox.x0;
731 r.y1 = span->text[rm.rm_eo - 1].bbox.y1;
733 if (!stop) {
734 printd (state.sock, "F %d %d %f %f %f %f",
735 pageno, 1,
736 r.x0, r.y0,
737 r.x1, r.y1);
739 else {
740 printd (state.sock, "R %d %d %f %f %f %f",
741 pageno, 2,
742 r.x0, r.y0,
743 r.x1, r.y1);
745 printd (state.sock, "T \"found at %d `%.*s' %f in %f sec\"",
746 pageno, rm.rm_eo - rm.rm_so, &buf[rm.rm_so],
747 span->text[0].bbox.y0 - drawpage->mediabox.y0,
748 now () - start);
749 stop = 1;
752 if (forward) {
753 pageno += 1;
754 y = 0;
756 else {
757 pageno -= 1;
758 y = INT_MAX;
760 fz_freetextspan (text);
761 pdf_droppage (drawpage);
763 end = now ();
764 if (!stop) {
765 printd (state.sock, "T \"no matches %f sec\"", end - start);
767 printd (state.sock, "d");
770 static void *mainloop (void *unused)
772 char *p = NULL;
773 int len, ret, oldlen = 0;
775 for (;;) {
776 len = readlen (state.sock);
777 if (len == 0) {
778 errx (1, "readlen returned 0");
781 if (oldlen < len + 1) {
782 p = realloc (p, len + 1);
783 if (!p) {
784 err (1, "realloc %d failed", len + 1);
786 oldlen = len + 1;
788 readdata (state.sock, p, len);
789 p[len] = 0;
791 if (!strncmp ("open", p, 4)) {
792 char *filename = p + 5;
794 openxref (filename);
795 initpdims ();
797 else if (!strncmp ("free", p, 4)) {
798 void *ptr;
800 ret = sscanf (p + 4, " %p", &ptr);
801 if (ret != 1) {
802 errx (1, "malformed free `%.*s' ret=%d", len, p, ret);
804 lock ("free");
805 freepage (ptr);
806 unlock ("free");
807 printd (state.sock, "d");
809 else if (!strncmp ("search", p, 6)) {
810 int icase, pageno, y, ret, len2, forward;
811 char *pattern;
812 regex_t re;
814 ret = sscanf (p + 6, " %d %d %d %d %n",
815 &icase, &pageno, &y, &forward, &len2);
816 if (ret != 4) {
817 errx (1, "malformed search `%s' ret=%d", p, ret);
820 pattern = p + 6 + len2;
821 ret = regcomp (&re, pattern,
822 REG_EXTENDED | (icase ? REG_ICASE : 0));
823 if (ret) {
824 char errbuf[80];
825 size_t size;
827 size = regerror (ret, &re, errbuf, sizeof (errbuf));
828 printd (state.sock, "T \"regcomp failed `%.*s'\"", (int) size, errbuf);
830 else {
831 search (&re, pageno, y, forward);
832 regfree (&re);
835 else if (!strncmp ("geometry", p, 8)) {
836 int w, h;
838 ret = sscanf (p + 8, " %d %d", &w, &h);
839 if (ret != 2) {
840 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
842 state.h = h;
843 if (w != state.w) {
844 int i;
845 state.w = w;
846 for (i = 0; i < state.texcount; ++i) {
847 state.texowners[i].slice = NULL;
850 lock ("geometry");
851 layout ();
852 process_outline ();
853 unlock ("geometry");
854 printd (state.sock, "d");
856 else if (!strncmp ("render", p, 6)) {
857 int pageno, pindex, w, h, ret;
858 struct page *page;
860 ret = sscanf (p + 6, " %d %d %d %d", &pageno, &pindex, &w, &h);
861 if (ret != 4) {
862 errx (1, "bad render line `%.*s' ret=%d", len, p, ret);
865 page = render (pageno, pindex);
866 printd (state.sock, "r %d %d %d %p\n",
867 pageno,
868 state.w,
869 state.h,
870 page);
872 else {
873 errx (1, "unknown command %.*s", len, p);
876 return NULL;
879 static void upload2 (struct page *page, int slicenum, const char *cap)
881 int i;
882 int w, h;
883 double start, end;
884 struct slice *slice = &page->slices[slicenum];
886 w = page->pixmap->w;
887 h = page->pixmap->h;
889 ARSERT (w == slice->w);
890 if (slice->texindex != -1
891 && state.texowners[slice->texindex].slice == slice) {
892 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[slice->texindex]);
894 else {
895 int subimage = 0;
896 int index = (state.texindex++ % state.texcount);
897 size_t offset = 0;
899 for (i = 0; i < slicenum; ++i) {
900 offset += w * page->slices[i].h * 4;
903 if (state.texowners[index].w == slice->w) {
904 if (state.texowners[index].h >= slice->h ) {
905 subimage = 1;
907 else {
908 state.texowners[index].h = slice->h;
911 else {
912 state.texowners[index].h = slice->h;
915 state.texowners[index].slice = slice;
916 state.texowners[index].w = slice->w;
917 slice->texindex = index;
919 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[slice->texindex]);
920 start = now ();
921 if (subimage) {
923 GLenum err = glGetError ();
924 if (err != GL_NO_ERROR) {
925 printf ("\e[0;31mERROR1 %d %d %#x\e[0m\n", w, slice->h, err);
926 abort ();
929 glTexSubImage2D (GL_TEXTURE_RECTANGLE_ARB,
934 slice->h,
935 state.texform,
936 state.texty,
937 page->pixmap->samples + offset
940 GLenum err = glGetError ();
941 if (err != GL_NO_ERROR) {
942 printf ("\e[0;31mERROR %d %d %#x\e[0m\n", w, slice->h, err);
943 abort ();
947 else {
948 glTexImage2D (GL_TEXTURE_RECTANGLE_ARB,
950 GL_RGBA8,
952 slice->h,
954 state.texform,
955 state.texty,
956 page->pixmap->samples + offset
960 end = now ();
961 lprintf ("%s[%d] slice=%d(%d,%d) texid=%d %f sec\n",
962 subimage ? "sub" : "img",
963 page->pageno, slicenum,
964 slice->w, slice->h,
965 state.texids[slice->texindex],
966 end - start);
970 CAMLprim value ml_preload (value ptr_v)
972 int i;
973 int ret;
974 void *ptr;
975 CAMLparam1 (ptr_v);
976 char *s = String_val (ptr_v);
977 struct page *page;
979 if (trylock ("ml_preload")) {
980 goto done;
982 ret = sscanf (s, "%p", &ptr);
983 if (ret != 1) {
984 errx (1, "cannot parse pointer `%s'", s);
987 page = ptr;
988 for (i = 0; i < page->slicecount; ++i) {
989 upload2 (ptr, i, "preload");
992 unlock ("ml_preload");
993 done:
994 CAMLreturn (Val_unit);
997 CAMLprim value ml_draw (value dispy_v, value w_v, value h_v,
998 value py_v, value ptr_v)
1000 CAMLparam5 (dispy_v, w_v, h_v, py_v, ptr_v);
1001 int dispy = Int_val (dispy_v);
1002 int w = Int_val (w_v);
1003 int h = Int_val (h_v);
1004 int py = Int_val (py_v);
1005 char *s = String_val (ptr_v);
1006 int ret;
1007 void *ptr;
1008 struct page *page;
1009 int slicenum = 0;
1011 if (trylock ("ml_draw")) {
1012 goto done;
1015 ret = sscanf (s, "%p", &ptr);
1016 if (ret != 1) {
1017 errx (1, "cannot parse pointer `%s'", s);
1019 page = ptr;
1021 w = page->pixmap->w;
1023 ARSERT (h >= 0 && "ml_draw wrong h");
1025 glEnable (GL_TEXTURE_RECTANGLE_ARB);
1026 if (state.useatifs) {
1027 glEnable (GL_FRAGMENT_SHADER_ATI);
1030 for (slicenum = 0; slicenum < page->slicecount; ++slicenum) {
1031 struct slice *slice = &page->slices[slicenum];
1032 if (slice->h > py) {
1033 break;
1035 py -= slice->h;
1038 h = MIN (state.h, h);
1039 while (h) {
1040 int th;
1041 struct slice *slice = &page->slices[slicenum];
1043 ARSERT (slicenum < page->slicecount && "ml_draw wrong slicenum");
1045 th = MIN (h, slice->h - py);
1046 upload2 (page, slicenum, "upload");
1048 glBegin (GL_QUADS);
1050 glTexCoord2i (0, py);
1051 glVertex2i (0, dispy);
1053 glTexCoord2i (w, py);
1054 glVertex2i (w, dispy);
1056 glTexCoord2i (w, py+th);
1057 glVertex2i (w, dispy + th);
1059 glTexCoord2i (0, py+th);
1060 glVertex2i (0, dispy + th);
1062 glEnd ();
1064 h -= th;
1065 py = 0;
1066 dispy += th;
1067 slicenum += 1;
1070 glDisable (GL_TEXTURE_RECTANGLE_ARB);
1071 if (state.useatifs) {
1072 glDisable (GL_FRAGMENT_SHADER_ATI);
1075 unlock ("ml_draw");
1076 done:
1077 CAMLreturn (Val_unit);
1080 static pdf_link *getlink (struct page *page, int x, int y)
1082 fz_point p;
1083 fz_matrix ctm;
1084 pdf_link *link;
1086 p.x = x;
1087 p.y = y;
1089 ctm = fz_invertmatrix (page->pagedim->ctm);
1090 p = fz_transformpoint (ctm, p);
1092 for (link = page->drawpage->links; link; link = link->next) {
1093 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
1094 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
1095 if (link->kind == PDF_LGOTO) {
1096 return link;
1101 return NULL;
1104 CAMLprim value ml_checklink (value ptr_v, value x_v, value y_v)
1106 CAMLparam3 (ptr_v, x_v, y_v);
1107 char *s = String_val (ptr_v);
1108 int ret;
1110 if (trylock ("ml_checklink")) {
1111 ret = 0;
1113 else {
1114 ret = NULL != getlink (parse_pointer ("ml_checklink", s),
1115 Int_val (x_v), Int_val (y_v));
1116 unlock ("ml_checklink");
1118 CAMLreturn (Val_bool (ret));
1121 CAMLprim value ml_getlink (value ptr_v, value x_v, value y_v)
1123 CAMLparam3 (ptr_v, x_v, y_v);
1124 CAMLlocal2 (ret_v, tup_v);
1125 pdf_link *link;
1126 struct page *page;
1127 char *s = String_val (ptr_v);
1129 if (trylock ("ml_gettext")) {
1130 ret_v = Val_int (0);
1131 goto done;
1134 page = parse_pointer ("ml_getlink", s);
1136 link = getlink (page, Int_val (x_v), Int_val (y_v));
1137 if (link) {
1138 int pageno;
1139 fz_point p;
1140 fz_obj *obj;
1142 pageno = -1;
1143 obj = fz_arrayget (link->dest, 0);
1144 if (fz_isindirect (obj)) {
1145 pageno = pdf_findpageobject (state.xref, obj) - 1;
1147 else if (fz_isint (obj)) {
1148 pageno = fz_toint (obj);
1151 if (fz_arraylen (link->dest) > 3) {
1152 p.x = fz_toint (fz_arrayget (link->dest, 2));
1153 p.y = fz_toint (fz_arrayget (link->dest, 3));
1154 p = fz_transformpoint (page->pagedim->ctm, p);
1156 else {
1157 p.x = 0.0;
1158 p.y = 0.0;
1161 tup_v = caml_alloc_tuple (2);
1162 ret_v = caml_alloc_small (1, 1);
1163 Field (tup_v, 0) = Val_int (pageno);
1164 Field (tup_v, 1) = Val_int (p.y);
1165 Field (ret_v, 0) = tup_v;
1167 else {
1168 ret_v = Val_int (0);
1170 unlock ("ml_getlink");
1172 done:
1173 CAMLreturn (ret_v);
1176 CAMLprim value ml_gettext (value ptr_v, value rect_v, value oy_v, value rectsel_v)
1178 CAMLparam4 (ptr_v, rect_v, oy_v, rect_v);
1179 fz_matrix ctm;
1180 fz_point p1, p2;
1181 struct page *page;
1182 fz_textspan *span;
1183 char *s = String_val (ptr_v);
1184 int rectsel = Bool_val (rectsel_v);
1185 int i, bx0, bx1, by0, by1, x0, x1, y0, y1, oy;
1187 /* stop GCC from complaining about uninitialized variables */
1188 int rx0 = rx0, rx1 = rx1, ry0 = ry0, ry1 = ry1;
1190 if (trylock ("ml_gettext")) {
1191 goto done;
1194 page = parse_pointer ("ml_gettext", s);
1196 oy = Int_val (oy_v);
1197 p1.x = Int_val (Field (rect_v, 0));
1198 p1.y = Int_val (Field (rect_v, 1));
1199 p2.x = Int_val (Field (rect_v, 2));
1200 p2.y = Int_val (Field (rect_v, 3));
1202 if (0) {
1203 glEnable (GL_BLEND);
1204 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
1205 glBlendFunc (GL_DST_ALPHA, GL_SRC_ALPHA);
1206 glColor4f (0, 0, 0, 0.2);
1207 glRecti (p1.x, p1.y, p2.x, p2.y);
1208 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
1209 glDisable (GL_BLEND);
1212 ctm = page->pagedim->ctm;
1213 if (!page->text) {
1214 fz_error error;
1215 fz_device *tdev;
1217 page->text = fz_newtextspan ();
1218 tdev = fz_newtextdevice (page->text);
1219 error = pdf_runcontentstream (tdev, page->pagedim->ctm, state.xref,
1220 page->drawpage->resources,
1221 page->drawpage->contents);
1222 if (error) die (error);
1223 fz_freedevice (tdev);
1226 printf ("\ec");
1228 printf ("BBox %f %f %f %f\n", p1.x, p1.y, p2.x, p2.y);
1229 p1.x += page->pixmap->x;
1230 p1.y += page->pixmap->y;
1231 p2.x += page->pixmap->x;
1232 p2.y += page->pixmap->y;
1233 x0 = p1.x;
1234 y0 = p1.y;
1235 x1 = p2.x;
1236 y1 = p2.y;
1237 printf ("BBox %d %d %d %d %d %d\n", x0, y0, x1, y1, oy, page->pageno);
1239 for (span = page->text; span; span = span->next) {
1240 int seen = 0;
1242 /* fz_debugtextspanxml (span); */
1243 for (i = 0; i < span->len; ++i) {
1244 long c;
1246 bx0 = span->text[i].bbox.x0;
1247 bx1 = span->text[i].bbox.x1;
1248 by0 = span->text[i].bbox.y0 + oy;
1249 by1 = span->text[i].bbox.y1 + oy;
1251 if ((bx1 >= x0 && bx0 <= x1 && by1 >= y0 && by0 <= y1)) {
1252 if (!seen) {
1253 rx0 = bx0 - page->pixmap->x;
1254 rx1 = bx1 - page->pixmap->x;
1255 ry0 = by0;
1256 ry1 = by1;
1259 seen = 1;
1260 c = span->text[i].c;
1261 if (c < 256) {
1262 if ((isprint (c) && !isspace (c))) {
1263 if (!rectsel) {
1264 bx0 -= page->pixmap->x;
1265 bx1 -= page->pixmap->x;
1266 glEnable (GL_BLEND);
1267 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
1268 glBlendFunc (GL_DST_ALPHA, GL_SRC_ALPHA);
1269 glColor4f (0.5, 0.5, 0.0, 0.6);
1270 glRecti (bx0, by0, bx1, by1);
1271 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
1272 glDisable (GL_BLEND);
1274 if (isprint (c) || c ==' ') {
1275 rx1 = bx1;
1276 ry1 = by1;
1279 putc (c, stdout);
1281 else {
1282 putc ('?', stdout);
1287 if (rectsel) {
1288 if (seen) {
1289 glEnable (GL_BLEND);
1290 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
1291 glBlendFunc (GL_DST_ALPHA, GL_SRC_ALPHA);
1292 glColor4f (0.5, 0.5, 0.0, 0.6);
1293 glRecti (rx0, ry0, rx1, ry1);
1294 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
1295 glDisable (GL_BLEND);
1299 if (seen && span->eol) {
1300 x0 = page->pixmap->x;
1301 putc ('\n', stdout);
1304 unlock ("ml_gettext");
1306 done:
1307 CAMLreturn (Val_unit);
1310 static void initgl (void)
1312 #ifdef _BIG_ENDIAN
1313 if (strstr ((char *) glGetString (GL_EXTENSIONS),
1314 "GL_ATI_fragment_shader")) {
1315 /* Here, with MESA, rv280, powerpc32: BGRA(rev) is slow while
1316 ABGR is fast, so fix things in the shader */
1317 state.texform = GL_ABGR_EXT;
1318 state.texty = GL_UNSIGNED_INT_8_8_8_8;
1320 glBindFragmentShaderATI (1);
1321 glBeginFragmentShaderATI ();
1323 glSampleMapATI (GL_REG_0_ATI, GL_TEXTURE0_ARB, GL_SWIZZLE_STR_ATI);
1325 glColorFragmentOp1ATI (GL_MOV_ATI,
1326 GL_REG_1_ATI, GL_RED_BIT_ATI, GL_NONE,
1327 GL_REG_0_ATI, GL_BLUE, GL_NONE);
1328 glColorFragmentOp1ATI (GL_MOV_ATI,
1329 GL_REG_1_ATI, GL_BLUE_BIT_ATI, GL_NONE,
1330 GL_REG_0_ATI, GL_RED, GL_NONE);
1331 glColorFragmentOp1ATI (
1332 GL_MOV_ATI,
1333 GL_REG_0_ATI, GL_RED_BIT_ATI | GL_BLUE_BIT_ATI, GL_NONE,
1334 GL_REG_1_ATI, GL_NONE, GL_NONE
1337 glEndFragmentShaderATI ();
1338 state.useatifs = 1;
1340 else {
1341 state.texform = GL_BGRA_EXT;
1342 state.texty = GL_UNSIGNED_INT_8_8_8_8_REV;
1344 #else
1345 state.texform = GL_BGRA_EXT;
1346 state.texty = GL_UNSIGNED_INT_8_8_8_8;
1347 #endif
1350 CAMLprim value ml_init (value sock_v)
1352 int ret;
1353 CAMLparam1 (sock_v);
1355 state.texcount = 128;
1356 state.sliceheight = 64;
1358 state.texids = calloc (state.texcount * sizeof (*state.texids), 1);
1359 if (!state.texids) {
1360 err (1, "calloc texids %zu", state.texcount * sizeof (*state.texids));
1363 state.texowners = calloc (state.texcount * sizeof (*state.texowners), 1);
1364 if (!state.texowners) {
1365 err (1, "calloc texowners %zu",
1366 state.texcount * sizeof (*state.texowners));
1369 glGenTextures (state.texcount, state.texids);
1371 state.sock = Int_val (sock_v);
1372 initgl ();
1374 state.cache = fz_newglyphcache ();
1375 if (!state.cache) {
1376 errx (1, "fz_newglyphcache failed");
1379 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
1380 if (ret) {
1381 errx (1, "pthread_create: %s", strerror (errno));
1384 CAMLreturn (Val_unit);