fbpdf: bound vertical position to FBCOLS in zoom
[fbpdf.git] / djvulibre.c
blob322dd7404a38a6ad877b9cc8176e3bf0c6536416
1 #include <stdlib.h>
2 #include <string.h>
3 #include <libdjvu/ddjvuapi.h>
4 #include "draw.h"
5 #include "doc.h"
7 #define MIN(a, b) ((a) < (b) ? (a) : (b))
9 struct doc {
10 ddjvu_context_t *ctx;
11 ddjvu_document_t *doc;
14 int djvu_handle(struct doc *doc)
16 ddjvu_message_t *msg;
17 msg = ddjvu_message_wait(doc->ctx);
18 while ((msg = ddjvu_message_peek(doc->ctx))) {
19 if (msg->m_any.tag == DDJVU_ERROR) {
20 fprintf(stderr,"ddjvu: %s\n", msg->m_error.message);
21 return 1;
23 ddjvu_message_pop(doc->ctx);
25 return 0;
28 static void djvu_render(ddjvu_page_t *page, int mode, void *bitmap, int cols,
29 ddjvu_rect_t *prect, ddjvu_rect_t *rrect)
31 ddjvu_format_t *fmt;
32 fmt = ddjvu_format_create(DDJVU_FORMAT_GREY8, 0, 0);
33 ddjvu_format_set_row_order(fmt, 1);
35 ddjvu_page_render(page, mode, prect, rrect, fmt, cols, bitmap);
36 ddjvu_format_release(fmt);
39 #define SIZE (1 << 13)
40 static char img[SIZE * SIZE];
42 int doc_draw(struct doc *doc, fbval_t *bitmap, int p, int rows, int cols,
43 int zoom, int rotate)
45 ddjvu_page_t *page;
46 ddjvu_rect_t rect;
47 ddjvu_pageinfo_t info;
48 int w, h;
49 int i, j;
50 page = ddjvu_page_create_by_pageno(doc->doc, p - 1);
51 if (!page)
52 return -1;
53 if (!ddjvu_page_decoding_done(page))
54 if (djvu_handle(doc))
55 return -1;
57 ddjvu_document_get_pageinfo(doc->doc, p - 1, &info);
58 rect.x = 0;
59 rect.y = 0;
60 rect.w = ddjvu_page_get_width(page);
61 rect.h = ddjvu_page_get_height(page);
63 /* mode: DDJVU_RENDER_(BLACK|COLOR|BACKGROUND|FOREGROUND) */
64 djvu_render(page, DDJVU_RENDER_FOREGROUND, img, SIZE, &rect, &rect);
65 ddjvu_page_release(page);
66 zoom /= 4;
67 w = MIN(cols, rect.w * zoom / 10);
68 h = MIN(cols, rect.h * zoom / 10);
69 for (i = 0; i < h; i++) {
70 int xs = i * cols + (cols - w) / 2;
71 for (j = 0; j < w; j++)
72 bitmap[xs + j] = img[i * 10 / zoom * SIZE + j * 10 / zoom];
74 return 0;
77 int doc_pages(struct doc *doc)
79 return ddjvu_document_get_pagenum(doc->doc);
82 struct doc *doc_open(char *path)
84 struct doc *doc = malloc(sizeof(*doc));
85 doc->ctx = ddjvu_context_create("fbpdf");
86 if (!doc->ctx)
87 goto fail;
88 doc->doc = ddjvu_document_create_by_filename(doc->ctx, path, 1);
89 if (!doc->doc)
90 goto fail;
91 if (!ddjvu_document_decoding_done(doc->doc))
92 if (djvu_handle(doc))
93 goto fail;
94 return doc;
95 fail:
96 doc_close(doc);
97 return NULL;
100 void doc_close(struct doc *doc)
102 if (doc->doc)
103 ddjvu_context_release(doc->ctx);
104 if (doc->ctx)
105 ddjvu_document_release(doc->doc);
106 free(doc);