1use std::collections::HashSet;
30use std::sync::Arc;
31
32use retex_engine::Engine;
33use retex_engine::nodes::{GlyphData, NodeData, NodeRef, glyph_sub, id, kern_sub};
34use retex_font::{LoadedFont, ShapedItem};
35
36use crate::luaotfload::loaded_font;
37
38const PROTECTED: u16 = 256;
40
41fn is_raw_glyph(e: &Engine, p: NodeRef, font: u32) -> bool {
43 let n = e.nodes.get(p);
44 matches!(&n.data, NodeData::Glyph(g) if g.font == font && n.subtype < PROTECTED)
45}
46
47fn glyph_list(e: &Engine, head: NodeRef, font: u32) -> Option<Vec<NodeRef>> {
50 let mut v = Vec::new();
51 let mut p = head;
52 while !p.is_null() {
53 if !is_raw_glyph(e, p, font) {
54 return None;
55 }
56 v.push(p);
57 p = e.nodes.next(p);
58 }
59 Some(v)
60}
61
62fn disc_lists(e: &Engine, d: NodeRef) -> [NodeRef; 3] {
63 match &e.nodes.get(d).data {
64 NodeData::Disc {
65 pre, post, replace, ..
66 } => [*pre, *post, *replace],
67 _ => [NodeRef::NULL; 3],
68 }
69}
70
71fn set_disc_lists(e: &mut Engine, d: NodeRef, lists: [NodeRef; 3]) {
72 if let NodeData::Disc {
73 pre, post, replace, ..
74 } = &mut e.nodes.get_mut(d).data
75 {
76 [*pre, *post, *replace] = lists;
77 }
78}
79
80const CONTEXT_LEN: usize = 8;
82
83fn context(e: &Engine, mut p: NodeRef, font: u32, forward: bool) -> Vec<u32> {
89 let mut out = Vec::new();
90 while !p.is_null() && out.len() < CONTEXT_LEN {
91 match &e.nodes.get(p).data {
92 NodeData::Glue { .. } => out.push(0x20),
93 NodeData::Glyph(g) if g.font == font => out.push(g.chr),
94 _ => break,
95 }
96 p = if forward {
97 e.nodes.next(p)
98 } else {
99 e.nodes.prev(p)
100 };
101 }
102 if !forward {
103 out.reverse();
104 }
105 out
106}
107
108fn chr(e: &Engine, p: NodeRef) -> u32 {
109 match &e.nodes.get(p).data {
110 NodeData::Glyph(g) => g.chr,
111 _ => 0,
112 }
113}
114
115struct DiscRun {
118 segs: Vec<Vec<NodeRef>>,
119 discs: Vec<NodeRef>,
120 lists: Vec<[Vec<NodeRef>; 3]>,
122}
123
124pub fn process_list(e: &mut Engine, head: NodeRef) -> NodeRef {
127 let mut head = head;
128 let mut p = head;
129 while !p.is_null() {
130 let node = e.nodes.get(p);
131 match &node.data {
132 NodeData::Glyph(g) if node.subtype < PROTECTED => {
133 let font = g.font;
134 let Some(lf) = loaded_font(e, font) else {
135 p = e.nodes.next(p);
136 continue;
137 };
138 let mut run = DiscRun {
139 segs: vec![vec![p]],
140 discs: Vec::new(),
141 lists: Vec::new(),
142 };
143 let mut q = e.nodes.next(p);
144 while !q.is_null() {
145 if is_raw_glyph(e, q, font) {
146 run.segs.last_mut().expect("segment").push(q);
147 } else if e.nodes.id(q) == id::DISC {
148 let [pre, post, rep] = disc_lists(e, q);
149 let (Some(a), Some(b), Some(c)) = (
150 glyph_list(e, pre, font),
151 glyph_list(e, post, font),
152 glyph_list(e, rep, font),
153 ) else {
154 break;
155 };
156 run.discs.push(q);
157 run.lists.push([a, b, c]);
158 run.segs.push(Vec::new());
159 } else {
160 break;
161 }
162 q = e.nodes.next(q);
163 }
164 let first = p;
165 let ctx = if lf.shaper.uses_context {
166 (
167 context(e, e.nodes.prev(first), font, false),
168 context(e, q, font, true),
169 )
170 } else {
171 (Vec::new(), Vec::new())
172 };
173 let new_first = if run.discs.is_empty() {
174 shape_plain(e, &lf, &run.segs[0], &ctx)
175 } else {
176 shape_disc_run(e, &lf, &run, &ctx)
177 .unwrap_or_else(|| shape_separately(e, &lf, &run))
178 };
179 if first == head {
180 head = new_first;
181 }
182 p = q;
183 }
184 NodeData::Disc { .. } => {
185 let lists = disc_lists(e, p);
186 let new = lists.map(|l| if l.is_null() { l } else { process_list(e, l) });
187 set_disc_lists(e, p, new);
188 p = e.nodes.next(p);
189 }
190 _ => p = e.nodes.next(p),
191 }
192 }
193 head
194}
195
196fn build(
205 e: &mut Engine,
206 items: &[ShapedItem],
207 src: &[NodeRef],
208 reused: &mut HashSet<NodeRef>,
209) -> Vec<NodeRef> {
210 let mut out = Vec::with_capacity(items.len());
211 let Some(&last_src) = src.last() else {
212 return out;
213 };
214 let source = |k: usize| src.get(k).copied().unwrap_or(last_src);
215 for it in items {
216 match it {
217 ShapedItem::Glyph(g) => {
218 let s = source(g.cluster);
219 let mut data = match &e.nodes.get(s).data {
220 NodeData::Glyph(d) => d.clone(),
221 _ => GlyphData::default(),
222 };
223 let attr = e.nodes.get(s).attr.clone();
224 data.chr = g.code;
225 data.xoffset = g.x_offset;
226 data.yoffset = g.y_offset;
227 data.components = NodeRef::NULL;
228 let mut subtype = glyph_sub::CHARACTER | PROTECTED;
229 if !g.components.is_empty() {
230 let mut ch = NodeRef::NULL;
231 let mut tail = NodeRef::NULL;
232 for (k, &c) in g.components.iter().enumerate() {
233 let n = e.nodes.copy_node(source(g.cluster + k));
234 if let NodeData::Glyph(gd) = &mut e.nodes.get_mut(n).data {
235 gd.chr = c;
236 }
237 if ch.is_null() {
238 ch = n;
239 } else {
240 e.nodes.link(tail, n);
241 }
242 tail = n;
243 }
244 data.components = ch;
245 subtype = PROTECTED;
249 }
250 let n = if data.components.is_null() && reused.insert(s) {
251 let node = e.nodes.get_mut(s);
252 node.subtype = subtype;
253 node.data = NodeData::Glyph(data);
254 s
255 } else {
256 let n = e.nodes.alloc(id::GLYPH, subtype, NodeData::Glyph(data));
257 e.nodes.get_mut(n).attr = attr;
258 n
259 };
260 out.push(n);
261 }
262 ShapedItem::Kern(k) => {
263 let attr = e.nodes.get(last_src).attr.clone();
264 let n = e.nodes.new_kern(*k, kern_sub::FONT);
265 e.nodes.sync_as_copied(n);
267 e.nodes.get_mut(n).attr = attr;
268 out.push(n);
269 }
270 }
271 }
272 for i in 1..out.len() {
274 if e.nodes.id(out[i]) == id::KERN {
275 let a = e.nodes.get(out[i - 1]).attr.clone();
276 e.nodes.get_mut(out[i]).attr = a;
277 }
278 }
279 out
280}
281
282fn link_all(e: &mut Engine, nodes: &[NodeRef]) -> NodeRef {
284 for w in nodes.windows(2) {
285 e.nodes.link(w[0], w[1]);
286 }
287 if let Some(&f) = nodes.first() {
288 e.nodes.get_mut(f).prev = NodeRef::NULL;
289 }
290 if let Some(&l) = nodes.last() {
291 e.nodes.get_mut(l).next = NodeRef::NULL;
292 }
293 nodes.first().copied().unwrap_or(NodeRef::NULL)
294}
295
296fn free_glyphs(e: &mut Engine, nodes: &[NodeRef], reused: &HashSet<NodeRef>) {
299 for &n in nodes {
300 if !reused.contains(&n) {
301 e.nodes.get_mut(n).next = NodeRef::NULL;
302 e.nodes.flush_list(n);
303 }
304 }
305}
306
307fn splice(e: &mut Engine, first: NodeRef, last: NodeRef, new: &[NodeRef]) -> NodeRef {
310 let prev = e.nodes.get(first).prev;
311 let next = e.nodes.next(last);
312 let mut cur = prev;
313 for &n in new {
314 if cur.is_null() {
315 e.nodes.get_mut(n).prev = NodeRef::NULL;
316 } else {
317 e.nodes.link(cur, n);
318 }
319 cur = n;
320 }
321 if cur.is_null() {
322 return next;
323 }
324 e.nodes.link(cur, next);
325 if !next.is_null() {
326 e.nodes.get_mut(next).prev = cur;
327 }
328 new.first().copied().unwrap_or(next)
329}
330
331type Context = (Vec<u32>, Vec<u32>);
334
335fn shape_plain(e: &mut Engine, lf: &Arc<LoadedFont>, run: &[NodeRef], ctx: &Context) -> NodeRef {
336 let chars: Vec<u32> = run.iter().map(|&n| chr(e, n)).collect();
337 let items = lf
338 .shaper
339 .shape_in_context(&lf.file, &lf.tex, &ctx.0, &chars, &ctx.1);
340 let unchanged = items.len() == run.len()
341 && items.iter().zip(&chars).all(|(it, &c)| {
342 matches!(it, ShapedItem::Glyph(g) if g.code == c && g.components.is_empty()
343 && g.x_offset == 0 && g.y_offset == 0)
344 });
345 let first = run[0];
346 let last = *run.last().expect("non-empty run");
347 if unchanged {
348 for &n in run {
349 e.nodes.get_mut(n).subtype |= PROTECTED;
350 }
351 return first;
352 }
353 let mut reused = HashSet::new();
354 let new = build(e, &items, run, &mut reused);
355 let new_first = splice(e, first, last, &new);
356 free_glyphs(e, run, &reused);
357 new_first
358}
359
360fn n_chars(it: &ShapedItem) -> usize {
361 match it {
362 ShapedItem::Glyph(g) => g.components.len().max(1),
363 ShapedItem::Kern(_) => 0,
364 }
365}
366
367fn shape_disc_run(
371 e: &mut Engine,
372 lf: &Arc<LoadedFont>,
373 run: &DiscRun,
374 ctx: &Context,
375) -> Option<NodeRef> {
376 let k = run.discs.len();
377 if run.segs[1..k].iter().any(Vec::is_empty) {
378 return None;
379 }
380 let mut usrc: Vec<NodeRef> = Vec::new();
382 let mut starts = Vec::with_capacity(k);
383 for i in 0..k {
384 usrc.extend(&run.segs[i]);
385 starts.push(usrc.len());
386 usrc.extend(&run.lists[i][2]);
387 }
388 usrc.extend(&run.segs[k]);
389 let uchars: Vec<u32> = usrc.iter().map(|&n| chr(e, n)).collect();
390 let has = |c: u32| lf.tex.has_char(c);
391 if retex_font::normalize::normalize(&uchars, has) != uchars {
392 return None;
393 }
394 let shape = |src: &[NodeRef]| {
395 let chars: Vec<u32> = src.iter().map(|&n| chr(e, n)).collect();
396 lf.shaper.shape(&lf.file, &lf.tex, &chars)
397 };
398 let u = lf
399 .shaper
400 .shape_in_context(&lf.file, &lf.tex, &ctx.0, &uchars, &ctx.1);
401 let n = u.len();
402 let is_kern = |i: usize| matches!(u[i], ShapedItem::Kern(_));
403 struct Piece {
404 pre: (Vec<ShapedItem>, Vec<NodeRef>),
405 post: (Vec<ShapedItem>, Vec<NodeRef>),
406 lo: usize,
407 hi: usize,
408 }
409 let mut pieces: Vec<Piece> = Vec::with_capacity(k);
410 let mut prev_hi = 0usize;
411 let glyph_id = |it: &ShapedItem| match it {
412 ShapedItem::Glyph(g) => g.glyph,
413 ShapedItem::Kern(_) => None,
414 };
415 for (&a, lists) in starts.iter().zip(&run.lists) {
416 let [pre, post, rep] = lists;
417 let b = a + rep.len();
418 let mut lo = 0;
421 while lo < n
422 && match &u[lo] {
423 ShapedItem::Glyph(g) => g.cluster + n_chars(&u[lo]) <= a,
424 ShapedItem::Kern(_) => true,
425 }
426 {
427 lo += 1;
428 }
429 while lo > 0 && is_kern(lo - 1) {
430 lo -= 1;
431 }
432 let mut s = 0;
433 while s < n
434 && match &u[n - 1 - s] {
435 ShapedItem::Glyph(g) => g.cluster >= b,
436 ShapedItem::Kern(_) => true,
437 }
438 {
439 s += 1;
440 }
441 while s > 0 && is_kern(n - s) {
442 s -= 1;
443 }
444 let hi = n - s;
445 if lo < prev_hi || hi < lo {
446 return None;
447 }
448 let ca = u[..lo]
450 .iter()
451 .filter_map(|it| match it {
452 ShapedItem::Glyph(g) => Some(g.cluster + n_chars(it)),
453 ShapedItem::Kern(_) => None,
454 })
455 .max()
456 .unwrap_or(0)
457 .min(a);
458 let cb = u[hi..]
459 .iter()
460 .filter_map(|it| match it {
461 ShapedItem::Glyph(g) => Some(g.cluster),
462 ShapedItem::Kern(_) => None,
463 })
464 .min()
465 .unwrap_or(usrc.len())
466 .max(b);
467 let mut psrc = usrc[ca..a].to_vec();
470 psrc.extend(pre);
471 let mut qsrc = post.clone();
472 qsrc.extend(&usrc[b..cb]);
473 let mut pre_items = shape(&psrc);
474 let mut post_items = shape(&qsrc);
475 if let (Some(l), Some(r)) = (
476 lo.checked_sub(1).and_then(|i| glyph_id(&u[i])),
477 pre_items.first().and_then(glyph_id),
478 ) {
479 let k = lf.shaper.pair_kern(&lf.file, &lf.tex, l, r);
480 if k != 0 {
481 pre_items.insert(0, ShapedItem::Kern(k));
482 }
483 }
484 if let (Some(l), Some(r)) = (
485 post_items.last().and_then(glyph_id),
486 u.get(hi).and_then(glyph_id),
487 ) {
488 let k = lf.shaper.pair_kern(&lf.file, &lf.tex, l, r);
489 if k != 0 {
490 post_items.push(ShapedItem::Kern(k));
491 }
492 }
493 pieces.push(Piece {
494 pre: (pre_items, psrc),
495 post: (post_items, qsrc),
496 lo,
497 hi,
498 });
499 prev_hi = hi;
500 }
501 let mut out: Vec<NodeRef> = Vec::new();
503 let mut pos = 0usize;
504 let mut reused = HashSet::new();
505 for (i, pc) in pieces.iter().enumerate() {
506 out.extend(build(e, &u[pos..pc.lo], &usrc, &mut reused));
507 let pre = build(e, &pc.pre.0, &pc.pre.1, &mut reused);
508 let post = build(e, &pc.post.0, &pc.post.1, &mut reused);
509 let rep = build(e, &u[pc.lo..pc.hi], &usrc, &mut reused);
510 let d = run.discs[i];
511 let lists = [link_all(e, &pre), link_all(e, &post), link_all(e, &rep)];
512 set_disc_lists(e, d, lists);
513 out.push(d);
514 pos = pc.hi;
515 }
516 out.extend(build(e, &u[pos..], &usrc, &mut reused));
517 let first = run.segs[0][0];
519 let last = run
520 .segs
521 .last()
522 .and_then(|s| s.last().copied())
523 .unwrap_or(*run.discs.last().expect("a discretionary"));
524 let new_first = splice(e, first, last, &out);
525 for seg in &run.segs {
526 free_glyphs(e, seg, &reused);
527 }
528 for l in &run.lists {
529 for part in l {
530 free_glyphs(e, part, &reused);
531 }
532 }
533 Some(new_first)
534}
535
536fn shape_separately(e: &mut Engine, lf: &Arc<LoadedFont>, run: &DiscRun) -> NodeRef {
538 let mut first = NodeRef::NULL;
539 for (i, seg) in run.segs.iter().enumerate() {
540 if !seg.is_empty() {
541 let f = shape_plain(e, lf, seg, &(Vec::new(), Vec::new()));
542 if i == 0 {
543 first = f;
544 }
545 }
546 if let Some(&d) = run.discs.get(i) {
547 let lists = disc_lists(e, d);
548 let new = lists.map(|l| if l.is_null() { l } else { process_list(e, l) });
549 set_disc_lists(e, d, new);
550 }
551 }
552 first
553}