imprimatur 0.8.0 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +26 -10
- data/Cargo.lock +22 -5
- data/Cargo.toml +3 -2
- data/README.md +22 -0
- data/ext/imprimatur_native/cli/Cargo.toml +1 -1
- data/ext/imprimatur_native/core/Cargo.toml +1 -1
- data/ext/imprimatur_native/core/src/read/budget.rs +6 -0
- data/ext/imprimatur_native/core/src/read/markdown.rs +91 -5
- data/ext/imprimatur_native/core/src/read/pdf/isolation/protocol.rs +3 -1
- data/ext/imprimatur_native/core/src/read/pdf/isolation/recovery.rs +180 -0
- data/ext/imprimatur_native/core/src/read/pdf/isolation/stream.rs +17 -6
- data/ext/imprimatur_native/core/src/read/pdf/isolation.rs +10 -0
- data/ext/imprimatur_native/core/src/read/pdf/layout/blocks.rs +259 -0
- data/ext/imprimatur_native/core/src/read/pdf/layout.rs +2 -257
- data/ext/imprimatur_native/core/src/read.rs +12 -0
- data/ext/imprimatur_native/ffi/Cargo.toml +2 -1
- data/ext/imprimatur_native/ffi/src/barcode.rs +1 -1
- data/ext/imprimatur_native/ffi/src/classes.rs +52 -0
- data/ext/imprimatur_native/ffi/src/convert.rs +5 -20
- data/ext/imprimatur_native/ffi/src/document.rs +1 -1
- data/ext/imprimatur_native/ffi/src/lib.rs +26 -23
- data/ext/imprimatur_native/ffi/src/pdf.rs +48 -24
- data/ext/imprimatur_native/ffi/src/read.rs +2 -2
- data/lib/imprimatur/pdf_reader.rb +3 -2
- data/lib/imprimatur/version.rb +1 -1
- data/lib/imprimatur.rb +2 -0
- metadata +4 -1
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
use std::collections::HashMap;
|
|
2
|
+
|
|
3
|
+
use super::{Line, PageLines};
|
|
4
|
+
use crate::read::content::{Block, Bounds, Page, Placed, Text};
|
|
5
|
+
|
|
6
|
+
/// The document's pages, from their lines: blocks of the lines that are
|
|
7
|
+
/// not running headers or footers, and, with `drop_repeated_anywhere`, not
|
|
8
|
+
/// text repeated at the same spot on most pages anywhere on the page.
|
|
9
|
+
pub fn pages(
|
|
10
|
+
pages: &[PageLines],
|
|
11
|
+
labels: Option<&[Option<String>]>,
|
|
12
|
+
drop_repeated_anywhere: bool,
|
|
13
|
+
) -> Vec<Page> {
|
|
14
|
+
let boilerplate = repeated_keys(pages, |line| line.margin);
|
|
15
|
+
let margin_kept =
|
|
16
|
+
|line: &&Line| line.margin == 0 || boilerplate.binary_search(&line.margin).is_err();
|
|
17
|
+
let repeated =
|
|
18
|
+
if drop_repeated_anywhere { repeated_keys(pages, |line| line.repeat) } else { Vec::new() };
|
|
19
|
+
let kept = |line: &&Line| {
|
|
20
|
+
margin_kept(line) && (repeated.is_empty() || repeated.binary_search(&line.repeat).is_err())
|
|
21
|
+
};
|
|
22
|
+
let body = body_size(pages, &margin_kept);
|
|
23
|
+
let levels = heading_sizes(pages, &margin_kept, body);
|
|
24
|
+
let mut out = Vec::with_capacity(pages.len());
|
|
25
|
+
let mut paragraph: Vec<&Line> = Vec::new();
|
|
26
|
+
// Each page's blocks, collected here, then moved out at their size.
|
|
27
|
+
let mut blocks = Vec::new();
|
|
28
|
+
for (index, (number, page)) in (1..).zip(pages).enumerate() {
|
|
29
|
+
paragraph.clear();
|
|
30
|
+
for line in page.lines.iter().filter(kept) {
|
|
31
|
+
if let Some(last) = paragraph.last()
|
|
32
|
+
&& !continues(last, line)
|
|
33
|
+
{
|
|
34
|
+
blocks.push(block(page, ¶graph, body, &levels));
|
|
35
|
+
paragraph.clear();
|
|
36
|
+
}
|
|
37
|
+
paragraph.push(line);
|
|
38
|
+
}
|
|
39
|
+
if !paragraph.is_empty() {
|
|
40
|
+
blocks.push(block(page, ¶graph, body, &levels));
|
|
41
|
+
}
|
|
42
|
+
#[expect(
|
|
43
|
+
clippy::drain_collect,
|
|
44
|
+
clippy::iter_with_drain,
|
|
45
|
+
reason = "`blocks` keeps its buffer for the next page"
|
|
46
|
+
)]
|
|
47
|
+
let blocks = blocks.drain(..).collect();
|
|
48
|
+
let label = labels
|
|
49
|
+
.map_or_else(|| printed_label(page), |labels| labels.get(index).cloned().flatten());
|
|
50
|
+
out.push(Page { number, blocks, images: page.images, label });
|
|
51
|
+
}
|
|
52
|
+
out
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/// The page's own printed label, from a single header or footer line that
|
|
56
|
+
/// looks like one: a bare page number or roman numeral ("`-i-`", "`7`"), or
|
|
57
|
+
/// the same after a short label word ("`Page 70`" -> "`70`"). Unlike the
|
|
58
|
+
/// boilerplate this document's other margin lines are checked against, a
|
|
59
|
+
/// running "`Page 70`", "`Page 71`", ... header is not noise here: each
|
|
60
|
+
/// instance *is* that page's label, not a repeated line to drop.
|
|
61
|
+
fn printed_label(page: &PageLines) -> Option<String> {
|
|
62
|
+
let mut candidates =
|
|
63
|
+
page.lines.iter().filter(|line: &&Line| line.margin != 0).filter_map(|line| {
|
|
64
|
+
let text = page.text(line).trim();
|
|
65
|
+
page_number_label(text)
|
|
66
|
+
});
|
|
67
|
+
let label = candidates.next()?;
|
|
68
|
+
candidates.next().is_none().then_some(label)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/// `text` as a page label, if it looks like one, stripped of a leading
|
|
72
|
+
/// label word such as "Page" when there is one.
|
|
73
|
+
fn page_number_label(text: &str) -> Option<String> {
|
|
74
|
+
if looks_like_page_number(text) {
|
|
75
|
+
return Some(text.to_owned());
|
|
76
|
+
}
|
|
77
|
+
let word_end = text.find(|ch: char| !ch.is_ascii_alphabetic())?;
|
|
78
|
+
if word_end == 0 {
|
|
79
|
+
return None;
|
|
80
|
+
}
|
|
81
|
+
let rest = text[word_end..].trim_start_matches(|ch: char| !ch.is_alphanumeric());
|
|
82
|
+
looks_like_page_number(rest).then(|| rest.to_owned())
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
fn looks_like_page_number(text: &str) -> bool {
|
|
86
|
+
let core = text.trim_matches(|ch: char| !ch.is_alphanumeric());
|
|
87
|
+
!core.is_empty()
|
|
88
|
+
&& core.len() <= 8
|
|
89
|
+
&& (core.chars().all(|ch| ch.is_ascii_digit())
|
|
90
|
+
|| core.chars().all(|ch| {
|
|
91
|
+
matches!(ch.to_ascii_lowercase(), 'i' | 'v' | 'x' | 'l' | 'c' | 'd' | 'm')
|
|
92
|
+
}))
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/// Whether `next` carries on the paragraph `last` is in: same direction,
|
|
96
|
+
/// similar size, and no more than a line and a half below it.
|
|
97
|
+
fn continues(last: &Line, next: &Line) -> bool {
|
|
98
|
+
let size = last.size.max(next.size).max(1.0);
|
|
99
|
+
last.turns == next.turns
|
|
100
|
+
&& (last.size - next.size).abs() <= 0.15 * size
|
|
101
|
+
&& last.y - next.y > 0.0
|
|
102
|
+
&& last.y - next.y <= 1.55 * size
|
|
103
|
+
&& last.bold == next.bold
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/// A paragraph of lines as a block: a heading when its few short lines
|
|
107
|
+
/// are set in a heading size, otherwise a paragraph with its lines on lines
|
|
108
|
+
/// of their own, words hyphenated across them joined again.
|
|
109
|
+
fn block(page: &PageLines, lines: &[&Line], body: f64, levels: &[f64]) -> Placed {
|
|
110
|
+
let first = lines[0];
|
|
111
|
+
let length: usize = lines.iter().map(|line| line.span.len()).sum();
|
|
112
|
+
let short = lines.len() <= 3 && length <= 200;
|
|
113
|
+
let text = paragraph_text(page, lines);
|
|
114
|
+
let level =
|
|
115
|
+
if short { levels.iter().position(|&size| first.size >= size - 0.25) } else { None };
|
|
116
|
+
let sized = level
|
|
117
|
+
.filter(|_| first.size >= body * 1.15)
|
|
118
|
+
.map(|level| u8::try_from(level.min(2) + 1).unwrap_or(3));
|
|
119
|
+
let numbered = (short && first.bold && first.size >= body - 0.25)
|
|
120
|
+
.then(|| numbered_heading_level(&text))
|
|
121
|
+
.flatten();
|
|
122
|
+
let block = match sized.or(numbered) {
|
|
123
|
+
Some(level) => Block::Heading { level, text: Text::plain(text) },
|
|
124
|
+
None => Block::Paragraph { text: Text::plain(text) },
|
|
125
|
+
};
|
|
126
|
+
Placed { block, bounds: bounds(page, lines) }
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
fn paragraph_text(page: &PageLines, lines: &[&Line]) -> String {
|
|
130
|
+
let length: usize = lines.iter().map(|line| line.span.len()).sum();
|
|
131
|
+
let mut text = String::with_capacity(length + lines.len());
|
|
132
|
+
for (index, line) in lines.iter().enumerate() {
|
|
133
|
+
let line = page.text(line);
|
|
134
|
+
if index > 0 {
|
|
135
|
+
let joined = text.ends_with('-') && {
|
|
136
|
+
let mut before = text.chars().rev().skip(1);
|
|
137
|
+
before.next().is_some_and(char::is_lowercase)
|
|
138
|
+
&& line.chars().next().is_some_and(char::is_lowercase)
|
|
139
|
+
};
|
|
140
|
+
if joined {
|
|
141
|
+
text.pop();
|
|
142
|
+
} else {
|
|
143
|
+
text.push('\n');
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
text.push_str(line);
|
|
147
|
+
}
|
|
148
|
+
text
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
fn numbered_heading_level(text: &str) -> Option<u8> {
|
|
152
|
+
let (depth, rest) = numbered_prefix(text)?;
|
|
153
|
+
if depth < 2 || !(rest.is_empty() || rest.starts_with(' ')) {
|
|
154
|
+
return None;
|
|
155
|
+
}
|
|
156
|
+
let title = rest.trim_start();
|
|
157
|
+
if title.contains("....") || title.starts_with(|ch: char| !ch.is_alphanumeric()) {
|
|
158
|
+
return None;
|
|
159
|
+
}
|
|
160
|
+
Some(u8::try_from(depth).unwrap_or(6).min(6))
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
fn numbered_prefix(text: &str) -> Option<(usize, &str)> {
|
|
164
|
+
let bytes = text.as_bytes();
|
|
165
|
+
let mut groups = 0_usize;
|
|
166
|
+
let mut pos = 0_usize;
|
|
167
|
+
loop {
|
|
168
|
+
let start = pos;
|
|
169
|
+
while bytes.get(pos).is_some_and(u8::is_ascii_digit) {
|
|
170
|
+
pos += 1;
|
|
171
|
+
}
|
|
172
|
+
if pos == start {
|
|
173
|
+
break;
|
|
174
|
+
}
|
|
175
|
+
groups += 1;
|
|
176
|
+
if groups >= 4
|
|
177
|
+
|| bytes.get(pos) != Some(&b'.')
|
|
178
|
+
|| !bytes.get(pos + 1).is_some_and(u8::is_ascii_digit)
|
|
179
|
+
{
|
|
180
|
+
break;
|
|
181
|
+
}
|
|
182
|
+
pos += 1;
|
|
183
|
+
}
|
|
184
|
+
(groups > 0).then(|| (groups, &text[pos..]))
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/// Where upright lines lie on the page, from its top-left corner: from the
|
|
188
|
+
/// top of the first line's capitals to below the last line's descenders.
|
|
189
|
+
fn bounds(page: &PageLines, lines: &[&Line]) -> Option<Bounds> {
|
|
190
|
+
if lines.iter().any(|line| line.turns != 0) {
|
|
191
|
+
return None;
|
|
192
|
+
}
|
|
193
|
+
let (first, last) = (lines.first()?, lines.last()?);
|
|
194
|
+
let left = lines.iter().map(|line| line.left).fold(f64::MAX, f64::min);
|
|
195
|
+
let right = lines.iter().map(|line| line.right).fold(f64::MIN, f64::max);
|
|
196
|
+
let top = page.height - first.size.mul_add(0.8, first.y);
|
|
197
|
+
let bottom = page.height - last.size.mul_add(-0.25, last.y);
|
|
198
|
+
Some(Bounds { left, top, right, bottom })
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/// The keys `key` returns for lines that repeat on enough pages to be
|
|
202
|
+
/// boilerplate rather than coincidence, sorted.
|
|
203
|
+
fn repeated_keys(pages: &[PageLines], key: impl Fn(&Line) -> u64) -> Vec<u64> {
|
|
204
|
+
if pages.len() < 3 {
|
|
205
|
+
return Vec::new();
|
|
206
|
+
}
|
|
207
|
+
let mut counts: HashMap<u64, usize> = HashMap::new();
|
|
208
|
+
let mut seen: Vec<u64> = Vec::new();
|
|
209
|
+
for page in pages {
|
|
210
|
+
seen.clear();
|
|
211
|
+
seen.extend(page.lines.iter().map(&key).filter(|&key| key != 0));
|
|
212
|
+
seen.sort_unstable();
|
|
213
|
+
seen.dedup();
|
|
214
|
+
for &key in &seen {
|
|
215
|
+
*counts.entry(key).or_default() += 1;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
let threshold = (pages.len() * 2 / 5).max(3);
|
|
219
|
+
let mut repeated: Vec<u64> =
|
|
220
|
+
counts.into_iter().filter(|&(_, count)| count >= threshold).map(|(key, _)| key).collect();
|
|
221
|
+
repeated.sort_unstable();
|
|
222
|
+
repeated
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/// Every page's lines that `kept` keeps.
|
|
226
|
+
fn kept_lines<'p>(
|
|
227
|
+
pages: &'p [PageLines],
|
|
228
|
+
kept: &'p impl Fn(&&Line) -> bool,
|
|
229
|
+
) -> impl Iterator<Item = &'p Line> {
|
|
230
|
+
pages.iter().flat_map(|page| &page.lines).filter(kept)
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/// The most common font size, by characters.
|
|
234
|
+
fn body_size(pages: &[PageLines], kept: &impl Fn(&&Line) -> bool) -> f64 {
|
|
235
|
+
let mut counts: HashMap<i64, usize> = HashMap::new();
|
|
236
|
+
for line in kept_lines(pages, kept) {
|
|
237
|
+
#[expect(clippy::cast_possible_truncation, reason = "font sizes are small")]
|
|
238
|
+
let key = (line.size * 2.0).round() as i64;
|
|
239
|
+
*counts.entry(key).or_default() += line.span.len();
|
|
240
|
+
}
|
|
241
|
+
#[expect(clippy::cast_precision_loss, reason = "a small integer")]
|
|
242
|
+
counts
|
|
243
|
+
.into_iter()
|
|
244
|
+
.max_by_key(|&(size, count)| (count, -size))
|
|
245
|
+
.map_or(0.0, |(size, _)| size as f64 / 2.0)
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/// The sizes of headings, largest first: distinct sizes clearly above the
|
|
249
|
+
/// body's, three at most.
|
|
250
|
+
fn heading_sizes(pages: &[PageLines], kept: &impl Fn(&&Line) -> bool, body: f64) -> Vec<f64> {
|
|
251
|
+
let mut sizes: Vec<f64> = kept_lines(pages, kept)
|
|
252
|
+
.filter(|line| line.size >= body * 1.15 && line.span.len() <= 200)
|
|
253
|
+
.map(|line| (line.size * 2.0).round() / 2.0)
|
|
254
|
+
.collect();
|
|
255
|
+
sizes.sort_by(|a, b| b.total_cmp(a));
|
|
256
|
+
sizes.dedup();
|
|
257
|
+
sizes.truncate(3);
|
|
258
|
+
sizes
|
|
259
|
+
}
|
|
@@ -3,15 +3,15 @@
|
|
|
3
3
|
//! the running headers and footers left out.
|
|
4
4
|
|
|
5
5
|
mod bidi;
|
|
6
|
+
mod blocks;
|
|
6
7
|
#[cfg(test)]
|
|
7
8
|
mod tests;
|
|
8
9
|
|
|
9
|
-
use std::collections::HashMap;
|
|
10
10
|
use std::ops::Range;
|
|
11
11
|
|
|
12
12
|
use self::bidi::{Scratch, is_mark};
|
|
13
|
+
pub use self::blocks::pages;
|
|
13
14
|
use super::content::{Glyph, PageText};
|
|
14
|
-
use crate::read::content::{Block, Bounds, Page, Placed, Text};
|
|
15
15
|
use crate::read::span;
|
|
16
16
|
use crate::script::Counts;
|
|
17
17
|
|
|
@@ -250,258 +250,3 @@ fn repeat_key(text: &str, left: f64, y: f64, turns: u8) -> u64 {
|
|
|
250
250
|
}
|
|
251
251
|
hash.max(1)
|
|
252
252
|
}
|
|
253
|
-
|
|
254
|
-
/// The document's pages, from their lines: blocks of the lines that are
|
|
255
|
-
/// not running headers or footers, and, with `drop_repeated_anywhere`, not
|
|
256
|
-
/// text repeated at the same spot on most pages anywhere on the page.
|
|
257
|
-
pub fn pages(
|
|
258
|
-
pages: &[PageLines],
|
|
259
|
-
labels: Option<&[Option<String>]>,
|
|
260
|
-
drop_repeated_anywhere: bool,
|
|
261
|
-
) -> Vec<Page> {
|
|
262
|
-
let boilerplate = repeated_keys(pages, |line| line.margin);
|
|
263
|
-
let margin_kept =
|
|
264
|
-
|line: &&Line| line.margin == 0 || boilerplate.binary_search(&line.margin).is_err();
|
|
265
|
-
let repeated =
|
|
266
|
-
if drop_repeated_anywhere { repeated_keys(pages, |line| line.repeat) } else { Vec::new() };
|
|
267
|
-
let kept = |line: &&Line| {
|
|
268
|
-
margin_kept(line) && (repeated.is_empty() || repeated.binary_search(&line.repeat).is_err())
|
|
269
|
-
};
|
|
270
|
-
let body = body_size(pages, &margin_kept);
|
|
271
|
-
let levels = heading_sizes(pages, &margin_kept, body);
|
|
272
|
-
let mut out = Vec::with_capacity(pages.len());
|
|
273
|
-
let mut paragraph: Vec<&Line> = Vec::new();
|
|
274
|
-
// Each page's blocks, collected here, then moved out at their size.
|
|
275
|
-
let mut blocks = Vec::new();
|
|
276
|
-
for (index, (number, page)) in (1..).zip(pages).enumerate() {
|
|
277
|
-
paragraph.clear();
|
|
278
|
-
for line in page.lines.iter().filter(kept) {
|
|
279
|
-
if let Some(last) = paragraph.last()
|
|
280
|
-
&& !continues(last, line)
|
|
281
|
-
{
|
|
282
|
-
blocks.push(block(page, ¶graph, body, &levels));
|
|
283
|
-
paragraph.clear();
|
|
284
|
-
}
|
|
285
|
-
paragraph.push(line);
|
|
286
|
-
}
|
|
287
|
-
if !paragraph.is_empty() {
|
|
288
|
-
blocks.push(block(page, ¶graph, body, &levels));
|
|
289
|
-
}
|
|
290
|
-
#[expect(
|
|
291
|
-
clippy::drain_collect,
|
|
292
|
-
clippy::iter_with_drain,
|
|
293
|
-
reason = "`blocks` keeps its buffer for the next page"
|
|
294
|
-
)]
|
|
295
|
-
let blocks = blocks.drain(..).collect();
|
|
296
|
-
let label = labels
|
|
297
|
-
.map_or_else(|| printed_label(page), |labels| labels.get(index).cloned().flatten());
|
|
298
|
-
out.push(Page { number, blocks, images: page.images, label });
|
|
299
|
-
}
|
|
300
|
-
out
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
/// The page's own printed label, from a single header or footer line that
|
|
304
|
-
/// looks like one: a bare page number or roman numeral ("`-i-`", "`7`"), or
|
|
305
|
-
/// the same after a short label word ("`Page 70`" -> "`70`"). Unlike the
|
|
306
|
-
/// boilerplate this document's other margin lines are checked against, a
|
|
307
|
-
/// running "`Page 70`", "`Page 71`", ... header is not noise here: each
|
|
308
|
-
/// instance *is* that page's label, not a repeated line to drop.
|
|
309
|
-
fn printed_label(page: &PageLines) -> Option<String> {
|
|
310
|
-
let mut candidates =
|
|
311
|
-
page.lines.iter().filter(|line: &&Line| line.margin != 0).filter_map(|line| {
|
|
312
|
-
let text = page.text(line).trim();
|
|
313
|
-
page_number_label(text)
|
|
314
|
-
});
|
|
315
|
-
let label = candidates.next()?;
|
|
316
|
-
candidates.next().is_none().then_some(label)
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
/// `text` as a page label, if it looks like one, stripped of a leading
|
|
320
|
-
/// label word such as "Page" when there is one.
|
|
321
|
-
fn page_number_label(text: &str) -> Option<String> {
|
|
322
|
-
if looks_like_page_number(text) {
|
|
323
|
-
return Some(text.to_owned());
|
|
324
|
-
}
|
|
325
|
-
let word_end = text.find(|ch: char| !ch.is_ascii_alphabetic())?;
|
|
326
|
-
if word_end == 0 {
|
|
327
|
-
return None;
|
|
328
|
-
}
|
|
329
|
-
let rest = text[word_end..].trim_start_matches(|ch: char| !ch.is_alphanumeric());
|
|
330
|
-
looks_like_page_number(rest).then(|| rest.to_owned())
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
fn looks_like_page_number(text: &str) -> bool {
|
|
334
|
-
let core = text.trim_matches(|ch: char| !ch.is_alphanumeric());
|
|
335
|
-
!core.is_empty()
|
|
336
|
-
&& core.len() <= 8
|
|
337
|
-
&& (core.chars().all(|ch| ch.is_ascii_digit())
|
|
338
|
-
|| core.chars().all(|ch| {
|
|
339
|
-
matches!(ch.to_ascii_lowercase(), 'i' | 'v' | 'x' | 'l' | 'c' | 'd' | 'm')
|
|
340
|
-
}))
|
|
341
|
-
}
|
|
342
|
-
|
|
343
|
-
/// Whether `next` carries on the paragraph `last` is in: same direction,
|
|
344
|
-
/// similar size, and no more than a line and a half below it.
|
|
345
|
-
fn continues(last: &Line, next: &Line) -> bool {
|
|
346
|
-
let size = last.size.max(next.size).max(1.0);
|
|
347
|
-
last.turns == next.turns
|
|
348
|
-
&& (last.size - next.size).abs() <= 0.15 * size
|
|
349
|
-
&& last.y - next.y > 0.0
|
|
350
|
-
&& last.y - next.y <= 1.55 * size
|
|
351
|
-
&& last.bold == next.bold
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
/// A paragraph of lines as a block: a heading when its few short lines
|
|
355
|
-
/// are set in a heading size, otherwise a paragraph with its lines on lines
|
|
356
|
-
/// of their own, words hyphenated across them joined again.
|
|
357
|
-
fn block(page: &PageLines, lines: &[&Line], body: f64, levels: &[f64]) -> Placed {
|
|
358
|
-
let first = lines[0];
|
|
359
|
-
let length: usize = lines.iter().map(|line| line.span.len()).sum();
|
|
360
|
-
let short = lines.len() <= 3 && length <= 200;
|
|
361
|
-
let text = paragraph_text(page, lines);
|
|
362
|
-
let level =
|
|
363
|
-
if short { levels.iter().position(|&size| first.size >= size - 0.25) } else { None };
|
|
364
|
-
let sized = level
|
|
365
|
-
.filter(|_| first.size >= body * 1.15)
|
|
366
|
-
.map(|level| u8::try_from(level.min(2) + 1).unwrap_or(3));
|
|
367
|
-
let numbered = (short && first.bold && first.size >= body - 0.25)
|
|
368
|
-
.then(|| numbered_heading_level(&text))
|
|
369
|
-
.flatten();
|
|
370
|
-
let block = match sized.or(numbered) {
|
|
371
|
-
Some(level) => Block::Heading { level, text: Text::plain(text) },
|
|
372
|
-
None => Block::Paragraph { text: Text::plain(text) },
|
|
373
|
-
};
|
|
374
|
-
Placed { block, bounds: bounds(page, lines) }
|
|
375
|
-
}
|
|
376
|
-
|
|
377
|
-
fn paragraph_text(page: &PageLines, lines: &[&Line]) -> String {
|
|
378
|
-
let length: usize = lines.iter().map(|line| line.span.len()).sum();
|
|
379
|
-
let mut text = String::with_capacity(length + lines.len());
|
|
380
|
-
for (index, line) in lines.iter().enumerate() {
|
|
381
|
-
let line = page.text(line);
|
|
382
|
-
if index > 0 {
|
|
383
|
-
let joined = text.ends_with('-') && {
|
|
384
|
-
let mut before = text.chars().rev().skip(1);
|
|
385
|
-
before.next().is_some_and(char::is_lowercase)
|
|
386
|
-
&& line.chars().next().is_some_and(char::is_lowercase)
|
|
387
|
-
};
|
|
388
|
-
if joined {
|
|
389
|
-
text.pop();
|
|
390
|
-
} else {
|
|
391
|
-
text.push('\n');
|
|
392
|
-
}
|
|
393
|
-
}
|
|
394
|
-
text.push_str(line);
|
|
395
|
-
}
|
|
396
|
-
text
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
fn numbered_heading_level(text: &str) -> Option<u8> {
|
|
400
|
-
let (depth, rest) = numbered_prefix(text)?;
|
|
401
|
-
if depth < 2 || !(rest.is_empty() || rest.starts_with(' ')) {
|
|
402
|
-
return None;
|
|
403
|
-
}
|
|
404
|
-
let title = rest.trim_start();
|
|
405
|
-
if title.contains("....") || title.starts_with(|ch: char| !ch.is_alphanumeric()) {
|
|
406
|
-
return None;
|
|
407
|
-
}
|
|
408
|
-
Some(u8::try_from(depth).unwrap_or(6).min(6))
|
|
409
|
-
}
|
|
410
|
-
|
|
411
|
-
fn numbered_prefix(text: &str) -> Option<(usize, &str)> {
|
|
412
|
-
let bytes = text.as_bytes();
|
|
413
|
-
let mut groups = 0_usize;
|
|
414
|
-
let mut pos = 0_usize;
|
|
415
|
-
loop {
|
|
416
|
-
let start = pos;
|
|
417
|
-
while bytes.get(pos).is_some_and(u8::is_ascii_digit) {
|
|
418
|
-
pos += 1;
|
|
419
|
-
}
|
|
420
|
-
if pos == start {
|
|
421
|
-
break;
|
|
422
|
-
}
|
|
423
|
-
groups += 1;
|
|
424
|
-
if groups >= 4
|
|
425
|
-
|| bytes.get(pos) != Some(&b'.')
|
|
426
|
-
|| !bytes.get(pos + 1).is_some_and(u8::is_ascii_digit)
|
|
427
|
-
{
|
|
428
|
-
break;
|
|
429
|
-
}
|
|
430
|
-
pos += 1;
|
|
431
|
-
}
|
|
432
|
-
(groups > 0).then(|| (groups, &text[pos..]))
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
/// Where upright lines lie on the page, from its top-left corner: from the
|
|
436
|
-
/// top of the first line's capitals to below the last line's descenders.
|
|
437
|
-
fn bounds(page: &PageLines, lines: &[&Line]) -> Option<Bounds> {
|
|
438
|
-
if lines.iter().any(|line| line.turns != 0) {
|
|
439
|
-
return None;
|
|
440
|
-
}
|
|
441
|
-
let (first, last) = (lines.first()?, lines.last()?);
|
|
442
|
-
let left = lines.iter().map(|line| line.left).fold(f64::MAX, f64::min);
|
|
443
|
-
let right = lines.iter().map(|line| line.right).fold(f64::MIN, f64::max);
|
|
444
|
-
let top = page.height - first.size.mul_add(0.8, first.y);
|
|
445
|
-
let bottom = page.height - last.size.mul_add(-0.25, last.y);
|
|
446
|
-
Some(Bounds { left, top, right, bottom })
|
|
447
|
-
}
|
|
448
|
-
|
|
449
|
-
/// The keys `key` returns for lines that repeat on enough pages to be
|
|
450
|
-
/// boilerplate rather than coincidence, sorted.
|
|
451
|
-
fn repeated_keys(pages: &[PageLines], key: impl Fn(&Line) -> u64) -> Vec<u64> {
|
|
452
|
-
if pages.len() < 3 {
|
|
453
|
-
return Vec::new();
|
|
454
|
-
}
|
|
455
|
-
let mut counts: HashMap<u64, usize> = HashMap::new();
|
|
456
|
-
let mut seen: Vec<u64> = Vec::new();
|
|
457
|
-
for page in pages {
|
|
458
|
-
seen.clear();
|
|
459
|
-
seen.extend(page.lines.iter().map(&key).filter(|&key| key != 0));
|
|
460
|
-
seen.sort_unstable();
|
|
461
|
-
seen.dedup();
|
|
462
|
-
for &key in &seen {
|
|
463
|
-
*counts.entry(key).or_default() += 1;
|
|
464
|
-
}
|
|
465
|
-
}
|
|
466
|
-
let threshold = (pages.len() * 2 / 5).max(3);
|
|
467
|
-
let mut repeated: Vec<u64> =
|
|
468
|
-
counts.into_iter().filter(|&(_, count)| count >= threshold).map(|(key, _)| key).collect();
|
|
469
|
-
repeated.sort_unstable();
|
|
470
|
-
repeated
|
|
471
|
-
}
|
|
472
|
-
|
|
473
|
-
/// Every page's lines that `kept` keeps.
|
|
474
|
-
fn kept_lines<'p>(
|
|
475
|
-
pages: &'p [PageLines],
|
|
476
|
-
kept: &'p impl Fn(&&Line) -> bool,
|
|
477
|
-
) -> impl Iterator<Item = &'p Line> {
|
|
478
|
-
pages.iter().flat_map(|page| &page.lines).filter(kept)
|
|
479
|
-
}
|
|
480
|
-
|
|
481
|
-
/// The most common font size, by characters.
|
|
482
|
-
fn body_size(pages: &[PageLines], kept: &impl Fn(&&Line) -> bool) -> f64 {
|
|
483
|
-
let mut counts: HashMap<i64, usize> = HashMap::new();
|
|
484
|
-
for line in kept_lines(pages, kept) {
|
|
485
|
-
#[expect(clippy::cast_possible_truncation, reason = "font sizes are small")]
|
|
486
|
-
let key = (line.size * 2.0).round() as i64;
|
|
487
|
-
*counts.entry(key).or_default() += line.span.len();
|
|
488
|
-
}
|
|
489
|
-
#[expect(clippy::cast_precision_loss, reason = "a small integer")]
|
|
490
|
-
counts
|
|
491
|
-
.into_iter()
|
|
492
|
-
.max_by_key(|&(size, count)| (count, -size))
|
|
493
|
-
.map_or(0.0, |(size, _)| size as f64 / 2.0)
|
|
494
|
-
}
|
|
495
|
-
|
|
496
|
-
/// The sizes of headings, largest first: distinct sizes clearly above the
|
|
497
|
-
/// body's, three at most.
|
|
498
|
-
fn heading_sizes(pages: &[PageLines], kept: &impl Fn(&&Line) -> bool, body: f64) -> Vec<f64> {
|
|
499
|
-
let mut sizes: Vec<f64> = kept_lines(pages, kept)
|
|
500
|
-
.filter(|line| line.size >= body * 1.15 && line.span.len() <= 200)
|
|
501
|
-
.map(|line| (line.size * 2.0).round() / 2.0)
|
|
502
|
-
.collect();
|
|
503
|
-
sizes.sort_by(|a, b| b.total_cmp(a));
|
|
504
|
-
sizes.dedup();
|
|
505
|
-
sizes.truncate(3);
|
|
506
|
-
sizes
|
|
507
|
-
}
|
|
@@ -42,6 +42,7 @@ pub use content::{
|
|
|
42
42
|
pub(crate) use image::png;
|
|
43
43
|
pub use image::{Image, ImageFormat, ImageLocation};
|
|
44
44
|
pub(crate) use image::{PngColor, png_with_transparency};
|
|
45
|
+
pub use markdown::{Section, SectionKind, TableLines};
|
|
45
46
|
|
|
46
47
|
use crate::zip::reader::ZipReader;
|
|
47
48
|
use crate::{Error, Result};
|
|
@@ -123,6 +124,17 @@ pub fn markdown(document: &[u8], limits: &Limits) -> Result<String> {
|
|
|
123
124
|
Ok(content.to_markdown())
|
|
124
125
|
}
|
|
125
126
|
|
|
127
|
+
/// Reads a document as Markdown with its outline: [`content`], then
|
|
128
|
+
/// [`Content::to_markdown_outline`].
|
|
129
|
+
///
|
|
130
|
+
/// # Errors
|
|
131
|
+
/// As [`markdown`].
|
|
132
|
+
pub fn markdown_outline(document: &[u8], limits: &Limits) -> Result<(String, Vec<Section>)> {
|
|
133
|
+
let content = content(document, limits)?;
|
|
134
|
+
content.ensure_text_layer()?;
|
|
135
|
+
Ok(content.to_markdown_outline())
|
|
136
|
+
}
|
|
137
|
+
|
|
126
138
|
/// Calls `each` with every image in a document, as a file.
|
|
127
139
|
///
|
|
128
140
|
/// A PDF's images come once each, from the first page that draws them; a
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[package]
|
|
2
2
|
name = "imprimatur_native"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.9.1"
|
|
4
4
|
description = "Ruby bindings for the imprimatur crate"
|
|
5
5
|
publish = false
|
|
6
6
|
edition.workspace = true
|
|
@@ -19,4 +19,5 @@ workspace = true
|
|
|
19
19
|
imprimatur = { workspace = true, features = ["archive", "fonts", "json", "isolation"] }
|
|
20
20
|
serde_json.workspace = true
|
|
21
21
|
magnus.workspace = true
|
|
22
|
+
matryona-machines = { workspace = true, features = ["ruby"] }
|
|
22
23
|
rb-sys.workspace = true
|
|
@@ -143,5 +143,5 @@ pub fn define(ruby: &Ruby, imprimatur: magnus::RModule) -> Result<(), Error> {
|
|
|
143
143
|
class.define_method("width", method!(Barcode::width, 0))?;
|
|
144
144
|
class.define_method("height", method!(Barcode::height, 0))?;
|
|
145
145
|
class.define_method("modules", method!(Barcode::modules, 0))?;
|
|
146
|
-
|
|
146
|
+
matryona_machines::ruby::Class::pin_wrapped::<Barcode>(ruby, class).map(drop)
|
|
147
147
|
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
//! Classes resolved once at load and pinned.
|
|
2
|
+
|
|
3
|
+
use std::sync::OnceLock;
|
|
4
|
+
|
|
5
|
+
use magnus::{Error, ExceptionClass, RClass, RModule, Ruby, prelude::*};
|
|
6
|
+
use matryona_machines::ruby::Class;
|
|
7
|
+
|
|
8
|
+
pub struct Classes {
|
|
9
|
+
pub formula: Class,
|
|
10
|
+
pub error: Class,
|
|
11
|
+
pub no_text_layer: Class,
|
|
12
|
+
pub password_required: Class,
|
|
13
|
+
pub unsupported_document: Class,
|
|
14
|
+
pub limit_exceeded: Class,
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
matryona_machines::registry! {
|
|
18
|
+
static CLASSES: Classes = "imprimatur";
|
|
19
|
+
pub fn classes;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
pub fn resolve(ruby: &Ruby, imprimatur: RModule) -> Result<(), Error> {
|
|
23
|
+
let class = |name| Class::resolve(ruby, imprimatur, name);
|
|
24
|
+
let classes = Classes {
|
|
25
|
+
formula: class("Formula")?,
|
|
26
|
+
error: class("Error")?,
|
|
27
|
+
no_text_layer: class("NoTextLayer")?,
|
|
28
|
+
password_required: class("PasswordRequired")?,
|
|
29
|
+
unsupported_document: class("UnsupportedDocument")?,
|
|
30
|
+
limit_exceeded: class("LimitExceeded")?,
|
|
31
|
+
};
|
|
32
|
+
CLASSES.set(ruby, classes).map(drop)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
pub fn exception(ruby: &Ruby, class: Class) -> ExceptionClass {
|
|
36
|
+
ExceptionClass::from_value(class.get(ruby).as_value())
|
|
37
|
+
.unwrap_or_else(|| ruby.exception_standard_error())
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/// `Date` is only there once something has required 'date'.
|
|
41
|
+
pub fn date(ruby: &Ruby) -> Result<Option<RClass>, Error> {
|
|
42
|
+
static DATE: OnceLock<Class> = OnceLock::new();
|
|
43
|
+
if let Some(class) = DATE.get() {
|
|
44
|
+
return Ok(Some(class.get(ruby)));
|
|
45
|
+
}
|
|
46
|
+
let object = ruby.class_object();
|
|
47
|
+
if !object.funcall::<_, _, bool>("const_defined?", ("Date",))? {
|
|
48
|
+
return Ok(None);
|
|
49
|
+
}
|
|
50
|
+
let class: RClass = object.const_get("Date")?;
|
|
51
|
+
Ok(Some(DATE.get_or_init(|| Class::pin(ruby, class)).get(ruby)))
|
|
52
|
+
}
|
|
@@ -2,32 +2,17 @@
|
|
|
2
2
|
|
|
3
3
|
use imprimatur::xlsx::{Cell, DateTime};
|
|
4
4
|
use magnus::prelude::*;
|
|
5
|
-
use magnus::{Error, Float, Integer,
|
|
5
|
+
use magnus::{Error, Float, Integer, RString, Ruby, Value};
|
|
6
6
|
|
|
7
|
+
use crate::classes::{self, classes};
|
|
7
8
|
use crate::{OrRaise, domain_error};
|
|
8
9
|
|
|
9
10
|
/// The largest integer every `f64` neighbour of which is also an integer:
|
|
10
11
|
/// beyond it, Excel would silently store a different number.
|
|
11
12
|
const MAX_EXACT_INTEGER: u64 = 1 << 53;
|
|
12
13
|
|
|
13
|
-
/// Ruby classes looked up once per call, not once per cell.
|
|
14
|
-
pub struct Classes {
|
|
15
|
-
formula: RClass,
|
|
16
|
-
date: Option<RClass>,
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
impl Classes {
|
|
20
|
-
pub fn load(ruby: &Ruby) -> Result<Self, Error> {
|
|
21
|
-
let imprimatur: magnus::RModule = ruby.class_object().const_get("Imprimatur")?;
|
|
22
|
-
// Date is only there once something has required 'date'.
|
|
23
|
-
let date_defined: bool = ruby.class_object().funcall("const_defined?", ("Date",))?;
|
|
24
|
-
let date = if date_defined { Some(ruby.class_object().const_get("Date")?) } else { None };
|
|
25
|
-
Ok(Self { formula: imprimatur.const_get("Formula")?, date })
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
|
|
29
14
|
/// `nil` is no cell.
|
|
30
|
-
pub fn to_cell(ruby: &Ruby, value: Value
|
|
15
|
+
pub fn to_cell(ruby: &Ruby, value: Value) -> Result<Option<Cell>, Error> {
|
|
31
16
|
if value.is_nil() {
|
|
32
17
|
return Ok(None);
|
|
33
18
|
}
|
|
@@ -46,14 +31,14 @@ pub fn to_cell(ruby: &Ruby, value: Value, classes: &Classes) -> Result<Option<Ce
|
|
|
46
31
|
if value.is_kind_of(ruby.class_false_class()) {
|
|
47
32
|
return Ok(Some(Cell::Bool(false)));
|
|
48
33
|
}
|
|
49
|
-
if value.is_kind_of(classes.
|
|
34
|
+
if value.is_kind_of(classes(ruby)?.formula.get(ruby)) {
|
|
50
35
|
let expression: String = value.funcall("expression", ())?;
|
|
51
36
|
return Ok(Some(Cell::formula(expression)));
|
|
52
37
|
}
|
|
53
38
|
if value.is_kind_of(ruby.class_time()) {
|
|
54
39
|
return time_cell(ruby, value).map(Some);
|
|
55
40
|
}
|
|
56
|
-
if let Some(date) = classes
|
|
41
|
+
if let Some(date) = classes::date(ruby)?
|
|
57
42
|
&& value.is_kind_of(date)
|
|
58
43
|
{
|
|
59
44
|
// DateTime is a Date with a time of day; a plain Date has none.
|