1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
//! 출력에 실제 포함된 TextRun의 문자 경계와 clip을 사용한 링크 영역 질의 (#6963).
use crate::document_core::{hyperlink::HyperlinkTarget, DocumentCore};
use crate::error::HwpError;
use crate::model::{
control::{Control, FieldType},
hyperlink::command_uri,
};
use crate::paint::{GroupKind, LayerNode, LayerNodeKind, PageLayerTree, PaintOp, RenderProfile};
use crate::renderer::{
hyperlinks::{clipped_rect, PdfLink, PdfNamedDestination},
render_tree::BoundingBox,
};
#[derive(Debug, Clone, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PageHyperlink {
pub target: HyperlinkTarget,
pub field_id: u32,
/// 이 사각형에 포함된 표시 문자 범위.
pub start: usize,
pub end: usize,
pub uri: String,
pub rect: BoundingBox,
}
impl PageHyperlink {
pub fn pdf_link(&self) -> PdfLink {
PdfLink {
uri: self.uri.clone(),
rect: self.rect,
}
}
}
impl DocumentCore {
/// 0-based 페이지의 실제 출력 링크 조각. 줄바꿈·서식 분할은 각각의 사각형으로 반환한다.
pub fn page_hyperlinks_native(
&self,
page: u32,
profile: RenderProfile,
) -> Result<Vec<PageHyperlink>, HwpError> {
self.hyperlinks_in_layer_tree(&self.build_page_layer_tree_with_profile(page, profile)?)
}
/// 이미 생성한 출력 트리를 재사용한다. glyph sidecar와 fallback을 이중으로 세지 않는다.
pub fn hyperlinks_in_layer_tree(
&self,
tree: &PageLayerTree,
) -> Result<Vec<PageHyperlink>, HwpError> {
let mut links = Vec::new();
let page = BoundingBox {
x: 0.0,
y: 0.0,
width: tree.page_width,
height: tree.page_height,
};
self.collect_layer_hyperlinks(&tree.root, page, &mut links)?;
Ok(links)
}
/// Bookmarks use the same actual text replay positions as link rectangles.
pub fn bookmarks_in_layer_tree(
&self,
tree: &PageLayerTree,
) -> Result<Vec<PdfNamedDestination>, HwpError> {
fn walk(
core: &DocumentCore,
node: &LayerNode,
found: &mut std::collections::BTreeMap<String, PdfNamedDestination>,
) -> Result<(), HwpError> {
match &node.kind {
LayerNodeKind::Group {
children,
group_kind,
..
} => {
if matches!(
group_kind,
GroupKind::Header
| GroupKind::Footer
| GroupKind::MasterPage
| GroupKind::FootnoteArea
) {
return Ok(());
}
for child in children {
walk(core, child, found)?;
}
}
LayerNodeKind::ClipPath { child, .. } | LayerNodeKind::ClipRect { child, .. } => {
walk(core, child, found)?
}
LayerNodeKind::Leaf { ops } => {
for op in ops {
let PaintOp::TextRun { bbox, run, .. } = op else {
continue;
};
let (Some(section), Some(para), Some(start)) =
(run.section_index, run.para_index, run.char_start)
else {
continue;
};
let target = if let Some(cell) = &run.cell_context {
HyperlinkTarget {
section,
para: cell.parent_para_index,
cell_path: cell
.path
.iter()
.map(|e| (e.control_index, e.cell_index, e.cell_para_index))
.collect(),
}
} else {
HyperlinkTarget::body(section, para)
};
let Ok(paragraph) = core.hyperlink_paragraph(&target) else {
continue;
};
if !paragraph
.controls
.iter()
.any(|control| matches!(control, Control::Bookmark(_)))
{
continue;
}
let positions = paragraph.control_text_positions();
let count = run.text.chars().count();
let replay = run.replay_positions_for(run.display_or_text());
for (index, control) in paragraph.controls.iter().enumerate() {
let Control::Bookmark(bookmark) = control else {
continue;
};
let Some(&position) = positions.get(index) else {
continue;
};
if position < start
|| position > start + count
|| (position == start + count
&& position != paragraph.text.chars().count())
{
continue;
}
let Some(&offset) = replay.get(position - start) else {
continue;
};
// A PDF destination navigates to the owning line.
// Complex runs use that line's actual paint bounds;
// ordinary horizontal runs retain the exact advance.
let x = if run.is_vertical
|| run.rotation != 0.0
|| run.char_overlap.is_some()
|| run.display_or_text().chars().count() != count
{
bbox.x
} else {
bbox.x + offset
};
found
.entry(bookmark.name.clone())
.or_insert(PdfNamedDestination {
name: bookmark.name.clone(),
x,
y: bbox.y,
});
}
}
}
}
Ok(())
}
let mut found = std::collections::BTreeMap::new();
walk(self, &tree.root, &mut found)?;
Ok(found.into_values().collect())
}
fn collect_layer_hyperlinks(
&self,
node: &LayerNode,
clip: BoundingBox,
links: &mut Vec<PageHyperlink>,
) -> Result<(), HwpError> {
match &node.kind {
LayerNodeKind::Group {
children,
group_kind,
..
} => {
// 이 컨테이너들의 para_index는 본문과 다른 좌표계다. 본문 링크를 잘못 붙이지 않는다.
if matches!(
group_kind,
GroupKind::Header
| GroupKind::Footer
| GroupKind::MasterPage
| GroupKind::FootnoteArea
) {
return Ok(());
}
for child in children {
self.collect_layer_hyperlinks(child, clip, links)?;
}
}
LayerNodeKind::ClipPath { child, .. } => {
self.collect_layer_hyperlinks(child, clip, links)?;
}
LayerNodeKind::ClipRect {
clip: child_clip,
child,
..
} => {
if let Some(intersection) = clipped_rect(*child_clip, clip) {
self.collect_layer_hyperlinks(child, intersection, links)?;
}
}
LayerNodeKind::Leaf { ops } => {
for op in ops {
let PaintOp::TextRun { bbox, run, .. } = op else {
continue;
};
let (Some(section), Some(para), Some(char_start)) =
(run.section_index, run.para_index, run.char_start)
else {
continue;
};
let target = if let Some(cell) = &run.cell_context {
if cell.path.is_empty() {
continue;
}
HyperlinkTarget {
section,
para: cell.parent_para_index,
cell_path: cell
.path
.iter()
.map(|e| (e.control_index, e.cell_index, e.cell_para_index))
.collect(),
}
} else {
HyperlinkTarget::body(section, para)
};
let Ok(paragraph) = self.hyperlink_paragraph(&target) else {
continue;
};
let count = run.text.chars().count();
let Some(run_end) = char_start.checked_add(count) else {
continue;
};
for range in ¶graph.field_ranges {
let Some(Control::Field(field)) = paragraph.controls.get(range.control_idx)
else {
continue;
};
if field.field_type != FieldType::Hyperlink {
continue;
}
let start = char_start.max(range.start_char_idx);
let end = run_end.min(range.end_char_idx);
if start >= end {
continue;
}
let uri = command_uri(&field.command);
if crate::model::hyperlink::classify_destination(&uri).is_none() {
continue;
}
// 보이지 않는 반복 셀 조각에는 클릭 영역을 만들지 않는다.
if clipped_rect(*bbox, clip).is_none() {
continue;
}
if run.is_vertical
|| run.rotation != 0.0
|| run.char_overlap.is_some()
|| run.display_or_text().chars().count() != count
{
return Err(HwpError::RenderError("회전·세로쓰기·표시값 치환 링크의 출력 영역은 아직 지원하지 않습니다".into()));
}
// K1은 layout owner의 실제 경계, K0은 SVG/Skia와 같은 replay 경계를 사용한다.
let positions = run.replay_positions_for(run.display_or_text());
let Some((&x1, &x2)) = positions
.get(start - char_start)
.zip(positions.get(end - char_start))
else {
continue;
};
let rect = BoundingBox {
x: bbox.x + x1,
y: bbox.y,
width: x2 - x1,
height: bbox.height,
};
if let Some(rect) = clipped_rect(rect, clip) {
links.push(PageHyperlink {
target: target.clone(),
field_id: field.field_id,
start,
end,
uri,
rect,
});
}
}
}
}
}
Ok(())
}
}