-
Notifications
You must be signed in to change notification settings - Fork 134
/
layout.rs
311 lines (261 loc) · 11.3 KB
/
layout.rs
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
///! Basic CSS block layout.
use style::{StyledNode, Display};
use css::Value::{Keyword, Length};
use css::Unit::Px;
use std::default::Default;
use std::iter::AdditiveIterator; // for `sum`
pub use self::BoxType::{AnonymousBlock, InlineNode, BlockNode};
// CSS box model. All sizes are in px.
#[derive(Default, Debug)]
pub struct Rect {
pub x: f32,
pub y: f32,
pub width: f32,
pub height: f32,
}
#[derive(Default, Debug)]
pub struct Dimensions {
/// Position of the content area relative to the document origin:
pub content: Rect,
// Surrounding edges:
pub padding: EdgeSizes,
pub border: EdgeSizes,
pub margin: EdgeSizes,
}
#[derive(Default, Debug)]
pub struct EdgeSizes {
pub left: f32,
pub right: f32,
pub top: f32,
pub bottom: f32,
}
impl Copy for Rect {}
impl Copy for Dimensions {}
impl Copy for EdgeSizes {}
/// A node in the layout tree.
pub struct LayoutBox<'a> {
pub dimensions: Dimensions,
pub box_type: BoxType<'a>,
pub children: Vec<LayoutBox<'a>>,
}
pub enum BoxType<'a> {
BlockNode(&'a StyledNode<'a>),
InlineNode(&'a StyledNode<'a>),
AnonymousBlock,
}
impl<'a> LayoutBox<'a> {
fn new(box_type: BoxType) -> LayoutBox {
LayoutBox {
box_type: box_type,
dimensions: Default::default(),
children: Vec::new(),
}
}
fn get_style_node(&self) -> &'a StyledNode<'a> {
match self.box_type {
BlockNode(node) => node,
InlineNode(node) => node,
AnonymousBlock => panic!("Anonymous block box has no style node")
}
}
}
/// Transform a style tree into a layout tree.
pub fn layout_tree<'a>(node: &'a StyledNode<'a>, mut containing_block: Dimensions) -> LayoutBox<'a> {
// The layout algorithm expects the container height to start at 0.
// TODO: Save the initial containing block height, for calculating percent heights.
containing_block.content.height = 0.0;
let mut root_box = build_layout_tree(node);
root_box.layout(containing_block);
return root_box;
}
/// Build the tree of LayoutBoxes, but don't perform any layout calculations yet.
fn build_layout_tree<'a>(style_node: &'a StyledNode<'a>) -> LayoutBox<'a> {
// Create the root box.
let mut root = LayoutBox::new(match style_node.display() {
Display::Block => BlockNode(style_node),
Display::Inline => InlineNode(style_node),
Display::None => panic!("Root node has display: none.")
});
// Create the descendant boxes.
for child in &style_node.children {
match child.display() {
Display::Block => root.children.push(build_layout_tree(child)),
Display::Inline => root.get_inline_container().children.push(build_layout_tree(child)),
Display::None => {} // Don't lay out nodes with `display: none;`
}
}
return root;
}
impl<'a> LayoutBox<'a> {
/// Lay out a box and its descendants.
fn layout(&mut self, containing_block: Dimensions) {
match self.box_type {
BlockNode(_) => self.layout_block(containing_block),
InlineNode(_) => {} // TODO
AnonymousBlock => {} // TODO
}
}
/// Lay out a block-level element and its descendants.
fn layout_block(&mut self, containing_block: Dimensions) {
// Child width can depend on parent width, so we need to calculate this box's width before
// laying out its children.
self.calculate_block_width(containing_block);
// Determine where the box is located within its container.
self.calculate_block_position(containing_block);
// Recursively lay out the children of this box.
self.layout_block_children();
// Parent height can depend on child height, so `calculate_height` must be called after the
// children are laid out.
self.calculate_block_height();
}
/// Calculate the width of a block-level non-replaced element in normal flow.
///
/// http://www.w3.org/TR/CSS2/visudet.html#blockwidth
///
/// Sets the horizontal margin/padding/border dimensions, and the `width`.
fn calculate_block_width(&mut self, containing_block: Dimensions) {
let style = self.get_style_node();
// `width` has initial value `auto`.
let auto = Keyword("auto".to_string());
let mut width = style.value("width").unwrap_or(auto.clone());
// margin, border, and padding have initial value 0.
let zero = Length(0.0, Px);
let mut margin_left = style.lookup("margin-left", "margin", &zero);
let mut margin_right = style.lookup("margin-right", "margin", &zero);
let border_left = style.lookup("border-left-width", "border-width", &zero);
let border_right = style.lookup("border-right-width", "border-width", &zero);
let padding_left = style.lookup("padding-left", "padding", &zero);
let padding_right = style.lookup("padding-right", "padding", &zero);
let total = [&margin_left, &margin_right, &border_left, &border_right,
&padding_left, &padding_right, &width].iter().map(|v| v.to_px()).sum();
// If width is not auto and the total is wider than the container, treat auto margins as 0.
if width != auto && total > containing_block.content.width {
if margin_left == auto {
margin_left = Length(0.0, Px);
}
if margin_right == auto {
margin_right = Length(0.0, Px);
}
}
// Adjust used values so that the above sum equals `containing_block.width`.
// Each arm of the `match` should increase the total width by exactly `underflow`,
// and afterward all values should be absolute lengths in px.
let underflow = containing_block.content.width - total;
match (width == auto, margin_left == auto, margin_right == auto) {
// If the values are overconstrained, calculate margin_right.
(false, false, false) => {
margin_right = Length(margin_right.to_px() + underflow, Px);
}
// If exactly one size is auto, its used value follows from the equality.
(false, false, true) => { margin_right = Length(underflow, Px); }
(false, true, false) => { margin_left = Length(underflow, Px); }
// If width is set to auto, any other auto values become 0.
(true, _, _) => {
if margin_left == auto { margin_left = Length(0.0, Px); }
if margin_right == auto { margin_right = Length(0.0, Px); }
if underflow >= 0.0 {
// Expand width to fill the underflow.
width = Length(underflow, Px);
} else {
// Width can't be negative. Adjust the right margin instead.
width = Length(0.0, Px);
margin_right = Length(margin_right.to_px() + underflow, Px);
}
}
// If margin-left and margin-right are both auto, their used values are equal.
(false, true, true) => {
margin_left = Length(underflow / 2.0, Px);
margin_right = Length(underflow / 2.0, Px);
}
}
let d = &mut self.dimensions;
d.content.width = width.to_px();
d.padding.left = padding_left.to_px();
d.padding.right = padding_right.to_px();
d.border.left = border_left.to_px();
d.border.right = border_right.to_px();
d.margin.left = margin_left.to_px();
d.margin.right = margin_right.to_px();
}
/// Finish calculating the block's edge sizes, and position it within its containing block.
///
/// http://www.w3.org/TR/CSS2/visudet.html#normal-block
///
/// Sets the vertical margin/padding/border dimensions, and the `x`, `y` values.
fn calculate_block_position(&mut self, containing_block: Dimensions) {
let style = self.get_style_node();
let d = &mut self.dimensions;
// margin, border, and padding have initial value 0.
let zero = Length(0.0, Px);
// If margin-top or margin-bottom is `auto`, the used value is zero.
d.margin.top = style.lookup("margin-top", "margin", &zero).to_px();
d.margin.bottom = style.lookup("margin-bottom", "margin", &zero).to_px();
d.border.top = style.lookup("border-top-width", "border-width", &zero).to_px();
d.border.bottom = style.lookup("border-bottom-width", "border-width", &zero).to_px();
d.padding.top = style.lookup("padding-top", "padding", &zero).to_px();
d.padding.bottom = style.lookup("padding-bottom", "padding", &zero).to_px();
d.content.x = containing_block.content.x +
d.margin.left + d.border.left + d.padding.left;
// Position the box below all the previous boxes in the container.
d.content.y = containing_block.content.height + containing_block.content.y +
d.margin.top + d.border.top + d.padding.top;
}
/// Lay out the block's children within its content area.
///
/// Sets `self.dimensions.height` to the total content height.
fn layout_block_children(&mut self) {
let d = &mut self.dimensions;
for child in &mut self.children {
child.layout(*d);
// Increment the height so each child is laid out below the previous one.
d.content.height = d.content.height + child.dimensions.margin_box().height;
}
}
/// Height of a block-level non-replaced element in normal flow with overflow visible.
fn calculate_block_height(&mut self) {
// If the height is set to an explicit length, use that exact length.
// Otherwise, just keep the value set by `layout_block_children`.
if let Some(Length(h, Px)) = self.get_style_node().value("height") {
self.dimensions.content.height = h;
}
}
/// Where a new inline child should go.
fn get_inline_container(&mut self) -> &mut LayoutBox<'a> {
match self.box_type {
InlineNode(_) | AnonymousBlock => self,
BlockNode(_) => {
// If we've just generated an anonymous block box, keep using it.
// Otherwise, create a new one.
match self.children.last() {
Some(&LayoutBox { box_type: AnonymousBlock,..}) => {}
_ => self.children.push(LayoutBox::new(AnonymousBlock))
}
self.children.last_mut().unwrap()
}
}
}
}
impl Rect {
pub fn expanded_by(self, edge: EdgeSizes) -> Rect {
Rect {
x: self.x - edge.left,
y: self.y - edge.top,
width: self.width + edge.left + edge.right,
height: self.height + edge.top + edge.bottom,
}
}
}
impl Dimensions {
/// The area covered by the content area plus its padding.
pub fn padding_box(self) -> Rect {
self.content.expanded_by(self.padding)
}
/// The area covered by the content area plus padding and borders.
pub fn border_box(self) -> Rect {
self.padding_box().expanded_by(self.border)
}
/// The area covered by the content area plus padding, borders, and margin.
pub fn margin_box(self) -> Rect {
self.border_box().expanded_by(self.margin)
}
}