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
//! Resolve style and layout
use std::{
cell::RefCell,
time::{SystemTime, UNIX_EPOCH},
};
use debug_timer::debug_timer;
use parley::LayoutContext;
use selectors::Element as _;
use style::dom::TDocument;
#[cfg(feature = "parallel-construct")]
use rayon::prelude::*;
// FIXME: static thread_local FontCtx isn't necessarily correct in multi-document context.
// Should use thread_local crate with ThreadLocal value store in the Document.
thread_local! {
pub(crate) static LAYOUT_CTX: RefCell<Option<Box<LayoutContext<TextBrush>>>> = const { RefCell::new(None) };
}
#[cfg(feature = "incremental")]
use style::selector_parser::RestyleDamage;
use taffy::AvailableSpace;
use crate::{
BaseDocument, NON_INCREMENTAL,
events::ScrollAnimationState,
layout::{
construct::{
ConstructionTask, ConstructionTaskData, ConstructionTaskResult,
ConstructionTaskResultData, build_inline_layout_into, collect_layout_children,
},
damage::{ALL_DAMAGE, CONSTRUCT_BOX, CONSTRUCT_DESCENDENT, CONSTRUCT_FC},
},
node::TextBrush,
};
impl BaseDocument {
/// Restyle the tree and then relayout it
pub fn resolve(&mut self, current_time_for_animations: f64) {
if TDocument::as_node(&&self.nodes[0])
.first_element_child()
.is_none()
{
println!("No DOM - not resolving");
return;
}
// Process messages that have been sent to our message channel (e.g. loaded resource)
self.handle_messages();
self.resolve_scroll_animation();
// D-2c-followup: root_element widened to Option<&Node>. The early
// `is_none()` guard above ensures this branch is only taken when a root
// element exists, so `unwrap_or(0)` is dead — but it's still the
// compiler requirement. The guard above is now LOAD-BEARING for the
// unwrap_or(0) safety: deleting it would silently propagate `0` to
// `propagate_damage_flags` / `flush_styles_to_layout`, which would
// compute layout against the document root node (id 0, an empty
// layout block) producing garbage layout with no panic. The
// debug_assert below catches a future refactor that breaks this
// invariant on day 1.
debug_assert!(
self.root_element().is_some(),
"resolve: 'no DOM' guard above lost its effect — root_element became None when an element child was expected"
);
let root_node_id = self.root_element().map(|r| r.id).unwrap_or(0);
debug_timer!(timer, feature = "log_phase_times");
// we need to resolve stylist first since it will need to drive our layout bits
self.resolve_stylist(current_time_for_animations);
timer.record_time("style");
// Propagate damage flags (from mutation and restyles) up and down the tree
#[cfg(feature = "incremental")]
self.propagate_damage_flags(root_node_id, RestyleDamage::empty());
#[cfg(feature = "incremental")]
timer.record_time("damage");
// Fix up tree for layout (insert anonymous blocks as necessary, etc)
self.resolve_layout_children();
timer.record_time("construct");
self.resolve_deferred_tasks();
timer.record_time("pconstruct");
// Merge stylo into taffy
self.flush_styles_to_layout(root_node_id);
timer.record_time("flush");
// Next we resolve layout with the data resolved by stlist
self.resolve_layout();
timer.record_time("layout");
// Clear all damage and dirty flags
#[cfg(feature = "incremental")]
{
for (_, node) in self.nodes.iter_mut() {
node.clear_damage_mut();
node.unset_dirty_descendants();
}
timer.record_time("c_damage");
}
let mut subdoc_is_animating = false;
for &node_id in &self.sub_document_nodes {
let node = &mut self.nodes[node_id];
let size = node.final_layout.size;
if let Some(mut sub_doc) = node.subdoc_mut().map(|doc| doc.inner_mut()) {
// Set viewport
// viewport_mut handles change detection. So we just unconditionally set the values;
let mut sub_viewport = sub_doc.viewport_mut();
sub_viewport.hidpi_scale = self.viewport.hidpi_scale;
sub_viewport.zoom = self.viewport.zoom;
sub_viewport.color_scheme = self.viewport.color_scheme;
let viewport_scale = self.viewport.scale();
sub_viewport.window_size = (
(size.width * viewport_scale) as u32,
(size.height * viewport_scale) as u32,
);
drop(sub_viewport);
sub_doc.resolve(current_time_for_animations);
subdoc_is_animating |= sub_doc.is_animating();
}
}
self.subdoc_is_animating = subdoc_is_animating;
timer.record_time("subdocs");
timer.print_times(&format!("Resolve({}): ", self.id()));
}
pub fn resolve_scroll_animation(&mut self) {
match &mut self.scroll_animation {
ScrollAnimationState::Fling(fling_state) => {
let time_ms = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64 as f64;
let time_diff_ms = time_ms - fling_state.last_seen_time;
// 0.95 @ 60fps normalized to actual frame times
let deceleration = 1.0 - ((0.05 / 16.66666) * time_diff_ms);
fling_state.x_velocity *= deceleration;
fling_state.y_velocity *= deceleration;
fling_state.last_seen_time = time_ms;
let fling_state = fling_state.clone();
let dx = fling_state.x_velocity * time_diff_ms;
let dy = fling_state.y_velocity * time_diff_ms;
self.scroll_by(Some(fling_state.target), dx, dy, &mut |_| {});
if fling_state.x_velocity.abs() < 0.1 && fling_state.y_velocity.abs() < 0.1 {
self.scroll_animation = ScrollAnimationState::None;
}
}
ScrollAnimationState::None => {
// Do nothing
}
}
}
/// Ensure that the layout_children field is populated for all nodes
pub fn resolve_layout_children(&mut self) {
resolve_layout_children_recursive(self, self.root_node().id);
fn resolve_layout_children_recursive(doc: &mut BaseDocument, node_id: usize) {
let mut damage = doc.nodes[node_id].damage().unwrap_or(ALL_DAMAGE);
let _flags = doc.nodes[node_id].flags;
if NON_INCREMENTAL || damage.intersects(CONSTRUCT_FC | CONSTRUCT_BOX) {
//} || flags.contains(NodeFlags::IS_INLINE_ROOT) {
let mut layout_children = Vec::new();
let mut anonymous_block: Option<usize> = None;
collect_layout_children(doc, node_id, &mut layout_children, &mut anonymous_block);
// Recurse into newly collected layout children
for child_id in layout_children.iter().copied() {
resolve_layout_children_recursive(doc, child_id);
doc.nodes[child_id].layout_parent.set(Some(node_id));
if let Some(data) = doc.nodes[child_id].stylo_element_data.get_mut() {
data.damage
.remove(CONSTRUCT_DESCENDENT | CONSTRUCT_FC | CONSTRUCT_BOX);
}
}
*doc.nodes[node_id].layout_children.borrow_mut() = Some(layout_children.clone());
// *doc.nodes[node_id].paint_children.borrow_mut() = Some(layout_children);
damage.remove(CONSTRUCT_DESCENDENT | CONSTRUCT_FC | CONSTRUCT_BOX);
// damage.insert(RestyleDamage::RELAYOUT | RestyleDamage::REPAINT);
} else {
//if damage.contains(CONSTRUCT_DESCENDENT) {
let layout_children = doc.nodes[node_id].layout_children.borrow_mut().take();
if let Some(layout_children) = layout_children {
// Recurse into previously computed layout children
for child_id in layout_children.iter().copied() {
resolve_layout_children_recursive(doc, child_id);
doc.nodes[child_id].layout_parent.set(Some(node_id));
}
*doc.nodes[node_id].layout_children.borrow_mut() = Some(layout_children);
}
// damage.remove(CONSTRUCT_DESCENDENT);
// damage.insert(RestyleDamage::RELAYOUT | RestyleDamage::REPAINT);
}
doc.nodes[node_id].set_damage(damage);
}
}
pub fn resolve_deferred_tasks(&mut self) {
let mut deferred_construction_nodes = std::mem::take(&mut self.deferred_construction_nodes);
// Deduplicate deferred tasks by node_id to avoid redundant work
deferred_construction_nodes.sort_unstable_by_key(|task| task.node_id);
deferred_construction_nodes.dedup_by_key(|task| task.node_id);
#[cfg(feature = "parallel-construct")]
let iter = deferred_construction_nodes.into_par_iter();
#[cfg(not(feature = "parallel-construct"))]
let iter = deferred_construction_nodes.into_iter();
let results: Vec<ConstructionTaskResult> = iter
.map(|task: ConstructionTask| match task.data {
ConstructionTaskData::InlineLayout(mut layout) => {
#[cfg(feature = "parallel-construct")]
let mut layout_ctx = LAYOUT_CTX
.take()
.unwrap_or_else(|| Box::new(LayoutContext::new()));
#[cfg(feature = "parallel-construct")]
let layout_ctx_mut = &mut layout_ctx;
#[cfg(feature = "parallel-construct")]
let mut font_ctx = self
.thread_font_contexts
.get_or(|| {
RefCell::new(Box::new(
self.font_ctx
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone(),
))
})
.borrow_mut();
#[cfg(feature = "parallel-construct")]
let font_ctx_mut = &mut *font_ctx;
#[cfg(not(feature = "parallel-construct"))]
let layout_ctx_mut = &mut self.layout_ctx;
#[cfg(not(feature = "parallel-construct"))]
let font_ctx_mut =
&mut *self.font_ctx.lock().unwrap_or_else(|e| e.into_inner());
layout.content_widths = None;
build_inline_layout_into(
&self.nodes,
layout_ctx_mut,
font_ctx_mut,
&mut layout,
self.viewport.scale(),
task.node_id,
);
#[cfg(feature = "parallel-construct")]
{
LAYOUT_CTX.set(Some(layout_ctx));
}
// Pre-populate the content_widths cache. When there are no inline boxes,
// this is trivially safe and saves a Parley call during layout. When there
// ARE inline boxes, their sizes are not yet set (box sizing happens during
// compute_inline_layout_inner), so the cached widths may be stale — they
// will be recomputed on first access during layout. Only cache when no
// inline boxes are present (pure text runs) where box sizes are irrelevant.
if layout.layout.inline_boxes().is_empty() {
layout.content_widths();
}
ConstructionTaskResult {
node_id: task.node_id,
data: ConstructionTaskResultData::InlineLayout(layout),
}
}
})
.collect();
for result in results {
match result.data {
ConstructionTaskResultData::InlineLayout(layout) => {
self.nodes[result.node_id].cache.clear();
if let Some(elem) = self.nodes[result.node_id].element_data_mut() {
elem.inline_layout_data = Some(layout);
}
}
}
}
self.deferred_construction_nodes.clear();
}
/// Walk the nodes now that they're properly styled and transfer their styles to the taffy style system
///
/// TODO: update taffy to use an associated type instead of slab key
/// TODO: update taffy to support traited styles so we don't even need to rely on taffy for storage
pub fn resolve_layout(&mut self) {
let size = self.stylist.device().au_viewport_size();
let available_space = taffy::Size {
width: AvailableSpace::Definite(size.width.to_f32_px()),
height: AvailableSpace::Definite(size.height.to_f32_px()),
};
// D-2c-followup: propagate the `Option<&Node>` widening; the early
// guard above guarantees this `unwrap_or(0)` is unreachable, but the
// compiler won't let us call `.id` on `Option<&Node>` anymore.
debug_assert!(
self.root_element().is_some(),
"resolve_layout: 'no DOM' guard above lost its effect — root_element became None when an element child was expected"
);
let root_element_id =
taffy::NodeId::from(self.root_element().map(|r| r.id).unwrap_or(0));
// println!("\n\nRESOLVE LAYOUT\n===========\n");
taffy::compute_root_layout(self, root_element_id, available_space);
taffy::round_layout(self, root_element_id);
// println!("\n\n");
// taffy::print_tree(self, root_node_id)
}
}