Ely Office: six offline-first desktop apps in Rust and GPUI

ElyDoc, ElyTable, ElyShow (LibreOfficeKit), ElyPDF (MuPDF), ElyTree (Git),
ElyMark (Milkdown and CodeMirror in CEF). ElyMail and ElyAgent follow.
This commit is contained in:
ZacharyZhang-NY committed 2026-10-08 21:20:08 -04:00
commit b7fca0146d
817 files changed
+143101

No files matched your search

+86
View File
@@ -0,0 +1,86 @@
/* Alternate text dropped from redacted pages (PDF-09). */
#include "ely_shim.h"
typedef void (bdc_fn)(fz_context *ctx, pdf_processor *proc, const char *tag, pdf_obj *raw, pdf_obj *cooked);
static void drop_said(fz_context *ctx, pdf_obj *dict)
{
if (!pdf_is_dict(ctx, dict))
return;
pdf_dict_del(ctx, dict, PDF_NAME(ActualText));
pdf_dict_del(ctx, dict, PDF_NAME(Alt));
pdf_dict_del(ctx, dict, PDF_NAME(E));
}
static void quiet_bdc(fz_context *ctx, pdf_processor *proc, const char *tag, pdf_obj *raw, pdf_obj *cooked)
{
bdc_fn **out = fz_user_context(ctx);
drop_said(ctx, raw);
drop_said(ctx, cooked);
(*out)(ctx, proc, tag, raw, cooked);
}
/* Each output stream writes marked content through `quiet_bdc`. */
static pdf_processor *quiet_factory(fz_context *ctx, pdf_document *doc, pdf_processor *chain, int struct_parents,
fz_matrix transform, pdf_filter_options *options, void *sopts)
{
bdc_fn **out = fz_user_context(ctx);
if (chain->op_BDC != quiet_bdc)
{
*out = chain->op_BDC;
chain->op_BDC = quiet_bdc;
}
return pdf_new_sanitize_filter(ctx, doc, chain, struct_parents, transform, options, sopts);
}
/* Strips elements on `page`, by own, inherited or kids' `Pg`. */
static int quiet_elem(fz_context *ctx, pdf_obj *elem, int page, int inherited)
{
pdf_obj *kids;
int pg, i, on = 0;
if (!pdf_is_dict(ctx, elem) || pdf_mark_obj(ctx, elem))
return 0;
fz_try(ctx)
{
pg = pdf_dict_gets(ctx, elem, "Pg") ? pdf_to_num(ctx, pdf_dict_gets(ctx, elem, "Pg")) : inherited;
on = pg == page;
kids = pdf_dict_get(ctx, elem, PDF_NAME(K));
if (pdf_is_array(ctx, kids))
for (i = 0; i < pdf_array_len(ctx, kids); i++)
on |= quiet_elem(ctx, pdf_array_get(ctx, kids, i), page, pg);
else
on |= quiet_elem(ctx, kids, page, pg);
if (on)
{
drop_said(ctx, elem);
pdf_dict_del(ctx, elem, PDF_NAME(T));
}
}
fz_always(ctx)
pdf_unmark_obj(ctx, elem);
fz_catch(ctx)
fz_rethrow(ctx);
return on;
}
/* Drops what marked content says on `page`, forms too. */
void ely_drop_alt(fz_context *ctx, pdf_document *pdf, pdf_page *page)
{
pdf_sanitize_filter_options sopts = { 0 };
pdf_filter_factory list[2] = { { quiet_factory, NULL }, { NULL, NULL } };
pdf_filter_options opts = { 0 };
void *before = fz_user_context(ctx);
bdc_fn *out = NULL;
list[0].options = &sopts;
opts.recurse = 1;
opts.filters = list;
fz_set_user_context(ctx, &out);
fz_try(ctx)
pdf_filter_page_contents(ctx, pdf, page, &opts);
fz_always(ctx)
fz_set_user_context(ctx, before);
fz_catch(ctx)
fz_rethrow(ctx);
quiet_elem(ctx, pdf_dict_getp(ctx, pdf_trailer(ctx, pdf), "Root/StructTreeRoot"), pdf_to_num(ctx, page->obj), 0);
}
+461
View File
@@ -0,0 +1,461 @@
/* Annotations: list, add, change, delete (PDF-05). */
#include <math.h>
#include <string.h>
#include "ely_shim.h"
static const char *stamps[] = { "Approved", "AsIs", "Confidential", "Departmental", "Draft", "Experimental",
"Expired", "Final", "ForComment", "ForPublicRelease", "NotApproved", "NotForPublicRelease", "Sold",
"TopSecret", NULL };
void ely_json_string(fz_context *ctx, fz_output *out, const char *s)
{
fz_write_byte(ctx, out, '"');
for (; *s; s++)
{
unsigned char c = (unsigned char)*s;
if (c == '"' || c == '\\')
fz_write_printf(ctx, out, "\\%c", c);
else if (c < 32)
fz_write_printf(ctx, out, "\\u%04x", c);
else
fz_write_byte(ctx, out, c);
}
fz_write_byte(ctx, out, '"');
}
fz_json *ely_member(fz_context *ctx, fz_json *obj, const char *key, int type)
{
fz_json *value = fz_json_object_get(ctx, obj, key);
if (value && value->type != type)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a bad %s", key);
return value;
}
float ely_number(fz_context *ctx, fz_json *array, int at)
{
fz_json *value = fz_json_array_get(ctx, array, at);
if (!value || value->type != FZ_JSON_NUMBER)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a bad number list");
return (float)value->u.number;
}
/* Four numbers, at least `least` wide and high. */
fz_rect ely_rect(fz_context *ctx, fz_json *array, float least)
{
fz_rect r;
if (!array || array->type != FZ_JSON_ARRAY || fz_json_array_length(ctx, array) != 4)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a bad rectangle");
r = fz_make_rect(ely_number(ctx, array, 0), ely_number(ctx, array, 1), ely_number(ctx, array, 2),
ely_number(ctx, array, 3));
if (r.x1 - r.x0 < least || r.y1 - r.y0 < least)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a rectangle too small");
return r;
}
static enum pdf_annot_type kind_of(fz_context *ctx, const char *kind)
{
if (!strcmp(kind, "highlight")) return PDF_ANNOT_HIGHLIGHT;
if (!strcmp(kind, "underline")) return PDF_ANNOT_UNDERLINE;
if (!strcmp(kind, "strikeout")) return PDF_ANNOT_STRIKE_OUT;
if (!strcmp(kind, "note")) return PDF_ANNOT_TEXT;
if (!strcmp(kind, "square")) return PDF_ANNOT_SQUARE;
if (!strcmp(kind, "circle")) return PDF_ANNOT_CIRCLE;
if (!strcmp(kind, "line")) return PDF_ANNOT_LINE;
if (!strcmp(kind, "ink")) return PDF_ANNOT_INK;
if (!strcmp(kind, "stamp")) return PDF_ANNOT_STAMP;
fz_throw(ctx, FZ_ERROR_ARGUMENT, "no annotation kind %s", kind);
}
static int rgb_of(fz_context *ctx, pdf_annot *annot)
{
float c[4], k;
int n;
pdf_annot_color(ctx, annot, &n, c);
if (n == 1)
c[1] = c[2] = c[0];
else if (n == 4)
{
k = 1 - c[3];
c[0] = (1 - c[0]) * k, c[1] = (1 - c[1]) * k, c[2] = (1 - c[2]) * k;
}
else if (n != 3)
return -1;
return ((int)(c[0] * 255 + 0.5f) << 16) | ((int)(c[1] * 255 + 0.5f) << 8) | (int)(c[2] * 255 + 0.5f);
}
static int color_of(fz_context *ctx, fz_json *spec)
{
fz_json *color = ely_member(ctx, spec, "color", FZ_JSON_NUMBER);
if (!color)
return -1;
if (color->u.number < 0 || color->u.number > 0xffffff)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a bad color");
return (int)color->u.number;
}
static const char *text_of(fz_context *ctx, fz_json *spec, const char *key)
{
fz_json *text = ely_member(ctx, spec, key, FZ_JSON_STRING);
return text ? text->u.string : NULL;
}
static int is_stamp(const char *name)
{
int i;
for (i = 0; name && stamps[i]; i++)
if (!strcmp(stamps[i], name))
return 1;
return 0;
}
/* Throws unless `spec` makes a whole annotation. */
static enum pdf_annot_type check(fz_context *ctx, fz_json *spec, int pages)
{
fz_json *page = ely_member(ctx, spec, "page", FZ_JSON_NUMBER);
fz_json *kind = ely_member(ctx, spec, "kind", FZ_JSON_STRING);
fz_json *list;
enum pdf_annot_type type;
int i, n;
if (!page || page->u.number < 0 || page->u.number >= pages || !kind)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "an annotation with no page or kind");
type = kind_of(ctx, kind->u.string);
color_of(ctx, spec);
text_of(ctx, spec, "contents");
text_of(ctx, spec, "author");
switch (type)
{
case PDF_ANNOT_HIGHLIGHT:
case PDF_ANNOT_UNDERLINE:
case PDF_ANNOT_STRIKE_OUT:
list = ely_member(ctx, spec, "rects", FZ_JSON_ARRAY);
n = list ? fz_json_array_length(ctx, list) : 0;
if (n == 0)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a mark over nothing");
for (i = 0; i < n; i++)
ely_rect(ctx, fz_json_array_get(ctx, list, i), 0.1f);
break;
case PDF_ANNOT_TEXT:
list = ely_member(ctx, spec, "at", FZ_JSON_ARRAY);
if (!list || fz_json_array_length(ctx, list) != 2)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a note with no place");
ely_number(ctx, list, 0), ely_number(ctx, list, 1);
break;
case PDF_ANNOT_LINE:
list = ely_member(ctx, spec, "line", FZ_JSON_ARRAY);
if (!list || fz_json_array_length(ctx, list) != 4)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a line with no ends");
if (fabsf(ely_number(ctx, list, 2) - ely_number(ctx, list, 0)) +
fabsf(ely_number(ctx, list, 3) - ely_number(ctx, list, 1)) < 2)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a line too short");
break;
case PDF_ANNOT_INK:
list = ely_member(ctx, spec, "strokes", FZ_JSON_ARRAY);
n = list ? fz_json_array_length(ctx, list) : 0;
if (n == 0)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "ink with no strokes");
for (i = 0; i < n; i++)
{
fz_json *stroke = fz_json_array_get(ctx, list, i);
int k, m = stroke->type == FZ_JSON_ARRAY ? fz_json_array_length(ctx, stroke) : 0;
if (m < 4 || m % 2)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a bad stroke");
for (k = 0; k < m; k++)
ely_number(ctx, stroke, k);
}
break;
case PDF_ANNOT_STAMP:
if (!is_stamp(text_of(ctx, spec, "icon")))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "no such stamp");
ely_rect(ctx, ely_member(ctx, spec, "rect", FZ_JSON_ARRAY), 2);
break;
default:
ely_rect(ctx, ely_member(ctx, spec, "rect", FZ_JSON_ARRAY), 2);
}
return type;
}
static fz_point point_at(fz_context *ctx, fz_json *list, int at)
{
return fz_make_point(ely_number(ctx, list, at), ely_number(ctx, list, at + 1));
}
/* Makes a checked `spec` inside the open step. */
static void make(fz_context *ctx, pdf_document *pdf, fz_json *spec, enum pdf_annot_type type)
{
pdf_page *page = NULL;
pdf_annot *annot = NULL;
fz_point *points = NULL;
fz_var(page);
fz_var(annot);
fz_var(points);
fz_try(ctx)
{
fz_json *list;
int i, k, n, color = color_of(ctx, spec);
page = pdf_load_page(ctx, pdf, (int)ely_member(ctx, spec, "page", FZ_JSON_NUMBER)->u.number);
annot = pdf_create_annot(ctx, page, type);
switch (type)
{
case PDF_ANNOT_HIGHLIGHT:
case PDF_ANNOT_UNDERLINE:
case PDF_ANNOT_STRIKE_OUT:
list = ely_member(ctx, spec, "rects", FZ_JSON_ARRAY);
n = fz_json_array_length(ctx, list);
for (i = 0; i < n; i++)
pdf_add_annot_quad_point(ctx, annot, fz_quad_from_rect(ely_rect(ctx, fz_json_array_get(ctx, list, i), 0.1f)));
break;
case PDF_ANNOT_TEXT:
{
fz_point at = point_at(ctx, ely_member(ctx, spec, "at", FZ_JSON_ARRAY), 0);
pdf_set_annot_rect(ctx, annot, fz_make_rect(at.x, at.y, at.x + 16, at.y + 16));
pdf_set_annot_popup(ctx, annot, fz_make_rect(at.x + 20, at.y, at.x + 220, at.y + 100));
break;
}
case PDF_ANNOT_LINE:
list = ely_member(ctx, spec, "line", FZ_JSON_ARRAY);
pdf_set_annot_line(ctx, annot, point_at(ctx, list, 0), point_at(ctx, list, 2));
break;
case PDF_ANNOT_INK:
list = ely_member(ctx, spec, "strokes", FZ_JSON_ARRAY);
n = fz_json_array_length(ctx, list);
for (i = 0; i < n; i++)
{
fz_json *stroke = fz_json_array_get(ctx, list, i);
int m = fz_json_array_length(ctx, stroke) / 2;
fz_free(ctx, points);
points = NULL;
points = fz_malloc_array(ctx, m, fz_point);
for (k = 0; k < m; k++)
points[k] = point_at(ctx, stroke, k * 2);
pdf_add_annot_ink_list(ctx, annot, m, points);
}
break;
case PDF_ANNOT_STAMP:
pdf_set_annot_icon_name(ctx, annot, text_of(ctx, spec, "icon"));
pdf_set_annot_rect(ctx, annot, ely_rect(ctx, ely_member(ctx, spec, "rect", FZ_JSON_ARRAY), 2));
break;
default:
pdf_set_annot_rect(ctx, annot, ely_rect(ctx, ely_member(ctx, spec, "rect", FZ_JSON_ARRAY), 2));
}
if (color >= 0)
{
float rgb[3] = { (color >> 16) / 255.0f, ((color >> 8) & 255) / 255.0f, (color & 255) / 255.0f };
pdf_set_annot_color(ctx, annot, 3, rgb);
}
if (text_of(ctx, spec, "contents"))
pdf_set_annot_contents(ctx, annot, text_of(ctx, spec, "contents"));
if (text_of(ctx, spec, "author"))
pdf_set_annot_author(ctx, annot, text_of(ctx, spec, "author"));
pdf_update_annot(ctx, annot);
}
fz_always(ctx)
{
fz_free(ctx, points);
pdf_drop_annot(ctx, annot);
fz_drop_page(ctx, (fz_page *)page);
}
fz_catch(ctx)
fz_rethrow(ctx);
}
/* A JSON list of annotations, added in one step. */
int ely_annotate(fz_context *ctx, fz_document *doc, const char *json)
{
pdf_document *pdf = NULL;
fz_pool *pool = NULL;
enum pdf_annot_type *types = NULL;
int begun = 0;
fz_var(pdf);
fz_var(pool);
fz_var(types);
fz_var(begun);
fz_try(ctx)
{
fz_json *specs;
int i, n, pages;
pdf = ely_pdf_of(ctx, doc);
pages = pdf_count_pages(ctx, pdf);
pool = fz_new_pool(ctx);
specs = fz_parse_json(ctx, pool, json);
n = specs->type == FZ_JSON_ARRAY ? fz_json_array_length(ctx, specs) : 0;
if (n == 0)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "no annotations to add");
types = fz_malloc_array(ctx, n, enum pdf_annot_type);
for (i = 0; i < n; i++)
types[i] = check(ctx, fz_json_array_get(ctx, specs, i), pages);
pdf_begin_operation(ctx, pdf, "Annotate");
begun = 1;
for (i = 0; i < n; i++)
make(ctx, pdf, fz_json_array_get(ctx, specs, i), types[i]);
pdf_end_operation(ctx, pdf);
}
fz_always(ctx)
{
fz_free(ctx, types);
fz_drop_pool(ctx, pool);
}
fz_catch(ctx)
return ely_edit_failed(ctx, pdf, begun);
return 0;
}
/* The annotation or widget object `id` on `page`. */
pdf_annot *ely_find_annot(fz_context *ctx, pdf_page *page, int id, int widget)
{
pdf_annot *annot = widget ? pdf_first_widget(ctx, page) : pdf_first_annot(ctx, page);
for (; annot; annot = widget ? pdf_next_widget(ctx, annot) : pdf_next_annot(ctx, annot))
if (pdf_to_num(ctx, pdf_annot_obj(ctx, annot)) == id)
return annot;
fz_throw(ctx, FZ_ERROR_ARGUMENT, "no %s %d on the page", widget ? "field" : "annotation", id);
}
/* Sets an annotation's colour or contents, in one step. */
int ely_change_annot(fz_context *ctx, fz_document *doc, int number, int id, const char *json)
{
pdf_document *pdf = NULL;
pdf_page *page = NULL;
fz_pool *pool = NULL;
int begun = 0;
fz_var(pdf);
fz_var(page);
fz_var(pool);
fz_var(begun);
fz_try(ctx)
{
pdf_annot *annot;
fz_json *spec;
const char *contents;
int color;
pdf = ely_pdf_of(ctx, doc);
page = pdf_load_page(ctx, pdf, number);
annot = ely_find_annot(ctx, page, id, 0);
pool = fz_new_pool(ctx);
spec = fz_parse_json(ctx, pool, json);
color = color_of(ctx, spec);
contents = text_of(ctx, spec, "contents");
if (color < 0 && !contents)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "no change");
pdf_begin_operation(ctx, pdf, "Change an annotation");
begun = 1;
if (color >= 0)
{
float rgb[3] = { (color >> 16) / 255.0f, ((color >> 8) & 255) / 255.0f, (color & 255) / 255.0f };
pdf_set_annot_color(ctx, annot, 3, rgb);
}
if (contents)
pdf_set_annot_contents(ctx, annot, contents);
pdf_update_annot(ctx, annot);
pdf_end_operation(ctx, pdf);
}
fz_always(ctx)
{
fz_drop_pool(ctx, pool);
fz_drop_page(ctx, (fz_page *)page);
}
fz_catch(ctx)
return ely_edit_failed(ctx, pdf, begun);
return 0;
}
/* Unlinks `field`; an emptied parent goes too. */
void ely_unlink_field(fz_context *ctx, pdf_document *pdf, pdf_obj *field)
{
pdf_obj *parent = pdf_dict_get(ctx, field, PDF_NAME(Parent));
pdf_obj *kids = parent ? pdf_dict_get(ctx, parent, PDF_NAME(Kids)) : pdf_dict_getp(ctx, pdf_trailer(ctx, pdf), "Root/AcroForm/Fields");
int at = pdf_array_find(ctx, kids, field);
if (at >= 0)
pdf_array_delete(ctx, kids, at);
if (parent && pdf_array_len(ctx, kids) == 0)
ely_unlink_field(ctx, pdf, parent);
}
/* Deletes annotation or field `id`, in one step. */
int ely_delete_annot(fz_context *ctx, fz_document *doc, int number, int id, int widget)
{
pdf_document *pdf = NULL;
pdf_page *page = NULL;
pdf_obj *field = NULL;
int begun = 0;
fz_var(pdf);
fz_var(page);
fz_var(field);
fz_var(begun);
fz_try(ctx)
{
pdf_annot *annot;
pdf = ely_pdf_of(ctx, doc);
page = pdf_load_page(ctx, pdf, number);
annot = ely_find_annot(ctx, page, id, widget);
field = pdf_keep_obj(ctx, pdf_annot_obj(ctx, annot));
pdf_begin_operation(ctx, pdf, widget ? "Delete a field" : "Delete an annotation");
begun = 1;
pdf_delete_annot(ctx, page, annot);
if (widget)
ely_unlink_field(ctx, pdf, field);
pdf_end_operation(ctx, pdf);
}
fz_always(ctx)
{
pdf_drop_obj(ctx, field);
fz_drop_page(ctx, (fz_page *)page);
}
fz_catch(ctx)
return ely_edit_failed(ctx, pdf, begun);
return 0;
}
static void write_annot(fz_context *ctx, fz_output *out, pdf_annot *annot)
{
fz_rect r = pdf_bound_annot(ctx, annot);
fz_write_printf(ctx, out, "{\"id\":%d,\"kind\":", pdf_to_num(ctx, pdf_annot_obj(ctx, annot)));
ely_json_string(ctx, out, pdf_string_from_annot_type(ctx, pdf_annot_type(ctx, annot)));
fz_write_printf(ctx, out, ",\"rect\":[%g,%g,%g,%g],\"color\":%d,\"contents\":", r.x0, r.y0, r.x1, r.y1,
rgb_of(ctx, annot));
ely_json_string(ctx, out, pdf_annot_contents(ctx, annot));
fz_write_string(ctx, out, ",\"author\":");
ely_json_string(ctx, out, pdf_annot_has_author(ctx, annot) ? pdf_annot_author(ctx, annot) : "");
fz_write_string(ctx, out, ",\"icon\":");
ely_json_string(ctx, out, pdf_annot_has_icon_name(ctx, annot) ? pdf_annot_icon_name(ctx, annot) : "");
fz_write_byte(ctx, out, '}');
}
/* JSON of a page's annotations and form fields. */
int ely_annots(fz_context *ctx, fz_document *doc, int number, unsigned char **data, size_t *len)
{
pdf_page *page = NULL;
fz_buffer *buf = NULL;
fz_output *out = NULL;
fz_var(page);
fz_var(buf);
fz_var(out);
fz_try(ctx)
{
pdf_annot *annot;
page = pdf_load_page(ctx, ely_pdf_of(ctx, doc), number);
buf = fz_new_buffer(ctx, 1024);
out = fz_new_output_with_buffer(ctx, buf);
fz_write_string(ctx, out, "{\"annots\":[");
for (annot = pdf_first_annot(ctx, page); annot; annot = pdf_next_annot(ctx, annot))
{
if (annot != pdf_first_annot(ctx, page))
fz_write_byte(ctx, out, ',');
write_annot(ctx, out, annot);
}
fz_write_string(ctx, out, "],\"fields\":[");
ely_write_fields(ctx, out, page);
fz_write_string(ctx, out, "]}");
fz_close_output(ctx, out);
*len = fz_buffer_extract(ctx, buf, data);
}
fz_always(ctx)
{
fz_drop_output(ctx, out);
fz_drop_buffer(ctx, buf);
fz_drop_page(ctx, (fz_page *)page);
}
fz_catch(ctx)
return ely_fail(ctx);
return 0;
}
+395
View File
@@ -0,0 +1,395 @@
/* Cleaning into a new file, counted before and after (PDF-10). */
#include <string.h>
#include "ely_shim.h"
enum { CLEAN_META = 1, CLEAN_ANNOTS = 2, CLEAN_FILES = 4, CLEAN_HIDDEN = 8, CLEAN_ALL = 15 };
/* What cleaning reaches, counted. */
typedef struct
{
int meta, annots, files, hidden_pages, scripts, hidden_annots;
} reach;
/* The filter running a page, and what it drops. */
typedef struct
{
pdf_processor *top;
int dropped;
} hiding;
static pdf_processor *hide_factory(fz_context *ctx, pdf_document *doc, pdf_processor *chain, int struct_parents,
fz_matrix transform, pdf_filter_options *options, void *sopts)
{
hiding *h = ((pdf_sanitize_filter_options *)sopts)->opaque;
h->top = pdf_new_sanitize_filter(ctx, doc, chain, struct_parents, transform, options, sopts);
/* Layers count as hidden only for a viewer's usage. */
h->top->usage = "View";
return h->top;
}
/* Unseen text: modes 3 and 7, or zero opacity. */
static int hide_text(fz_context *ctx, void *opaque, int *ucs, int len, fz_matrix trm, fz_matrix ctm, fz_rect bbox,
int tr, float ca, float CA)
{
hiding *h = opaque;
int fills = tr == 0 || tr == 2 || tr == 4 || tr == 6, strokes = tr == 1 || tr == 2 || tr == 5 || tr == 6;
int drop = h->top->hidden > 0 || tr == 3 || tr == 7 || ((!fills || ca == 0) && (!strokes || CA == 0));
(void)ctx, (void)ucs, (void)len, (void)trm, (void)ctm, (void)bbox;
h->dropped += drop;
return drop;
}
/* Drawing inside a layer that is off. */
static int hide_cull(fz_context *ctx, void *opaque, fz_rect bbox, fz_cull_type type)
{
hiding *h = opaque;
(void)ctx, (void)bbox, (void)type;
h->dropped += h->top->hidden > 0;
return h->top->hidden > 0;
}
/* Drops hidden text and hidden layers from `page`; how many. */
static int drop_hidden(fz_context *ctx, pdf_document *pdf, pdf_page *page)
{
hiding h = { NULL, 0 };
pdf_sanitize_filter_options sopts = { 0 };
pdf_filter_factory list[2] = { { hide_factory, NULL }, { NULL, NULL } };
pdf_filter_options opts = { 0 };
sopts.opaque = &h;
sopts.text_filter = hide_text;
sopts.culler = hide_cull;
list[0].options = &sopts;
opts.recurse = 1;
opts.filters = list;
pdf_filter_page_contents(ctx, pdf, page, &opts);
if (h.dropped)
ely_drop_alt(ctx, pdf, page);
return h.dropped;
}
static int is_script(fz_context *ctx, pdf_obj *action)
{
return pdf_is_dict(ctx, action) &&
(pdf_name_eq(ctx, pdf_dict_get(ctx, action, PDF_NAME(S)), PDF_NAME(JavaScript)) || pdf_dict_get(ctx, action, PDF_NAME(JS)));
}
/* `action` without its scripts, their Next chains kept. */
static pdf_obj *spliced(fz_context *ctx, pdf_document *pdf, pdf_obj *action, int *n)
{
pdf_obj *out = NULL, *each = NULL;
int i, k;
fz_var(each);
if (is_script(ctx, action))
{
if (pdf_mark_obj(ctx, action))
return NULL;
(*n)++;
fz_try(ctx)
out = spliced(ctx, pdf, pdf_dict_get(ctx, action, PDF_NAME(Next)), n);
fz_always(ctx)
pdf_unmark_obj(ctx, action);
fz_catch(ctx)
fz_rethrow(ctx);
return out;
}
if (!pdf_is_array(ctx, action))
return pdf_keep_obj(ctx, action);
out = pdf_new_array(ctx, pdf, pdf_array_len(ctx, action));
fz_try(ctx)
for (i = 0; i < pdf_array_len(ctx, action); i++)
{
each = spliced(ctx, pdf, pdf_array_get(ctx, action, i), n);
if (pdf_is_array(ctx, each))
for (k = 0; k < pdf_array_len(ctx, each); k++)
pdf_array_push(ctx, out, pdf_array_get(ctx, each, k));
else if (each)
pdf_array_push(ctx, out, each);
pdf_drop_obj(ctx, each);
each = NULL;
}
fz_always(ctx)
pdf_drop_obj(ctx, each);
fz_catch(ctx)
{
pdf_drop_obj(ctx, out);
fz_rethrow(ctx);
}
return out;
}
/* Splices scripts out of `dict[key]`; how many. */
static int splice_key(fz_context *ctx, pdf_document *pdf, pdf_obj *dict, const char *key)
{
pdf_obj *now = pdf_dict_gets(ctx, dict, key), *kept;
int n = 0;
if (!now)
return 0;
kept = spliced(ctx, pdf, now, &n);
if (n == 0)
pdf_drop_obj(ctx, kept);
else if (kept && !(pdf_is_array(ctx, kept) && pdf_array_len(ctx, kept) == 0))
pdf_dict_puts_drop(ctx, dict, key, kept);
else
{
pdf_drop_obj(ctx, kept);
pdf_dict_dels(ctx, dict, key);
}
return n;
}
static int drop_key(fz_context *ctx, pdf_obj *dict, const char *key)
{
int had = pdf_dict_gets(ctx, dict, key) != NULL;
pdf_dict_dels(ctx, dict, key);
return had;
}
/* Cleans `obj` and the direct values inside it. */
static void clean_obj(fz_context *ctx, pdf_document *pdf, pdf_obj *obj, int mask, reach *r)
{
pdf_obj *aa;
int i;
if (pdf_is_dict(ctx, obj))
{
if (mask & CLEAN_META)
r->meta += drop_key(ctx, obj, "Metadata") + drop_key(ctx, obj, "PieceInfo");
if (mask & CLEAN_FILES)
{
r->files += drop_key(ctx, obj, "EF");
drop_key(ctx, obj, "RF");
drop_key(ctx, obj, "AF");
}
if (mask & CLEAN_HIDDEN)
{
r->scripts += splice_key(ctx, pdf, obj, "A") + splice_key(ctx, pdf, obj, "OpenAction") +
splice_key(ctx, pdf, obj, "Next");
aa = pdf_dict_get(ctx, obj, PDF_NAME(AA));
for (i = pdf_dict_len(ctx, aa) - 1; i >= 0; i--)
r->scripts += splice_key(ctx, pdf, aa, pdf_to_name(ctx, pdf_dict_get_key(ctx, aa, i)));
if (pdf_is_dict(ctx, aa) && pdf_dict_len(ctx, aa) == 0)
pdf_dict_del(ctx, obj, PDF_NAME(AA));
}
for (i = 0; i < pdf_dict_len(ctx, obj); i++)
if (!pdf_is_indirect(ctx, pdf_dict_get_val(ctx, obj, i)))
clean_obj(ctx, pdf, pdf_dict_get_val(ctx, obj, i), mask, r);
}
else if (pdf_is_array(ctx, obj))
for (i = 0; i < pdf_array_len(ctx, obj); i++)
if (!pdf_is_indirect(ctx, pdf_array_get(ctx, obj, i)))
clean_obj(ctx, pdf, pdf_array_get(ctx, obj, i), mask, r);
}
/* Every object: metadata, embedded bytes, scripts. */
static void clean_all(fz_context *ctx, pdf_document *pdf, int mask, reach *r)
{
int i;
for (i = 1; i < pdf_xref_len(ctx, pdf); i++)
{
pdf_obj *obj = pdf_new_indirect(ctx, pdf, i, 0);
fz_try(ctx)
clean_obj(ctx, pdf, pdf_resolve_indirect(ctx, obj), mask, r);
fz_always(ctx)
pdf_drop_obj(ctx, obj);
fz_catch(ctx)
fz_rethrow(ctx);
}
}
static int unseen(fz_context *ctx, pdf_obj *annot)
{
return (pdf_dict_get_int(ctx, annot, PDF_NAME(F)) & (PDF_ANNOT_IS_HIDDEN | PDF_ANNOT_IS_INVISIBLE)) != 0;
}
/* Hidden fields go with their values. */
static int drop_hidden_widgets(fz_context *ctx, pdf_page *page)
{
pdf_annot *widget;
int n = 0;
restart:
for (widget = pdf_first_widget(ctx, page); widget; widget = pdf_next_widget(ctx, widget))
if (unseen(ctx, pdf_annot_obj(ctx, widget)))
{
pdf_obj *field = pdf_keep_obj(ctx, pdf_annot_obj(ctx, widget));
fz_try(ctx)
{
pdf_delete_annot(ctx, page, widget);
ely_unlink_field(ctx, page->doc, field);
}
fz_always(ctx)
pdf_drop_obj(ctx, field);
fz_catch(ctx)
fz_rethrow(ctx);
n++;
goto restart;
}
return n;
}
/* Links are not in MuPDF's annotation list. */
static int drop_hidden_links(fz_context *ctx, pdf_page *page)
{
pdf_obj *annots = pdf_dict_get(ctx, page->obj, PDF_NAME(Annots));
int i, n = 0;
for (i = pdf_array_len(ctx, annots) - 1; i >= 0; i--)
{
pdf_obj *annot = pdf_array_get(ctx, annots, i);
if (pdf_name_eq(ctx, pdf_dict_get(ctx, annot, PDF_NAME(Subtype)), PDF_NAME(Link)) && unseen(ctx, annot))
{
pdf_array_delete(ctx, annots, i);
n++;
}
}
return n;
}
static void sweep_page(fz_context *ctx, pdf_document *pdf, pdf_page *page, int mask, reach *r)
{
pdf_annot *annot;
if (mask & CLEAN_HIDDEN)
r->hidden_pages += drop_hidden(ctx, pdf, page) > 0;
restart:
for (annot = pdf_first_annot(ctx, page); annot; annot = pdf_next_annot(ctx, annot))
{
int file = pdf_annot_type(ctx, annot) == PDF_ANNOT_FILE_ATTACHMENT;
int hidden = (pdf_annot_flags(ctx, annot) & (PDF_ANNOT_IS_HIDDEN | PDF_ANNOT_IS_INVISIBLE)) != 0;
if ((file && (mask & CLEAN_FILES)) || (!file && (mask & CLEAN_ANNOTS)) || (hidden && (mask & CLEAN_HIDDEN)))
{
r->hidden_annots += hidden && !file;
r->annots += !file && !hidden;
pdf_delete_annot(ctx, page, annot);
goto restart;
}
}
if (mask & CLEAN_HIDDEN)
r->hidden_annots += drop_hidden_widgets(ctx, page) + drop_hidden_links(ctx, page);
}
/* Drops what `mask` names from `doc`, counting what was there. */
static reach sweep(fz_context *ctx, fz_document *doc, int mask)
{
pdf_document *pdf = ely_pdf_of(ctx, doc);
pdf_obj *trailer = pdf_trailer(ctx, pdf), *root = pdf_dict_get(ctx, trailer, PDF_NAME(Root));
pdf_obj *names = pdf_dict_get(ctx, root, PDF_NAME(Names)), *tree;
pdf_page *page = NULL;
reach r = { 0 };
int i;
fz_var(page);
if (mask & CLEAN_META)
{
r.meta = pdf_dict_len(ctx, pdf_dict_get(ctx, trailer, PDF_NAME(Info)));
pdf_dict_del(ctx, trailer, PDF_NAME(Info));
}
if ((mask & CLEAN_FILES) && names)
pdf_dict_del(ctx, names, PDF_NAME(EmbeddedFiles));
if (mask & CLEAN_HIDDEN)
{
tree = pdf_load_name_tree(ctx, pdf, PDF_NAME(JavaScript));
r.scripts = pdf_dict_len(ctx, tree);
pdf_drop_obj(ctx, tree);
if (names)
pdf_dict_del(ctx, names, PDF_NAME(JavaScript));
}
clean_all(ctx, pdf, mask, &r);
fz_try(ctx)
{
for (i = 0; i < pdf_count_pages(ctx, pdf); i++)
{
page = pdf_load_page(ctx, pdf, i);
sweep_page(ctx, pdf, page, mask, &r);
fz_drop_page(ctx, (fz_page *)page);
page = NULL;
}
}
fz_always(ctx)
fz_drop_page(ctx, (fz_page *)page);
fz_catch(ctx)
fz_rethrow(ctx);
return r;
}
static void write_reach(fz_context *ctx, fz_buffer *buf, reach r)
{
fz_append_printf(ctx, buf, "{\"meta\":%d,\"annots\":%d,\"files\":%d,\"hidden\":%d,\"scripts\":%d,\"hidden_annots\":%d}",
r.meta, r.annots, r.files, r.hidden_pages, r.scripts, r.hidden_annots);
}
/* Counts by sweeping a throwaway copy of `pdf`. */
static reach count_copy(fz_context *ctx, pdf_document *pdf, const char *raw, const char *password)
{
fz_document *copy = NULL;
reach r;
fz_var(copy);
fz_try(ctx)
{
pdf_save_snapshot(ctx, pdf, raw);
copy = fz_open_document(ctx, raw);
if (fz_needs_password(ctx, copy) && !fz_authenticate_password(ctx, copy, password))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "the copy refused its password");
r = sweep(ctx, copy, CLEAN_ALL);
}
fz_always(ctx)
fz_drop_document(ctx, copy);
fz_catch(ctx)
fz_rethrow(ctx);
return r;
}
/* What cleaning would reach, as JSON. */
int ely_clean_scan(fz_context *ctx, fz_document *doc, const char *raw, const char *password, unsigned char **data, size_t *len)
{
fz_buffer *buf = NULL;
fz_var(buf);
fz_try(ctx)
{
buf = fz_new_buffer(ctx, 128);
write_reach(ctx, buf, count_copy(ctx, ely_pdf_of(ctx, doc), raw, password));
*len = fz_buffer_extract(ctx, buf, data);
}
fz_always(ctx)
fz_drop_buffer(ctx, buf);
fz_catch(ctx)
return ely_fail(ctx);
return 0;
}
static void apply_clean(fz_context *ctx, fz_document *copy, void *arg)
{
sweep(ctx, copy, *(int *)arg);
}
/* Cleans `mask` into `out`, then counts what is left. */
int ely_clean(fz_context *ctx, fz_document *doc, int mask, const char *raw, const char *out, const char *password,
unsigned char **data, size_t *len)
{
fz_document *written = NULL;
fz_buffer *buf = NULL;
fz_var(written);
fz_var(buf);
fz_try(ctx)
{
reach left;
if (mask <= 0 || mask > CLEAN_ALL)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "nothing chosen to clean");
ely_save_copy(ctx, ely_pdf_of(ctx, doc), raw, out, password, NULL, apply_clean, &mask);
written = fz_open_document(ctx, out);
if (fz_needs_password(ctx, written) && !fz_authenticate_password(ctx, written, password))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "the written file refused its password");
left = count_copy(ctx, ely_pdf_of(ctx, written), raw, password);
buf = fz_new_buffer(ctx, 128);
write_reach(ctx, buf, left);
if (((mask & CLEAN_META) && left.meta) || ((mask & CLEAN_ANNOTS) && left.annots) || ((mask & CLEAN_FILES) && left.files) ||
((mask & CLEAN_HIDDEN) && (left.hidden_pages || left.scripts || left.hidden_annots)))
fz_throw(ctx, FZ_ERROR_FORMAT, "the written file still holds what was cleaned");
*len = fz_buffer_extract(ctx, buf, data);
}
fz_always(ctx)
{
fz_drop_buffer(ctx, buf);
fz_drop_document(ctx, written);
}
fz_catch(ctx)
return ely_fail(ctx);
return 0;
}
+489
View File
@@ -0,0 +1,489 @@
/* Form fields: list, add, fill, change (PDF-06). */
#include <stdio.h>
#include <string.h>
#include "ely_shim.h"
static const char *kind_name(enum pdf_widget_type type)
{
switch (type)
{
case PDF_WIDGET_TYPE_TEXT: return "text";
case PDF_WIDGET_TYPE_CHECKBOX: return "checkbox";
case PDF_WIDGET_TYPE_RADIOBUTTON: return "radio";
case PDF_WIDGET_TYPE_COMBOBOX: return "choice";
case PDF_WIDGET_TYPE_LISTBOX: return "list";
case PDF_WIDGET_TYPE_SIGNATURE: return "signature";
default: return "button";
}
}
/* The field that names `obj`. */
static pdf_obj *head_of(fz_context *ctx, pdf_obj *obj)
{
while (!pdf_dict_get(ctx, obj, PDF_NAME(T)) && pdf_dict_get(ctx, obj, PDF_NAME(Parent)))
obj = pdf_dict_get(ctx, obj, PDF_NAME(Parent));
return obj;
}
static pdf_obj *fields_of(fz_context *ctx, pdf_document *pdf)
{
pdf_obj *root = pdf_dict_get(ctx, pdf_trailer(ctx, pdf), PDF_NAME(Root));
pdf_obj *form = pdf_dict_get(ctx, root, PDF_NAME(AcroForm));
if (!form)
form = pdf_dict_put_dict(ctx, root, PDF_NAME(AcroForm), 2);
if (!pdf_is_array(ctx, pdf_dict_get(ctx, form, PDF_NAME(Fields))))
pdf_dict_put_array(ctx, form, PDF_NAME(Fields), 4);
return pdf_dict_get(ctx, form, PDF_NAME(Fields));
}
/* A value as text; names and streams too. */
static void write_value(fz_context *ctx, fz_output *out, pdf_obj *v)
{
char *text = NULL;
fz_var(text);
fz_try(ctx)
{
if (pdf_is_name(ctx, v))
ely_json_string(ctx, out, pdf_to_name(ctx, v));
else if (pdf_is_stream(ctx, v))
{
text = pdf_new_utf8_from_pdf_stream_obj(ctx, v);
ely_json_string(ctx, out, text);
}
else
ely_json_string(ctx, out, pdf_to_text_string(ctx, v));
}
fz_always(ctx)
fz_free(ctx, text);
fz_catch(ctx)
fz_rethrow(ctx);
}
static void write_options(fz_context *ctx, fz_output *out, pdf_obj *obj, int export)
{
int i, n = pdf_choice_field_option_count(ctx, obj);
fz_write_byte(ctx, out, '[');
for (i = 0; i < n; i++)
{
if (i)
fz_write_byte(ctx, out, ',');
ely_json_string(ctx, out, pdf_choice_field_option(ctx, obj, export, i));
}
fz_write_byte(ctx, out, ']');
}
void ely_write_fields(fz_context *ctx, fz_output *out, pdf_page *page)
{
pdf_annot *widget;
char *name = NULL;
fz_var(name);
fz_try(ctx)
{
for (widget = pdf_first_widget(ctx, page); widget; widget = pdf_next_widget(ctx, widget))
{
pdf_obj *obj = pdf_annot_obj(ctx, widget);
enum pdf_widget_type type = pdf_widget_type(ctx, widget);
fz_rect r = pdf_bound_widget(ctx, widget);
int button = type == PDF_WIDGET_TYPE_CHECKBOX || type == PDF_WIDGET_TYPE_RADIOBUTTON;
pdf_obj *as = pdf_dict_get(ctx, obj, PDF_NAME(AS));
fz_free(ctx, name);
name = NULL;
name = pdf_load_field_name(ctx, obj);
fz_write_printf(ctx, out, "%s{\"id\":%d,\"kind\":\"%s\",\"name\":", widget == pdf_first_widget(ctx, page) ? "" : ",",
pdf_to_num(ctx, obj), kind_name(type));
ely_json_string(ctx, out, name);
fz_write_printf(ctx, out, ",\"rect\":[%g,%g,%g,%g],\"value\":", r.x0, r.y0, r.x1, r.y1);
write_value(ctx, out, pdf_dict_get_inheritable(ctx, obj, PDF_NAME(V)));
fz_write_string(ctx, out, ",\"on\":");
ely_json_string(ctx, out, button ? pdf_to_name(ctx, pdf_button_field_on_state(ctx, obj)) : "");
fz_write_printf(ctx, out, ",\"checked\":%s,\"readonly\":%s,\"options\":",
button && pdf_is_name(ctx, as) && !pdf_name_eq(ctx, as, PDF_NAME(Off)) ? "true" : "false",
pdf_widget_is_readonly(ctx, widget) ? "true" : "false");
write_options(ctx, out, obj, 1);
fz_write_string(ctx, out, ",\"labels\":");
write_options(ctx, out, obj, 0);
fz_write_byte(ctx, out, '}');
}
}
fz_always(ctx)
fz_free(ctx, name);
fz_catch(ctx)
fz_rethrow(ctx);
}
/* Shows `state` on each button under `node`, else Off. */
static void show_state(fz_context *ctx, pdf_obj *node, pdf_obj *state)
{
pdf_obj *kids = pdf_dict_get(ctx, node, PDF_NAME(Kids));
int i;
if (kids)
{
for (i = 0; i < pdf_array_len(ctx, kids); i++)
show_state(ctx, pdf_array_get(ctx, kids, i), state);
return;
}
pdf_dict_put(ctx, node, PDF_NAME(AS), pdf_dict_get(ctx, pdf_dict_getp(ctx, node, "AP/N"), state) ? state : PDF_NAME(Off));
}
/* Fills field widget `id` with `value`, in one step. */
int ely_fill(fz_context *ctx, fz_document *doc, int number, int id, const char *value)
{
pdf_document *pdf = NULL;
pdf_page *page = NULL;
pdf_obj *state = NULL;
int begun = 0;
fz_var(pdf);
fz_var(page);
fz_var(state);
fz_var(begun);
fz_try(ctx)
{
pdf_annot *widget;
pdf_obj *obj;
enum pdf_widget_type type;
pdf = ely_pdf_of(ctx, doc);
page = pdf_load_page(ctx, pdf, number);
widget = ely_find_annot(ctx, page, id, 1);
obj = pdf_annot_obj(ctx, widget);
type = pdf_widget_type(ctx, widget);
if (pdf_widget_is_readonly(ctx, widget))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "the field is read only");
if (type == PDF_WIDGET_TYPE_CHECKBOX || type == PDF_WIDGET_TYPE_RADIOBUTTON)
{
state = pdf_new_name(ctx, value);
if (!pdf_name_eq(ctx, state, PDF_NAME(Off)) && !pdf_name_eq(ctx, state, pdf_button_field_on_state(ctx, obj)))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "the button has no state %s", value);
}
else if (type != PDF_WIDGET_TYPE_TEXT && type != PDF_WIDGET_TYPE_COMBOBOX && type != PDF_WIDGET_TYPE_LISTBOX)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a %s field cannot be filled", kind_name(type));
pdf_begin_operation(ctx, pdf, "Fill a field");
begun = 1;
if (state)
{
pdf_dict_put(ctx, head_of(ctx, obj), PDF_NAME(V), state);
show_state(ctx, head_of(ctx, obj), state);
}
else if (!pdf_set_field_value(ctx, pdf, obj, value, 1))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "the field refused the value");
pdf_update_annot(ctx, widget);
pdf_end_operation(ctx, pdf);
}
fz_always(ctx)
{
pdf_drop_obj(ctx, state);
fz_drop_page(ctx, (fz_page *)page);
}
fz_catch(ctx)
return ely_edit_failed(ctx, pdf, begun);
return 0;
}
/* Throws unless `prefix` plus `name` is free for `kind`. */
static pdf_obj *check_name(fz_context *ctx, pdf_obj *fields, const char *prefix, const char *name, const char *kind,
pdf_obj *self)
{
pdf_obj *found = NULL;
char *full = NULL;
if (!name[0] || strchr(name, '.'))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a bad field name");
fz_var(full);
fz_try(ctx)
{
full = fz_asprintf(ctx, "%s%s", prefix, name);
found = pdf_lookup_field(ctx, fields, full);
}
fz_always(ctx)
fz_free(ctx, full);
fz_catch(ctx)
fz_rethrow(ctx);
if (!found || (self && !pdf_objcmp(ctx, found, self)))
return NULL;
if (!strcmp(kind, "radio") && pdf_field_type(ctx, found) == PDF_WIDGET_TYPE_RADIOBUTTON &&
pdf_dict_get(ctx, found, PDF_NAME(Kids)))
return found;
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a field named %s%s exists", prefix, name);
}
/* The full name of `field`'s parent, with a dot. */
static char *parent_path(fz_context *ctx, pdf_obj *field)
{
pdf_obj *parent = pdf_dict_get(ctx, field, PDF_NAME(Parent));
char *name = parent ? pdf_load_field_name(ctx, parent) : NULL, *path = NULL;
fz_try(ctx)
path = fz_asprintf(ctx, "%s%s", name ? name : "", name && name[0] ? "." : "");
fz_always(ctx)
fz_free(ctx, name);
fz_catch(ctx)
fz_rethrow(ctx);
return path;
}
static void put_options(fz_context *ctx, pdf_obj *field, fz_json *options)
{
pdf_obj *opt = pdf_dict_put_array(ctx, field, PDF_NAME(Opt), 4);
int i, n = fz_json_array_length(ctx, options);
for (i = 0; i < n; i++)
pdf_array_push_text_string(ctx, opt, fz_json_array_get(ctx, options, i)->u.string);
}
static void check_options(fz_context *ctx, fz_json *options)
{
int i, n = options ? fz_json_array_length(ctx, options) : 0;
if (n == 0)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a choice with no options");
for (i = 0; i < n; i++)
if (fz_json_array_get(ctx, options, i)->type != FZ_JSON_STRING || !fz_json_array_get(ctx, options, i)->u.string[0])
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a bad option");
}
/* An on state no button in `group` has. */
static pdf_obj *new_state(fz_context *ctx, pdf_obj *group)
{
pdf_obj *kids = pdf_dict_get(ctx, group, PDF_NAME(Kids));
char name[32];
int n, i, taken;
for (n = pdf_array_len(ctx, kids) + 1;; n++)
{
snprintf(name, sizeof name, "Choice%d", n);
for (i = 0, taken = 0; i < pdf_array_len(ctx, kids); i++)
taken |= !strcmp(pdf_to_name(ctx, pdf_button_field_on_state(ctx, pdf_array_get(ctx, kids, i))), name);
if (!taken)
return pdf_new_name(ctx, name);
}
}
/* Adds a field of four kinds, in one step. */
int ely_add_field(fz_context *ctx, fz_document *doc, int number, const char *json)
{
pdf_document *pdf = NULL;
pdf_page *page = NULL;
pdf_annot *widget = NULL;
pdf_obj *state = NULL;
fz_pool *pool = NULL;
int begun = 0;
fz_var(pdf);
fz_var(page);
fz_var(widget);
fz_var(state);
fz_var(pool);
fz_var(begun);
fz_try(ctx)
{
fz_json *spec, *options, *kindj, *namej;
const char *kind, *name;
pdf_obj *fields, *group, *obj, *mk;
fz_rect rect;
pdf = ely_pdf_of(ctx, doc);
page = pdf_load_page(ctx, pdf, number);
pool = fz_new_pool(ctx);
spec = fz_parse_json(ctx, pool, json);
kindj = ely_member(ctx, spec, "kind", FZ_JSON_STRING);
namej = ely_member(ctx, spec, "name", FZ_JSON_STRING);
options = ely_member(ctx, spec, "options", FZ_JSON_ARRAY);
if (!kindj || !namej)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a field with no kind or name");
kind = kindj->u.string, name = namej->u.string;
if (strcmp(kind, "text") && strcmp(kind, "checkbox") && strcmp(kind, "radio") && strcmp(kind, "choice"))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "no field kind %s", kind);
if (!strcmp(kind, "choice"))
check_options(ctx, options);
rect = ely_rect(ctx, ely_member(ctx, spec, "rect", FZ_JSON_ARRAY), 4);
group = check_name(ctx, pdf_dict_getp(ctx, pdf_trailer(ctx, pdf), "Root/AcroForm/Fields"), "", name, kind, NULL);
pdf_begin_operation(ctx, pdf, "Add a field");
begun = 1;
fields = fields_of(ctx, pdf);
widget = pdf_create_annot_raw(ctx, page, PDF_ANNOT_WIDGET);
obj = pdf_annot_obj(ctx, widget);
pdf_dict_put(ctx, obj, PDF_NAME(P), page->obj);
pdf_dict_put_int(ctx, obj, PDF_NAME(F), PDF_ANNOT_IS_PRINT);
pdf_dict_put_rect(ctx, obj, PDF_NAME(Rect), fz_transform_rect(rect, ely_to_user(ctx, page)));
pdf_dict_put_text_string(ctx, obj, PDF_NAME(DA), "/Helv 0 Tf 0 g");
mk = pdf_dict_put_dict(ctx, obj, PDF_NAME(MK), 1);
pdf_array_push_real(ctx, pdf_dict_put_array(ctx, mk, PDF_NAME(BC), 1), 0);
if (!strcmp(kind, "radio"))
{
if (!group)
{
group = pdf_add_new_dict(ctx, pdf, 4);
pdf_dict_put(ctx, group, PDF_NAME(FT), PDF_NAME(Btn));
pdf_dict_put_int(ctx, group, PDF_NAME(Ff), PDF_BTN_FIELD_IS_RADIO | PDF_BTN_FIELD_IS_NO_TOGGLE_TO_OFF);
pdf_dict_put_text_string(ctx, group, PDF_NAME(T), name);
pdf_dict_put(ctx, group, PDF_NAME(V), PDF_NAME(Off));
pdf_dict_put_array(ctx, group, PDF_NAME(Kids), 2);
pdf_array_push_drop(ctx, fields, group);
}
state = new_state(ctx, group);
pdf_dict_put(ctx, obj, PDF_NAME(Parent), group);
pdf_array_push(ctx, pdf_dict_get(ctx, group, PDF_NAME(Kids)), obj);
}
else
{
pdf_dict_put_text_string(ctx, obj, PDF_NAME(T), name);
pdf_array_push(ctx, fields, obj);
}
if (!strcmp(kind, "text"))
pdf_dict_put(ctx, obj, PDF_NAME(FT), PDF_NAME(Tx));
else if (!strcmp(kind, "choice"))
{
pdf_dict_put(ctx, obj, PDF_NAME(FT), PDF_NAME(Ch));
pdf_dict_put_int(ctx, obj, PDF_NAME(Ff), PDF_CH_FIELD_IS_COMBO);
put_options(ctx, obj, options);
}
else if (!strcmp(kind, "checkbox"))
{
pdf_dict_put(ctx, obj, PDF_NAME(FT), PDF_NAME(Btn));
pdf_dict_put(ctx, obj, PDF_NAME(V), PDF_NAME(Off));
state = pdf_new_name(ctx, "Yes");
}
/* The on look is drawn under its own state. */
if (state)
pdf_dict_put(ctx, obj, PDF_NAME(AS), state);
pdf_annot_request_resynthesis(ctx, widget);
pdf_update_annot(ctx, widget);
if (state)
pdf_dict_put(ctx, obj, PDF_NAME(AS), PDF_NAME(Off));
pdf_end_operation(ctx, pdf);
}
fz_always(ctx)
{
fz_drop_pool(ctx, pool);
pdf_drop_obj(ctx, state);
pdf_drop_annot(ctx, widget);
fz_drop_page(ctx, (fz_page *)page);
}
fz_catch(ctx)
return ely_edit_failed(ctx, pdf, begun);
return 0;
}
/* Renames a field or sets its options. */
int ely_change_field(fz_context *ctx, fz_document *doc, int number, int id, const char *json)
{
pdf_document *pdf = NULL;
pdf_page *page = NULL;
fz_pool *pool = NULL;
char *path = NULL;
int begun = 0;
fz_var(pdf);
fz_var(page);
fz_var(pool);
fz_var(path);
fz_var(begun);
fz_try(ctx)
{
pdf_annot *widget;
pdf_obj *obj, *head;
fz_json *spec, *name, *options;
enum pdf_widget_type type;
pdf = ely_pdf_of(ctx, doc);
page = pdf_load_page(ctx, pdf, number);
widget = ely_find_annot(ctx, page, id, 1);
obj = pdf_annot_obj(ctx, widget);
head = head_of(ctx, obj);
type = pdf_widget_type(ctx, widget);
pool = fz_new_pool(ctx);
spec = fz_parse_json(ctx, pool, json);
name = ely_member(ctx, spec, "name", FZ_JSON_STRING);
options = ely_member(ctx, spec, "options", FZ_JSON_ARRAY);
if (!name && !options)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "no change");
if (name)
{
path = parent_path(ctx, head);
check_name(ctx, pdf_dict_getp(ctx, pdf_trailer(ctx, pdf), "Root/AcroForm/Fields"), path, name->u.string, "", head);
}
if (options && type != PDF_WIDGET_TYPE_COMBOBOX && type != PDF_WIDGET_TYPE_LISTBOX)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "only a choice has options");
if (options)
check_options(ctx, options);
pdf_begin_operation(ctx, pdf, "Change a field");
begun = 1;
if (name)
pdf_dict_put_text_string(ctx, head, PDF_NAME(T), name->u.string);
if (options)
{
int i, kept = 0;
const char *value = pdf_to_text_string(ctx, pdf_dict_get_inheritable(ctx, obj, PDF_NAME(V)));
for (i = 0; i < fz_json_array_length(ctx, options); i++)
kept |= !strcmp(fz_json_array_get(ctx, options, i)->u.string, value);
if (obj != head)
pdf_dict_del(ctx, obj, PDF_NAME(Opt));
put_options(ctx, head, options);
if (!kept)
pdf_dict_del(ctx, head, PDF_NAME(V));
}
pdf_annot_request_resynthesis(ctx, widget);
pdf_update_annot(ctx, widget);
pdf_end_operation(ctx, pdf);
}
fz_always(ctx)
{
fz_drop_pool(ctx, pool);
fz_free(ctx, path);
fz_drop_page(ctx, (fz_page *)page);
}
fz_catch(ctx)
return ely_edit_failed(ctx, pdf, begun);
return 0;
}
/* Writes each named node under `kids`, with its full name. */
static void write_names(fz_context *ctx, fz_output *out, pdf_obj *kids, const char *prefix, int depth, int *first)
{
int i;
if (depth > 32)
fz_throw(ctx, FZ_ERROR_FORMAT, "a field tree too deep");
for (i = 0; i < pdf_array_len(ctx, kids); i++)
{
pdf_obj *node = pdf_array_get(ctx, kids, i);
pdf_obj *t = pdf_dict_get(ctx, node, PDF_NAME(T));
char *name = NULL;
fz_var(name);
fz_try(ctx)
{
name = t ? fz_asprintf(ctx, "%s%s%s", prefix, prefix[0] ? "." : "", pdf_to_text_string(ctx, t)) : fz_strdup(ctx, prefix);
if (t)
{
fz_write_string(ctx, out, *first ? "" : ",");
ely_json_string(ctx, out, name);
*first = 0;
}
write_names(ctx, out, pdf_dict_get(ctx, node, PDF_NAME(Kids)), name, depth + 1, first);
}
fz_always(ctx)
fz_free(ctx, name);
fz_catch(ctx)
fz_rethrow(ctx);
}
}
/* Every field name in the form, widgets or not. */
int ely_field_names(fz_context *ctx, fz_document *doc, unsigned char **data, size_t *len)
{
fz_buffer *buf = NULL;
fz_output *out = NULL;
fz_var(buf);
fz_var(out);
fz_try(ctx)
{
int first = 1;
pdf_document *pdf = ely_pdf_of(ctx, doc);
buf = fz_new_buffer(ctx, 256);
out = fz_new_output_with_buffer(ctx, buf);
fz_write_byte(ctx, out, '[');
write_names(ctx, out, pdf_dict_getp(ctx, pdf_trailer(ctx, pdf), "Root/AcroForm/Fields"), "", 0, &first);
fz_write_byte(ctx, out, ']');
fz_close_output(ctx, out);
*len = fz_buffer_extract(ctx, buf, data);
}
fz_always(ctx)
{
fz_drop_output(ctx, out);
fz_drop_buffer(ctx, buf);
}
fz_catch(ctx)
return ely_fail(ctx);
return 0;
}
+364
View File
@@ -0,0 +1,364 @@
/* Pages from another PDF, with their links, notes and fields. */
#include <stdio.h>
#include <string.h>
#include "ely_shim.h"
/* A source link to its own page `page`. */
typedef struct
{
pdf_obj *annot;
pdf_obj *rest;
int page;
} inner_link;
/* Takes page references off the source's annotations, links noted. */
static int unhook(fz_context *ctx, pdf_document *src, inner_link *links, int room)
{
int i, j, n = 0, count = pdf_count_pages(ctx, src);
for (i = 0; i < count; i++)
{
pdf_obj *annots = pdf_dict_get(ctx, pdf_lookup_page_obj(ctx, src, i), PDF_NAME(Annots));
for (j = 0; j < pdf_array_len(ctx, annots); j++)
{
pdf_obj *annot = pdf_array_get(ctx, annots, j);
pdf_obj *page = ely_target(ctx, src, annot);
int to = page ? pdf_lookup_page_number(ctx, src, page) : -1;
pdf_dict_del(ctx, annot, PDF_NAME(P));
if (to < 0 || n == room)
continue;
/* The view after the page: /XYZ, /Fit and so on. */
pdf_obj *dest = pdf_dict_get(ctx, annot, PDF_NAME(Dest));
if (!dest)
dest = pdf_dict_getp(ctx, annot, "A/D");
if (pdf_is_name(ctx, dest) || pdf_is_string(ctx, dest))
dest = pdf_lookup_dest(ctx, src, dest);
if (pdf_is_dict(ctx, dest))
dest = pdf_dict_get(ctx, dest, PDF_NAME(D));
links[n].annot = pdf_keep_obj(ctx, annot);
links[n].rest = pdf_copy_array(ctx, dest);
pdf_array_delete(ctx, links[n].rest, 0);
links[n].page = to;
n++;
pdf_dict_del(ctx, annot, PDF_NAME(Dest));
pdf_dict_del(ctx, annot, PDF_NAME(A));
}
}
return n;
}
/* The top of the field tree `widget` belongs to. */
static pdf_obj *root_field(fz_context *ctx, pdf_obj *widget)
{
pdf_obj *parent;
while ((parent = pdf_dict_get(ctx, widget, PDF_NAME(Parent))) != NULL)
widget = parent;
return widget;
}
/* The source form's default look and its font renames. */
typedef struct
{
pdf_obj *da;
pdf_obj *q;
pdf_obj *renames;
} form_look;
static int hex(int c)
{
return c >= '0' && c <= '9' ? c - '0' : (c | 32) >= 'a' && (c | 32) <= 'f' ? (c | 32) - 'a' + 10 : -1;
}
/* A name token's bytes, #xx escapes decoded. */
static void decode_name(const char *token, size_t len, char *out)
{
size_t i, k = 0;
for (i = 0; i < len; i++)
{
if (token[i] == '#' && i + 2 < len && hex(token[i + 1]) >= 0 && hex(token[i + 2]) >= 0)
{
out[k++] = (char)(hex(token[i + 1]) * 16 + hex(token[i + 2]));
i += 2;
}
else
out[k++] = token[i];
}
out[k] = 0;
}
/* Writes `name` as a name token, odd bytes escaped. */
static void encode_name(fz_context *ctx, fz_buffer *buf, const char *name)
{
const unsigned char *c;
fz_append_byte(ctx, buf, '/');
for (c = (const unsigned char *)name; *c; c++)
if (*c < 0x21 || *c > 0x7e || strchr("#/[]()<>{}%", *c))
fz_append_printf(ctx, buf, "#%02X", *c);
else
fz_append_byte(ctx, buf, *c);
}
/* `name`, or `name` and `n` when n is above one. */
static char *candidate(fz_context *ctx, const char *name, const char *gap, int n)
{
return n == 1 ? fz_strdup(ctx, name) : fz_asprintf(ctx, "%s%s%d", name, gap, n);
}
/* Merges the source's form fonts; taken names get numbered. */
static void merge_fonts(fz_context *ctx, pdf_document *pdf, pdf_graft_map *map, pdf_document *src, form_look *look)
{
pdf_obj *from = pdf_dict_getp(ctx, pdf_trailer(ctx, src), "Root/AcroForm/DR/Font");
pdf_obj *to, *font = NULL;
char *fresh = NULL;
int i, n;
fz_var(font);
fz_var(fresh);
if (!from)
return;
to = pdf_dict_getp(ctx, pdf_trailer(ctx, pdf), "Root/AcroForm/DR/Font");
if (!to)
{
to = pdf_new_dict(ctx, pdf, 4);
pdf_dict_putp_drop(ctx, pdf_trailer(ctx, pdf), "Root/AcroForm/DR/Font", to);
}
fz_try(ctx)
for (i = 0; i < pdf_dict_len(ctx, from); i++)
{
const char *name = pdf_to_name(ctx, pdf_dict_get_key(ctx, from, i));
font = pdf_graft_mapped_object(ctx, map, pdf_dict_get_val(ctx, from, i));
for (n = 1;; n++)
{
pdf_obj *held;
fz_free(ctx, fresh);
fresh = candidate(ctx, name, "_", n);
held = pdf_dict_gets(ctx, to, fresh);
if (!held)
pdf_dict_puts(ctx, to, fresh, font);
if (!held || (pdf_is_indirect(ctx, held) && pdf_to_num(ctx, held) == pdf_to_num(ctx, font)))
break;
}
if (n > 1)
pdf_dict_puts_drop(ctx, look->renames, name, pdf_new_name(ctx, fresh));
pdf_drop_obj(ctx, font);
font = NULL;
}
fz_always(ctx)
{
pdf_drop_obj(ctx, font);
fz_free(ctx, fresh);
}
fz_catch(ctx)
fz_rethrow(ctx);
}
/* `node`'s /DA with renamed fonts renamed. */
static void rename_fonts(fz_context *ctx, pdf_obj *node, pdf_obj *renames)
{
const char *da = pdf_dict_get_text_string(ctx, node, PDF_NAME(DA));
fz_buffer *buf = NULL;
char *name = NULL;
fz_var(buf);
fz_var(name);
if (!*da || !pdf_dict_len(ctx, renames))
return;
fz_try(ctx)
{
unsigned char *data;
size_t len;
buf = fz_new_buffer(ctx, 64);
while (*da)
{
size_t word = 1;
pdf_obj *to;
if (*da != '/')
{
fz_append_byte(ctx, buf, *da++);
continue;
}
while (da[word] && !strchr(" \t\r\n\f/[]()<>{}%", da[word]))
word++;
fz_free(ctx, name);
name = fz_malloc(ctx, word);
decode_name(da + 1, word - 1, name);
to = pdf_dict_gets(ctx, renames, name);
if (to)
encode_name(ctx, buf, pdf_to_name(ctx, to));
else
fz_append_data(ctx, buf, da, word);
da += word;
}
len = fz_buffer_storage(ctx, buf, &data);
pdf_dict_put_string(ctx, node, PDF_NAME(DA), (const char *)data, len);
}
fz_always(ctx)
{
fz_drop_buffer(ctx, buf);
fz_free(ctx, name);
}
fz_catch(ctx)
fz_rethrow(ctx);
}
/* Gives a field tree the source's look, fonts renamed. */
static void restyle(fz_context *ctx, pdf_obj *node, form_look *look, int root)
{
pdf_obj *kids = pdf_dict_get(ctx, node, PDF_NAME(Kids));
int i;
/* The form's defaults a field inherits: look and alignment. */
if (root && look->da && !pdf_dict_get(ctx, node, PDF_NAME(DA)))
pdf_dict_put(ctx, node, PDF_NAME(DA), look->da);
if (root && look->q && !pdf_dict_get(ctx, node, PDF_NAME(Q)))
pdf_dict_put(ctx, node, PDF_NAME(Q), look->q);
rename_fonts(ctx, node, look->renames);
for (i = 0; i < pdf_array_len(ctx, kids); i++)
restyle(ctx, pdf_array_get(ctx, kids, i), look, 0);
}
/* Joins `field` to the form; a taken name gets numbered. */
static void add_field(fz_context *ctx, pdf_document *pdf, pdf_obj *field, form_look *look)
{
pdf_obj *fields = pdf_dict_getp(ctx, pdf_trailer(ctx, pdf), "Root/AcroForm/Fields");
const char *name = pdf_dict_get_text_string(ctx, field, PDF_NAME(T));
char *renamed = NULL;
int i, n, taken;
fz_var(renamed);
if (!fields)
{
fields = pdf_new_array(ctx, pdf, 1);
pdf_dict_putp_drop(ctx, pdf_trailer(ctx, pdf), "Root/AcroForm/Fields", fields);
}
for (i = 0; i < pdf_array_len(ctx, fields); i++)
if (pdf_to_num(ctx, pdf_array_get(ctx, fields, i)) == pdf_to_num(ctx, field))
return;
fz_try(ctx)
{
for (n = 1, taken = 1; taken; n++)
{
fz_free(ctx, renamed);
renamed = candidate(ctx, name, " ", n);
for (taken = 0, i = 0; i < pdf_array_len(ctx, fields) && !taken; i++)
taken = !strcmp(pdf_dict_get_text_string(ctx, pdf_array_get(ctx, fields, i), PDF_NAME(T)), renamed);
}
if (strcmp(renamed, name))
pdf_dict_put_text_string(ctx, field, PDF_NAME(T), renamed);
restyle(ctx, field, look, 1);
pdf_array_push(ctx, fields, field);
}
fz_always(ctx)
fz_free(ctx, renamed);
fz_catch(ctx)
fz_rethrow(ctx);
}
/* Grafts each page's annotations and reconnects them. */
static void reconnect(fz_context *ctx, pdf_document *pdf, pdf_graft_map *map, pdf_document *src, int at, form_look *look)
{
int i, j, count = pdf_count_pages(ctx, src);
for (i = 0; i < count; i++)
{
pdf_obj *annots = pdf_dict_get(ctx, pdf_lookup_page_obj(ctx, src, i), PDF_NAME(Annots));
pdf_obj *page = pdf_lookup_page_obj(ctx, pdf, at + i);
pdf_obj *grafted;
if (!annots)
continue;
grafted = pdf_graft_mapped_object(ctx, map, annots);
pdf_dict_put_drop(ctx, page, PDF_NAME(Annots), grafted);
for (j = 0; j < pdf_array_len(ctx, grafted); j++)
{
pdf_obj *annot = pdf_array_get(ctx, grafted, j);
pdf_dict_put(ctx, annot, PDF_NAME(P), page);
if (pdf_name_eq(ctx, pdf_dict_get(ctx, annot, PDF_NAME(Subtype)), PDF_NAME(Widget)))
add_field(ctx, pdf, root_field(ctx, annot), look);
}
}
}
/* Annotations and form look come over; inner links point home. */
static void graft_annots(fz_context *ctx, pdf_document *pdf, pdf_graft_map *map, pdf_document *src, int at,
inner_link *links, int n)
{
form_look look = { NULL, NULL, NULL };
pdf_obj *da = pdf_dict_getp(ctx, pdf_trailer(ctx, src), "Root/AcroForm/DA");
pdf_obj *q = pdf_dict_getp(ctx, pdf_trailer(ctx, src), "Root/AcroForm/Q");
int i, j;
fz_var(look.da);
fz_var(look.renames);
fz_var(look.q);
fz_try(ctx)
{
look.renames = pdf_new_dict(ctx, pdf, 1);
look.da = da ? pdf_graft_mapped_object(ctx, map, da) : NULL;
look.q = q ? pdf_graft_mapped_object(ctx, map, q) : NULL;
merge_fonts(ctx, pdf, map, src, &look);
reconnect(ctx, pdf, map, src, at, &look);
}
fz_always(ctx)
{
pdf_drop_obj(ctx, look.renames);
pdf_drop_obj(ctx, look.da);
pdf_drop_obj(ctx, look.q);
}
fz_catch(ctx)
fz_rethrow(ctx);
for (i = 0; i < n; i++)
{
pdf_obj *annot = pdf_graft_mapped_object(ctx, map, links[i].annot);
pdf_obj *dest = pdf_new_array(ctx, pdf, 1 + pdf_array_len(ctx, links[i].rest));
pdf_array_push(ctx, dest, pdf_lookup_page_obj(ctx, pdf, at + links[i].page));
for (j = 0; j < pdf_array_len(ctx, links[i].rest); j++)
pdf_array_push(ctx, dest, pdf_array_get(ctx, links[i].rest, j));
pdf_dict_put_drop(ctx, annot, PDF_NAME(Dest), dest);
pdf_drop_obj(ctx, annot);
}
}
/* Every page of the PDF at `path`, inserted at `at`. */
int ely_insert_file(fz_context *ctx, fz_document *doc, int at, const char *path, int *count)
{
pdf_document *pdf = NULL, *src = NULL;
pdf_graft_map *map = NULL;
inner_link *links = NULL;
int begun = 0, i, n = 0, room = 0;
fz_var(pdf);
fz_var(src);
fz_var(map);
fz_var(links);
fz_var(n);
fz_var(begun);
fz_try(ctx)
{
pdf = ely_pdf_of(ctx, doc);
if (at < 0 || at > pdf_count_pages(ctx, pdf))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "no place %d to insert at", at);
src = pdf_open_document(ctx, path);
if (pdf_needs_password(ctx, src))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "the file to insert is locked");
*count = pdf_count_pages(ctx, src);
for (i = 0; i < *count; i++)
room += pdf_array_len(ctx, pdf_dict_get(ctx, pdf_lookup_page_obj(ctx, src, i), PDF_NAME(Annots)));
links = fz_calloc(ctx, room + 1, sizeof *links);
n = unhook(ctx, src, links, room);
map = pdf_new_graft_map(ctx, pdf);
pdf_begin_operation(ctx, pdf, "Insert pages");
begun = 1;
for (i = 0; i < *count; i++)
pdf_graft_mapped_page(ctx, map, at + i, src, i);
graft_annots(ctx, pdf, map, src, at, links, n);
pdf_end_operation(ctx, pdf);
}
fz_always(ctx)
{
for (i = 0; links && i < n; i++)
{
pdf_drop_obj(ctx, links[i].annot);
pdf_drop_obj(ctx, links[i].rest);
}
fz_free(ctx, links);
pdf_drop_graft_map(ctx, map);
pdf_drop_document(ctx, src);
}
fz_catch(ctx)
return ely_edit_failed(ctx, pdf, begun);
return 0;
}
+389
View File
@@ -0,0 +1,389 @@
/* Document properties and attachments (PDF-07). */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ely_shim.h"
static const char *shown[] = { "Title", "Author", "Subject", "Keywords", "Creator", "Producer", "CreationDate",
"ModDate", NULL };
/* Only these change; the rest the producer wrote. */
static const char *editable[] = { "Title", "Author", "Subject", "Keywords", NULL };
/* Properties as JSON; null when the file has none. */
int ely_metadata(fz_context *ctx, fz_document *doc, unsigned char **data, size_t *len)
{
fz_buffer *buf = NULL;
fz_output *out = NULL;
char *value = NULL;
fz_var(buf);
fz_var(out);
fz_var(value);
fz_try(ctx)
{
char key[32];
int i, n;
buf = fz_new_buffer(ctx, 256);
out = fz_new_output_with_buffer(ctx, buf);
fz_write_byte(ctx, out, '{');
for (i = 0; shown[i]; i++)
{
fz_snprintf(key, sizeof key, "info:%s", shown[i]);
fz_write_printf(ctx, out, "%s\"%s\":", i ? "," : "", shown[i]);
n = fz_lookup_metadata(ctx, doc, key, NULL, 0);
if (n < 0)
{
fz_write_string(ctx, out, "null");
continue;
}
fz_free(ctx, value);
value = NULL;
value = fz_malloc(ctx, n);
fz_lookup_metadata(ctx, doc, key, value, n);
ely_json_string(ctx, out, value);
}
fz_write_byte(ctx, out, '}');
fz_close_output(ctx, out);
*len = fz_buffer_extract(ctx, buf, data);
}
fz_always(ctx)
{
fz_free(ctx, value);
fz_drop_output(ctx, out);
fz_drop_buffer(ctx, buf);
}
fz_catch(ctx)
return ely_fail(ctx);
return 0;
}
/* Sets the given properties, in one step. */
int ely_set_metadata(fz_context *ctx, fz_document *doc, const char *json)
{
pdf_document *pdf = NULL;
fz_pool *pool = NULL;
int begun = 0;
fz_var(pdf);
fz_var(pool);
fz_var(begun);
fz_try(ctx)
{
fz_json *spec;
fz_json_object *field;
char key[32];
int i;
pdf = ely_pdf_of(ctx, doc);
pool = fz_new_pool(ctx);
spec = fz_parse_json(ctx, pool, json);
if (spec->type != FZ_JSON_OBJECT || !spec->u.object)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "no properties to set");
for (field = spec->u.object; field; field = field->next)
{
for (i = 0; editable[i] && strcmp(editable[i], field->key); i++)
continue;
if (!editable[i] || field->value->type != FZ_JSON_STRING)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a property that does not change: %s", field->key);
}
pdf_begin_operation(ctx, pdf, "Set properties");
begun = 1;
for (field = spec->u.object; field; field = field->next)
{
fz_snprintf(key, sizeof key, "info:%s", field->key);
fz_set_metadata(ctx, doc, key, field->value->u.string);
}
pdf_end_operation(ctx, pdf);
}
fz_always(ctx)
fz_drop_pool(ctx, pool);
fz_catch(ctx)
return ely_edit_failed(ctx, pdf, begun);
return 0;
}
static int by_name(const void *a, const void *b)
{
return strcmp(*(const char *const *)a, *(const char *const *)b);
}
/* The embedded files, by name; NULL names end it. */
static const char **names_of(fz_context *ctx, pdf_obj *tree, int *count)
{
const char **names;
int i, n = pdf_dict_len(ctx, tree);
names = fz_malloc_array(ctx, n + 1, const char *);
for (i = 0; i < n; i++)
names[i] = pdf_to_name(ctx, pdf_dict_get_key(ctx, tree, i));
names[n] = NULL;
qsort(names, n, sizeof *names, by_name);
*count = n;
return names;
}
/* An embedded file's length: its /Size, else its bytes. */
static int64_t file_size(fz_context *ctx, pdf_obj *fs)
{
pdf_obj *ef = pdf_dict_get(ctx, fs, PDF_NAME(EF));
pdf_obj *file = pdf_dict_get(ctx, ef, PDF_NAME(F)) ? pdf_dict_get(ctx, ef, PDF_NAME(F)) : pdf_dict_get(ctx, ef, PDF_NAME(UF));
pdf_obj *size = pdf_dict_getl(ctx, file, PDF_NAME(Params), PDF_NAME(Size), NULL);
fz_buffer *bytes;
int64_t n;
if (pdf_is_int(ctx, size))
return pdf_to_int64(ctx, size);
bytes = pdf_load_embedded_file_contents(ctx, fs);
n = (int64_t)fz_buffer_storage(ctx, bytes, NULL);
fz_drop_buffer(ctx, bytes);
return n;
}
static void write_file(fz_context *ctx, fz_output *out, const char *key, const char *name, int page, pdf_obj *fs, int *first)
{
pdf_filespec_params params;
pdf_get_filespec_params(ctx, fs, &params);
fz_write_string(ctx, out, *first ? "{\"key\":" : ",{\"key\":");
*first = 0;
ely_json_string(ctx, out, key);
fz_write_string(ctx, out, ",\"name\":");
ely_json_string(ctx, out, name);
fz_write_printf(ctx, out, ",\"page\":%d,\"size\":%ld,\"created\":%ld,\"modified\":%ld,\"type\":", page,
(long)file_size(ctx, fs), (long)params.created, (long)params.modified);
ely_json_string(ctx, out, params.mimetype ? params.mimetype : "");
fz_write_string(ctx, out, ",\"note\":");
ely_json_string(ctx, out, pdf_dict_get_text_string(ctx, fs, PDF_NAME(Desc)));
fz_write_byte(ctx, out, '}');
}
/* The page's file annotations, as attachments. */
static void write_page_files(fz_context *ctx, fz_output *out, pdf_document *pdf, int number, int *first)
{
pdf_page *page = pdf_load_page(ctx, pdf, number);
char key[48];
fz_try(ctx)
{
pdf_annot *annot;
for (annot = pdf_first_annot(ctx, page); annot; annot = pdf_next_annot(ctx, annot))
{
pdf_obj *fs;
pdf_filespec_params params;
if (pdf_annot_type(ctx, annot) != PDF_ANNOT_FILE_ATTACHMENT)
continue;
fs = pdf_annot_filespec(ctx, annot);
if (!pdf_is_embedded_file(ctx, fs))
continue;
pdf_get_filespec_params(ctx, fs, &params);
fz_snprintf(key, sizeof key, "a:%d:%d", number, pdf_to_num(ctx, pdf_annot_obj(ctx, annot)));
write_file(ctx, out, key, params.filename ? params.filename : "", number, fs, first);
}
}
fz_always(ctx)
fz_drop_page(ctx, (fz_page *)page);
fz_catch(ctx)
fz_rethrow(ctx);
}
/* Every embedded file: the tree's by name, then pages'. */
int ely_attachments(fz_context *ctx, fz_document *doc, unsigned char **data, size_t *len)
{
pdf_obj *tree = NULL;
const char **names = NULL;
fz_buffer *buf = NULL;
fz_output *out = NULL;
char *key = NULL;
fz_var(tree);
fz_var(names);
fz_var(buf);
fz_var(out);
fz_var(key);
fz_try(ctx)
{
pdf_document *pdf = ely_pdf_of(ctx, doc);
int i, n, first = 1;
tree = pdf_load_name_tree(ctx, pdf, PDF_NAME(EmbeddedFiles));
names = names_of(ctx, tree, &n);
buf = fz_new_buffer(ctx, 256);
out = fz_new_output_with_buffer(ctx, buf);
fz_write_byte(ctx, out, '[');
for (i = 0; i < n; i++)
{
pdf_obj *fs = pdf_dict_gets(ctx, tree, names[i]);
if (!pdf_is_embedded_file(ctx, fs))
continue;
fz_free(ctx, key);
key = NULL;
key = fz_asprintf(ctx, "n:%s", names[i]);
write_file(ctx, out, key, names[i], -1, fs, &first);
}
for (i = 0; i < pdf_count_pages(ctx, pdf); i++)
write_page_files(ctx, out, pdf, i, &first);
fz_write_byte(ctx, out, ']');
fz_close_output(ctx, out);
*len = fz_buffer_extract(ctx, buf, data);
}
fz_always(ctx)
{
fz_free(ctx, key);
fz_drop_output(ctx, out);
fz_drop_buffer(ctx, buf);
fz_free(ctx, names);
pdf_drop_obj(ctx, tree);
}
fz_catch(ctx)
return ely_fail(ctx);
return 0;
}
/* The file `key` names; a page annotation's loads its page. */
static pdf_obj *file_of(fz_context *ctx, pdf_document *pdf, const char *key, pdf_obj *tree, pdf_page **page, pdf_annot **annot)
{
pdf_obj *fs = NULL;
int number, id;
if (!strncmp(key, "n:", 2))
fs = pdf_dict_gets(ctx, tree, key + 2);
else if (sscanf(key, "a:%d:%d", &number, &id) == 2 && number >= 0 && number < pdf_count_pages(ctx, pdf))
{
*page = pdf_load_page(ctx, pdf, number);
*annot = ely_find_annot(ctx, *page, id, 0);
if (pdf_annot_type(ctx, *annot) == PDF_ANNOT_FILE_ATTACHMENT)
fs = pdf_annot_filespec(ctx, *annot);
}
if (!pdf_is_embedded_file(ctx, fs))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "no attachment %s", key);
return fs;
}
/* An embedded file's bytes. */
int ely_attachment(fz_context *ctx, fz_document *doc, const char *key, unsigned char **data, size_t *len)
{
pdf_obj *tree = NULL;
pdf_page *page = NULL;
fz_buffer *buf = NULL;
fz_var(tree);
fz_var(page);
fz_var(buf);
fz_try(ctx)
{
pdf_document *pdf = ely_pdf_of(ctx, doc);
pdf_annot *annot = NULL;
tree = pdf_load_name_tree(ctx, pdf, PDF_NAME(EmbeddedFiles));
unsigned char *bytes;
buf = pdf_load_embedded_file_contents(ctx, file_of(ctx, pdf, key, tree, &page, &annot));
/* A copy: the document may hold this buffer. */
*len = fz_buffer_storage(ctx, buf, &bytes);
*data = fz_malloc(ctx, *len ? *len : 1);
memcpy(*data, bytes, *len);
}
fz_always(ctx)
{
fz_drop_buffer(ctx, buf);
fz_drop_page(ctx, (fz_page *)page);
pdf_drop_obj(ctx, tree);
}
fz_catch(ctx)
return ely_fail(ctx);
return 0;
}
/* Writes `tree` back flat, its names in order. */
static void put_tree(fz_context *ctx, pdf_document *pdf, pdf_obj *tree)
{
pdf_obj *root = pdf_dict_get(ctx, pdf_trailer(ctx, pdf), PDF_NAME(Root));
pdf_obj *names = pdf_dict_get(ctx, root, PDF_NAME(Names)), *list;
const char **sorted = NULL;
int i, n;
fz_var(sorted);
if (!names)
names = pdf_dict_put_dict(ctx, root, PDF_NAME(Names), 1);
list = pdf_dict_put_array(ctx, pdf_dict_put_dict(ctx, names, PDF_NAME(EmbeddedFiles), 1), PDF_NAME(Names), 8);
fz_try(ctx)
{
sorted = names_of(ctx, tree, &n);
for (i = 0; i < n; i++)
{
pdf_array_push_text_string(ctx, list, sorted[i]);
pdf_array_push(ctx, list, pdf_dict_gets(ctx, tree, sorted[i]));
}
}
fz_always(ctx)
fz_free(ctx, sorted);
fz_catch(ctx)
fz_rethrow(ctx);
}
/* Embeds the file at `path` as `name`, in one step. */
int ely_attach(fz_context *ctx, fz_document *doc, const char *name, const char *path)
{
pdf_document *pdf = NULL;
pdf_obj *tree = NULL, *fs = NULL;
fz_buffer *contents = NULL;
int begun = 0;
fz_var(pdf);
fz_var(tree);
fz_var(fs);
fz_var(contents);
fz_var(begun);
fz_try(ctx)
{
pdf = ely_pdf_of(ctx, doc);
if (!name[0])
fz_throw(ctx, FZ_ERROR_ARGUMENT, "an attachment with no name");
tree = pdf_load_name_tree(ctx, pdf, PDF_NAME(EmbeddedFiles));
if (!tree)
tree = pdf_new_dict(ctx, pdf, 1);
if (pdf_dict_gets(ctx, tree, name))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "an attachment named %s exists", name);
contents = fz_read_file(ctx, path);
pdf_begin_operation(ctx, pdf, "Attach a file");
begun = 1;
fs = pdf_add_embedded_file(ctx, pdf, name, NULL, contents, -1, -1, 1);
pdf_dict_puts(ctx, tree, name, fs);
put_tree(ctx, pdf, tree);
pdf_end_operation(ctx, pdf);
}
fz_always(ctx)
{
pdf_drop_obj(ctx, fs);
fz_drop_buffer(ctx, contents);
pdf_drop_obj(ctx, tree);
}
fz_catch(ctx)
return ely_edit_failed(ctx, pdf, begun);
return 0;
}
/* Removes the file `key`: a tree entry or its annotation. */
int ely_detach(fz_context *ctx, fz_document *doc, const char *key)
{
pdf_document *pdf = NULL;
pdf_obj *tree = NULL;
pdf_page *page = NULL;
int begun = 0;
fz_var(pdf);
fz_var(tree);
fz_var(page);
fz_var(begun);
fz_try(ctx)
{
pdf_annot *annot = NULL;
pdf = ely_pdf_of(ctx, doc);
tree = pdf_load_name_tree(ctx, pdf, PDF_NAME(EmbeddedFiles));
file_of(ctx, pdf, key, tree, &page, &annot);
pdf_begin_operation(ctx, pdf, "Remove an attachment");
begun = 1;
if (annot)
pdf_delete_annot(ctx, page, annot);
else
{
pdf_dict_dels(ctx, tree, key + 2);
put_tree(ctx, pdf, tree);
}
pdf_end_operation(ctx, pdf);
}
fz_always(ctx)
{
fz_drop_page(ctx, (fz_page *)page);
pdf_drop_obj(ctx, tree);
}
fz_catch(ctx)
return ely_edit_failed(ctx, pdf, begun);
return 0;
}
+392
View File
@@ -0,0 +1,392 @@
/* MuPDF behind plain return codes: fz_try never crosses into Rust. */
#include <mupdf/fitz.h>
#include <mupdf/pdf.h>
#include <string.h>
static char last_error[512];
/* Takes the caught error to Rust; MuPDF counts it handled. */
int ely_fail(fz_context *ctx)
{
int code;
fz_strlcpy(last_error, fz_convert_error(ctx, &code), sizeof last_error);
return -1;
}
/* A second failure while handling the first. */
void ely_fail_also(fz_context *ctx, const char *what)
{
char also[256];
int code;
fz_snprintf(also, sizeof also, "; %s: %s", what, fz_convert_error(ctx, &code));
fz_strlcat(last_error, also, sizeof last_error);
}
const char *ely_error(void)
{
return last_error;
}
fz_context *ely_init(void)
{
fz_context *ctx = fz_new_context(NULL, NULL, FZ_STORE_DEFAULT);
if (!ctx)
{
fz_strlcpy(last_error, "no MuPDF context", sizeof last_error);
return NULL;
}
fz_try(ctx)
fz_register_document_handlers(ctx);
fz_catch(ctx)
{
ely_fail(ctx);
fz_drop_context(ctx);
return NULL;
}
return ctx;
}
/* What MuPDF warned while opening, for repair reports. */
static char warned[4096];
typedef struct
{
fz_warning_cb *next;
void *user;
} passing;
static void keep_warning(void *user, const char *message)
{
passing *p = user;
if (strlen(warned) + strlen(message) + 2 < sizeof warned)
{
fz_strlcat(warned, message, sizeof warned);
fz_strlcat(warned, "\n", sizeof warned);
}
if (p->next)
p->next(p->user, message);
}
static passing watching;
static int watched;
/* Collects MuPDF's warnings until `ely_watch_end`. */
void ely_watch_begin(fz_context *ctx)
{
watching.next = fz_warning_callback(ctx, &watching.user);
warned[0] = 0;
watched = 1;
fz_set_warning_callback(ctx, keep_warning, &watching);
}
/* 1 if MuPDF warned since `ely_watch_begin`. */
int ely_watch_end(fz_context *ctx)
{
if (!watched)
return 0;
fz_flush_warnings(ctx);
fz_set_warning_callback(ctx, watching.next, watching.user);
watched = 0;
return warned[0] != 0;
}
int ely_open(fz_context *ctx, const char *path, fz_document **out)
{
ely_watch_begin(ctx);
fz_try(ctx)
*out = fz_open_document(ctx, path);
fz_always(ctx)
ely_watch_end(ctx);
fz_catch(ctx)
return ely_fail(ctx);
return 0;
}
/* Reads every object and non-image stream; 1 if any warned. */
int ely_scan(fz_context *ctx, fz_document *doc)
{
pdf_document *pdf = pdf_document_from_fz_document(ctx, doc);
int i;
if (!pdf)
return 0;
ely_watch_begin(ctx);
for (i = 1; i < pdf_xref_len(ctx, pdf); i++)
{
pdf_obj *obj = NULL;
fz_buffer *bytes = NULL;
fz_var(obj);
fz_var(bytes);
fz_try(ctx)
{
obj = pdf_new_indirect(ctx, pdf, i, 0);
pdf_cache_object(ctx, pdf, i);
/* Pictures are checked as they draw, or before an overwrite. */
if (pdf_is_stream(ctx, obj) && !pdf_name_eq(ctx, pdf_dict_get(ctx, obj, PDF_NAME(Subtype)), PDF_NAME(Image)))
bytes = pdf_load_stream_number(ctx, pdf, i);
}
fz_always(ctx)
{
fz_drop_buffer(ctx, bytes);
pdf_drop_obj(ctx, obj);
}
fz_catch(ctx)
{
/* An unreadable object goes in the report. */
fz_warn(ctx, "object %d: %s", i, fz_caught_message(ctx));
fz_ignore_error(ctx);
}
}
return ely_watch_end(ctx);
}
/* The warnings of the last watch. */
const char *ely_open_warnings(void)
{
return warned;
}
void ely_close(fz_context *ctx, fz_document *doc)
{
fz_drop_document(ctx, doc);
}
/* 1 locked, 0 open, -1 an error. */
int ely_needs_password(fz_context *ctx, fz_document *doc)
{
int locked = 0;
fz_try(ctx)
locked = fz_needs_password(ctx, doc);
fz_catch(ctx)
return ely_fail(ctx);
return locked;
}
/* Access bits: 4 owner; 0 refused, -1 an error. */
int ely_authenticate(fz_context *ctx, fz_document *doc, const char *password)
{
int access = 0;
fz_try(ctx)
access = fz_authenticate_password(ctx, doc, password);
fz_catch(ctx)
return ely_fail(ctx);
return access;
}
int ely_count_pages(fz_context *ctx, fz_document *doc, int *out)
{
fz_try(ctx)
*out = fz_count_pages(ctx, doc);
fz_catch(ctx)
return ely_fail(ctx);
return 0;
}
int ely_page_bounds(fz_context *ctx, fz_document *doc, int number, float out[4])
{
fz_page *page = NULL;
fz_var(page);
fz_try(ctx)
{
page = fz_load_page(ctx, doc, number);
fz_rect box = fz_bound_page(ctx, page);
out[0] = box.x0; out[1] = box.y0; out[2] = box.x1; out[3] = box.y1;
}
fz_always(ctx)
fz_drop_page(ctx, page);
fz_catch(ctx)
return ely_fail(ctx);
return 0;
}
/* The page turned, scaled and moved to the origin. */
static fz_matrix placed(fz_rect box, float scale, int rotate)
{
fz_matrix ctm = fz_concat(fz_rotate(rotate), fz_scale(scale, scale));
fz_rect turned = fz_transform_rect(box, ctm);
return fz_concat(ctm, fz_translate(-turned.x0, -turned.y0));
}
/* Paints device pixels x, y, w, h as BGRA. */
int ely_render(fz_context *ctx, fz_document *doc, int number, float scale, int rotate,
const int tile[4], int dark, unsigned char *bgra)
{
fz_page *page = NULL;
fz_pixmap *pix = NULL;
fz_device *dev = NULL;
fz_var(page);
fz_var(pix);
fz_var(dev);
fz_try(ctx)
{
page = fz_load_page(ctx, doc, number);
fz_matrix ctm = placed(fz_bound_page(ctx, page), scale, rotate);
fz_irect area = fz_make_irect(tile[0], tile[1], tile[0] + tile[2], tile[1] + tile[3]);
pix = fz_new_pixmap_with_bbox(ctx, fz_device_bgr(ctx), area, NULL, 0);
fz_clear_pixmap_with_value(ctx, pix, 0xff);
dev = fz_new_draw_device(ctx, fz_identity, pix);
fz_run_page(ctx, page, dev, ctm, NULL);
fz_close_device(ctx, dev);
if (dark)
fz_invert_pixmap_luminance(ctx, pix);
int stride = (int)fz_pixmap_stride(ctx, pix);
unsigned char *rows = fz_pixmap_samples(ctx, pix);
for (int y = 0; y < tile[3]; y++)
for (int x = 0; x < tile[2]; x++)
{
const unsigned char *from = rows + y * stride + x * 3;
unsigned char *to = bgra + ((size_t)y * tile[2] + x) * 4;
to[0] = from[0]; to[1] = from[1]; to[2] = from[2]; to[3] = 0xff;
}
}
fz_always(ctx)
{
fz_drop_device(ctx, dev);
fz_drop_pixmap(ctx, pix);
fz_drop_page(ctx, page);
}
fz_catch(ctx)
return ely_fail(ctx);
return 0;
}
/* One character: line, code point, box in page points. */
typedef struct
{
int line;
int c;
float x0, y0, x1, y1;
} ely_char;
static void add_chars(fz_context *ctx, fz_buffer *buf, fz_stext_block *block, int *line)
{
for (; block; block = block->next)
{
if (block->type == FZ_STEXT_BLOCK_STRUCT && block->u.s.down)
add_chars(ctx, buf, block->u.s.down->first_block, line);
if (block->type != FZ_STEXT_BLOCK_TEXT)
continue;
for (fz_stext_line *l = block->u.t.first_line; l; l = l->next, ++*line)
for (fz_stext_char *ch = l->first_char; ch; ch = ch->next)
{
fz_rect box = fz_rect_from_quad(ch->quad);
ely_char one = { *line, ch->c, box.x0, box.y0, box.x1, box.y1 };
fz_append_data(ctx, buf, &one, sizeof one);
}
}
}
/* The page's characters in reading order; free with ely_free. */
int ely_text(fz_context *ctx, fz_document *doc, int number, unsigned char **data, size_t *len)
{
fz_page *page = NULL;
fz_stext_page *text = NULL;
fz_buffer *buf = NULL;
fz_var(page);
fz_var(text);
fz_var(buf);
fz_try(ctx)
{
page = fz_load_page(ctx, doc, number);
text = fz_new_stext_page_from_page(ctx, page, NULL);
buf = fz_new_buffer(ctx, 4096);
int line = 0;
add_chars(ctx, buf, text->first_block, &line);
*len = fz_buffer_extract(ctx, buf, data);
}
fz_always(ctx)
{
fz_drop_buffer(ctx, buf);
fz_drop_stext_page(ctx, text);
fz_drop_page(ctx, page);
}
fz_catch(ctx)
return ely_fail(ctx);
return 0;
}
/* Each hit: its quad count, then those quads. */
static int add_hit(fz_context *ctx, void *opaque, int count, fz_quad *quads)
{
fz_buffer *buf = opaque;
fz_append_data(ctx, buf, &count, sizeof count);
fz_append_data(ctx, buf, quads, sizeof *quads * count);
return 0;
}
/* Every hit on a page; free with ely_free. */
int ely_search(fz_context *ctx, fz_document *doc, int number, const char *needle,
unsigned char **data, size_t *len)
{
fz_page *page = NULL;
fz_stext_page *text = NULL;
fz_buffer *buf = NULL;
fz_var(page);
fz_var(text);
fz_var(buf);
fz_try(ctx)
{
page = fz_load_page(ctx, doc, number);
text = fz_new_stext_page_from_page(ctx, page, NULL);
buf = fz_new_buffer(ctx, 256);
fz_search_stext_page_cb(ctx, text, needle, add_hit, buf);
*len = fz_buffer_extract(ctx, buf, data);
}
fz_always(ctx)
{
fz_drop_buffer(ctx, buf);
fz_drop_stext_page(ctx, text);
fz_drop_page(ctx, page);
}
fz_catch(ctx)
return ely_fail(ctx);
return 0;
}
static void outline_json(fz_context *ctx, fz_output *out, fz_document *doc, fz_outline *item)
{
fz_write_string(ctx, out, "[");
for (; item; item = item->next)
{
int page = item->page.page >= 0 ? fz_page_number_from_location(ctx, doc, item->page) : -1;
fz_write_printf(ctx, out, "{%q:%q,%q:%d,%q:%g,%q:", "title", item->title ? item->title : "",
"page", page, "y", item->y, "down");
outline_json(ctx, out, doc, item->down);
fz_write_string(ctx, out, item->next ? "}," : "}");
}
fz_write_string(ctx, out, "]");
}
/* Bookmarks as JSON: title, page or -1, y, down. */
int ely_outline(fz_context *ctx, fz_document *doc, unsigned char **data, size_t *len)
{
fz_outline *outline = NULL;
fz_buffer *buf = NULL;
fz_output *out = NULL;
fz_var(outline);
fz_var(buf);
fz_var(out);
fz_try(ctx)
{
outline = fz_load_outline(ctx, doc);
buf = fz_new_buffer(ctx, 1024);
out = fz_new_output_with_buffer(ctx, buf);
outline_json(ctx, out, doc, outline);
fz_close_output(ctx, out);
*len = fz_buffer_extract(ctx, buf, data);
}
fz_always(ctx)
{
fz_drop_output(ctx, out);
fz_drop_buffer(ctx, buf);
fz_drop_outline(ctx, outline);
}
fz_catch(ctx)
return ely_fail(ctx);
return 0;
}
void ely_free(fz_context *ctx, void *data)
{
fz_free(ctx, data);
}
+284
View File
@@ -0,0 +1,284 @@
/* OCR: recognise a page, add a hidden text layer (PDF-08). */
#include <string.h>
#include "ely_shim.h"
static const char to_unicode[] =
"/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n"
"/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n"
"/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n"
"1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n"
"1 beginbfrange\n<0000> <FFFF> <0000>\nendbfrange\n"
"endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend\n";
/* Lines Tesseract reads on a page, page space, as JSON. */
int ely_ocr_page(fz_context *ctx, fz_document *doc, int number, const char *lang, const char *datadir, float dpi,
unsigned char **data, size_t *len)
{
fz_page *page = NULL;
fz_pixmap *pix = NULL;
fz_image *image = NULL;
fz_stext_page *text = NULL;
fz_device *sdev = NULL, *ocr = NULL;
fz_buffer *buf = NULL, *words = NULL;
fz_output *out = NULL;
fz_var(page);
fz_var(pix);
fz_var(image);
fz_var(text);
fz_var(sdev);
fz_var(ocr);
fz_var(buf);
fz_var(words);
fz_var(out);
fz_try(ctx)
{
float zoom = dpi / 72;
fz_rect area;
fz_stext_block *block;
fz_stext_line *line;
fz_stext_char *ch;
int first = 1;
if (dpi < 72 || dpi > 600)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a resolution of %g dpi", dpi);
page = fz_load_page(ctx, doc, number);
pix = fz_new_pixmap_from_page(ctx, page, fz_scale(zoom, zoom), fz_device_gray(ctx), 0);
image = fz_new_image_from_pixmap(ctx, pix, NULL);
area = fz_make_rect(0, 0, (float)pix->w, (float)pix->h);
text = fz_new_stext_page(ctx, area);
sdev = fz_new_stext_device(ctx, text, NULL);
ocr = fz_new_ocr_device(ctx, sdev, fz_identity, area, 0, lang, datadir, NULL, NULL);
fz_fill_image(ctx, ocr, image, fz_make_matrix(area.x1, 0, 0, area.y1, 0, 0), 1, fz_default_color_params);
fz_close_device(ctx, ocr);
fz_close_device(ctx, sdev);
buf = fz_new_buffer(ctx, 1024);
out = fz_new_output_with_buffer(ctx, buf);
fz_write_byte(ctx, out, '[');
for (block = text->first_block; block; block = block->next)
{
if (block->type != FZ_STEXT_BLOCK_TEXT)
continue;
for (line = block->u.t.first_line; line; line = line->next)
{
fz_rect r = fz_transform_rect(line->bbox, fz_scale(1 / zoom, 1 / zoom));
if (!line->first_char)
continue;
fz_drop_buffer(ctx, words);
words = NULL;
words = fz_new_buffer(ctx, 128);
for (ch = line->first_char; ch; ch = ch->next)
fz_append_rune(ctx, words, ch->c);
fz_terminate_buffer(ctx, words);
fz_write_printf(ctx, out, "%s{\"rect\":[%g,%g,%g,%g],\"text\":", first ? "" : ",", r.x0, r.y0, r.x1, r.y1);
ely_json_string(ctx, out, fz_string_from_buffer(ctx, words));
fz_write_byte(ctx, out, '}');
first = 0;
}
}
fz_write_byte(ctx, out, ']');
fz_close_output(ctx, out);
*len = fz_buffer_extract(ctx, buf, data);
}
fz_always(ctx)
{
fz_drop_output(ctx, out);
fz_drop_buffer(ctx, buf);
fz_drop_buffer(ctx, words);
fz_drop_device(ctx, ocr);
fz_drop_device(ctx, sdev);
fz_drop_stext_page(ctx, text);
fz_drop_image(ctx, image);
fz_drop_pixmap(ctx, pix);
fz_drop_page(ctx, page);
}
fz_catch(ctx)
return ely_fail(ctx);
return 0;
}
/* A font with no glyphs; codes are UTF-16 units. */
static pdf_obj *glyphless(fz_context *ctx, pdf_document *pdf)
{
pdf_obj *font = NULL, *cid = NULL, *desc = NULL, *info, *bbox, *kids;
fz_buffer *cmap = NULL;
fz_var(font);
fz_var(cid);
fz_var(desc);
fz_var(cmap);
fz_try(ctx)
{
desc = pdf_add_new_dict(ctx, pdf, 8);
pdf_dict_put(ctx, desc, PDF_NAME(Type), PDF_NAME(FontDescriptor));
pdf_dict_put_name(ctx, desc, PDF_NAME(FontName), "GlyphLessFont");
pdf_dict_put_int(ctx, desc, PDF_NAME(Flags), 5);
bbox = pdf_dict_put_array(ctx, desc, PDF_NAME(FontBBox), 4);
pdf_array_push_int(ctx, bbox, 0), pdf_array_push_int(ctx, bbox, 0);
pdf_array_push_int(ctx, bbox, 500), pdf_array_push_int(ctx, bbox, 1000);
pdf_dict_put_int(ctx, desc, PDF_NAME(ItalicAngle), 0);
pdf_dict_put_int(ctx, desc, PDF_NAME(Ascent), 1000);
pdf_dict_put_int(ctx, desc, PDF_NAME(Descent), 0);
pdf_dict_put_int(ctx, desc, PDF_NAME(CapHeight), 1000);
pdf_dict_put_int(ctx, desc, PDF_NAME(StemV), 80);
cid = pdf_add_new_dict(ctx, pdf, 8);
pdf_dict_put(ctx, cid, PDF_NAME(Type), PDF_NAME(Font));
pdf_dict_put(ctx, cid, PDF_NAME(Subtype), PDF_NAME(CIDFontType2));
pdf_dict_put_name(ctx, cid, PDF_NAME(BaseFont), "GlyphLessFont");
info = pdf_dict_put_dict(ctx, cid, PDF_NAME(CIDSystemInfo), 3);
pdf_dict_put_text_string(ctx, info, PDF_NAME(Registry), "Adobe");
pdf_dict_put_text_string(ctx, info, PDF_NAME(Ordering), "Identity");
pdf_dict_put_int(ctx, info, PDF_NAME(Supplement), 0);
pdf_dict_put(ctx, cid, PDF_NAME(FontDescriptor), desc);
pdf_dict_put_int(ctx, cid, PDF_NAME(DW), 500);
pdf_dict_put(ctx, cid, PDF_NAME(CIDToGIDMap), PDF_NAME(Identity));
font = pdf_add_new_dict(ctx, pdf, 6);
pdf_dict_put(ctx, font, PDF_NAME(Type), PDF_NAME(Font));
pdf_dict_put(ctx, font, PDF_NAME(Subtype), PDF_NAME(Type0));
pdf_dict_put_name(ctx, font, PDF_NAME(BaseFont), "GlyphLessFont");
pdf_dict_put(ctx, font, PDF_NAME(Encoding), PDF_NAME(Identity_H));
kids = pdf_dict_put_array(ctx, font, PDF_NAME(DescendantFonts), 1);
pdf_array_push(ctx, kids, cid);
cmap = fz_new_buffer_from_copied_data(ctx, (const unsigned char *)to_unicode, strlen(to_unicode));
pdf_dict_put_drop(ctx, font, PDF_NAME(ToUnicode), pdf_add_stream(ctx, pdf, cmap, NULL, 0));
}
fz_always(ctx)
{
pdf_drop_obj(ctx, desc);
pdf_drop_obj(ctx, cid);
fz_drop_buffer(ctx, cmap);
}
fz_catch(ctx)
{
pdf_drop_obj(ctx, font);
fz_rethrow(ctx);
}
return font;
}
/* Drops the page's earlier Ely OCR layers. */
static void drop_layers(fz_context *ctx, pdf_obj *page)
{
pdf_obj *contents = pdf_dict_get(ctx, page, PDF_NAME(Contents));
int i;
for (i = pdf_array_len(ctx, contents) - 1; i >= 0; i--)
if (pdf_dict_gets(ctx, pdf_array_get(ctx, contents, i), "ElyOCR"))
pdf_array_delete(ctx, contents, i);
}
/* Throws unless every line is whole and in the BMP. */
static void check_layer(fz_context *ctx, fz_json *pages, int count)
{
int i, k;
for (i = 0; i < fz_json_array_length(ctx, pages); i++)
{
fz_json *spec = fz_json_array_get(ctx, pages, i);
fz_json *page = ely_member(ctx, spec, "page", FZ_JSON_NUMBER);
fz_json *lines = ely_member(ctx, spec, "lines", FZ_JSON_ARRAY);
if (!page || page->u.number < 0 || page->u.number >= count || !lines)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a layer with no page or lines");
for (k = 0; k < fz_json_array_length(ctx, lines); k++)
{
fz_json *line = fz_json_array_get(ctx, lines, k);
fz_json *words = ely_member(ctx, line, "text", FZ_JSON_STRING);
const char *s;
int c;
ely_rect(ctx, ely_member(ctx, line, "rect", FZ_JSON_ARRAY), 0.5f);
if (!words || !words->u.string[0])
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a line with no text");
for (s = words->u.string; *s; )
{
s += fz_chartorune(&c, s);
if (c > 0xFFFF || c == FZ_REPLACEMENT_CHARACTER)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a character the layer cannot hold: U+%X", c);
}
}
}
}
/* One line: hidden text stretched over its box. */
static void write_line(fz_context *ctx, fz_buffer *buf, fz_json *line, fz_matrix to_user, const char *font)
{
fz_rect r = ely_rect(ctx, ely_member(ctx, line, "rect", FZ_JSON_ARRAY), 0.5f);
const char *s = ely_member(ctx, line, "text", FZ_JSON_STRING)->u.string, *p;
float size = r.y1 - r.y0;
int n = 0, c;
fz_matrix m;
for (p = s; *p; n++)
p += fz_chartorune(&c, p);
/* Each code is half an em wide. */
m = fz_concat(fz_make_matrix((r.x1 - r.x0) / (0.5f * n), 0, 0, -size, r.x0, r.y1 - 0.2f * size), to_user);
fz_append_printf(ctx, buf, "BT 3 Tr /%s 1 Tf %g %g %g %g %g %g Tm <", font, m.a, m.b, m.c, m.d, m.e, m.f);
for (p = s; *p; )
{
p += fz_chartorune(&c, p);
fz_append_printf(ctx, buf, "%04x", c);
}
fz_append_string(ctx, buf, "> Tj ET\n");
}
/* Hidden text on pages, earlier layers first dropped if asked. */
int ely_text_layer(fz_context *ctx, fz_document *doc, const char *json, int replace)
{
pdf_document *pdf = NULL;
pdf_page *page = NULL;
pdf_obj *font = NULL;
fz_buffer *buf = NULL;
fz_pool *pool = NULL;
int begun = 0;
fz_var(pdf);
fz_var(page);
fz_var(font);
fz_var(buf);
fz_var(pool);
fz_var(begun);
fz_try(ctx)
{
fz_json *pages;
int i, k;
pdf = ely_pdf_of(ctx, doc);
pool = fz_new_pool(ctx);
pages = fz_parse_json(ctx, pool, json);
if (pages->type != FZ_JSON_ARRAY || fz_json_array_length(ctx, pages) == 0)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "no pages to lay text on");
check_layer(ctx, pages, pdf_count_pages(ctx, pdf));
pdf_begin_operation(ctx, pdf, "Add recognised text");
begun = 1;
for (i = 0; i < fz_json_array_length(ctx, pages); i++)
{
fz_json *spec = fz_json_array_get(ctx, pages, i);
fz_json *lines = ely_member(ctx, spec, "lines", FZ_JSON_ARRAY);
char name[32];
page = pdf_load_page(ctx, pdf, (int)ely_member(ctx, spec, "page", FZ_JSON_NUMBER)->u.number);
if (replace)
drop_layers(ctx, page->obj);
if (fz_json_array_length(ctx, lines) > 0)
{
if (!font)
font = glyphless(ctx, pdf);
ely_add_resource(ctx, pdf, page->obj, PDF_NAME(Font), "ElyOCR", font, name, sizeof name);
buf = fz_new_buffer(ctx, 1024);
/* Its own state, so later text stays seen. */
fz_append_string(ctx, buf, "q\n");
for (k = 0; k < fz_json_array_length(ctx, lines); k++)
write_line(ctx, buf, fz_json_array_get(ctx, lines, k), ely_to_user(ctx, page), name);
fz_append_string(ctx, buf, "Q\n");
pdf_dict_puts(ctx, ely_append_content(ctx, pdf, page->obj, buf), "ElyOCR", PDF_TRUE);
fz_drop_buffer(ctx, buf);
buf = NULL;
}
fz_drop_page(ctx, (fz_page *)page);
page = NULL;
}
pdf_end_operation(ctx, pdf);
}
fz_always(ctx)
{
fz_drop_buffer(ctx, buf);
pdf_drop_obj(ctx, font);
fz_drop_page(ctx, (fz_page *)page);
fz_drop_pool(ctx, pool);
}
fz_catch(ctx)
return ely_edit_failed(ctx, pdf, begun);
return 0;
}
+237
View File
@@ -0,0 +1,237 @@
/* Bookmarks and links: change, list (PDF-07). */
#include <string.h>
#include "ely_shim.h"
/* A page point as a link target. */
static char *target(fz_context *ctx, fz_document *doc, fz_json *spec)
{
fz_json *page = ely_member(ctx, spec, "page", FZ_JSON_NUMBER);
fz_json *y = ely_member(ctx, spec, "y", FZ_JSON_NUMBER);
if (!page || page->u.number < 0 || page->u.number >= fz_count_pages(ctx, doc))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a target with no page");
return fz_format_link_uri(ctx, doc, fz_make_link_dest_xyz(0, (int)page->u.number, 0, y ? (float)y->u.number : 0, 0));
}
/* Walks `path`; the last step may land past the end. */
static int walk(fz_context *ctx, fz_outline_iterator *iter, fz_json *path)
{
int i, k, n = fz_json_array_length(ctx, path), at = FZ_OUTLINE_ITERATOR_AT_ITEM;
if (n == 0)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "an empty bookmark path");
for (i = 0; i < n; i++)
{
int steps = (int)ely_number(ctx, path, i);
if (i > 0)
{
at = fz_outline_iterator_down(ctx, iter);
if (at < 0)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "no bookmark at that path");
}
at = fz_outline_iterator_item(ctx, iter) ? FZ_OUTLINE_ITERATOR_AT_ITEM : FZ_OUTLINE_ITERATOR_AT_EMPTY;
for (k = 0; k < steps; k++)
if (at != FZ_OUTLINE_ITERATOR_AT_ITEM || (at = fz_outline_iterator_next(ctx, iter)) < 0)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "no bookmark at that path");
if (i < n - 1 && at != FZ_OUTLINE_ITERATOR_AT_ITEM)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "no bookmark at that path");
}
return at;
}
/* Adds, renames, retargets or deletes one bookmark, in one step. */
int ely_outline_edit(fz_context *ctx, fz_document *doc, const char *json)
{
pdf_document *pdf = NULL;
fz_outline_iterator *iter = NULL;
fz_pool *pool = NULL;
char *uri = NULL;
int begun = 0;
fz_var(pdf);
fz_var(iter);
fz_var(pool);
fz_var(uri);
fz_var(begun);
fz_try(ctx)
{
fz_json *spec, *op, *path, *title, *expect;
fz_outline_item *now, item = { 0 };
int at;
pdf = ely_pdf_of(ctx, doc);
pool = fz_new_pool(ctx);
spec = fz_parse_json(ctx, pool, json);
op = ely_member(ctx, spec, "op", FZ_JSON_STRING);
path = ely_member(ctx, spec, "path", FZ_JSON_ARRAY);
title = ely_member(ctx, spec, "title", FZ_JSON_STRING);
expect = ely_member(ctx, spec, "expect", FZ_JSON_STRING);
if (!op || !path || (strcmp(op->u.string, "add") && strcmp(op->u.string, "edit") && strcmp(op->u.string, "delete")))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a bad bookmark change");
if (title && !title->u.string[0])
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a bookmark with no title");
if (!strcmp(op->u.string, "add") && !title)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a new bookmark with no title");
if (strcmp(op->u.string, "add") && !expect)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a change that does not name its bookmark");
if (ely_member(ctx, spec, "page", FZ_JSON_NUMBER))
uri = target(ctx, doc, spec);
else if (!strcmp(op->u.string, "add"))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a new bookmark with no target");
pdf_begin_operation(ctx, pdf, "Change bookmarks");
begun = 1;
iter = fz_new_outline_iterator(ctx, doc);
at = walk(ctx, iter, path);
if (!strcmp(op->u.string, "add"))
{
item.title = (char *)title->u.string;
item.uri = uri;
fz_outline_iterator_insert(ctx, iter, &item);
}
else
{
now = at == FZ_OUTLINE_ITERATOR_AT_ITEM ? fz_outline_iterator_item(ctx, iter) : NULL;
if (!now || strcmp(now->title ? now->title : "", expect->u.string))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "the bookmark changed meanwhile");
if (!strcmp(op->u.string, "delete"))
fz_outline_iterator_delete(ctx, iter);
else
{
item = *now;
if (title)
item.title = (char *)title->u.string;
if (uri)
item.uri = uri;
fz_outline_iterator_update(ctx, iter, &item);
}
}
pdf_end_operation(ctx, pdf);
}
fz_always(ctx)
{
fz_free(ctx, uri);
fz_drop_outline_iterator(ctx, iter);
fz_drop_pool(ctx, pool);
}
fz_catch(ctx)
return ely_edit_failed(ctx, pdf, begun);
return 0;
}
/* The page's links: box, address, and page if inside. */
int ely_links(fz_context *ctx, fz_document *doc, int number, unsigned char **data, size_t *len)
{
fz_page *page = NULL;
fz_link *links = NULL, *link;
fz_buffer *buf = NULL;
fz_output *out = NULL;
fz_var(page);
fz_var(links);
fz_var(buf);
fz_var(out);
fz_try(ctx)
{
page = fz_load_page(ctx, doc, number);
links = fz_load_links(ctx, page);
buf = fz_new_buffer(ctx, 256);
out = fz_new_output_with_buffer(ctx, buf);
fz_write_byte(ctx, out, '[');
for (link = links; link; link = link->next)
{
int to = -1;
float x = 0, y = 0;
if (!fz_is_external_link(ctx, link->uri))
to = fz_page_number_from_location(ctx, doc, fz_resolve_link(ctx, doc, link->uri, &x, &y));
fz_write_printf(ctx, out, "%s{\"rect\":[%g,%g,%g,%g],\"uri\":", link == links ? "" : ",",
link->rect.x0, link->rect.y0, link->rect.x1, link->rect.y1);
ely_json_string(ctx, out, link->uri ? link->uri : "");
fz_write_printf(ctx, out, ",\"page\":%d,\"y\":%g}", to, y);
}
fz_write_byte(ctx, out, ']');
fz_close_output(ctx, out);
*len = fz_buffer_extract(ctx, buf, data);
}
fz_always(ctx)
{
fz_drop_output(ctx, out);
fz_drop_buffer(ctx, buf);
fz_drop_link(ctx, links);
fz_drop_page(ctx, page);
}
fz_catch(ctx)
return ely_fail(ctx);
return 0;
}
/* Only web and mail addresses leave the document. */
static int outward(const char *uri)
{
return !strncmp(uri, "https://", 8) || !strncmp(uri, "http://", 7) || !strncmp(uri, "mailto:", 7);
}
/* Adds, retargets or deletes one link, in one step. */
int ely_link_edit(fz_context *ctx, fz_document *doc, int number, const char *json)
{
pdf_document *pdf = NULL;
pdf_page *page = NULL;
fz_pool *pool = NULL;
char *uri = NULL;
int begun = 0;
fz_var(pdf);
fz_var(page);
fz_var(pool);
fz_var(uri);
fz_var(begun);
fz_try(ctx)
{
fz_json *spec, *op, *index, *expect, *web;
fz_link *link = NULL;
fz_rect box = fz_empty_rect;
int i;
pdf = ely_pdf_of(ctx, doc);
page = pdf_load_page(ctx, pdf, number);
pool = fz_new_pool(ctx);
spec = fz_parse_json(ctx, pool, json);
op = ely_member(ctx, spec, "op", FZ_JSON_STRING);
index = ely_member(ctx, spec, "index", FZ_JSON_NUMBER);
expect = ely_member(ctx, spec, "expect", FZ_JSON_STRING);
web = ely_member(ctx, spec, "uri", FZ_JSON_STRING);
if (!op || (strcmp(op->u.string, "add") && strcmp(op->u.string, "edit") && strcmp(op->u.string, "delete")))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a bad link change");
if (web && !outward(web->u.string))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "only web and mail addresses: %s", web->u.string);
if (web)
uri = fz_strdup(ctx, web->u.string);
else if (ely_member(ctx, spec, "page", FZ_JSON_NUMBER))
uri = target(ctx, doc, spec);
else if (strcmp(op->u.string, "delete"))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a link with no target");
if (strcmp(op->u.string, "add"))
{
if (!index || !expect)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a change that does not name its link");
for (link = page->links, i = 0; link && i < (int)index->u.number; link = link->next)
i++;
if (!link || strcmp(link->uri ? link->uri : "", expect->u.string))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "the link changed meanwhile");
}
if (!strcmp(op->u.string, "add"))
box = ely_rect(ctx, ely_member(ctx, spec, "rect", FZ_JSON_ARRAY), 2);
pdf_begin_operation(ctx, pdf, "Change links");
begun = 1;
if (!strcmp(op->u.string, "add"))
fz_drop_link(ctx, pdf_create_link(ctx, page, box, uri));
else if (!strcmp(op->u.string, "delete"))
pdf_delete_link(ctx, page, link);
else
fz_set_link_uri(ctx, link, uri);
pdf_end_operation(ctx, pdf);
}
fz_always(ctx)
{
fz_free(ctx, uri);
fz_drop_pool(ctx, pool);
fz_drop_page(ctx, (fz_page *)page);
}
fz_catch(ctx)
return ely_edit_failed(ctx, pdf, begun);
return 0;
}
+189
View File
@@ -0,0 +1,189 @@
/* Page images, text, optimized copies, repaired copies (PDF-13, PDF-14). */
#include <string.h>
#include "ely_shim.h"
/* Page `number` as a PNG at `dpi`, white, as printed. */
int ely_export_image(fz_context *ctx, fz_document *doc, int number, float dpi, const char *path)
{
fz_pixmap *pixmap = NULL;
fz_var(pixmap);
fz_try(ctx)
{
if (dpi < 18 || dpi > 1200)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a resolution outside 18 to 1200 dpi");
ely_watch_begin(ctx);
pixmap = fz_new_pixmap_from_page_number(ctx, doc, number, fz_scale(dpi / 72, dpi / 72), fz_device_rgb(ctx), 0);
if (ely_watch_end(ctx))
fz_throw(ctx, FZ_ERROR_FORMAT, "page %d did not read whole: %s", number + 1, ely_open_warnings());
fz_save_pixmap_as_png(ctx, pixmap, path);
}
fz_always(ctx)
{
ely_watch_end(ctx);
fz_drop_pixmap(ctx, pixmap);
}
fz_catch(ctx)
return ely_fail(ctx);
return 0;
}
/* Every page's text, UTF-8, pages parted by form feeds. */
int ely_export_text(fz_context *ctx, fz_document *doc, const char *path)
{
fz_output *out = NULL;
fz_stext_page *text = NULL;
fz_buffer *buf = NULL;
fz_var(out);
fz_var(text);
fz_var(buf);
fz_try(ctx)
{
int i;
ely_watch_begin(ctx);
out = fz_new_output_with_path(ctx, path, 0);
for (i = 0; i < fz_count_pages(ctx, doc); i++)
{
if (i > 0)
fz_write_byte(ctx, out, '\f');
text = fz_new_stext_page_from_page_number(ctx, doc, i, NULL);
buf = fz_new_buffer_from_stext_page(ctx, text);
fz_write_buffer(ctx, out, buf);
fz_drop_buffer(ctx, buf);
buf = NULL;
fz_drop_stext_page(ctx, text);
text = NULL;
}
/* Partial text is no export. */
if (ely_watch_end(ctx))
fz_throw(ctx, FZ_ERROR_FORMAT, "the text did not read whole: %s", ely_open_warnings());
fz_close_output(ctx, out);
}
fz_always(ctx)
{
ely_watch_end(ctx);
fz_drop_buffer(ctx, buf);
fz_drop_stext_page(ctx, text);
fz_drop_output(ctx, out);
}
fz_catch(ctx)
return ely_fail(ctx);
return 0;
}
typedef struct
{
int from, to;
} downsample;
static void shrink_images(fz_context *ctx, fz_document *copy, void *arg)
{
downsample *d = arg;
pdf_image_rewriter_options opts = { 0 };
if (!d->to)
return;
opts.color_lossless_image_subsample_method = opts.color_lossy_image_subsample_method = FZ_SUBSAMPLE_BICUBIC;
opts.gray_lossless_image_subsample_method = opts.gray_lossy_image_subsample_method = FZ_SUBSAMPLE_BICUBIC;
opts.bitonal_image_subsample_method = FZ_SUBSAMPLE_BICUBIC;
opts.color_lossless_image_subsample_threshold = opts.color_lossy_image_subsample_threshold = d->from;
opts.gray_lossless_image_subsample_threshold = opts.gray_lossy_image_subsample_threshold = d->from;
opts.bitonal_image_subsample_threshold = d->from;
opts.color_lossless_image_subsample_to = opts.color_lossy_image_subsample_to = d->to;
opts.gray_lossless_image_subsample_to = opts.gray_lossy_image_subsample_to = d->to;
opts.bitonal_image_subsample_to = d->to;
/* Never, the default, drops the smaller picture. */
opts.color_lossless_image_recompress_method = opts.gray_lossless_image_recompress_method = FZ_RECOMPRESS_LOSSLESS;
opts.color_lossy_image_recompress_method = opts.gray_lossy_image_recompress_method = FZ_RECOMPRESS_SAME;
opts.bitonal_image_recompress_method = FZ_RECOMPRESS_SAME;
pdf_rewrite_images(ctx, ely_pdf_of(ctx, copy), &opts);
}
/* Writes `out` compressed, images above `from` dpi taken to `to`. */
int ely_optimize(fz_context *ctx, fz_document *doc, const char *raw, const char *out, const char *password, int compress,
int from, int to)
{
fz_try(ctx)
{
pdf_write_options opts = pdf_default_write_options;
downsample d = { from, to };
if (to && (to < 36 || from <= to))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a downsampling from %d to %d dpi", from, to);
opts.do_compress = opts.do_compress_images = opts.do_compress_fonts = compress;
ely_save_copy(ctx, ely_pdf_of(ctx, doc), raw, out, password, &opts, shrink_images, &d);
}
fz_catch(ctx)
return ely_fail(ctx);
return 0;
}
/* 1 when MuPDF rebuilt the file's structure to read it. */
int ely_repaired(fz_context *ctx, fz_document *doc)
{
int repaired = 0;
fz_try(ctx)
repaired = pdf_was_repaired(ctx, ely_pdf_of(ctx, doc));
fz_catch(ctx)
return ely_fail(ctx);
return repaired;
}
/* The repaired document written whole to `path`. */
int ely_write_repaired(fz_context *ctx, fz_document *doc, const char *path)
{
fz_try(ctx)
{
pdf_write_options opts = pdf_default_write_options;
opts.do_garbage = 1;
pdf_save_document(ctx, ely_pdf_of(ctx, doc), path, &opts);
}
fz_catch(ctx)
return ely_fail(ctx);
return 0;
}
/* Leave to print was checked; the printer gets no lock. */
int ely_print_copy(fz_context *ctx, fz_document *doc, const char *raw, const char *out, const char *password)
{
fz_try(ctx)
{
pdf_write_options opts = pdf_default_write_options;
opts.do_encrypt = PDF_ENCRYPT_NONE;
ely_save_copy(ctx, ely_pdf_of(ctx, doc), raw, out, password, &opts, NULL, NULL);
}
fz_catch(ctx)
return ely_fail(ctx);
return 0;
}
/* Decodes every picture; 1 if MuPDF warned on any. */
int ely_check_pictures(fz_context *ctx, fz_document *doc)
{
pdf_document *pdf = ely_pdf_of(ctx, doc);
int i;
ely_watch_begin(ctx);
for (i = 1; i < pdf_xref_len(ctx, pdf); i++)
{
pdf_obj *obj = NULL;
fz_buffer *bytes = NULL;
fz_var(obj);
fz_var(bytes);
fz_try(ctx)
{
obj = pdf_new_indirect(ctx, pdf, i, 0);
if (pdf_is_stream(ctx, obj) && pdf_name_eq(ctx, pdf_dict_get(ctx, obj, PDF_NAME(Subtype)), PDF_NAME(Image)))
bytes = pdf_load_stream_number(ctx, pdf, i);
}
fz_always(ctx)
{
fz_drop_buffer(ctx, bytes);
pdf_drop_obj(ctx, obj);
}
fz_catch(ctx)
{
fz_warn(ctx, "picture %d: %s", i, fz_caught_message(ctx));
fz_ignore_error(ctx);
}
}
return ely_watch_end(ctx);
}
+487
View File
@@ -0,0 +1,487 @@
/* Page edits, undo and saving; one undo step each. */
#include <stdlib.h>
#include "ely_shim.h"
pdf_document *ely_pdf_of(fz_context *ctx, fz_document *doc)
{
pdf_document *pdf = pdf_specifics(ctx, doc);
if (!pdf)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "not a PDF");
return pdf;
}
/* MuPDF's font and image caches outlive an undo; they go. */
void ely_forget_resources(fz_context *ctx, pdf_document *pdf)
{
pdf_drop_resource_tables(ctx, pdf);
pdf->resources.fonts = NULL;
pdf->resources.colorspaces = NULL;
pdf->resources.images = NULL;
}
/* Reports the failure; a begun step is rolled back. */
int ely_edit_failed(fz_context *ctx, pdf_document *pdf, int begun)
{
int code = ely_fail(ctx);
if (begun)
{
fz_try(ctx)
{
pdf_abandon_operation(ctx, pdf);
ely_forget_resources(ctx, pdf);
}
fz_catch(ctx)
ely_fail_also(ctx, "rolling back");
}
return code;
}
int ely_journal(fz_context *ctx, fz_document *doc)
{
fz_try(ctx)
pdf_enable_journal(ctx, ely_pdf_of(ctx, doc));
fz_catch(ctx)
return ely_fail(ctx);
return 0;
}
int ely_undo(fz_context *ctx, fz_document *doc, int redo)
{
fz_try(ctx)
{
pdf_document *pdf = ely_pdf_of(ctx, doc);
if (redo)
pdf_redo(ctx, pdf);
else
pdf_undo(ctx, pdf);
ely_forget_resources(ctx, pdf);
}
fz_catch(ctx)
return ely_fail(ctx);
return 0;
}
/* MuPDF's undo position and step count; saves add steps. */
int ely_state(fz_context *ctx, fz_document *doc, int *at, int *count)
{
fz_try(ctx)
*at = pdf_undoredo_state(ctx, ely_pdf_of(ctx, doc), count);
fz_catch(ctx)
return ely_fail(ctx);
return 0;
}
static int by_number(const void *a, const void *b)
{
return *(const int *)a - *(const int *)b;
}
/* Object numbers, sorted for lookups. */
typedef struct
{
int *nums;
int n;
} gone_set;
static int is_gone(fz_context *ctx, gone_set *gone, pdf_obj *obj)
{
int num = pdf_to_num(ctx, obj);
return num && bsearch(&num, gone->nums, gone->n, sizeof(int), by_number) != NULL;
}
/* Deleted pages, and the annotations they held. */
typedef struct
{
gone_set pages;
gone_set annots;
} gone_pages;
/* The page a link, bookmark or action points to. */
pdf_obj *ely_target(fz_context *ctx, pdf_document *pdf, pdf_obj *obj)
{
pdf_obj *dest = pdf_dict_get(ctx, obj, PDF_NAME(Dest));
if (!dest)
{
pdf_obj *action = pdf_dict_get(ctx, obj, PDF_NAME(A));
if (!pdf_name_eq(ctx, pdf_dict_get(ctx, action, PDF_NAME(S)), PDF_NAME(GoTo)))
return NULL;
dest = pdf_dict_get(ctx, action, PDF_NAME(D));
}
if (pdf_is_name(ctx, dest) || pdf_is_string(ctx, dest))
dest = pdf_lookup_dest(ctx, pdf, dest);
if (pdf_is_dict(ctx, dest))
dest = pdf_dict_get(ctx, dest, PDF_NAME(D));
return pdf_is_array(ctx, dest) ? pdf_array_get(ctx, dest, 0) : NULL;
}
/* Bookmarks to gone pages keep their place, lose the jump. */
static void forget_in_outline(fz_context *ctx, pdf_document *pdf, pdf_obj *item, gone_set *gone)
{
for (; item; item = pdf_dict_get(ctx, item, PDF_NAME(Next)))
{
pdf_obj *page = ely_target(ctx, pdf, item);
if (page && is_gone(ctx, gone, page))
{
pdf_dict_del(ctx, item, PDF_NAME(Dest));
pdf_dict_del(ctx, item, PDF_NAME(A));
}
forget_in_outline(ctx, pdf, pdf_dict_get(ctx, item, PDF_NAME(First)), gone);
}
}
/* Whether a field keeps a widget on a kept page. */
static int prune_field(fz_context *ctx, pdf_obj *field, gone_pages *gone)
{
pdf_obj *kids = pdf_dict_get(ctx, field, PDF_NAME(Kids));
int i;
if (!kids)
{
/* A deleted page held it, or its /P names one. */
pdf_obj *page = pdf_dict_get(ctx, field, PDF_NAME(P));
if (!pdf_name_eq(ctx, pdf_dict_get(ctx, field, PDF_NAME(Subtype)), PDF_NAME(Widget)))
return 1;
return !is_gone(ctx, &gone->annots, field) && !(page && is_gone(ctx, &gone->pages, page));
}
for (i = pdf_array_len(ctx, kids) - 1; i >= 0; i--)
if (!prune_field(ctx, pdf_array_get(ctx, kids, i), gone))
pdf_array_delete(ctx, kids, i);
return pdf_array_len(ctx, kids) > 0;
}
/* Drops what pointed into deleted pages. */
static void forget_pages(fz_context *ctx, pdf_document *pdf, gone_pages *gone)
{
pdf_obj *root = pdf_dict_get(ctx, pdf_trailer(ctx, pdf), PDF_NAME(Root));
pdf_obj *outlines = pdf_dict_get(ctx, root, PDF_NAME(Outlines));
pdf_obj *fields = pdf_dict_getp(ctx, root, "AcroForm/Fields");
int i, j, count = pdf_count_pages(ctx, pdf);
forget_in_outline(ctx, pdf, pdf_dict_get(ctx, outlines, PDF_NAME(First)), &gone->pages);
for (i = 0; i < count; i++)
{
pdf_obj *annots = pdf_dict_get(ctx, pdf_lookup_page_obj(ctx, pdf, i), PDF_NAME(Annots));
for (j = pdf_array_len(ctx, annots) - 1; j >= 0; j--)
{
pdf_obj *annot = pdf_array_get(ctx, annots, j);
pdf_obj *page;
if (!pdf_name_eq(ctx, pdf_dict_get(ctx, annot, PDF_NAME(Subtype)), PDF_NAME(Link)))
continue;
page = ely_target(ctx, pdf, annot);
if (page && is_gone(ctx, &gone->pages, page))
pdf_array_delete(ctx, annots, j);
}
}
for (i = pdf_array_len(ctx, fields) - 1; i >= 0; i--)
if (!prune_field(ctx, pdf_array_get(ctx, fields, i), gone))
pdf_array_delete(ctx, fields, i);
}
/* Checks `pages` are sorted page numbers without repeats. */
static void check_pages(fz_context *ctx, pdf_document *pdf, const int *pages, int n)
{
int i, count = pdf_count_pages(ctx, pdf);
if (n <= 0)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "no pages given");
for (i = 0; i < n; i++)
if (pages[i] < 0 || pages[i] >= count || (i > 0 && pages[i] <= pages[i - 1]))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "page %d is out of order or range", pages[i]);
}
/* Deletes checked `pages` and what pointed there. */
static void delete_pages(fz_context *ctx, pdf_document *pdf, const int *pages, int n)
{
gone_pages gone = { { NULL, n }, { NULL, 0 } };
int i, j, held = 0;
fz_var(gone.pages.nums);
fz_var(gone.annots.nums);
fz_try(ctx)
{
gone.pages.nums = fz_malloc_array(ctx, n, int);
for (i = 0; i < n; i++)
{
pdf_obj *page = pdf_lookup_page_obj(ctx, pdf, pages[i]);
gone.pages.nums[i] = pdf_to_num(ctx, page);
held += pdf_array_len(ctx, pdf_dict_get(ctx, page, PDF_NAME(Annots)));
}
gone.annots.nums = fz_malloc_array(ctx, held + 1, int);
for (i = 0; i < n; i++)
{
pdf_obj *annots = pdf_dict_get(ctx, pdf_lookup_page_obj(ctx, pdf, pages[i]), PDF_NAME(Annots));
for (j = 0; j < pdf_array_len(ctx, annots); j++)
gone.annots.nums[gone.annots.n++] = pdf_to_num(ctx, pdf_array_get(ctx, annots, j));
}
qsort(gone.pages.nums, n, sizeof(int), by_number);
qsort(gone.annots.nums, gone.annots.n, sizeof(int), by_number);
for (i = n - 1; i >= 0; i--)
pdf_delete_page(ctx, pdf, pages[i]);
forget_pages(ctx, pdf, &gone);
}
fz_always(ctx)
{
fz_free(ctx, gone.pages.nums);
fz_free(ctx, gone.annots.nums);
}
fz_catch(ctx)
fz_rethrow(ctx);
}
int ely_delete_pages(fz_context *ctx, fz_document *doc, const int *pages, int n)
{
pdf_document *pdf = NULL;
int begun = 0;
fz_var(pdf);
fz_var(begun);
fz_try(ctx)
{
pdf = ely_pdf_of(ctx, doc);
check_pages(ctx, pdf, pages, n);
if (n == pdf_count_pages(ctx, pdf))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a PDF keeps at least one page");
pdf_begin_operation(ctx, pdf, "Delete pages");
begun = 1;
delete_pages(ctx, pdf, pages, n);
pdf_end_operation(ctx, pdf);
}
fz_catch(ctx)
return ely_edit_failed(ctx, pdf, begun);
return 0;
}
/* Moves `pages` before page `to`, in their order. */
int ely_move_pages(fz_context *ctx, fz_document *doc, const int *pages, int n, int to)
{
pdf_document *pdf = NULL;
pdf_obj **moved = NULL;
int begun = 0, i, at;
fz_var(pdf);
fz_var(begun);
fz_var(moved);
fz_try(ctx)
{
pdf = ely_pdf_of(ctx, doc);
check_pages(ctx, pdf, pages, n);
if (to < 0 || to > pdf_count_pages(ctx, pdf))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "no place %d to move to", to);
moved = fz_calloc(ctx, n, sizeof *moved);
for (i = 0; i < n; i++)
moved[i] = pdf_keep_obj(ctx, pdf_lookup_page_obj(ctx, pdf, pages[i]));
pdf_begin_operation(ctx, pdf, "Move pages");
begun = 1;
for (i = n - 1; i >= 0; i--)
pdf_delete_page(ctx, pdf, pages[i]);
for (at = to, i = 0; i < n; i++)
at -= pages[i] < to;
for (i = 0; i < n; i++)
pdf_insert_page(ctx, pdf, at + i, moved[i]);
pdf_end_operation(ctx, pdf);
}
fz_always(ctx)
{
for (i = 0; moved && i < n; i++)
pdf_drop_obj(ctx, moved[i]);
fz_free(ctx, moved);
}
fz_catch(ctx)
return ely_edit_failed(ctx, pdf, begun);
return 0;
}
/* Turns `pages` by a multiple of 90 degrees. */
int ely_rotate_pages(fz_context *ctx, fz_document *doc, const int *pages, int n, int by)
{
pdf_document *pdf = NULL;
int begun = 0, i;
fz_var(pdf);
fz_var(begun);
fz_try(ctx)
{
pdf = ely_pdf_of(ctx, doc);
check_pages(ctx, pdf, pages, n);
if (by % 90)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a turn of %d degrees", by);
pdf_begin_operation(ctx, pdf, "Rotate pages");
begun = 1;
for (i = 0; i < n; i++)
{
pdf_obj *page = pdf_lookup_page_obj(ctx, pdf, pages[i]);
int now = pdf_to_int(ctx, pdf_dict_get_inheritable(ctx, page, PDF_NAME(Rotate)));
pdf_dict_put_int(ctx, page, PDF_NAME(Rotate), ((now + by) % 360 + 360) % 360);
}
pdf_end_operation(ctx, pdf);
}
fz_catch(ctx)
return ely_edit_failed(ctx, pdf, begun);
return 0;
}
/* Seen margins (top, right, bottom, left) to user sides. */
static fz_rect inset(fz_rect box, int rotate, const float seen[4])
{
/* User sides: 0 y1, 1 x1, 2 y0, 3 x0. */
static const int under[4][4] = { { 0, 1, 2, 3 }, { 3, 0, 1, 2 }, { 2, 3, 0, 1 }, { 1, 2, 3, 0 } };
float side[4] = { 0, 0, 0, 0 };
int i, turn = ((rotate % 360 + 360) % 360) / 90;
for (i = 0; i < 4; i++)
side[under[turn][i]] = seen[i];
box.y1 -= side[0];
box.x1 -= side[1];
box.y0 += side[2];
box.x0 += side[3];
return box;
}
/* Crops `pages` by seen margins in points; zeros uncrop. */
int ely_crop_pages(fz_context *ctx, fz_document *doc, const int *pages, int n, const float margins[4])
{
pdf_document *pdf = NULL;
int begun = 0, i;
fz_var(pdf);
fz_var(begun);
fz_try(ctx)
{
int none = margins[0] == 0 && margins[1] == 0 && margins[2] == 0 && margins[3] == 0;
pdf = ely_pdf_of(ctx, doc);
check_pages(ctx, pdf, pages, n);
pdf_begin_operation(ctx, pdf, "Crop pages");
begun = 1;
for (i = 0; i < n; i++)
{
pdf_obj *page = pdf_lookup_page_obj(ctx, pdf, pages[i]);
fz_rect media = pdf_to_rect(ctx, pdf_dict_get_inheritable(ctx, page, PDF_NAME(MediaBox)));
int rotate = pdf_to_int(ctx, pdf_dict_get_inheritable(ctx, page, PDF_NAME(Rotate)));
/* Points as shown; user units may be larger. */
float unit = pdf_to_real(ctx, pdf_dict_get(ctx, page, PDF_NAME(UserUnit)));
float user[4];
int side;
for (side = 0; side < 4; side++)
user[side] = margins[side] / (unit > 0 ? unit : 1);
fz_rect crop = inset(media, rotate, user);
if (none)
{
pdf_dict_del(ctx, page, PDF_NAME(CropBox));
continue;
}
if (crop.x1 - crop.x0 < 1 || crop.y1 - crop.y0 < 1)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "the margins leave nothing of page %d", pages[i] + 1);
pdf_dict_put_rect(ctx, page, PDF_NAME(CropBox), crop);
}
pdf_end_operation(ctx, pdf);
}
fz_catch(ctx)
return ely_edit_failed(ctx, pdf, begun);
return 0;
}
/* A blank page of w by h points at `at`. */
int ely_insert_blank(fz_context *ctx, fz_document *doc, int at, float w, float h)
{
pdf_document *pdf = NULL;
pdf_obj *page = NULL;
int begun = 0;
fz_var(pdf);
fz_var(page);
fz_var(begun);
fz_try(ctx)
{
pdf = ely_pdf_of(ctx, doc);
if (at < 0 || at > pdf_count_pages(ctx, pdf) || w < 1 || h < 1)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a blank page at %d of %g by %g", at, w, h);
pdf_begin_operation(ctx, pdf, "Insert a blank page");
begun = 1;
page = pdf_add_page(ctx, pdf, fz_make_rect(0, 0, w, h), 0, NULL, NULL);
pdf_insert_page(ctx, pdf, at, page);
pdf_end_operation(ctx, pdf);
}
fz_always(ctx)
pdf_drop_obj(ctx, page);
fz_catch(ctx)
return ely_edit_failed(ctx, pdf, begun);
return 0;
}
/* Pages of `pdf` other than the sorted `keep`. */
static int *others(fz_context *ctx, pdf_document *pdf, const int *keep, int n, int *k)
{
int i, count = pdf_count_pages(ctx, pdf);
int *rest = fz_malloc_array(ctx, count + 1, int);
*k = 0;
for (i = 0; i < count; i++)
if (bsearch(&i, keep, n, sizeof(int), by_number) == NULL)
rest[(*k)++] = i;
return rest;
}
/* A snapshot, reopened, changed, unsigned, compacted to `out`. */
void ely_save_copy(fz_context *ctx, pdf_document *pdf, const char *raw, const char *out, const char *password,
const pdf_write_options *opts, ely_change *change, void *arg)
{
fz_document *copy = NULL;
fz_var(copy);
fz_try(ctx)
{
pdf_write_options compact = opts ? *opts : pdf_default_write_options;
pdf_save_snapshot(ctx, pdf, raw);
copy = fz_open_document(ctx, raw);
if (fz_needs_password(ctx, copy) && !fz_authenticate_password(ctx, copy, password))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "the written copy refused its password");
if (change)
change(ctx, copy, arg);
ely_unsign(ctx, ely_pdf_of(ctx, copy));
/* Unused objects, such as deleted pages, go. */
compact.do_garbage = 2;
pdf_save_document(ctx, ely_pdf_of(ctx, copy), out, &compact);
}
fz_always(ctx)
fz_drop_document(ctx, copy);
fz_catch(ctx)
fz_rethrow(ctx);
}
typedef struct
{
const int *pages;
int n;
} kept;
/* Deletes every page not kept. */
static void keep_only(fz_context *ctx, fz_document *copy, void *arg)
{
kept *keep = arg;
pdf_document *written = ely_pdf_of(ctx, copy);
int k, *rest = others(ctx, written, keep->pages, keep->n, &k);
fz_try(ctx)
{
if (k > 0)
delete_pages(ctx, written, rest, k);
}
fz_always(ctx)
fz_free(ctx, rest);
fz_catch(ctx)
fz_rethrow(ctx);
}
int ely_save(fz_context *ctx, fz_document *doc, const char *raw, const char *out, const char *password)
{
fz_try(ctx)
ely_save_copy(ctx, ely_pdf_of(ctx, doc), raw, out, password, NULL, NULL, NULL);
fz_catch(ctx)
return ely_fail(ctx);
return 0;
}
/* Saves only `pages` to `out`; the document is untouched. */
int ely_extract(fz_context *ctx, fz_document *doc, const int *pages, int n,
const char *raw, const char *out, const char *password)
{
fz_try(ctx)
{
pdf_document *pdf = ely_pdf_of(ctx, doc);
kept keep = { pages, n };
check_pages(ctx, pdf, pages, n);
ely_save_copy(ctx, pdf, raw, out, password, NULL, keep_only, &keep);
}
fz_catch(ctx)
return ely_fail(ctx);
return 0;
}
+336
View File
@@ -0,0 +1,336 @@
/* Images and form XObjects: list, move, scale, swap, add (PDF-04). */
#include <math.h>
#include "ely_shim.h"
/* One drawn object: its kind and where it lands. */
typedef struct
{
int form;
fz_matrix ctm;
fz_rect rect;
} drawn;
/* Counts top-level draws, following q, Q and cm. */
typedef struct
{
pdf_processor super;
fz_matrix ctm;
fz_matrix *stack;
int depth, room;
fz_matrix page;
drawn *found;
int n, cap;
} inventory;
static void inv_q(fz_context *ctx, pdf_processor *proc)
{
inventory *inv = (inventory *)proc;
if (inv->depth == inv->room)
{
inv->room = inv->room * 2 + 8;
inv->stack = fz_realloc_array(ctx, inv->stack, inv->room, fz_matrix);
}
inv->stack[inv->depth++] = inv->ctm;
}
static void inv_Q(fz_context *ctx, pdf_processor *proc)
{
inventory *inv = (inventory *)proc;
if (inv->depth > 0)
inv->ctm = inv->stack[--inv->depth];
}
static void inv_cm(fz_context *ctx, pdf_processor *proc, float a, float b, float c, float d, float e, float f)
{
inventory *inv = (inventory *)proc;
inv->ctm = fz_concat(fz_make_matrix(a, b, c, d, e, f), inv->ctm);
}
static void found(fz_context *ctx, inventory *inv, int form, fz_rect box)
{
if (inv->n == inv->cap)
{
inv->cap = inv->cap * 2 + 8;
inv->found = fz_realloc_array(ctx, inv->found, inv->cap, drawn);
}
inv->found[inv->n].form = form;
inv->found[inv->n].ctm = inv->ctm;
inv->found[inv->n++].rect = fz_transform_rect(box, fz_concat(inv->ctm, inv->page));
}
static void inv_image(fz_context *ctx, pdf_processor *proc, const char *name, fz_image *image)
{
found(ctx, (inventory *)proc, 0, fz_unit_rect);
}
static void inv_form(fz_context *ctx, pdf_processor *proc, const char *name, pdf_obj *form)
{
fz_rect box = fz_transform_rect(pdf_xobject_bbox(ctx, form), pdf_xobject_matrix(ctx, form));
found(ctx, (inventory *)proc, 1, box);
}
/* The page's top-level draws, in content order. */
static int take_inventory(fz_context *ctx, pdf_document *pdf, pdf_page *page, drawn **out)
{
inventory *inv = pdf_new_processor(ctx, sizeof *inv);
int n = 0;
fz_try(ctx)
{
inv->super.op_q = inv_q;
inv->super.op_Q = inv_Q;
inv->super.op_cm = inv_cm;
inv->super.op_Do_image = inv_image;
inv->super.op_Do_form = inv_form;
inv->ctm = fz_identity;
pdf_page_transform(ctx, page, NULL, &inv->page);
pdf_process_contents(ctx, &inv->super, pdf, pdf_page_resources(ctx, page), pdf_page_contents(ctx, page), NULL, NULL);
pdf_close_processor(ctx, &inv->super);
*out = inv->found;
n = inv->n;
inv->found = NULL;
}
fz_always(ctx)
{
fz_free(ctx, inv->stack);
fz_free(ctx, inv->found);
pdf_drop_processor(ctx, &inv->super);
}
fz_catch(ctx)
fz_rethrow(ctx);
return n;
}
/* JSON of the page's images and forms. */
int ely_objects(fz_context *ctx, fz_document *doc, int number, unsigned char **data, size_t *len)
{
pdf_page *page = NULL;
drawn *list = NULL;
fz_buffer *buf = NULL;
fz_var(page);
fz_var(list);
fz_var(buf);
fz_try(ctx)
{
pdf_document *pdf = ely_pdf_of(ctx, doc);
int i, n;
page = pdf_load_page(ctx, pdf, number);
n = take_inventory(ctx, pdf, page, &list);
buf = fz_new_buffer(ctx, 256);
fz_append_byte(ctx, buf, '[');
for (i = 0; i < n; i++)
fz_append_printf(ctx, buf, "%s{\"kind\":\"%s\",\"rect\":[%g,%g,%g,%g]}", i ? "," : "",
list[i].form ? "form" : "image", list[i].rect.x0, list[i].rect.y0, list[i].rect.x1, list[i].rect.y1);
fz_append_byte(ctx, buf, ']');
*len = fz_buffer_extract(ctx, buf, data);
}
fz_always(ctx)
{
fz_drop_buffer(ctx, buf);
fz_free(ctx, list);
fz_drop_page(ctx, (fz_page *)page);
}
fz_catch(ctx)
return ely_fail(ctx);
return 0;
}
/* What the rewrite does at draw `target`. */
typedef struct
{
int target, seen, drop;
fz_matrix x;
const char *rename;
pdf_processor *out;
void (*image)(fz_context *, pdf_processor *, const char *, fz_image *);
void (*form)(fz_context *, pdf_processor *, const char *, pdf_obj *);
} hook;
/* Wraps the chosen draw in `x`, renames or drops it. */
static int at_target(fz_context *ctx, hook *h, const char **name)
{
if (h->seen++ != h->target)
return 0;
if (!h->drop)
{
h->out->op_q(ctx, h->out);
h->out->op_cm(ctx, h->out, h->x.a, h->x.b, h->x.c, h->x.d, h->x.e, h->x.f);
if (h->rename)
*name = h->rename;
}
return 1;
}
static void hook_image(fz_context *ctx, pdf_processor *proc, const char *name, fz_image *image)
{
hook *h = fz_user_context(ctx);
int hit = at_target(ctx, h, &name);
if (!(hit && h->drop))
h->image(ctx, proc, name, image);
if (hit && !h->drop)
h->out->op_Q(ctx, h->out);
}
static void hook_form(fz_context *ctx, pdf_processor *proc, const char *name, pdf_obj *form)
{
hook *h = fz_user_context(ctx);
int hit = at_target(ctx, h, &name);
if (!(hit && h->drop))
h->form(ctx, proc, name, form);
if (hit && !h->drop)
h->out->op_Q(ctx, h->out);
}
/* Rewrites the page's content with `h` at its target draw. */
static void rewrite(fz_context *ctx, pdf_document *pdf, pdf_page *page, hook *h)
{
fz_buffer *buf = fz_new_buffer(ctx, 1024);
pdf_processor *out = NULL;
void *before = fz_user_context(ctx);
fz_var(out);
fz_try(ctx)
{
out = pdf_new_buffer_processor(ctx, buf, 0, 0);
h->out = out;
h->image = out->op_Do_image;
h->form = out->op_Do_form;
out->op_Do_image = hook_image;
out->op_Do_form = hook_form;
fz_set_user_context(ctx, h);
pdf_process_contents(ctx, out, pdf, pdf_page_resources(ctx, page), pdf_page_contents(ctx, page), NULL, NULL);
pdf_close_processor(ctx, out);
if (h->seen <= h->target)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "no drawn object %d", h->target);
pdf_dict_put_drop(ctx, page->obj, PDF_NAME(Contents), pdf_add_stream(ctx, pdf, buf, NULL, 0));
}
fz_always(ctx)
{
fz_set_user_context(ctx, before);
pdf_drop_processor(ctx, out);
fz_drop_buffer(ctx, buf);
}
fz_catch(ctx)
fz_rethrow(ctx);
}
/* The draw's matrix in page space. */
static fz_matrix placed_at(fz_context *ctx, pdf_document *pdf, pdf_page *page, int index, fz_rect *rect)
{
drawn *list = NULL;
fz_matrix at = fz_identity, page_ctm;
fz_var(list);
fz_try(ctx)
{
int n = take_inventory(ctx, pdf, page, &list);
if (index < 0 || index >= n)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "no drawn object %d", index);
pdf_page_transform(ctx, page, NULL, &page_ctm);
at = fz_concat(list[index].ctm, page_ctm);
*rect = list[index].rect;
}
fz_always(ctx)
fz_free(ctx, list);
fz_catch(ctx)
fz_rethrow(ctx);
return at;
}
/* Draw `index` moved by page-space `t`, swapped, or dropped. */
int ely_place(fz_context *ctx, fz_document *doc, int number, int index, const float t[6], int drop, const char *path)
{
pdf_document *pdf = NULL;
pdf_page *page = NULL;
fz_image *image = NULL;
pdf_obj *ref = NULL;
int begun = 0;
fz_var(pdf);
fz_var(page);
fz_var(image);
fz_var(ref);
fz_var(begun);
fz_try(ctx)
{
hook h = { index, 0, drop, fz_identity, NULL, NULL, NULL, NULL };
fz_matrix change = fz_make_matrix(t[0], t[1], t[2], t[3], t[4], t[5]), at;
fz_rect rect;
char name[32];
pdf = ely_pdf_of(ctx, doc);
page = pdf_load_page(ctx, pdf, number);
pdf_begin_operation(ctx, pdf, drop ? "Delete an object" : path ? "Replace an image" : "Move an object");
begun = 1;
at = placed_at(ctx, pdf, page, index, &rect);
if (path)
{
/* The new picture fits inside the old one's box. */
float box = (rect.x1 - rect.x0) / (rect.y1 - rect.y0), own;
float cx = (rect.x0 + rect.x1) / 2, cy = (rect.y0 + rect.y1) / 2;
image = fz_new_image_from_file(ctx, path);
own = (float)image->w / image->h;
change = fz_concat(fz_concat(fz_translate(-cx, -cy), fz_scale(fminf(1, own / box), fminf(1, box / own))), fz_translate(cx, cy));
ref = pdf_add_image(ctx, pdf, image);
h.rename = ely_add_resource(ctx, pdf, page->obj, PDF_NAME(XObject), "ElyIm", ref, name, sizeof name);
}
if (fz_matrix_expansion(change) < 0.001f)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a change that leaves nothing");
h.x = fz_concat(fz_concat(at, change), fz_invert_matrix(at));
rewrite(ctx, pdf, page, &h);
pdf_end_operation(ctx, pdf);
}
fz_always(ctx)
{
pdf_drop_obj(ctx, ref);
fz_drop_image(ctx, image);
fz_drop_page(ctx, (fz_page *)page);
}
fz_catch(ctx)
return ely_edit_failed(ctx, pdf, begun);
return 0;
}
/* An image file drawn into page-space `rect`, in one step. */
int ely_add_image(fz_context *ctx, fz_document *doc, int number, const char *path, const float rect[4])
{
pdf_document *pdf = NULL;
pdf_page *page = NULL;
fz_image *image = NULL;
pdf_obj *ref = NULL;
fz_buffer *buf = NULL;
int begun = 0;
fz_var(pdf);
fz_var(page);
fz_var(image);
fz_var(ref);
fz_var(buf);
fz_var(begun);
fz_try(ctx)
{
fz_matrix m;
char name[32];
pdf = ely_pdf_of(ctx, doc);
page = pdf_load_page(ctx, pdf, number);
if (rect[2] - rect[0] < 1 || rect[3] - rect[1] < 1)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "an image box of nothing");
image = fz_new_image_from_file(ctx, path);
pdf_begin_operation(ctx, pdf, "Add an image");
begun = 1;
ref = pdf_add_image(ctx, pdf, image);
ely_add_resource(ctx, pdf, page->obj, PDF_NAME(XObject), "ElyIm", ref, name, sizeof name);
/* The unit square, bottom left first, onto the box. */
m = fz_concat(fz_make_matrix(rect[2] - rect[0], 0, 0, rect[1] - rect[3], rect[0], rect[3]), ely_to_user(ctx, page));
buf = fz_new_buffer(ctx, 128);
fz_append_printf(ctx, buf, "q %g %g %g %g %g %g cm /%s Do Q\n", m.a, m.b, m.c, m.d, m.e, m.f, name);
ely_append_content(ctx, pdf, page->obj, buf);
pdf_end_operation(ctx, pdf);
}
fz_always(ctx)
{
fz_drop_buffer(ctx, buf);
pdf_drop_obj(ctx, ref);
fz_drop_image(ctx, image);
fz_drop_page(ctx, (fz_page *)page);
}
fz_catch(ctx)
return ely_edit_failed(ctx, pdf, begun);
return 0;
}
+423
View File
@@ -0,0 +1,423 @@
/* True removal into a new file, then checked (PDF-09, QA-14). */
#include <math.h>
#include <string.h>
#include "ely_shim.h"
/* Regions by page, page space. */
typedef struct
{
int page;
fz_rect rect;
} region;
static int touches(fz_rect a, fz_rect b)
{
return !fz_is_empty_rect(fz_intersect_rect(a, b));
}
/* Throws unless every region is whole and on a page. */
static region *regions_of(fz_context *ctx, fz_json *list, int pages, int *n)
{
region *out;
int i;
*n = list && list->type == FZ_JSON_ARRAY ? fz_json_array_length(ctx, list) : 0;
if (*n == 0)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "nothing marked to remove");
out = fz_malloc_array(ctx, *n, region);
fz_try(ctx)
{
for (i = 0; i < *n; i++)
{
fz_json *spec = fz_json_array_get(ctx, list, i);
fz_json *page = ely_member(ctx, spec, "page", FZ_JSON_NUMBER);
if (!page || page->u.number < 0 || page->u.number >= pages)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a region off the pages");
out[i].page = (int)page->u.number;
out[i].rect = ely_rect(ctx, ely_member(ctx, spec, "rect", FZ_JSON_ARRAY), 1);
}
}
fz_catch(ctx)
{
fz_free(ctx, out);
fz_rethrow(ctx);
}
return out;
}
/* Drops annotations and fields that touch `area`; they carry text. */
static void drop_touching(fz_context *ctx, pdf_page *page, fz_rect area)
{
pdf_annot *annot;
int widgets;
for (widgets = 0; widgets < 2; widgets++)
{
restart:
for (annot = widgets ? pdf_first_widget(ctx, page) : pdf_first_annot(ctx, page); annot;
annot = widgets ? pdf_next_widget(ctx, annot) : pdf_next_annot(ctx, annot))
if (touches(pdf_bound_annot(ctx, annot), area))
{
pdf_obj *field = pdf_keep_obj(ctx, pdf_annot_obj(ctx, annot));
fz_try(ctx)
{
pdf_delete_annot(ctx, page, annot);
/* A field left with no widget still holds its value. */
if (widgets)
ely_unlink_field(ctx, page->doc, field);
}
fz_always(ctx)
pdf_drop_obj(ctx, field);
fz_catch(ctx)
fz_rethrow(ctx);
goto restart;
}
}
}
/* Applies `regions` to the copy, page by page. */
static void redact(fz_context *ctx, pdf_document *pdf, region *regions, int n)
{
pdf_redact_options opts = { 1, PDF_REDACT_IMAGE_PIXELS, PDF_REDACT_LINE_ART_REMOVE_IF_TOUCHED, PDF_REDACT_TEXT_REMOVE };
pdf_page *page = NULL;
int i, k;
fz_var(page);
fz_try(ctx)
{
for (i = 0; i < pdf_count_pages(ctx, pdf); i++)
{
int any = 0;
for (k = 0; k < n; k++)
any |= regions[k].page == i;
if (!any)
continue;
page = pdf_load_page(ctx, pdf, i);
for (k = 0; k < n; k++)
if (regions[k].page == i)
drop_touching(ctx, page, regions[k].rect);
/* Marks after drops, or a drop takes a mark. */
for (k = 0; k < n; k++)
if (regions[k].page == i)
{
pdf_annot *mark = pdf_create_annot(ctx, page, PDF_ANNOT_REDACT);
pdf_set_annot_rect(ctx, mark, regions[k].rect);
pdf_drop_annot(ctx, mark);
}
pdf_redact_page(ctx, pdf, page, &opts);
ely_drop_alt(ctx, pdf, page);
pdf_dict_del(ctx, page->obj, PDF_NAME(Thumb));
fz_drop_page(ctx, (fz_page *)page);
page = NULL;
}
}
fz_always(ctx)
fz_drop_page(ctx, (fz_page *)page);
fz_catch(ctx)
fz_rethrow(ctx);
}
/* A glyph box shrunk a tenth, as redaction judges. */
static fz_rect shrunk(fz_rect r)
{
float w = (r.x1 - r.x0) / 10, h = (r.y1 - r.y0) / 10;
return fz_make_rect(r.x0 + w, r.y0 + h, r.x1 - w, r.y1 - h);
}
/* Characters on `page` inside `area`, hidden ones too. */
static int chars_in(fz_context *ctx, fz_document *doc, int number, fz_rect area)
{
fz_stext_page *text = NULL;
int n = 0;
fz_var(text);
fz_try(ctx)
{
fz_stext_block *block;
fz_stext_line *line;
fz_stext_char *ch;
text = fz_new_stext_page_from_page_number(ctx, doc, number, NULL);
for (block = text->first_block; block; block = block->next)
if (block->type == FZ_STEXT_BLOCK_TEXT)
for (line = block->u.t.first_line; line; line = line->next)
for (ch = line->first_char; ch; ch = ch->next)
n += touches(shrunk(fz_rect_from_quad(ch->quad)), area);
}
fz_always(ctx)
fz_drop_stext_page(ctx, text);
fz_catch(ctx)
fz_rethrow(ctx);
return n;
}
/* Pixels in `area` that are not black once drawn. */
static int light_in(fz_context *ctx, fz_document *doc, int number, fz_rect area)
{
fz_pixmap *pix = NULL;
int n = 0;
fz_var(pix);
fz_try(ctx)
{
fz_page *page = fz_load_page(ctx, doc, number);
fz_irect box = fz_round_rect(fz_intersect_rect(area, fz_bound_page(ctx, page)));
unsigned char *s;
int x, y;
fz_drop_page(ctx, page);
/* One pixel in from each edge: boxes antialias. */
box.x0++, box.y0++, box.x1--, box.y1--;
if (box.x1 <= box.x0 || box.y1 <= box.y0)
break;
pix = fz_new_pixmap_with_bbox(ctx, fz_device_rgb(ctx), box, NULL, 0);
fz_clear_pixmap_with_value(ctx, pix, 255);
page = fz_load_page(ctx, doc, number);
fz_try(ctx)
{
fz_device *dev = fz_new_draw_device(ctx, fz_identity, pix);
fz_try(ctx)
{
fz_run_page(ctx, page, dev, fz_identity, NULL);
fz_close_device(ctx, dev);
}
fz_always(ctx)
fz_drop_device(ctx, dev);
fz_catch(ctx)
fz_rethrow(ctx);
}
fz_always(ctx)
fz_drop_page(ctx, page);
fz_catch(ctx)
fz_rethrow(ctx);
for (y = 0, s = pix->samples; y < pix->h; y++, s += pix->stride - pix->w * 3)
for (x = 0; x < pix->w; x++, s += 3)
n += s[0] > 40 || s[1] > 40 || s[2] > 40;
}
fz_always(ctx)
fz_drop_pixmap(ctx, pix);
fz_catch(ctx)
fz_rethrow(ctx);
return n;
}
/* Counts drawings in the regions, our boxes aside. */
typedef struct
{
fz_device super;
region *regions;
int n, page, leaks;
} leak_dev;
static int in_regions(leak_dev *d, fz_rect r)
{
int k;
for (k = 0; k < d->n; k++)
if (d->regions[k].page == d->page && touches(r, d->regions[k].rect))
return 1;
return 0;
}
static int black(fz_context *ctx, fz_colorspace *cs, const float *color)
{
float rgb[3];
if (!cs)
return 0;
fz_convert_color(ctx, cs, color, fz_device_rgb(ctx), rgb, NULL, fz_default_color_params);
return rgb[0] <= 0.02f && rgb[1] <= 0.02f && rgb[2] <= 0.02f;
}
/* Whether `r`, black, is one of the region boxes. */
static int is_box(fz_context *ctx, leak_dev *d, fz_rect r, fz_colorspace *cs, const float *color)
{
int k;
if (!black(ctx, cs, color))
return 0;
for (k = 0; k < d->n; k++)
{
fz_rect b = d->regions[k].rect;
if (d->regions[k].page == d->page && fabsf(r.x0 - b.x0) < 1 && fabsf(r.y0 - b.y0) < 1 &&
fabsf(r.x1 - b.x1) < 1 && fabsf(r.y1 - b.y1) < 1)
return 1;
}
return 0;
}
static void leak_fill_path(fz_context *ctx, fz_device *dev, const fz_path *path, int even_odd, fz_matrix ctm,
fz_colorspace *cs, const float *color, float alpha, fz_color_params cp)
{
leak_dev *d = (leak_dev *)dev;
fz_rect r = fz_bound_path(ctx, path, NULL, ctm);
(void)even_odd, (void)alpha, (void)cp;
if (in_regions(d, r) && !is_box(ctx, d, r, cs, color))
d->leaks++;
}
static void leak_stroke_path(fz_context *ctx, fz_device *dev, const fz_path *path, const fz_stroke_state *stroke,
fz_matrix ctm, fz_colorspace *cs, const float *color, float alpha, fz_color_params cp)
{
leak_dev *d = (leak_dev *)dev;
(void)cs, (void)color, (void)alpha, (void)cp;
d->leaks += in_regions(d, fz_bound_path(ctx, path, stroke, ctm));
}
static void leak_fill_shade(fz_context *ctx, fz_device *dev, fz_shade *shade, fz_matrix ctm, float alpha, fz_color_params cp)
{
leak_dev *d = (leak_dev *)dev;
(void)alpha, (void)cp;
d->leaks += in_regions(d, fz_bound_shade(ctx, shade, ctm));
}
static void leak_fill_image_mask(fz_context *ctx, fz_device *dev, fz_image *image, fz_matrix ctm, fz_colorspace *cs,
const float *color, float alpha, fz_color_params cp)
{
leak_dev *d = (leak_dev *)dev;
(void)image, (void)alpha, (void)cp;
d->leaks += in_regions(d, fz_transform_rect(fz_unit_rect, ctm)) && !black(ctx, cs, color);
}
/* Image pixels in `area` neither white nor black. */
static int image_light(fz_context *ctx, fz_image *image, fz_matrix ctm, fz_rect area)
{
fz_irect box = fz_round_rect(fz_intersect_rect(area, fz_transform_rect(fz_unit_rect, ctm)));
fz_pixmap *pix = NULL;
fz_device *draw = NULL;
int n = 0, x, y;
box.x0++, box.y0++, box.x1--, box.y1--;
if (box.x1 <= box.x0 || box.y1 <= box.y0)
return 0;
fz_var(pix);
fz_var(draw);
fz_try(ctx)
{
unsigned char *s;
pix = fz_new_pixmap_with_bbox(ctx, fz_device_rgb(ctx), box, NULL, 1);
fz_clear_pixmap(ctx, pix);
draw = fz_new_draw_device(ctx, fz_identity, pix);
fz_fill_image(ctx, draw, image, ctm, 1, fz_default_color_params);
fz_close_device(ctx, draw);
for (y = 0, s = pix->samples; y < pix->h; y++, s += pix->stride - pix->w * 4)
for (x = 0; x < pix->w; x++, s += 4)
{
int high = s[0] > 215 && s[1] > 215 && s[2] > 215, low = s[0] < 40 && s[1] < 40 && s[2] < 40;
n += s[3] > 200 && !high && !low;
}
}
fz_always(ctx)
{
fz_drop_device(ctx, draw);
fz_drop_pixmap(ctx, pix);
}
fz_catch(ctx)
fz_rethrow(ctx);
return n;
}
static void leak_fill_image(fz_context *ctx, fz_device *dev, fz_image *image, fz_matrix ctm, float alpha, fz_color_params cp)
{
leak_dev *d = (leak_dev *)dev;
int k;
(void)alpha, (void)cp;
for (k = 0; k < d->n; k++)
if (d->regions[k].page == d->page)
d->leaks += image_light(ctx, image, ctm, d->regions[k].rect);
}
/* Drawings left in the regions of page `number`. */
static int leaks_on(fz_context *ctx, fz_document *doc, int number, region *regions, int n)
{
leak_dev *d = fz_new_derived_device(ctx, leak_dev);
fz_page *page = NULL;
int leaks = 0;
fz_var(page);
d->super.fill_path = leak_fill_path;
d->super.stroke_path = leak_stroke_path;
d->super.fill_shade = leak_fill_shade;
d->super.fill_image = leak_fill_image;
d->super.fill_image_mask = leak_fill_image_mask;
d->regions = regions, d->n = n, d->page = number;
fz_try(ctx)
{
page = fz_load_page(ctx, doc, number);
fz_run_page(ctx, page, &d->super, fz_identity, NULL);
fz_close_device(ctx, &d->super);
leaks = d->leaks;
}
fz_always(ctx)
{
fz_drop_page(ctx, page);
fz_drop_device(ctx, &d->super);
}
fz_catch(ctx)
fz_rethrow(ctx);
return leaks;
}
typedef struct
{
region *regions;
int n;
} marked;
static void apply_marks(fz_context *ctx, fz_document *copy, void *arg)
{
marked *m = arg;
redact(ctx, ely_pdf_of(ctx, copy), m->regions, m->n);
}
/* Checks `out`: no text, no light in any region. */
static void check_redacted(fz_context *ctx, const char *out, const char *password, region *regions, int n, fz_buffer *report)
{
fz_document *doc = fz_open_document(ctx, out);
fz_try(ctx)
{
int i, text = 0, light = 0, objects = 0, versions;
if (fz_needs_password(ctx, doc) && !fz_authenticate_password(ctx, doc, password))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "the written file refused its password");
for (i = 0; i < n; i++)
{
text += chars_in(ctx, doc, regions[i].page, regions[i].rect);
light += light_in(ctx, doc, regions[i].page, regions[i].rect);
objects += pdf_dict_get(ctx, pdf_lookup_page_obj(ctx, ely_pdf_of(ctx, doc), regions[i].page), PDF_NAME(Thumb)) != NULL;
}
for (i = 0; i < fz_count_pages(ctx, doc); i++)
objects += leaks_on(ctx, doc, i, regions, n);
versions = pdf_count_versions(ctx, ely_pdf_of(ctx, doc));
fz_append_printf(ctx, report, "{\"regions\":%d,\"text\":%d,\"light\":%d,\"objects\":%d,\"versions\":%d}", n, text,
light, objects, versions);
if (text || light || objects || versions != 1)
fz_throw(ctx, FZ_ERROR_FORMAT, "the written file still holds what was removed: %d characters, %d light pixels, %d drawings, %d versions",
text, light, objects, versions);
}
fz_always(ctx)
fz_drop_document(ctx, doc);
fz_catch(ctx)
fz_rethrow(ctx);
}
/* Removes the marked regions into `out`, then checks it. */
int ely_redact(fz_context *ctx, fz_document *doc, const char *json, const char *raw, const char *out,
const char *password, unsigned char **data, size_t *len)
{
fz_pool *pool = NULL;
marked m = { NULL, 0 };
fz_buffer *report = NULL;
fz_var(pool);
fz_var(m);
fz_var(report);
fz_try(ctx)
{
pdf_document *pdf = ely_pdf_of(ctx, doc);
pool = fz_new_pool(ctx);
m.regions = regions_of(ctx, fz_parse_json(ctx, pool, json), pdf_count_pages(ctx, pdf), &m.n);
ely_save_copy(ctx, pdf, raw, out, password, NULL, apply_marks, &m);
report = fz_new_buffer(ctx, 128);
check_redacted(ctx, out, password, m.regions, m.n, report);
*len = fz_buffer_extract(ctx, report, data);
}
fz_always(ctx)
{
fz_drop_buffer(ctx, report);
fz_free(ctx, m.regions);
fz_drop_pool(ctx, pool);
}
fz_catch(ctx)
return ely_fail(ctx);
return 0;
}
+74
View File
@@ -0,0 +1,74 @@
/* Permissions and protected copies (PDF-11). */
#include <string.h>
#include "ely_shim.h"
enum { MAY_PRINT = 1, MAY_COPY = 2, MAY_EDIT = 4, MAY_ANNOTATE = 8, MAY_FILL = 16, MAY_ASSEMBLE = 32 };
/* What the document allows, as Ely's bits. */
int ely_permissions(fz_context *ctx, fz_document *doc)
{
int may = 0;
fz_try(ctx)
{
pdf_document *pdf = ely_pdf_of(ctx, doc);
int edit = pdf_has_permission(ctx, pdf, FZ_PERMISSION_EDIT) != 0;
int annotate = pdf_has_permission(ctx, pdf, FZ_PERMISSION_ANNOTATE) != 0;
may |= pdf_has_permission(ctx, pdf, FZ_PERMISSION_PRINT) ? MAY_PRINT : 0;
may |= pdf_has_permission(ctx, pdf, FZ_PERMISSION_COPY) ? MAY_COPY : 0;
may |= edit ? MAY_EDIT : 0;
may |= annotate ? MAY_ANNOTATE : 0;
may |= annotate || pdf_has_permission(ctx, pdf, FZ_PERMISSION_FORM) ? MAY_FILL : 0;
may |= edit || pdf_has_permission(ctx, pdf, FZ_PERMISSION_ASSEMBLE) ? MAY_ASSEMBLE : 0;
}
fz_catch(ctx)
return ely_fail(ctx);
return may;
}
/* PDF's permission bits for Ely's `may`. */
static int pdf_bits(int may)
{
int p = ~(PDF_PERM_PRINT | PDF_PERM_MODIFY | PDF_PERM_COPY | PDF_PERM_ANNOTATE | PDF_PERM_FORM |
PDF_PERM_ASSEMBLE | PDF_PERM_PRINT_HQ | 3);
p |= may & MAY_PRINT ? PDF_PERM_PRINT | PDF_PERM_PRINT_HQ : 0;
p |= may & MAY_COPY ? PDF_PERM_COPY : 0;
p |= may & MAY_EDIT ? PDF_PERM_MODIFY : 0;
p |= may & MAY_ANNOTATE ? PDF_PERM_ANNOTATE : 0;
p |= may & MAY_FILL ? PDF_PERM_FORM : 0;
p |= may & MAY_ASSEMBLE ? PDF_PERM_ASSEMBLE : 0;
return p;
}
static void put_password(fz_context *ctx, char *into, const char *password)
{
if (strlen(password) >= 128)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a password longer than 127 bytes");
strcpy(into, password);
}
/* Writes `out` with AES-256 and `may`, or unprotected. */
int ely_protect(fz_context *ctx, fz_document *doc, const char *raw, const char *out, const char *password,
int protect, const char *user, const char *owner, int may)
{
fz_try(ctx)
{
pdf_write_options opts = pdf_default_write_options;
opts.do_encrypt = protect ? PDF_ENCRYPT_AES_256 : PDF_ENCRYPT_NONE;
if (protect)
{
if (!*owner)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "an owner password is needed");
if (!strcmp(user, owner))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "the owner password equals the open password");
put_password(ctx, opts.upwd_utf8, user);
put_password(ctx, opts.opwd_utf8, owner);
opts.permissions = pdf_bits(may);
}
ely_save_copy(ctx, ely_pdf_of(ctx, doc), raw, out, password, &opts, NULL, NULL);
}
fz_catch(ctx)
return ely_fail(ctx);
return 0;
}
+56
View File
@@ -0,0 +1,56 @@
/* What the shim files share. */
#ifndef ELY_SHIM_H
#define ELY_SHIM_H
#include <mupdf/fitz.h>
#include <mupdf/pdf.h>
int ely_fail(fz_context *ctx);
const char *ely_error(void);
int ely_render(fz_context *ctx, fz_document *doc, int number, float scale, int rotate, const int tile[4], int dark,
unsigned char *bgra);
void ely_fail_also(fz_context *ctx, const char *what);
pdf_document *ely_pdf_of(fz_context *ctx, fz_document *doc);
int ely_edit_failed(fz_context *ctx, pdf_document *pdf, int begun);
void ely_forget_resources(fz_context *ctx, pdf_document *pdf);
pdf_obj *ely_target(fz_context *ctx, pdf_document *pdf, pdf_obj *obj);
typedef void (ely_change)(fz_context *ctx, fz_document *copy, void *arg);
void ely_save_copy(fz_context *ctx, pdf_document *pdf, const char *raw, const char *out, const char *password,
const pdf_write_options *opts,
ely_change *change, void *arg);
/* A text block as read, page space, and its glyphs. */
typedef struct
{
void *glyphs;
fz_font *font;
fz_point first;
float size;
int rgb;
fz_rect bbox;
int lines;
float gap;
} ely_shape;
fz_matrix ely_to_user(fz_context *ctx, pdf_page *page);
void ely_read_block(fz_context *ctx, fz_document *doc, pdf_page *page, int number, int index, const char *expected,
ely_shape *shape);
void ely_remove_block(fz_context *ctx, pdf_document *pdf, pdf_page *page, ely_shape *shape);
void ely_drop_shape(fz_context *ctx, ely_shape *shape);
pdf_obj *ely_append_content(fz_context *ctx, pdf_document *pdf, pdf_obj *page, fz_buffer *buf);
const char *ely_add_resource(fz_context *ctx, pdf_document *pdf, pdf_obj *page, pdf_obj *type, const char *stem,
pdf_obj *ref, char *name, size_t room);
void ely_json_string(fz_context *ctx, fz_output *out, const char *s);
fz_json *ely_member(fz_context *ctx, fz_json *obj, const char *key, int type);
float ely_number(fz_context *ctx, fz_json *array, int at);
fz_rect ely_rect(fz_context *ctx, fz_json *array, float least);
pdf_annot *ely_find_annot(fz_context *ctx, pdf_page *page, int id, int widget);
void ely_write_fields(fz_context *ctx, fz_output *out, pdf_page *page);
void ely_unlink_field(fz_context *ctx, pdf_document *pdf, pdf_obj *field);
void ely_unsign(fz_context *ctx, pdf_document *pdf);
void ely_watch_begin(fz_context *ctx);
int ely_watch_end(fz_context *ctx);
const char *ely_open_warnings(void);
void ely_drop_alt(fz_context *ctx, pdf_document *pdf, pdf_page *page);
#endif
+409
View File
@@ -0,0 +1,409 @@
/* Signatures: read and checked (PDF-12, QA-15). */
#include <limits.h>
#include <string.h>
#include <openssl/pkcs7.h>
#include <openssl/x509.h>
#include <mupdf/helpers/pkcs7-openssl.h>
#include "ely_shim.h"
static const char *digest_name(pdf_signature_error error)
{
switch (error)
{
case PDF_SIGNATURE_ERROR_OKAY: return "ok";
case PDF_SIGNATURE_ERROR_DIGEST_FAILURE: return "changed";
case PDF_SIGNATURE_ERROR_NO_CERTIFICATE: return "no_certificate";
default: return "unreadable";
}
}
static void put_hex(fz_context *ctx, fz_output *out, const unsigned char *data, int len)
{
int i;
fz_write_byte(ctx, out, '"');
for (i = 0; i < len; i++)
fz_write_printf(ctx, out, "%02x", data[i]);
fz_write_byte(ctx, out, '"');
}
static void put_cert(fz_context *ctx, fz_output *out, X509 *cert, int *first)
{
unsigned char *der = NULL;
int len = i2d_X509(cert, &der);
if (len <= 0)
fz_throw(ctx, FZ_ERROR_FORMAT, "a certificate that will not encode");
fz_try(ctx)
{
if (!*first)
fz_write_byte(ctx, out, ',');
*first = 0;
put_hex(ctx, out, der, len);
}
fz_always(ctx)
OPENSSL_free(der);
fz_catch(ctx)
fz_rethrow(ctx);
}
/* The signer's certificate first, then the rest it carries. */
static void put_certs(fz_context *ctx, fz_output *out, const char *contents, size_t len)
{
const unsigned char *at = (const unsigned char *)contents;
PKCS7 *p7 = len < INT_MAX ? d2i_PKCS7(NULL, &at, (long)len) : NULL;
STACK_OF(X509) *signers = NULL, *carried;
int i, first = 1;
if (!p7 || !PKCS7_type_is_signed(p7))
{
PKCS7_free(p7);
fz_throw(ctx, FZ_ERROR_FORMAT, "a signature that is not PKCS #7 signed data");
}
fz_try(ctx)
{
carried = p7->d.sign->cert;
signers = PKCS7_get0_signers(p7, NULL, 0);
fz_write_string(ctx, out, "[");
for (i = 0; i < sk_X509_num(signers); i++)
put_cert(ctx, out, sk_X509_value(signers, i), &first);
for (i = 0; i < sk_X509_num(carried); i++)
if (sk_X509_find(signers, sk_X509_value(carried, i)) < 0)
put_cert(ctx, out, sk_X509_value(carried, i), &first);
fz_write_string(ctx, out, "]");
}
fz_always(ctx)
{
sk_X509_free(signers);
PKCS7_free(p7);
}
fz_catch(ctx)
fz_rethrow(ctx);
}
static void put_text(fz_context *ctx, fz_output *out, const char *key, pdf_obj *value)
{
fz_write_printf(ctx, out, ",\"%s\":", key);
ely_json_string(ctx, out, pdf_is_string(ctx, value) ? pdf_to_text_string(ctx, value) : "");
}
static void put_signed(fz_context *ctx, fz_output *out, pdf_document *pdf, pdf_obj *field, pdf_pkcs7_verifier *verifier)
{
pdf_obj *v = pdf_dict_get_inheritable(ctx, field, PDF_NAME(V));
pdf_pkcs7_distinguished_name *dn = pdf_signature_get_signatory(ctx, verifier, pdf, field);
char *signer = NULL, *contents = NULL;
size_t len;
fz_var(signer);
fz_var(contents);
fz_try(ctx)
{
signer = dn ? pdf_signature_format_distinguished_name(ctx, dn) : NULL;
fz_write_printf(ctx, out, ",\"digest\":\"%s\"", digest_name(pdf_check_digest(ctx, verifier, pdf, field)));
fz_write_printf(ctx, out, ",\"later\":%d", pdf_signature_incremental_change_since_signing(ctx, pdf, field));
fz_write_printf(ctx, out, ",\"broken\":%d", pdf_validate_signature(ctx, pdf, field));
fz_write_string(ctx, out, ",\"signer\":");
ely_json_string(ctx, out, signer ? signer : "");
fz_write_string(ctx, out, ",\"common\":");
ely_json_string(ctx, out, dn && dn->cn ? dn->cn : "");
put_text(ctx, out, "date", pdf_dict_get(ctx, v, PDF_NAME(M)));
put_text(ctx, out, "reason", pdf_dict_get(ctx, v, PDF_NAME(Reason)));
put_text(ctx, out, "location", pdf_dict_get(ctx, v, PDF_NAME(Location)));
len = pdf_signature_contents(ctx, pdf, field, &contents);
fz_write_string(ctx, out, ",\"certs\":");
put_certs(ctx, out, contents, len);
}
fz_always(ctx)
{
fz_free(ctx, contents);
fz_free(ctx, signer);
pdf_signature_drop_distinguished_name(ctx, dn);
}
fz_catch(ctx)
fz_rethrow(ctx);
}
/* A broken signature reports why; the others still list. */
static void put_checked(fz_context *ctx, fz_output *out, pdf_document *pdf, pdf_obj *field, pdf_pkcs7_verifier *verifier)
{
fz_buffer *buf = fz_new_buffer(ctx, 256);
fz_output *part = NULL;
char why[256] = "";
fz_var(part);
fz_try(ctx)
{
part = fz_new_output_with_buffer(ctx, buf);
put_signed(ctx, part, pdf, field, verifier);
fz_close_output(ctx, part);
}
fz_always(ctx)
fz_drop_output(ctx, part);
fz_catch(ctx)
{
fz_strlcpy(why, fz_caught_message(ctx), sizeof why);
fz_ignore_error(ctx);
}
fz_try(ctx)
{
if (*why)
{
fz_write_string(ctx, out, ",\"digest\":\"unreadable\",\"error\":");
ely_json_string(ctx, out, why);
}
else
fz_write_buffer(ctx, out, buf);
}
fz_always(ctx)
fz_drop_buffer(ctx, buf);
fz_catch(ctx)
fz_rethrow(ctx);
}
/* A widget's page and page-space box; -1 for none. */
static int placed(fz_context *ctx, pdf_document *pdf, pdf_obj *field, fz_rect *box)
{
pdf_obj *widget = pdf_name_eq(ctx, pdf_dict_get(ctx, field, PDF_NAME(Subtype)), PDF_NAME(Widget)) ? field :
pdf_array_get(ctx, pdf_dict_get(ctx, field, PDF_NAME(Kids)), 0);
pdf_obj *page = pdf_dict_get(ctx, widget, PDF_NAME(P));
fz_matrix ctm;
int i, k, number = page ? pdf_lookup_page_number(ctx, pdf, page) : -1;
/* /P is optional; the page's /Annots tell. */
for (i = 0; number < 0 && i < pdf_count_pages(ctx, pdf); i++)
{
pdf_obj *annots = pdf_dict_get(ctx, pdf_lookup_page_obj(ctx, pdf, i), PDF_NAME(Annots));
for (k = 0; k < pdf_array_len(ctx, annots); k++)
if (pdf_to_num(ctx, pdf_array_get(ctx, annots, k)) == pdf_to_num(ctx, widget))
number = i, page = pdf_lookup_page_obj(ctx, pdf, i);
}
*box = fz_empty_rect;
if (number >= 0)
{
pdf_page_obj_transform(ctx, page, NULL, &ctm);
*box = fz_transform_rect(pdf_dict_get_rect(ctx, widget, PDF_NAME(Rect)), ctm);
}
return number;
}
static void put_field(fz_context *ctx, fz_output *out, pdf_document *pdf, pdf_obj *field, pdf_pkcs7_verifier *verifier, int *first)
{
fz_rect r;
int number = placed(ctx, pdf, field, &r), signd = pdf_signature_is_signed(ctx, pdf, field);
char *name = pdf_load_field_name(ctx, field);
fz_try(ctx)
{
fz_write_printf(ctx, out, "%s{\"page\":%d,\"object\":%d,\"rect\":[%g,%g,%g,%g],\"signed\":%s,\"name\":",
*first ? "" : ",", number, pdf_to_num(ctx, field), r.x0, r.y0, r.x1, r.y1, signd ? "true" : "false");
*first = 0;
ely_json_string(ctx, out, name);
if (signd)
put_checked(ctx, out, pdf, field, verifier);
fz_write_byte(ctx, out, '}');
}
fz_always(ctx)
fz_free(ctx, name);
fz_catch(ctx)
fz_rethrow(ctx);
}
/* Signature fields in the form tree, placed or not. */
static void put_tree(fz_context *ctx, fz_output *out, pdf_document *pdf, pdf_obj *node, pdf_pkcs7_verifier *verifier, int *first)
{
pdf_obj *kids = pdf_dict_get(ctx, node, PDF_NAME(Kids));
int i, leaf = 1;
if (pdf_mark_obj(ctx, node))
return;
fz_try(ctx)
{
for (i = 0; i < pdf_array_len(ctx, kids); i++)
leaf &= pdf_dict_get(ctx, pdf_array_get(ctx, kids, i), PDF_NAME(T)) == NULL;
if (!leaf)
for (i = 0; i < pdf_array_len(ctx, kids); i++)
put_tree(ctx, out, pdf, pdf_array_get(ctx, kids, i), verifier, first);
else if (pdf_name_eq(ctx, pdf_dict_get_inheritable(ctx, node, PDF_NAME(FT)), PDF_NAME(Sig)))
put_field(ctx, out, pdf, node, verifier, first);
}
fz_always(ctx)
pdf_unmark_obj(ctx, node);
fz_catch(ctx)
fz_rethrow(ctx);
}
/* Every signature field, as JSON, with its check. */
int ely_signatures(fz_context *ctx, fz_document *doc, unsigned char **data, size_t *len)
{
pdf_pkcs7_verifier *verifier = NULL;
fz_buffer *buf = NULL;
fz_output *out = NULL;
fz_var(verifier);
fz_var(buf);
fz_var(out);
fz_try(ctx)
{
pdf_document *pdf = ely_pdf_of(ctx, doc);
pdf_obj *fields = pdf_dict_getp(ctx, pdf_trailer(ctx, pdf), "Root/AcroForm/Fields");
int i, first = 1;
verifier = pkcs7_openssl_new_verifier(ctx);
buf = fz_new_buffer(ctx, 256);
out = fz_new_output_with_buffer(ctx, buf);
fz_write_byte(ctx, out, '[');
for (i = 0; i < pdf_array_len(ctx, fields); i++)
put_tree(ctx, out, pdf, pdf_array_get(ctx, fields, i), verifier, &first);
fz_write_byte(ctx, out, ']');
fz_close_output(ctx, out);
*len = fz_buffer_extract(ctx, buf, data);
}
fz_always(ctx)
{
fz_drop_output(ctx, out);
fz_drop_buffer(ctx, buf);
pdf_drop_verifier(ctx, verifier);
}
fz_catch(ctx)
return ely_fail(ctx);
return 0;
}
/* An empty field by number, or a new one. */
static pdf_annot *sign_field(fz_context *ctx, pdf_document *pdf, pdf_page *page, int object, const float *rect, const char *name)
{
pdf_obj *form = pdf_dict_getp(ctx, pdf_trailer(ctx, pdf), "Root/AcroForm/Fields");
pdf_annot *widget;
if (object >= 0)
{
widget = ely_find_annot(ctx, page, object, 1);
if (pdf_widget_type(ctx, widget) != PDF_WIDGET_TYPE_SIGNATURE)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "field %d is not a signature field", object);
if (pdf_signature_is_signed(ctx, pdf, pdf_annot_obj(ctx, widget)))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "field %d is signed already", object);
return widget;
}
if (!*name || strchr(name, '.') || (form && pdf_lookup_field(ctx, form, name)))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a signature field needs a new name without dots");
widget = pdf_create_signature_widget(ctx, page, (char *)name);
pdf_set_annot_rect(ctx, widget, fz_make_rect(rect[0], rect[1], rect[2], rect[3]));
return widget;
}
/* Signs into `raw` by an update, then checks it. */
int ely_sign(fz_context *ctx, fz_document *doc, const char *raw, const char *password, const char *pfx, const char *pfx_password,
int number, int object, const float *rect, const char *name, const char *reason, const char *location)
{
pdf_pkcs7_signer *signer = NULL;
pdf_pkcs7_verifier *verifier = NULL;
fz_document *copy = NULL, *signd = NULL;
pdf_page *page = NULL;
pdf_obj *made = NULL;
fz_var(made);
fz_var(signer);
fz_var(verifier);
fz_var(copy);
fz_var(signd);
fz_var(page);
fz_try(ctx)
{
pdf_write_options update = pdf_default_write_options;
pdf_document *pdf;
pdf_annot *widget;
int field;
signer = pkcs7_openssl_read_pfx(ctx, pfx, pfx_password);
pdf_save_snapshot(ctx, ely_pdf_of(ctx, doc), raw);
copy = fz_open_document(ctx, raw);
if (fz_needs_password(ctx, copy) && !fz_authenticate_password(ctx, copy, password))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "the copy refused its password");
pdf = ely_pdf_of(ctx, copy);
page = pdf_load_page(ctx, pdf, number);
widget = sign_field(ctx, pdf, page, object, rect, name);
field = pdf_to_num(ctx, pdf_annot_obj(ctx, widget));
pdf_sign_signature(ctx, widget, signer, PDF_SIGNATURE_SHOW_LABELS | PDF_SIGNATURE_SHOW_DATE | PDF_SIGNATURE_SHOW_TEXT_NAME, NULL, reason, location);
/* Earlier signatures cover earlier bytes; only append. */
update.do_incremental = 1;
pdf_save_document(ctx, pdf, raw, &update);
fz_drop_page(ctx, (fz_page *)page);
page = NULL;
signd = fz_open_document(ctx, raw);
if (fz_needs_password(ctx, signd) && !fz_authenticate_password(ctx, signd, password))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "the signed copy refused its password");
verifier = pkcs7_openssl_new_verifier(ctx);
made = pdf_new_indirect(ctx, ely_pdf_of(ctx, signd), field, 0);
if (pdf_check_digest(ctx, verifier, ely_pdf_of(ctx, signd), made) != PDF_SIGNATURE_ERROR_OKAY)
fz_throw(ctx, FZ_ERROR_FORMAT, "the new signature does not check");
}
fz_always(ctx)
{
pdf_drop_obj(ctx, made);
fz_drop_page(ctx, (fz_page *)page);
fz_drop_document(ctx, signd);
fz_drop_document(ctx, copy);
pdf_drop_verifier(ctx, verifier);
pdf_drop_signer(ctx, signer);
}
fz_catch(ctx)
return ely_fail(ctx);
return 0;
}
/* Signed fields under `field`; with `drop`, their values go. */
static int signed_under(fz_context *ctx, pdf_obj *field, int drop)
{
pdf_obj *kids = pdf_dict_get(ctx, field, PDF_NAME(Kids));
int i, n = 0;
if (pdf_mark_obj(ctx, field))
return 0;
fz_try(ctx)
{
if (pdf_name_eq(ctx, pdf_dict_get_inheritable(ctx, field, PDF_NAME(FT)), PDF_NAME(Sig)) &&
pdf_is_dict(ctx, pdf_dict_get(ctx, field, PDF_NAME(V))))
{
n++;
if (drop)
{
/* The drawn signature would still claim it. */
pdf_dict_del(ctx, field, PDF_NAME(V));
pdf_dict_del(ctx, field, PDF_NAME(AP));
/* Its own lock went with it; it can sign again. */
pdf_dict_put_int(ctx, field, PDF_NAME(Ff), pdf_dict_get_int(ctx, field, PDF_NAME(Ff)) & ~PDF_FIELD_IS_READ_ONLY);
for (i = 0; i < pdf_array_len(ctx, kids); i++)
pdf_dict_del(ctx, pdf_array_get(ctx, kids, i), PDF_NAME(AP));
}
}
for (i = 0; i < pdf_array_len(ctx, kids); i++)
n += signed_under(ctx, pdf_array_get(ctx, kids, i), drop);
}
fz_always(ctx)
pdf_unmark_obj(ctx, field);
fz_catch(ctx)
fz_rethrow(ctx);
return n;
}
/* SigFlags bit 2; MuPDF keeps its name private. */
enum { APPEND_ONLY = 2 };
static int signed_fields(fz_context *ctx, pdf_document *pdf, int drop)
{
pdf_obj *form = pdf_dict_getp(ctx, pdf_trailer(ctx, pdf), "Root/AcroForm");
pdf_obj *fields = pdf_dict_get(ctx, form, PDF_NAME(Fields));
int i, n = 0;
for (i = 0; i < pdf_array_len(ctx, fields); i++)
n += signed_under(ctx, pdf_array_get(ctx, fields, i), drop);
if (drop && n)
pdf_dict_put_int(ctx, form, PDF_NAME(SigFlags), pdf_dict_get_int(ctx, form, PDF_NAME(SigFlags)) & ~APPEND_ONLY);
return n;
}
/* Ely's whole-file writes break signatures, so carry none. */
void ely_unsign(fz_context *ctx, pdf_document *pdf)
{
signed_fields(ctx, pdf, 1);
}
/* How many signed fields the form holds. */
int ely_signed(fz_context *ctx, fz_document *doc)
{
int n = 0;
fz_try(ctx)
n = signed_fields(ctx, ely_pdf_of(ctx, doc), 0);
fz_catch(ctx)
return ely_fail(ctx);
return n;
}
+294
View File
@@ -0,0 +1,294 @@
/* Text blocks: list, take out glyphs, write new text (PDF-03). */
#include <math.h>
#include <string.h>
#include "ely_shim.h"
/* The page's text, read the same way every time. */
static fz_stext_page *read_text(fz_context *ctx, fz_document *doc, int number)
{
fz_stext_options opts = { 0 };
return fz_new_stext_page_from_page_number(ctx, doc, number, &opts);
}
/* The `index`th text block, or NULL. */
static fz_stext_block *nth_block(fz_stext_page *text, int index)
{
fz_stext_block *block;
for (block = text->first_block; block; block = block->next)
if (block->type == FZ_STEXT_BLOCK_TEXT && index-- == 0)
return block;
return NULL;
}
/* Glyph origins to take out, in user space. */
typedef struct
{
fz_point *at;
int *c;
int n;
int hit;
} targets;
/* The glyphs of `block` with their user-space origins. */
static void block_targets(fz_context *ctx, fz_stext_block *block, fz_matrix to_user, targets *t)
{
fz_stext_line *line;
fz_stext_char *ch;
int n = 0;
for (line = block->u.t.first_line; line; line = line->next)
for (ch = line->first_char; ch; ch = ch->next)
n++;
t->at = fz_malloc_array(ctx, n + 1, fz_point);
t->c = fz_malloc_array(ctx, n + 1, int);
t->n = t->hit = 0;
for (line = block->u.t.first_line; line; line = line->next)
for (ch = line->first_char; ch; ch = ch->next)
if (!(ch->flags & FZ_STEXT_SYNTHETIC))
{
t->at[t->n] = fz_transform_point(ch->origin, to_user);
t->c[t->n++] = ch->c;
}
}
/* Removes a glyph drawn at one of the targets. */
static int take_glyph(fz_context *ctx, void *opaque, int *ucs, int ucslen, fz_matrix trm, fz_matrix ctm,
fz_rect bbox, int tr, float ca, float CA)
{
targets *t = opaque;
fz_point at = fz_transform_point(fz_transform_point(fz_make_point(0, 0), trm), ctm);
int i, k;
for (i = 0; i < t->n; i++)
{
if (fabsf(at.x - t->at[i].x) > 0.5f || fabsf(at.y - t->at[i].y) > 0.5f)
continue;
for (k = 0; k < ucslen; k++)
if (ucs[k] == t->c[i] || t->c[i] == FZ_REPLACEMENT_CHARACTER)
{
t->hit++;
return 1;
}
}
return 0;
}
/* Runs the glyph filter over the page; `dry` changes nothing. */
static void filter_glyphs(fz_context *ctx, pdf_document *pdf, pdf_page *page, targets *t, int dry)
{
pdf_sanitize_filter_options sopts = { 0 };
pdf_filter_factory list[2] = { { pdf_new_sanitize_filter, NULL }, { NULL, NULL } };
pdf_filter_options opts = { 0 };
sopts.opaque = t;
sopts.text_filter = take_glyph;
list[0].options = &sopts;
opts.filters = list;
opts.no_update = dry;
t->hit = 0;
pdf_filter_page_contents(ctx, pdf, page, &opts);
}
/* User space from the page space MuPDF reports in. */
fz_matrix ely_to_user(fz_context *ctx, pdf_page *page)
{
fz_matrix ctm;
pdf_page_transform(ctx, page, NULL, &ctm);
return fz_invert_matrix(ctm);
}
/* Whether all of `block` sits in the page's own content. */
static int reachable(fz_context *ctx, pdf_document *pdf, pdf_page *page, fz_stext_block *block)
{
targets t = { NULL, NULL, 0, 0 };
int ok = 0;
fz_var(t.at);
fz_var(t.c);
pdf_begin_operation(ctx, pdf, "Look at text");
fz_try(ctx)
{
block_targets(ctx, block, ely_to_user(ctx, page), &t);
filter_glyphs(ctx, pdf, page, &t, 1);
ok = t.n > 0 && t.hit == t.n;
}
fz_always(ctx)
{
pdf_abandon_operation(ctx, pdf);
ely_forget_resources(ctx, pdf);
fz_free(ctx, t.at);
fz_free(ctx, t.c);
}
fz_catch(ctx)
fz_rethrow(ctx);
return ok;
}
/* The text of `block`, lines on lines. */
static void block_text(fz_context *ctx, fz_buffer *buf, fz_stext_block *block)
{
fz_stext_line *line;
fz_stext_char *ch;
for (line = block->u.t.first_line; line; line = line->next)
{
if (line != block->u.t.first_line)
fz_append_byte(ctx, buf, '\n');
for (ch = line->first_char; ch; ch = ch->next)
fz_append_rune(ctx, buf, ch->c);
}
}
/* Horizontal lines only; turned text is not edited. */
static int upright(fz_stext_block *block)
{
fz_stext_line *line;
for (line = block->u.t.first_line; line; line = line->next)
if (line->wmode || fabsf(line->dir.x - 1) > 0.01f)
return 0;
return 1;
}
/* JSON of the page's text blocks. */
int ely_text_blocks(fz_context *ctx, fz_document *doc, int number, unsigned char **data, size_t *len)
{
fz_stext_page *text = NULL;
pdf_page *page = NULL;
fz_buffer *buf = NULL, *words = NULL;
fz_output *out = NULL;
fz_var(text);
fz_var(page);
fz_var(buf);
fz_var(words);
fz_var(out);
fz_try(ctx)
{
pdf_document *pdf = ely_pdf_of(ctx, doc);
fz_stext_block *block;
int first = 1;
text = read_text(ctx, doc, number);
page = pdf_load_page(ctx, pdf, number);
buf = fz_new_buffer(ctx, 1024);
out = fz_new_output_with_buffer(ctx, buf);
fz_write_string(ctx, out, "[");
for (block = text->first_block; block; block = block->next)
{
fz_stext_char *ch;
int editable;
if (block->type != FZ_STEXT_BLOCK_TEXT)
continue;
ch = block->u.t.first_line->first_char;
editable = upright(block) && reachable(ctx, pdf, page, block);
fz_drop_buffer(ctx, words);
words = NULL;
words = fz_new_buffer(ctx, 256);
block_text(ctx, words, block);
fz_terminate_buffer(ctx, words);
fz_write_printf(ctx, out, "%s{\"rect\":[%g,%g,%g,%g],\"text\":%q,\"font\":%q,\"size\":%g,\"color\":%d,\"editable\":%s}",
first ? "" : ",", block->bbox.x0, block->bbox.y0, block->bbox.x1, block->bbox.y1,
fz_string_from_buffer(ctx, words), fz_font_name(ctx, ch->font), ch->size, (int)(ch->argb & 0xffffff),
editable ? "true" : "false");
first = 0;
}
fz_write_string(ctx, out, "]");
fz_close_output(ctx, out);
*len = fz_buffer_extract(ctx, buf, data);
}
fz_always(ctx)
{
fz_drop_output(ctx, out);
fz_drop_buffer(ctx, buf);
fz_drop_buffer(ctx, words);
fz_drop_page(ctx, (fz_page *)page);
fz_drop_stext_page(ctx, text);
}
fz_catch(ctx)
return ely_fail(ctx);
return 0;
}
/* Distinct baselines, and the gap between the first two. */
static void baselines(fz_stext_block *block, ely_shape *shape)
{
fz_stext_line *line;
float last = block->u.t.first_line->first_char->origin.y;
shape->lines = 1;
shape->gap = 0;
for (line = block->u.t.first_line->next; line; line = line->next)
{
float y = line->first_char->origin.y;
if (fabsf(y - last) <= 0.5f)
continue;
if (shape->lines == 1)
shape->gap = y - shape->first.y;
shape->lines++;
last = y;
}
/* Runs on one baseline: an ordinary line gap. */
if (shape->gap <= 0)
shape->gap = shape->size * 1.2f;
}
/* Reads block `index` and checks it; nothing changes. */
void ely_read_block(fz_context *ctx, fz_document *doc, pdf_page *page, int number, int index, const char *expected,
ely_shape *shape)
{
pdf_document *pdf = ely_pdf_of(ctx, doc);
fz_stext_page *text = NULL;
fz_buffer *words = NULL;
targets *t = fz_malloc_struct(ctx, targets);
shape->glyphs = t;
fz_var(text);
fz_var(words);
fz_try(ctx)
{
fz_stext_block *block;
fz_stext_char *ch;
text = read_text(ctx, doc, number);
block = nth_block(text, index);
if (!block)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "no text block %d", index);
words = fz_new_buffer(ctx, 256);
block_text(ctx, words, block);
fz_terminate_buffer(ctx, words);
if (strcmp(fz_string_from_buffer(ctx, words), expected))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "the text changed since it was read");
if (!upright(block) || !reachable(ctx, pdf, page, block))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "this text is not in the page's own content");
block_targets(ctx, block, ely_to_user(ctx, page), t);
ch = block->u.t.first_line->first_char;
shape->font = fz_keep_font(ctx, ch->font);
shape->first = ch->origin;
shape->size = ch->size;
shape->rgb = (int)(ch->argb & 0xffffff);
shape->bbox = block->bbox;
baselines(block, shape);
}
fz_always(ctx)
{
fz_drop_buffer(ctx, words);
fz_drop_stext_page(ctx, text);
}
fz_catch(ctx)
fz_rethrow(ctx);
}
/* Takes out the glyphs `ely_read_block` found. */
void ely_remove_block(fz_context *ctx, pdf_document *pdf, pdf_page *page, ely_shape *shape)
{
targets *t = shape->glyphs;
filter_glyphs(ctx, pdf, page, t, 0);
if (t->hit != t->n)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "%d of %d glyphs were found", t->hit, t->n);
}
void ely_drop_shape(fz_context *ctx, ely_shape *shape)
{
targets *t = shape->glyphs;
fz_drop_font(ctx, shape->font);
if (t)
{
fz_free(ctx, t->at);
fz_free(ctx, t->c);
fz_free(ctx, t);
}
shape->font = NULL;
shape->glyphs = NULL;
}
+449
View File
@@ -0,0 +1,449 @@
/* New text on a page: a pen, lines, content (PDF-03). */
#include <math.h>
#include <string.h>
#include "ely_shim.h"
typedef enum
{
PEN_CID,
PEN_SIMPLE,
PEN_CJK
} pen_kind;
/* A font to write with and its resource. */
typedef struct
{
pen_kind kind;
fz_font *font;
int ordering;
pdf_obj *ref;
} pen;
/* What to write, where, in what. */
typedef struct
{
const char *text;
const char *font;
float size;
int rgb;
/* Page space: left, top, width. */
float box[3];
} text_args;
/* The script face for typed signatures, from the worker. */
static const unsigned char *script_data;
static size_t script_len;
void ely_script_font(const unsigned char *data, size_t len)
{
script_data = data;
script_len = len;
}
/* The pen named `choice`; "original" writes in `own`. */
static void choose_pen(fz_context *ctx, const char *choice, fz_font *own, pen *p)
{
static const struct { const char *choice, *name; } latin[] = {
{ "helvetica", "Helvetica" }, { "times", "Times-Roman" }, { "courier", "Courier" } };
static const struct { const char *choice; int ordering; } cjk[] = {
{ "cjk-sc", FZ_ADOBE_GB }, { "cjk-tc", FZ_ADOBE_CNS }, { "cjk-jp", FZ_ADOBE_JAPAN }, { "cjk-kr", FZ_ADOBE_KOREA } };
size_t i;
if (!strcmp(choice, "script"))
{
if (!script_data)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "no script font was given");
p->kind = PEN_CID;
p->font = fz_new_font_from_memory(ctx, "GreatVibes", script_data, (int)script_len, 0, 0);
return;
}
if (!strcmp(choice, "original"))
{
if (!own || !pdf_font_writing_supported(ctx, own))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "the document's font cannot write new text");
p->kind = PEN_CID;
p->font = fz_keep_font(ctx, own);
return;
}
for (i = 0; i < nelem(latin); i++)
if (!strcmp(choice, latin[i].choice))
{
p->kind = PEN_SIMPLE;
p->font = fz_new_base14_font(ctx, latin[i].name);
return;
}
for (i = 0; i < nelem(cjk); i++)
if (!strcmp(choice, cjk[i].choice))
{
p->kind = PEN_CJK;
p->ordering = cjk[i].ordering;
p->font = fz_new_cjk_font(ctx, cjk[i].ordering);
return;
}
fz_throw(ctx, FZ_ERROR_ARGUMENT, "no font %s", choice);
}
/* The pen's font as a resource of `pdf`. */
static void add_pen(fz_context *ctx, pdf_document *pdf, pen *p)
{
switch (p->kind)
{
case PEN_CID:
p->ref = pdf_add_cid_font(ctx, pdf, p->font);
break;
case PEN_SIMPLE:
p->ref = pdf_add_simple_font(ctx, pdf, p->font, PDF_SIMPLE_ENCODING_LATIN);
break;
case PEN_CJK:
p->ref = pdf_add_cjk_font(ctx, pdf, p->font, p->ordering, 0, 0);
break;
}
}
/* The pen's glyph for `u`; 0 when it has none. */
static int glyph(fz_context *ctx, pen *p, int u)
{
if (p->kind == PEN_SIMPLE && fz_windows_1252_from_unicode(u) < 0)
return 0;
return fz_encode_character(ctx, p->font, u);
}
/* `u` as the pen's code, in hex. */
static void code(fz_context *ctx, fz_buffer *buf, pen *p, int u, int gid)
{
switch (p->kind)
{
case PEN_CID:
fz_append_printf(ctx, buf, "%04x", gid);
break;
case PEN_SIMPLE:
fz_append_printf(ctx, buf, "%02x", fz_windows_1252_from_unicode(u));
break;
case PEN_CJK:
if (u > 0xffff)
fz_append_printf(ctx, buf, "%04x%04x", 0xd800 + ((u - 0x10000) >> 10), 0xdc00 + ((u - 0x10000) & 0x3ff));
else
fz_append_printf(ctx, buf, "%04x", u);
break;
}
}
/* `text` as code points; the count is returned. */
static int runes(fz_context *ctx, const char *text, int **out)
{
int n = 0, c;
const char *s;
for (s = text; *s; n++)
s += fz_chartorune(&c, s);
*out = fz_malloc_array(ctx, n + 1, int);
for (n = 0, s = text; *s; n++)
s += fz_chartorune(&(*out)[n], s);
return n;
}
static float advance(fz_context *ctx, pen *p, int u, float size)
{
return fz_advance_glyph(ctx, p->font, glyph(ctx, p, u), 0) * size;
}
/* Lines no wider than `width`: [from, to) each. */
static int lay_out(fz_context *ctx, pen *p, const int *u, int n, float size, float width, int *from, int *to,
float *widest)
{
int i = 0, lines = 0;
*widest = 0;
while (i <= n)
{
int j, space = -1;
float run = 0, before = 0;
for (j = i; j < n && u[j] != '\n'; j++)
{
float w = advance(ctx, p, u[j], size);
if (run + w > width && j > i)
break;
if (u[j] == ' ')
space = j, before = run;
run += w;
}
from[lines] = i;
if (j < n && u[j] != '\n' && space > i)
{
/* Too long for the line: wrap at a space. */
to[lines++] = space;
*widest = fz_max(*widest, before);
i = space + 1;
}
else
{
to[lines++] = j;
*widest = fz_max(*widest, run);
i = j < n && u[j] != '\n' ? j : j + 1;
}
}
return lines;
}
/* A resource name in `type` that is free, given `ref`. */
const char *ely_add_resource(fz_context *ctx, pdf_document *pdf, pdf_obj *page, pdf_obj *type, const char *stem,
pdf_obj *ref, char *name, size_t room)
{
pdf_obj *res = pdf_dict_get_inheritable(ctx, page, PDF_NAME(Resources));
pdf_obj *dict;
int n;
if (!res)
res = pdf_dict_put_dict(ctx, page, PDF_NAME(Resources), 2);
dict = pdf_dict_get(ctx, res, type);
if (!dict)
dict = pdf_dict_put_dict(ctx, res, type, 2);
for (n = 1;; n++)
{
fz_snprintf(name, room, "%s%d", stem, n);
if (!pdf_dict_gets(ctx, dict, name))
break;
}
pdf_dict_puts(ctx, dict, name, ref);
return name;
}
/* The marker of a page whose own content Ely wrapped. */
static const char wrap[] = "q\n%Ely\n";
/* Adds `buf` after the page's content; the new stream. */
pdf_obj *ely_append_content(fz_context *ctx, pdf_document *pdf, pdf_obj *page, fz_buffer *buf)
{
pdf_obj *contents = pdf_dict_get(ctx, page, PDF_NAME(Contents));
pdf_obj *list, *first = pdf_is_array(ctx, contents) ? pdf_array_get(ctx, contents, 0) : NULL;
fz_buffer *head = NULL, *mark = first ? pdf_load_stream(ctx, first) : NULL;
pdf_obj *added = NULL;
int wrapped;
fz_var(head);
fz_try(ctx)
{
wrapped = mark && mark->len == strlen(wrap) && !memcmp(mark->data, wrap, mark->len);
if (wrapped)
list = contents;
else
{
list = pdf_new_array(ctx, pdf, 4);
head = fz_new_buffer_from_copied_data(ctx, (const unsigned char *)wrap, strlen(wrap));
pdf_array_push_drop(ctx, list, pdf_add_stream(ctx, pdf, head, NULL, 0));
if (pdf_is_array(ctx, contents))
{
int i;
for (i = 0; i < pdf_array_len(ctx, contents); i++)
pdf_array_push(ctx, list, pdf_array_get(ctx, contents, i));
}
else if (contents)
pdf_array_push(ctx, list, contents);
fz_drop_buffer(ctx, head);
head = fz_new_buffer_from_copied_data(ctx, (const unsigned char *)"Q\n", 2);
pdf_array_push_drop(ctx, list, pdf_add_stream(ctx, pdf, head, NULL, 0));
pdf_dict_put_drop(ctx, page, PDF_NAME(Contents), list);
}
added = pdf_add_stream(ctx, pdf, buf, NULL, 0);
pdf_array_push_drop(ctx, list, added);
}
fz_always(ctx)
{
fz_drop_buffer(ctx, head);
fz_drop_buffer(ctx, mark);
}
fz_catch(ctx)
fz_rethrow(ctx);
return added;
}
/* Text laid out: the pen, code points, lines, placement. */
typedef struct
{
pen p;
int *u, n;
int *from, *to, lines;
float widest;
fz_point first;
float gap;
} laid;
static void drop_laid(fz_context *ctx, laid *l)
{
fz_drop_font(ctx, l->p.font);
pdf_drop_obj(ctx, l->p.ref);
fz_free(ctx, l->u);
fz_free(ctx, l->from);
fz_free(ctx, l->to);
}
/* Lays `a` out from `first`, or names a missing glyph. */
static int lay_text(fz_context *ctx, text_args *a, fz_font *own, fz_point first, float gap, laid *l)
{
int i;
choose_pen(ctx, a->font, own, &l->p);
l->n = runes(ctx, a->text, &l->u);
for (i = 0; i < l->n; i++)
if (l->u[i] != '\n' && !glyph(ctx, &l->p, l->u[i]))
return l->u[i];
l->from = fz_malloc_array(ctx, l->n + 2, int);
l->to = fz_malloc_array(ctx, l->n + 2, int);
l->lines = lay_out(ctx, &l->p, l->u, l->n, a->size, a->box[2], l->from, l->to, &l->widest);
l->first = first;
l->gap = gap;
return 0;
}
/* The area laid text covers, in page space. */
static fz_rect laid_area(laid *l, float size)
{
return fz_make_rect(l->first.x, l->first.y - size, l->first.x + l->widest, l->first.y + (l->lines - 1) * l->gap + size * 0.3f);
}
/* Writes laid text onto `page` of `pdf`. */
static void draw_laid(fz_context *ctx, pdf_document *pdf, pdf_page *page, laid *l, text_args *a)
{
fz_buffer *buf = NULL;
fz_var(buf);
fz_try(ctx)
{
fz_matrix to_user = ely_to_user(ctx, page);
char name[32];
int i, line;
pdf_drop_obj(ctx, l->p.ref);
l->p.ref = NULL;
add_pen(ctx, pdf, &l->p);
ely_add_resource(ctx, pdf, page->obj, PDF_NAME(Font), "ElyF", l->p.ref, name, sizeof name);
buf = fz_new_buffer(ctx, 256);
fz_append_string(ctx, buf, "q\n");
for (line = 0; line < l->lines; line++)
{
fz_matrix tm = fz_concat(fz_make_matrix(1, 0, 0, -1, l->first.x, l->first.y + line * l->gap), to_user);
fz_append_printf(ctx, buf, "BT /%s %g Tf %g %g %g rg %g %g %g %g %g %g Tm <", name, a->size,
((a->rgb >> 16) & 255) / 255.0f, ((a->rgb >> 8) & 255) / 255.0f, (a->rgb & 255) / 255.0f,
tm.a, tm.b, tm.c, tm.d, tm.e, tm.f);
for (i = l->from[line]; i < l->to[line]; i++)
code(ctx, buf, &l->p, l->u[i], glyph(ctx, &l->p, l->u[i]));
fz_append_string(ctx, buf, "> Tj ET\n");
}
fz_append_string(ctx, buf, "Q\n");
ely_append_content(ctx, pdf, page->obj, buf);
}
fz_always(ctx)
fz_drop_buffer(ctx, buf);
fz_catch(ctx)
fz_rethrow(ctx);
}
/* Edits a snapshot copy and draws `region`; the document stays. */
static void preview(fz_context *ctx, pdf_document *pdf, int number, int block, const char *expected, text_args *a,
laid *l, const char *password, fz_rect region, float scale, unsigned char **pixels, int *w, int *h)
{
fz_buffer *buf = fz_new_buffer(ctx, 4096);
fz_output *out = NULL;
fz_document *copy = NULL;
pdf_page *page = NULL;
ely_shape shape = { NULL };
fz_var(out);
fz_var(copy);
fz_var(page);
fz_try(ctx)
{
int tile[4];
out = fz_new_output_with_buffer(ctx, buf);
pdf_write_snapshot(ctx, pdf, out);
fz_close_output(ctx, out);
copy = fz_open_document_with_buffer(ctx, "application/pdf", buf);
if (fz_needs_password(ctx, copy) && !fz_authenticate_password(ctx, copy, password))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "the copy refused its password");
page = pdf_load_page(ctx, ely_pdf_of(ctx, copy), number);
if (block >= 0)
{
ely_read_block(ctx, copy, page, number, block, expected, &shape);
ely_remove_block(ctx, ely_pdf_of(ctx, copy), page, &shape);
}
draw_laid(ctx, ely_pdf_of(ctx, copy), page, l, a);
region = fz_expand_rect(region, 8);
tile[0] = (int)floorf(region.x0 * scale), tile[1] = (int)floorf(region.y0 * scale);
tile[2] = (int)ceilf(region.x1 * scale) - tile[0], tile[3] = (int)ceilf(region.y1 * scale) - tile[1];
*pixels = fz_malloc(ctx, (size_t)tile[2] * tile[3] * 4);
if (ely_render(ctx, copy, number, scale, 0, tile, 0, *pixels) < 0)
fz_throw(ctx, FZ_ERROR_GENERIC, "%s", ely_error());
*w = tile[2], *h = tile[3];
}
fz_always(ctx)
{
ely_drop_shape(ctx, &shape);
fz_drop_page(ctx, (fz_page *)page);
fz_drop_document(ctx, copy);
fz_drop_output(ctx, out);
fz_drop_buffer(ctx, buf);
}
fz_catch(ctx)
fz_rethrow(ctx);
}
/* Edits, adds or previews text: 0, 2 missing, -1 failed. */
int ely_put_text(fz_context *ctx, fz_document *doc, int number, int block, const char *expected, const char *text,
const char *font, float size, int rgb, const float box[3], const char *password, float scale, int *missing,
int *grew, unsigned char **pixels, int *w, int *h)
{
pdf_document *pdf = NULL;
pdf_page *page = NULL;
ely_shape shape = { NULL };
laid l = { { PEN_SIMPLE, NULL, 0, NULL } };
int begun = 0;
fz_var(pdf);
fz_var(page);
fz_var(begun);
*pixels = NULL;
*grew = 0;
fz_try(ctx)
{
text_args a = { text, font, size, rgb, { box[0], box[1], box[2] } };
fz_point first = fz_make_point(box[0], box[1] + size * 0.8f);
float gap = size * 1.2f;
pdf = ely_pdf_of(ctx, doc);
page = pdf_load_page(ctx, pdf, number);
/* Checks precede the step, so redo survives a refusal. */
if (block >= 0)
{
ely_read_block(ctx, doc, page, number, block, expected, &shape);
first = shape.first;
gap = shape.gap;
}
*missing = lay_text(ctx, &a, shape.font, first, gap, &l);
if (!*missing)
{
fz_rect drawn = laid_area(&l, size), region = drawn;
if (block >= 0)
{
fz_rect room = fz_expand_rect(shape.bbox, 1);
region = fz_union_rect(shape.bbox, drawn);
*grew = fabsf(size - shape.size) > 0.01f || !fz_contains_rect(room, drawn);
}
if (scale > 0)
preview(ctx, pdf, number, block, expected, &a, &l, password, region, scale, pixels, w, h);
else
{
pdf_begin_operation(ctx, pdf, block >= 0 ? "Edit text" : "Add text");
begun = 1;
if (block >= 0)
ely_remove_block(ctx, pdf, page, &shape);
draw_laid(ctx, pdf, page, &l, &a);
pdf_end_operation(ctx, pdf);
begun = 0;
}
}
}
fz_always(ctx)
{
drop_laid(ctx, &l);
ely_drop_shape(ctx, &shape);
fz_drop_page(ctx, (fz_page *)page);
}
fz_catch(ctx)
{
fz_free(ctx, *pixels);
*pixels = NULL;
return ely_edit_failed(ctx, pdf, begun);
}
return *missing ? 2 : 0;
}