Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_austenite/src/eval/lib/model/outline.rs

17.9 KiB, 1 run

created by r1870400018:63274, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1// SPDX-License-Identifier: Apache-2.0
2// Original work copyright (c) the Typst project authors (typst-library `model/outline.rs`, version 0.15.1).
3// Modified for Austenite: the element's fields, defaults and default show, ported to Hematite's types, IR and error handling.
4// U5 owns this file: outline and outline.entry, with the entry's scoped functions (`indented`, `prefix`,
5// `inner`, `body`, `page`) a show rule on entries calls.
6//
7// Typst aligns entries of one level by their widest prefix through an introspected `PrefixInfo` element
8// per entry. Here the outline measures its own entries' prefixes when it is shown and carries the widest
9// inset per level on the copy of itself that its entries see as `outline.entry.parent`, which answers the
10// same question without an extra element kind. An entry's page number is `counter(page)` at the element,
11// which is U8's to answer.
12
13use crate::diag::DiagnosticKind;
14use crate::eval::args::Args;
15use crate::eval::content::{
16 Content,
17 ElemKind,
18 FieldDefault,
19 FieldSpec,
20 FieldType,
21};
22use crate::eval::intro::{
23 Counter,
24 CounterKey,
25};
26use crate::eval::lib::model::common::{
27 self,
28 expect,
29 natural,
30 to_content,
31 CastErr,
32 K,
33};
34use crate::eval::lib::model::{
35 figure,
36 link,
37 lookup,
38 ModelFn,
39};
40use crate::eval::select::Selector;
41use crate::eval::styles::{
42 StyleChain,
43 Styles,
44};
45use crate::eval::value::{
46 Fraction,
47 Length,
48 Ratio,
49 Relative,
50 Value,
51};
52use crate::eval::Engine;
53use crate::flow::{
54 self,
55 Region,
56};
57use crate::ir::Sp;
58use crate::syntax::Span;
59
60use oxedyne_fe2o3_core::prelude::*;
61
62use std::sync::Arc;
63
64const ANY: FieldType = FieldType::Any;
65
66static OUTLINE: [FieldSpec; 5] = [
67 FieldSpec::named("title", ANY, FieldDefault::Auto),
68 FieldSpec::named("target", ANY, FieldDefault::Computed),
69 FieldSpec::named("depth", ANY, FieldDefault::None),
70 FieldSpec::named("indent", ANY, FieldDefault::Auto),
71 FieldSpec::named("prefix-widths", ANY, FieldDefault::EmptyArray).synthesised().internal(),
72];
73
74static ENTRY: [FieldSpec; 4] = [
75 FieldSpec::required("level", ANY),
76 FieldSpec::required("element", ANY),
77 FieldSpec::named("fill", ANY, FieldDefault::Computed),
78 FieldSpec::named("parent", ANY, FieldDefault::None).internal(),
79];
80
81pub fn fields(kind: ElemKind) -> &'static [FieldSpec] {
82 match kind {
83 ElemKind::Outline => &OUTLINE,
84 ElemKind::OutlineEntry => &ENTRY,
85 _ => &[],
86 }
87}
88
89pub fn default_value(kind: ElemKind, name: &str) -> Option<Value> {
90 match (kind, name) {
91 (ElemKind::Outline, "target") => Some(Value::Selector(Arc::new(Selector::Elem(ElemKind::Heading, None)))),
92 (ElemKind::OutlineEntry, "fill") => {
93 // `repeat([.], gap: 0.15em)`, with whichever of those fields `repeat`'s schema has.
94 let r = ElemKind::Repeat;
95 let mut fields = Vec::new();
96 if let Some(id) = r.field_id("body") {
97 fields.push((id, Value::Content(common::text("."))));
98 }
99 if let Some(id) = r.field_id("gap") {
100 fields.push((id, common::em(0.15)));
101 }
102 Some(Value::Content(Content::new(r, fields, Span::detached())))
103 }
104 _ => None,
105 }
106}
107
108pub fn cast(kind: ElemKind, name: &str, v: Value) -> Result<Value, CastErr> {
109 match (kind, name) {
110 (ElemKind::Outline, "title") => match v {
111 Value::Auto | Value::None => Ok(v),
112 other => expect(&other, &[K::Content, K::None, K::Auto]).map(|_| to_content(other)),
113 },
114 (ElemKind::Outline, "target") => target(v),
115 (ElemKind::Outline, "depth") => match v {
116 Value::None => Ok(v),
117 Value::Int(_) => natural(&v, false).map(|_| v),
118 other => Err(CastErr::Type(common::mismatch("integer or none", &other))),
119 },
120 (ElemKind::Outline, "indent") => expect(&v, &[K::Rel, K::Func, K::Auto]).map(|_| common::relative(v)),
121 (ElemKind::OutlineEntry, "level") => natural(&v, false).map(|_| v),
122 (ElemKind::OutlineEntry, "element") => expect(&v, &[K::Content]).map(|_| to_content(v)),
123 (ElemKind::OutlineEntry, "fill") => match v {
124 Value::None => Ok(v),
125 other => expect(&other, &[K::Content, K::None]).map(|_| to_content(other)),
126 },
127 _ => Ok(v),
128 }
129}
130
131/// What an outline lists: a label, an element function, a location or a selector, kept as a selector.
132fn target(v: Value) -> Result<Value, CastErr> {
133 let sel = match &v {
134 Value::Selector(_) => return Ok(v),
135 Value::Label(l) => Selector::Label(l.clone()),
136 Value::Location(l) => Selector::Location(*l),
137 Value::Func(f) => match f.element() {
138 Some(k) => Selector::Elem(k, None),
139 None => return Err(CastErr::Value("only element functions can be used as selectors".to_string())),
140 },
141 other => return Err(CastErr::Type(common::mismatch("label, function, location, or selector", other))),
142 };
143 Ok(Value::Selector(Arc::new(sel)))
144}
145
146/// Headings in an outline are not themselves outlined or numbered, the outline is not justified, and
147/// it opens at the paragraph leading. Its entries find the outline through `outline.entry.parent`.
148pub fn show_set(elem: &Content, styles: &StyleChain) -> Outcome<Styles> {
149 let leading = res!(common::style(styles, ElemKind::Par, "leading"));
150 common::props(vec![
151 (ElemKind::Heading, "outlined", Value::Bool(false)),
152 (ElemKind::Heading, "numbering", Value::None),
153 (ElemKind::Par, "justify", Value::Bool(false)),
154 (ElemKind::Block, "above", leading),
155 (ElemKind::OutlineEntry, "parent", Value::Content(elem.clone())),
156 ])
157}
158
159// Outlinable elements
160
161/// Is the element listed in an outline, and at which level? `None` for an element that cannot be
162/// outlined at all.
163fn outlinable(e: &Content) -> Option<(bool, i64)> {
164 match e.kind() {
165 Some(ElemKind::Heading) => {
166 let level = match e.field("level") { Some(Value::Int(l)) => *l, _ => 1 };
167 Some((!matches!(e.field("outlined"), Some(Value::Bool(false))), level))
168 }
169 Some(ElemKind::Figure) => Some((figure::outlined(e), 1)),
170 Some(ElemKind::Equation) => {
171 let block = matches!(e.field("block"), Some(Value::Bool(true)));
172 let numbered = !matches!(e.field("numbering"), None | Some(Value::None));
173 Some((block && numbered, 1))
174 }
175 _ => None,
176 }
177}
178
179fn entry_element(engine: &mut Engine, entry: &Content, span: Span) -> Outcome<Content> {
180 match entry.field("element") {
181 Some(Value::Content(c)) => Ok(c.clone()),
182 _ => Err(engine.error(DiagnosticKind::Type, span, "missing argument: element")),
183 }
184}
185
186fn cannot(engine: &mut Engine, e: &Content, span: Span) -> Error<ErrTag> {
187 let name = e.kind().map(|k| k.name()).unwrap_or("sequence");
188 engine.error(DiagnosticKind::Type, span, fmt!("cannot outline {}", name))
189}
190
191/// The entry's prefix: the element's number in its numbering, with a figure's supplement; `none` for
192/// an unnumbered element.
193fn prefix(engine: &mut Engine, entry: &Content, span: Span) -> Outcome<Option<Content>> {
194 let e = res!(entry_element(engine, entry, span));
195 if outlinable(&e).is_none() {
196 return Err(cannot(engine, &e, span));
197 }
198 let numbering = match e.field("numbering") {
199 None | Some(Value::None) => return Ok(None),
200 Some(n) => n.clone(),
201 };
202 let loc = res!(element_location(engine, &e, span));
203 let counter = match (e.kind(), e.field("counter")) {
204 (Some(ElemKind::Figure), Some(Value::Counter(c))) => (**c).clone(),
205 (Some(k), _) => lookup::elem_counter(k),
206 _ => return Err(cannot(engine, &e, span)),
207 };
208 let numbers = res!(lookup::display_counter(engine, &counter, loc, &numbering, span));
209 Ok(Some(match e.kind() {
210 Some(ElemKind::Heading) => numbers,
211 _ => figure::prefix(&e, numbers),
212 }))
213}
214
215fn element_location(engine: &mut Engine, e: &Content, span: Span) -> Outcome<crate::eval::locate::Location> {
216 match e.location() {
217 Some(l) => Ok(l),
218 None if outlinable(e).is_some() => {
219 let name = e.kind().map(|k| k.name()).unwrap_or("element");
220 Err(engine.error_hint(DiagnosticKind::Type, span, fmt!("{} must have a location", name),
221 "try using a show rule to customize the outline.entry instead"))
222 }
223 None => Err(cannot(engine, e, span)),
224 }
225}
226
227/// The entry's body: a heading's body, a figure's caption body, nothing for an equation.
228fn body(engine: &mut Engine, entry: &Content, span: Span) -> Outcome<Content> {
229 let e = res!(entry_element(engine, entry, span));
230 match e.kind() {
231 Some(ElemKind::Heading) => Ok(common::body(&e, "body")),
232 Some(ElemKind::Figure) => Ok(figure::caption_body(&e)),
233 Some(ElemKind::Equation) => Ok(Content::empty()),
234 _ => Err(cannot(engine, &e, span)),
235 }
236}
237
238/// The page the element is on, in the page numbering there (`1` when the page has none).
239fn page(engine: &mut Engine, entry: &Content, span: Span) -> Outcome<Content> {
240 let e = res!(entry_element(engine, entry, span));
241 let loc = res!(element_location(engine, &e, span));
242 let counter = Counter { key: CounterKey::Page };
243 lookup::display_counter(engine, &counter, loc, &Value::str("1"), span)
244}
245
246/// Body, then the fill stretched to the line's end (or plain fractional space), then the page number,
247/// joined to what precedes it so it never stands alone on a line.
248fn inner(engine: &mut Engine, entry: &Content, styles: &StyleChain, body: Content, page: Content) -> Outcome<Content> {
249 let span = entry.span();
250 let rtl = common::is_rtl(styles);
251 let mut seq = Vec::new();
252 if rtl {
253 seq.push(common::text("\u{202B}"));
254 }
255 seq.push(body);
256 if rtl {
257 seq.push(common::text("\u{202C}"));
258 }
259 match res!(common::get(entry, styles, "fill")) {
260 Value::None => seq.push(res!(common::h(engine, Value::Fraction(Fraction(1.0)), false))),
261 filler => {
262 let space = Content::marker(ElemKind::Space, Span::detached());
263 seq.push(space.clone());
264 seq.push(res!(common::build(engine, ElemKind::Box, span, vec![filler], vec![
265 ("width", Value::Fraction(Fraction(1.0))),
266 ])));
267 seq.push(space);
268 }
269 }
270 seq.push(common::text("\u{2060}"));
271 seq.push(page);
272 Ok(common::seq(seq))
273}
274
275/// A relative length's parts in points, its em part resolved.
276fn rel_parts(styles: &StyleChain, v: &Value) -> (f64, f64) {
277 match v {
278 Value::Length(l) => (styles.resolve_length(*l), 0.0),
279 Value::Ratio(r) => (0.0, r.0),
280 Value::Relative(r) => (styles.resolve_length(r.abs), r.rel.0),
281 _ => (0.0, 0.0),
282 }
283}
284
285fn rel_value(abs: f64, rel: f64) -> Value {
286 if rel == 0.0 {
287 Value::Length(Length::pt(abs))
288 } else {
289 Value::Relative(Relative { abs: Length::pt(abs), rel: Ratio(rel) })
290 }
291}
292
293fn infinite() -> Region {
294 Region {
295 width: Sp(i32::MAX),
296 height: Sp(i32::MAX),
297 base: (Sp(i32::MAX), Sp(i32::MAX)),
298 expand_x: false,
299 expand_y: false,
300 }
301}
302
303/// `entry.indented(prefix, inner, gap: 0.5em)`: the entry as a block indented by its level, the prefix
304/// hanging in the indent so bodies of a level align.
305fn indented(
306 engine: &mut Engine,
307 entry: &Content,
308 styles: &StyleChain,
309 prefix: Option<Content>,
310 inner: Content,
311 gap: Value,
312 span: Span,
313)
314 -> Outcome<Content>
315{
316 let parent = match common::style_or(styles, ElemKind::OutlineEntry, "parent", Value::None) {
317 Value::Content(p) => p,
318 _ => return Err(engine.error(DiagnosticKind::Type, span, "must be called within the context of an outline")),
319 };
320 let level = match entry.field("level") {
321 Some(Value::Int(l)) => (*l).max(1),
322 _ => 1,
323 };
324 let prefix_width = match &prefix {
325 Some(p) => Some(res!(flow::measure(engine, p, styles, infinite())).width.to_pt()),
326 None => None,
327 };
328 let prefix_inset = prefix_width.map(|w| w + common::resolve_pt(styles, &gap));
329 let indent = res!(common::get(&parent, styles, "indent"));
330 let (base, hang): ((f64, f64), Option<f64>) = match &indent {
331 Value::Auto => {
332 let widths: Vec<Option<f64>> = match parent.field("prefix-widths") {
333 Some(Value::Array(a)) => a.iter().map(|v| match v {
334 Value::Length(l) => Some(l.abs),
335 _ => None,
336 }).collect(),
337 _ => Vec::new(),
338 };
339 let fallback = common::resolve_pt(styles, &common::em(1.2));
340 let get = |i: usize| widths.get(i).copied().flatten().unwrap_or(fallback);
341 let last = (level - 1) as usize;
342 let base: f64 = (0..last).map(get).sum();
343 (( base, 0.0), prefix_inset.map(|p| p.max(get(last))))
344 }
345 Value::Func(f) => {
346 let mut args = Args::new(span);
347 args.push(span, Value::Int(level - 1));
348 let v = res!(engine.call_func(f, args));
349 if let Err(e) = expect(&v, &[K::Rel]) {
350 return Err(engine.error(DiagnosticKind::Type, span, e.message()));
351 }
352 (rel_parts(styles, &v), prefix_inset)
353 }
354 amount => {
355 let (a, r) = rel_parts(styles, amount);
356 let depth = (level - 1) as f64;
357 ((a * depth, r * depth), prefix_inset)
358 }
359 };
360 let body = match (prefix, prefix_width, prefix_inset, hang) {
361 (Some(p), Some(w), Some(_), Some(hang)) => {
362 let pull = res!(common::h(engine, common::pt(-hang), false));
363 let skip = res!(common::h(engine, common::pt(hang - w), false));
364 common::seq(vec![pull, p, skip, inner])
365 }
366 _ => inner,
367 };
368 let inset = common::start_side(styles, rel_value(base.0 + hang.unwrap_or(0.0), base.1));
369 common::block(engine, body, span, vec![("inset", inset)])
370}
371
372pub fn show(engine: &mut Engine, elem: &Content, styles: &StyleChain) -> Outcome<Option<Content>> {
373 match elem.kind() {
374 Some(ElemKind::OutlineEntry) => show_entry(engine, elem, styles).map(Some),
375 _ => show_outline(engine, elem, styles).map(Some),
376 }
377}
378
379fn show_outline(engine: &mut Engine, elem: &Content, styles: &StyleChain) -> Outcome<Content> {
380 let span = elem.span();
381 let mut seq = Vec::new();
382 let title = match res!(common::get(elem, styles, "title")) {
383 Value::Auto => Some(common::text(common::local(styles, "outline"))),
384 Value::None => None,
385 v => Some(common::display(v)),
386 };
387 if let Some(t) = title {
388 seq.push(res!(common::raw_elem(ElemKind::Heading, span, vec![
389 ("depth", Value::Int(1)),
390 ("body", Value::Content(common::spanned(t, span))),
391 ])));
392 }
393 let target = match res!(common::get(elem, styles, "target")) {
394 Value::Selector(s) => (*s).clone(),
395 _ => Selector::Elem(ElemKind::Heading, None),
396 };
397 let depth = match res!(common::get(elem, styles, "depth")) {
398 Value::Int(d) => d,
399 _ => i64::MAX,
400 };
401 let found = res!(lookup::query(engine, &target, span));
402 let mut entries = Vec::new();
403 for e in found {
404 let (outlined, level) = match outlinable(&e) {
405 Some(x) => x,
406 None => return Err(cannot(engine, &e, span)),
407 };
408 if outlined && level <= depth {
409 entries.push(res!(common::raw_elem(ElemKind::OutlineEntry, span, vec![
410 ("level", Value::Int(level)),
411 ("element", Value::Content(e)),
412 ])));
413 }
414 }
415 // The widest prefix inset of each level, which auto-indented entries align to.
416 let mut widths: Vec<Option<f64>> = Vec::new();
417 if res!(common::get(elem, styles, "indent")).is_auto() {
418 let gap = common::resolve_pt(styles, &common::em(0.5));
419 for entry in &entries {
420 if let Some(p) = res!(prefix(engine, entry, span)) {
421 let w = res!(flow::measure(engine, &p, styles, infinite())).width.to_pt() + gap;
422 let level = match entry.field("level") { Some(Value::Int(l)) => (*l).max(1) as usize, _ => 1 };
423 if widths.len() < level {
424 widths.resize(level, None);
425 }
426 let slot = &mut widths[level - 1];
427 *slot = Some(slot.map_or(w, |m: f64| m.max(w)));
428 }
429 }
430 }
431 let widths_value = Value::array(widths.into_iter().map(|w| match w {
432 Some(p) => common::pt(p),
433 None => Value::None,
434 }).collect());
435 let mut parent = elem.clone();
436 parent.set(res!(common::fid(ElemKind::Outline, "prefix-widths")), widths_value);
437 let body = res!(common::set(common::seq(entries), ElemKind::OutlineEntry, "parent", Value::Content(parent)));
438 seq.push(body);
439 Ok(common::seq(seq))
440}
441
442fn show_entry(engine: &mut Engine, elem: &Content, styles: &StyleChain) -> Outcome<Content> {
443 let span = elem.span();
444 let e = res!(entry_element(engine, elem, span));
445 let pre = res!(prefix(engine, elem, span));
446 let b = res!(body(engine, elem, span));
447 let p = res!(page(engine, elem, span));
448 let inner = res!(inner(engine, elem, styles, b, p));
449 let block = if e.is(ElemKind::Equation) {
450 let body = common::seq(vec![pre.unwrap_or_else(Content::empty), inner]);
451 res!(common::block(engine, body, span, Vec::new()))
452 } else {
453 res!(indented(engine, elem, styles, pre, inner, common::em(0.5), span))
454 };
455 let loc = res!(element_location(engine, &e, span));
456 link::to_location(block, loc)
457}
458
459// Scoped functions
460
461pub fn method(name: &str) -> Option<ModelFn> {
462 match name {
463 "indented" => Some(ModelFn::EntryIndented),
464 "prefix" => Some(ModelFn::EntryPrefix),
465 "inner" => Some(ModelFn::EntryInner),
466 "body" => Some(ModelFn::EntryBody),
467 "page" => Some(ModelFn::EntryPage),
468 _ => None,
469 }
470}
471
472/// Runs an entry method; the receiver is the first positional argument, and all but `body` need the
473/// context's styles, as Typst's contextual functions do.
474pub fn call(f: ModelFn, engine: &mut Engine, mut args: Args) -> Outcome<Value> {
475 let span = args.span;
476 let entry = match res!(args.eat::<Value>()) {
477 Some(Value::Content(c)) if c.is(ElemKind::OutlineEntry) => c,
478 _ => return Err(engine.error(DiagnosticKind::Type, span, "expected outline entry")),
479 };
480 if f == ModelFn::EntryBody {
481 res!(super::finish(engine, &mut args));
482 return Ok(Value::Content(res!(body(engine, &entry, span))));
483 }
484 let styles = match &engine.context.styles {
485 Some(s) => s.clone(),
486 None => return Err(engine.error_hint(DiagnosticKind::Type, span, "can only be used when context is known",
487 "try wrapping this in a `context` expression")),
488 };
489 let out = match f {
490 ModelFn::EntryPrefix => {
491 res!(super::finish(engine, &mut args));
492 match res!(prefix(engine, &entry, span)) {
493 Some(c) => Value::Content(c),
494 None => Value::None,
495 }
496 }
497 ModelFn::EntryPage => {
498 res!(super::finish(engine, &mut args));
499 Value::Content(res!(page(engine, &entry, span)))
500 }
501 ModelFn::EntryInner => {
502 res!(super::finish(engine, &mut args));
503 let b = res!(body(engine, &entry, span));
504 let p = res!(page(engine, &entry, span));
505 Value::Content(res!(inner(engine, &entry, &styles, b, p)))
506 }
507 _ => {
508 let pre: Option<Content> = res!(args.eat::<Option<Content>>()).flatten();
509 let inner = match res!(args.eat::<Content>()) {
510 Some(c) => c,
511 None => return Err(engine.error(DiagnosticKind::Type, span, "missing argument: inner")),
512 };
513 let gap = match res!(args.named::<Value>("gap")) {
514 Some(g) => g,
515 None => common::em(0.5),
516 };
517 res!(super::finish(engine, &mut args));
518 Value::Content(res!(indented(engine, &entry, &styles, pre, inner, gap, span)))
519 }
520 };
521 Ok(out)
522}
523