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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
|
//! Composable layouts.
mod align;
mod columns;
mod container;
#[path = "enum.rs"]
mod enum_;
mod flow;
mod fragment;
mod grid;
mod hide;
mod list;
mod measure;
mod pad;
mod page;
mod par;
mod place;
mod regions;
mod repeat;
mod spacing;
mod stack;
mod table;
mod terms;
mod transform;
pub use self::align::*;
pub use self::columns::*;
pub use self::container::*;
pub use self::enum_::*;
pub use self::flow::*;
pub use self::fragment::*;
pub use self::grid::*;
pub use self::hide::*;
pub use self::list::*;
pub use self::measure::*;
pub use self::pad::*;
pub use self::page::*;
pub use self::par::*;
pub use self::place::*;
pub use self::regions::*;
pub use self::repeat::*;
pub use self::spacing::*;
pub use self::stack::*;
pub use self::table::*;
pub use self::terms::*;
pub use self::transform::*;
use std::mem;
use typed_arena::Arena;
use typst::diag::SourceResult;
use typst::eval::Tracer;
use typst::model::{applicable, realize, StyleVecBuilder};
use crate::math::{EquationElem, LayoutMath};
use crate::meta::DocumentElem;
use crate::prelude::*;
use crate::shared::BehavedBuilder;
use crate::text::{LinebreakElem, SmartQuoteElem, SpaceElem, TextElem};
use crate::visualize::PathElem;
use crate::visualize::PolygonElem;
use crate::visualize::{CircleElem, EllipseElem, ImageElem, RectElem, SquareElem};
/// Root-level layout.
pub trait LayoutRoot {
/// Layout into one frame per page.
fn layout_root(&self, vt: &mut Vt, styles: StyleChain) -> SourceResult<Document>;
}
impl LayoutRoot for Content {
#[tracing::instrument(name = "Content::layout_root", skip_all)]
fn layout_root(&self, vt: &mut Vt, styles: StyleChain) -> SourceResult<Document> {
#[comemo::memoize]
fn cached(
content: &Content,
world: Tracked<dyn World + '_>,
tracer: TrackedMut<Tracer>,
locator: Tracked<Locator>,
introspector: Tracked<Introspector>,
styles: StyleChain,
) -> SourceResult<Document> {
let mut locator = Locator::chained(locator);
let mut vt = Vt { world, tracer, locator: &mut locator, introspector };
let scratch = Scratch::default();
let (realized, styles) = realize_root(&mut vt, &scratch, content, styles)?;
realized
.with::<dyn LayoutRoot>()
.unwrap()
.layout_root(&mut vt, styles)
}
tracing::info!("Starting layout");
cached(
self,
vt.world,
TrackedMut::reborrow_mut(&mut vt.tracer),
vt.locator.track(),
vt.introspector,
styles,
)
}
}
/// Layout into regions.
pub trait Layout {
/// Layout into one frame per region.
fn layout(
&self,
vt: &mut Vt,
styles: StyleChain,
regions: Regions,
) -> SourceResult<Fragment>;
/// Layout without side effects.
///
/// This element must be layouted again in the same order for the results to
/// be valid.
fn measure(
&self,
vt: &mut Vt,
styles: StyleChain,
regions: Regions,
) -> SourceResult<Fragment> {
let mut locator = Locator::chained(vt.locator.track());
let mut vt = Vt {
world: vt.world,
tracer: TrackedMut::reborrow_mut(&mut vt.tracer),
locator: &mut locator,
introspector: vt.introspector,
};
self.layout(&mut vt, styles, regions)
}
}
impl Layout for Content {
#[tracing::instrument(name = "Content::layout", skip_all)]
fn layout(
&self,
vt: &mut Vt,
styles: StyleChain,
regions: Regions,
) -> SourceResult<Fragment> {
#[comemo::memoize]
fn cached(
content: &Content,
world: Tracked<dyn World + '_>,
tracer: TrackedMut<Tracer>,
locator: Tracked<Locator>,
introspector: Tracked<Introspector>,
styles: StyleChain,
regions: Regions,
) -> SourceResult<Fragment> {
let mut locator = Locator::chained(locator);
let mut vt = Vt { world, tracer, locator: &mut locator, introspector };
let scratch = Scratch::default();
let (realized, styles) = realize_block(&mut vt, &scratch, content, styles)?;
realized
.with::<dyn Layout>()
.unwrap()
.layout(&mut vt, styles, regions)
}
tracing::info!("Layouting `Content`");
let fragment = cached(
self,
vt.world,
TrackedMut::reborrow_mut(&mut vt.tracer),
vt.locator.track(),
vt.introspector,
styles,
regions,
)?;
vt.locator.visit_frames(&fragment);
Ok(fragment)
}
}
/// Realize into an element that is capable of root-level layout.
#[tracing::instrument(skip_all)]
fn realize_root<'a>(
vt: &mut Vt,
scratch: &'a Scratch<'a>,
content: &'a Content,
styles: StyleChain<'a>,
) -> SourceResult<(Content, StyleChain<'a>)> {
if content.can::<dyn LayoutRoot>() && !applicable(content, styles) {
return Ok((content.clone(), styles));
}
let mut builder = Builder::new(vt, scratch, true);
builder.accept(content, styles)?;
builder.interrupt_page(Some(styles))?;
let (pages, shared) = builder.doc.unwrap().pages.finish();
Ok((DocumentElem::new(pages.to_vec()).pack(), shared))
}
/// Realize into an element that is capable of block-level layout.
fn realize_block<'a>(
vt: &mut Vt,
scratch: &'a Scratch<'a>,
content: &'a Content,
styles: StyleChain<'a>,
) -> SourceResult<(Content, StyleChain<'a>)> {
if content.can::<dyn Layout>()
&& !content.is::<RectElem>()
&& !content.is::<SquareElem>()
&& !content.is::<EllipseElem>()
&& !content.is::<CircleElem>()
&& !content.is::<ImageElem>()
&& !content.is::<PolygonElem>()
&& !content.is::<PathElem>()
&& !applicable(content, styles)
{
return Ok((content.clone(), styles));
}
let mut builder = Builder::new(vt, scratch, false);
builder.accept(content, styles)?;
builder.interrupt_par()?;
let (children, shared) = builder.flow.0.finish();
Ok((FlowElem::new(children.to_vec()).pack(), shared))
}
/// Builds a document or a flow element from content.
struct Builder<'a, 'v, 't> {
/// The virtual typesetter.
vt: &'v mut Vt<'t>,
/// Scratch arenas for building.
scratch: &'a Scratch<'a>,
/// The current document building state.
doc: Option<DocBuilder<'a>>,
/// The current flow building state.
flow: FlowBuilder<'a>,
/// The current paragraph building state.
par: ParBuilder<'a>,
/// The current list building state.
list: ListBuilder<'a>,
}
/// Temporary storage arenas for building.
#[derive(Default)]
struct Scratch<'a> {
/// An arena where intermediate style chains are stored.
styles: Arena<StyleChain<'a>>,
/// An arena where intermediate content resulting from show rules is stored.
content: Arena<Content>,
}
impl<'a, 'v, 't> Builder<'a, 'v, 't> {
fn new(vt: &'v mut Vt<'t>, scratch: &'a Scratch<'a>, top: bool) -> Self {
Self {
vt,
scratch,
doc: top.then(DocBuilder::default),
flow: FlowBuilder::default(),
par: ParBuilder::default(),
list: ListBuilder::default(),
}
}
#[tracing::instrument(skip_all)]
fn accept(
&mut self,
mut content: &'a Content,
styles: StyleChain<'a>,
) -> SourceResult<()> {
if content.can::<dyn LayoutMath>() && !content.is::<EquationElem>() {
content =
self.scratch.content.alloc(EquationElem::new(content.clone()).pack());
}
if let Some(realized) = realize(self.vt, content, styles)? {
let stored = self.scratch.content.alloc(realized);
return self.accept(stored, styles);
}
if let Some((elem, local)) = content.to_styled() {
return self.styled(elem, local, styles);
}
if let Some(children) = content.to_sequence() {
for elem in children {
self.accept(elem, styles)?;
}
return Ok(());
}
if self.list.accept(content, styles) {
return Ok(());
}
self.interrupt_list()?;
if self.list.accept(content, styles) {
return Ok(());
}
if self.par.accept(content, styles) {
return Ok(());
}
self.interrupt_par()?;
if self.flow.accept(content, styles) {
return Ok(());
}
let keep = content
.to::<PagebreakElem>()
.map_or(false, |pagebreak| !pagebreak.weak(styles));
self.interrupt_page(keep.then_some(styles))?;
if let Some(doc) = &mut self.doc {
if doc.accept(content, styles) {
return Ok(());
}
}
if content.is::<PagebreakElem>() {
bail!(content.span(), "pagebreaks are not allowed inside of containers");
} else {
bail!(content.span(), "{} is not allowed here", content.func().name());
}
}
#[tracing::instrument(skip_all)]
fn styled(
&mut self,
elem: &'a Content,
map: &'a Styles,
styles: StyleChain<'a>,
) -> SourceResult<()> {
let stored = self.scratch.styles.alloc(styles);
let styles = stored.chain(map);
self.interrupt_style(map, None)?;
self.accept(elem, styles)?;
self.interrupt_style(map, Some(styles))?;
Ok(())
}
#[tracing::instrument(skip(self, local, outer))]
fn interrupt_style(
&mut self,
local: &Styles,
outer: Option<StyleChain<'a>>,
) -> SourceResult<()> {
if let Some(Some(span)) = local.interruption::<DocumentElem>() {
if self.doc.is_none() {
bail!(span, "document set rules are not allowed inside of containers");
}
if outer.is_none()
&& (!self.flow.0.is_empty()
|| !self.par.0.is_empty()
|| !self.list.items.is_empty())
{
bail!(span, "document set rules must appear before any content");
}
} else if let Some(Some(span)) = local.interruption::<PageElem>() {
if self.doc.is_none() {
bail!(span, "page configuration is not allowed inside of containers");
}
self.interrupt_page(outer)?;
} else if local.interruption::<ParElem>().is_some()
|| local.interruption::<AlignElem>().is_some()
{
self.interrupt_par()?;
} else if local.interruption::<ListElem>().is_some()
|| local.interruption::<EnumElem>().is_some()
|| local.interruption::<TermsElem>().is_some()
{
self.interrupt_list()?;
}
Ok(())
}
#[tracing::instrument(skip(self))]
fn interrupt_list(&mut self) -> SourceResult<()> {
if !self.list.items.is_empty() {
let staged = mem::take(&mut self.list.staged);
let (list, styles) = mem::take(&mut self.list).finish();
let stored = self.scratch.content.alloc(list);
self.accept(stored, styles)?;
for (content, styles) in staged {
self.accept(content, styles)?;
}
}
Ok(())
}
#[tracing::instrument(skip(self))]
fn interrupt_par(&mut self) -> SourceResult<()> {
self.interrupt_list()?;
if !self.par.0.is_empty() {
let (par, styles) = mem::take(&mut self.par).finish();
let stored = self.scratch.content.alloc(par);
self.accept(stored, styles)?;
}
Ok(())
}
#[tracing::instrument(skip_all)]
fn interrupt_page(&mut self, styles: Option<StyleChain<'a>>) -> SourceResult<()> {
self.interrupt_par()?;
let Some(doc) = &mut self.doc else { return Ok(()) };
if !self.flow.0.is_empty() || (doc.keep_next && styles.is_some()) {
let (flow, shared) = mem::take(&mut self.flow).0.finish();
let styles = if shared == StyleChain::default() {
styles.unwrap_or_default()
} else {
shared
};
let page = PageElem::new(FlowElem::new(flow.to_vec()).pack()).pack();
let stored = self.scratch.content.alloc(page);
self.accept(stored, styles)?;
}
Ok(())
}
}
/// Accepts pagebreaks and pages.
struct DocBuilder<'a> {
/// The page runs built so far.
pages: StyleVecBuilder<'a, Content>,
/// Whether to keep a following page even if it is empty.
keep_next: bool,
}
impl<'a> DocBuilder<'a> {
fn accept(&mut self, content: &Content, styles: StyleChain<'a>) -> bool {
if let Some(pagebreak) = content.to::<PagebreakElem>() {
self.keep_next = !pagebreak.weak(styles);
return true;
}
if content.is::<PageElem>() {
self.pages.push(content.clone(), styles);
self.keep_next = false;
return true;
}
false
}
}
impl Default for DocBuilder<'_> {
fn default() -> Self {
Self { pages: StyleVecBuilder::new(), keep_next: true }
}
}
/// Accepts flow content.
#[derive(Default)]
struct FlowBuilder<'a>(BehavedBuilder<'a>, bool);
impl<'a> FlowBuilder<'a> {
fn accept(&mut self, content: &'a Content, styles: StyleChain<'a>) -> bool {
if content.is::<ParbreakElem>() {
self.1 = true;
return true;
}
let last_was_parbreak = self.1;
self.1 = false;
if content.is::<VElem>()
|| content.is::<ColbreakElem>()
|| content.is::<MetaElem>()
{
self.0.push(content.clone(), styles);
return true;
}
if content.can::<dyn Layout>() || content.is::<ParElem>() {
let is_tight_list = if let Some(elem) = content.to::<ListElem>() {
elem.tight(styles)
} else if let Some(elem) = content.to::<EnumElem>() {
elem.tight(styles)
} else if let Some(elem) = content.to::<TermsElem>() {
elem.tight(styles)
} else {
false
};
if !last_was_parbreak && is_tight_list {
let leading = ParElem::leading_in(styles);
let spacing = VElem::list_attach(leading.into());
self.0.push(spacing.pack(), styles);
}
let (above, below) = if let Some(block) = content.to::<BlockElem>() {
(block.above(styles), block.below(styles))
} else {
(BlockElem::above_in(styles), BlockElem::below_in(styles))
};
self.0.push(above.pack(), styles);
self.0.push(content.clone(), styles);
self.0.push(below.pack(), styles);
return true;
}
false
}
}
/// Accepts paragraph content.
#[derive(Default)]
struct ParBuilder<'a>(BehavedBuilder<'a>);
impl<'a> ParBuilder<'a> {
fn accept(&mut self, content: &'a Content, styles: StyleChain<'a>) -> bool {
if content.is::<MetaElem>() {
if !self.0.is_basically_empty() {
self.0.push(content.clone(), styles);
return true;
}
} else if content.is::<SpaceElem>()
|| content.is::<TextElem>()
|| content.is::<HElem>()
|| content.is::<LinebreakElem>()
|| content.is::<SmartQuoteElem>()
|| content.to::<EquationElem>().map_or(false, |elem| !elem.block(styles))
|| content.is::<BoxElem>()
{
self.0.push(content.clone(), styles);
return true;
}
false
}
fn finish(self) -> (Content, StyleChain<'a>) {
let (children, shared) = self.0.finish();
(ParElem::new(children.to_vec()).pack(), shared)
}
}
/// Accepts list / enum items, spaces, paragraph breaks.
struct ListBuilder<'a> {
/// The list items collected so far.
items: StyleVecBuilder<'a, Content>,
/// Whether the list contains no paragraph breaks.
tight: bool,
/// Trailing content for which it is unclear whether it is part of the list.
staged: Vec<(&'a Content, StyleChain<'a>)>,
}
impl<'a> ListBuilder<'a> {
fn accept(&mut self, content: &'a Content, styles: StyleChain<'a>) -> bool {
if !self.items.is_empty()
&& (content.is::<SpaceElem>() || content.is::<ParbreakElem>())
{
self.staged.push((content, styles));
return true;
}
if (content.is::<ListItem>()
|| content.is::<EnumItem>()
|| content.is::<TermItem>())
&& self
.items
.elems()
.next()
.map_or(true, |first| first.func() == content.func())
{
self.items.push(content.clone(), styles);
self.tight &= self.staged.drain(..).all(|(t, _)| !t.is::<ParbreakElem>());
return true;
}
false
}
fn finish(self) -> (Content, StyleChain<'a>) {
let (items, shared) = self.items.finish();
let item = items.items().next().unwrap();
let output = if item.is::<ListItem>() {
ListElem::new(
items
.iter()
.map(|(item, local)| {
let item = item.to::<ListItem>().unwrap();
item.clone().with_body(item.body().styled_with_map(local.clone()))
})
.collect::<Vec<_>>(),
)
.with_tight(self.tight)
.pack()
} else if item.is::<EnumItem>() {
EnumElem::new(
items
.iter()
.map(|(item, local)| {
let item = item.to::<EnumItem>().unwrap();
item.clone().with_body(item.body().styled_with_map(local.clone()))
})
.collect::<Vec<_>>(),
)
.with_tight(self.tight)
.pack()
} else if item.is::<TermItem>() {
TermsElem::new(
items
.iter()
.map(|(item, local)| {
let item = item.to::<TermItem>().unwrap();
item.clone()
.with_term(item.term().styled_with_map(local.clone()))
.with_description(
item.description().styled_with_map(local.clone()),
)
})
.collect::<Vec<_>>(),
)
.with_tight(self.tight)
.pack()
} else {
unreachable!()
};
(output, shared)
}
}
impl Default for ListBuilder<'_> {
fn default() -> Self {
Self {
items: StyleVecBuilder::default(),
tight: true,
staged: vec![],
}
}
}
|