1use crate::scene3d::Scene3D;
4use strata_layout::{LayoutNode, Rect};
5use strata_primitives::geom::EdgeInsets;
6use strata_style::effects::{BackdropFilter, ClipPath};
7use strata_style::types::{
8 BlendMode, BorderCollapse, BorderRadius, BorderStyle, BoxShadow, Color, ColorStop, Display,
9 FontWeight, Isolation, Overflow, Position,
10};
11
12#[derive(Debug, Clone, PartialEq)]
14pub enum DrawCommand {
15 DrawRect {
16 bounds: Rect,
17 color: Color,
18 },
19 DrawRoundedRect {
20 bounds: Rect,
21 color: Color,
22 border_radius: BorderRadius,
23 border_width: EdgeInsets<f32>,
24 border_color: Option<Color>,
25 },
26 DrawShadow {
27 bounds: Rect,
28 shadow: BoxShadow,
29 border_radius: BorderRadius,
30 },
31 DrawInsetShadow {
32 bounds: Rect,
33 shadow: BoxShadow,
34 border_radius: BorderRadius,
35 },
36 DrawLinearGradient {
37 bounds: Rect,
38 angle_deg: f32,
39 stops: Vec<ColorStop>,
40 border_radius: BorderRadius,
41 },
42 DrawRadialGradient {
43 bounds: Rect,
44 center: (f32, f32),
45 stops: Vec<ColorStop>,
46 border_radius: BorderRadius,
47 },
48 PushBackdropFilter {
49 bounds: Rect,
50 radius: BorderRadius,
51 filter: BackdropFilter,
52 },
53 PopBackdropFilter,
54 PushFilter {
55 bounds: Rect,
56 filter: BackdropFilter,
57 },
58 PopFilter,
59 PushClipPath {
60 bounds: Rect,
61 clip_path: ClipPath,
62 },
63 PopClipPath,
64 PushBlendMode {
65 mode: BlendMode,
66 },
67 PopBlendMode,
68 PushIsolation {
69 isolate: bool,
70 },
71 PopIsolation,
72 PushOpacity {
73 alpha: f32,
74 },
75 PopOpacity,
76 DrawBorder {
77 bounds: Rect,
78 widths: EdgeInsets<f32>,
79 color: Color,
80 border_radius: BorderRadius,
81 style: BorderStyle,
82 },
83 DrawText {
84 origin: (f32, f32),
85 bounds_width: Option<f32>,
86 bounds_height: Option<f32>,
87 text_align: strata_style::TextAlign,
88 text: String,
89 font_size: f32,
90 line_height: f32,
91 font_weight: FontWeight,
92 color: Color,
93 is_monospace: bool,
94 font_family: strata_primitives::AtomId,
95 },
96 DrawTextFragments {
97 fragments: Vec<strata_layout::TextFragment>,
98 },
99 DrawViewport3D {
100 bounds: Rect,
101 scene: std::sync::Arc<Scene3D>,
102 },
103 DrawCanvas2D {
104 bounds: Rect,
105 commands: Vec<crate::canvas2d::CanvasCommand>,
106 },
107 DrawSvgPath {
108 bounds: Rect,
109 path_data: String,
110 stroke_color: Option<Color>,
111 fill_color: Option<Color>,
112 stroke_width: f32,
113 stroke_linecap: strata_layout::StrokeLineCap,
114 stroke_linejoin: strata_layout::StrokeLineJoin,
115 stroke_dasharray: Vec<f32>,
116 fill_rule: strata_layout::FillRule,
117 view_box: (f32, f32),
118 },
119 DrawGpuPath {
120 bounds: Rect,
121 path: strata_gpu_path::Path,
122 stroke: Option<strata_gpu_path::StrokeOptions>,
123 fill_color: Option<Color>,
124 stroke_color: Option<Color>,
125 transform: Option<strata_primitives::geom::Matrix4x4>,
126 },
127 DrawImage {
128 bounds: Rect,
129 image: strata_layout::ImageResource,
130 },
131 PushClip {
132 bounds: Rect,
133 radius: BorderRadius,
134 },
135 PopClip,
136 PushTransform {
137 matrix: strata_primitives::geom::Matrix4x4,
138 },
139 PopTransform,
140}
141
142impl DrawCommand {
143 #[inline]
145 pub fn is_clip(&self) -> bool {
146 matches!(
147 self,
148 Self::PushClip { .. }
149 | Self::PopClip
150 | Self::PushBackdropFilter { .. }
151 | Self::PopBackdropFilter
152 | Self::PushClipPath { .. }
153 | Self::PopClipPath
154 )
155 }
156
157 #[inline]
163 pub fn is_state_command(&self) -> bool {
164 matches!(
165 self,
166 Self::PushClip { .. }
167 | Self::PopClip
168 | Self::PushBackdropFilter { .. }
169 | Self::PopBackdropFilter
170 | Self::PushClipPath { .. }
171 | Self::PopClipPath
172 | Self::PushFilter { .. }
173 | Self::PopFilter
174 | Self::PushBlendMode { .. }
175 | Self::PopBlendMode
176 | Self::PushIsolation { .. }
177 | Self::PopIsolation
178 | Self::PushOpacity { .. }
179 | Self::PopOpacity
180 | Self::PushTransform { .. }
181 | Self::PopTransform
182 )
183 }
184
185 pub fn bounds(&self) -> Option<Rect> {
187 match self {
188 Self::DrawRect { bounds, .. } => Some(*bounds),
189 Self::DrawRoundedRect { bounds, .. } => Some(*bounds),
190 Self::DrawShadow { bounds, shadow, .. } => {
191 let spread = shadow.spread_radius + shadow.blur_radius;
192 Some(Rect::new(
193 bounds.x + shadow.offset_x - spread,
194 bounds.y + shadow.offset_y - spread,
195 bounds.width + spread * 2.0,
196 bounds.height + spread * 2.0,
197 ))
198 }
199 Self::DrawInsetShadow { bounds, .. } => Some(*bounds),
200 Self::DrawLinearGradient { bounds, .. } => Some(*bounds),
201 Self::DrawRadialGradient { bounds, .. } => Some(*bounds),
202 Self::PushBackdropFilter { bounds, .. } => Some(*bounds),
203 Self::PopBackdropFilter => None,
204 Self::PushFilter { bounds, .. } => Some(*bounds),
205 Self::PopFilter => None,
206 Self::PushClipPath { bounds, .. } => Some(*bounds),
207 Self::PopClipPath => None,
208 Self::PushBlendMode { .. } | Self::PopBlendMode => None,
209 Self::PushIsolation { .. } | Self::PopIsolation => None,
210 Self::PushOpacity { .. } | Self::PopOpacity => None,
211 Self::DrawBorder { bounds, .. } => Some(*bounds),
212 Self::DrawText {
213 origin,
214 bounds_width,
215 bounds_height,
216 text,
217 font_size,
218 line_height,
219 is_monospace,
220 ..
221 } => {
222 let (w, h) = draw_text_paint_size(
223 text,
224 *bounds_width,
225 *bounds_height,
226 *font_size,
227 *line_height,
228 *is_monospace,
229 );
230 Some(Rect::new(origin.0, origin.1, w, h))
231 }
232 Self::DrawTextFragments { fragments } => {
233 if fragments.is_empty() {
234 None
235 } else {
236 let mut min_x = f32::MAX;
237 let mut min_y = f32::MAX;
238 let mut max_x = f32::MIN;
239 let mut max_y = f32::MIN;
240 for f in fragments {
241 min_x = min_x.min(f.bounds.x);
242 min_y = min_y.min(f.bounds.y);
243 max_x = max_x.max(f.bounds.x + f.bounds.width);
244 max_y = max_y.max(f.bounds.y + f.bounds.height);
245 }
246 Some(Rect::new(
247 min_x,
248 min_y,
249 (max_x - min_x).max(0.0),
250 (max_y - min_y).max(0.0),
251 ))
252 }
253 }
254 Self::DrawViewport3D { bounds, .. } => Some(*bounds),
255 Self::DrawCanvas2D { bounds, .. } => Some(*bounds),
256 Self::DrawSvgPath { bounds, .. } => Some(*bounds),
257 Self::DrawGpuPath { bounds, .. } => Some(*bounds),
258 Self::DrawImage { bounds, .. } => Some(*bounds),
259 Self::PushClip { bounds, .. } => Some(*bounds),
260 Self::PopClip => None,
261 Self::PushTransform { .. } | Self::PopTransform => None,
262 }
263 }
264}
265
266pub fn layout_draw_text_lines<'a>(
269 text: &'a str,
270 bounds_width: Option<f32>,
271 bounds_height: Option<f32>,
272 font_size: f32,
273 line_height: f32,
274 text_align: strata_style::TextAlign,
275 mut char_advance: impl FnMut(char) -> f32,
276) -> (Vec<(f32, &'a str)>, f32) {
277 let max_w = bounds_width.filter(|w| w.is_finite() && *w > 0.0);
278 let mut raw_lines: Vec<(&'a str, f32)> = Vec::new();
279 for para in text.split('\n') {
280 if let Some(limit) = max_w {
281 let mut line_start = 0usize;
282 let mut cur_w = 0.0f32;
283 let mut last_break: Option<(usize, usize, f32)> = None;
284 let mut in_ws = false;
285 let mut ws_end_prev = 0usize;
286 let mut ws_w_prev = 0.0f32;
287 for (idx, ch) in para.char_indices() {
288 let ch_end = idx + ch.len_utf8();
289 let cw = char_advance(ch);
290 if ch.is_whitespace() {
291 if !in_ws {
292 ws_end_prev = idx;
293 ws_w_prev = cur_w;
294 in_ws = true;
295 }
296 last_break = Some((ws_end_prev, ch_end, ws_w_prev));
297 cur_w += cw;
298 } else {
299 in_ws = false;
300 if cur_w + cw > limit + 0.01 && idx > line_start {
301 if let Some((end_b, next_b, bw)) =
302 last_break.filter(|(eb, _, _)| *eb > line_start)
303 {
304 raw_lines.push((¶[line_start..end_b], bw));
305 line_start = next_b;
306 cur_w = para[line_start..ch_end]
307 .chars()
308 .map(&mut char_advance)
309 .sum();
310 last_break = None;
311 } else {
312 raw_lines.push((¶[line_start..idx], cur_w));
313 line_start = idx;
314 cur_w = cw;
315 last_break = None;
316 }
317 } else {
318 cur_w += cw;
319 }
320 }
321 }
322 raw_lines.push((¶[line_start..], cur_w));
323 } else {
324 let w: f32 = para.chars().map(&mut char_advance).sum();
325 raw_lines.push((para, w));
326 }
327 }
328
329 let aligned: Vec<(f32, &'a str)> = raw_lines
330 .into_iter()
331 .map(|(line, lw)| {
332 let ox = match (max_w, text_align) {
333 (Some(limit), strata_style::TextAlign::Center) => ((limit - lw) * 0.5).max(0.0),
334 (Some(limit), strata_style::TextAlign::Right) => (limit - lw).max(0.0),
335 _ => 0.0,
336 };
337 (ox, line)
338 })
339 .collect();
340
341 let single_line_h = effective_draw_text_line_height(font_size, line_height);
342 let total_text_h = aligned.len().max(1) as f32 * single_line_h;
343 let start_y_offset = bounds_height
344 .map(|bh| ((bh.max(single_line_h) - total_text_h) * 0.5).max(0.0))
345 .unwrap_or(0.0);
346
347 (aligned, start_y_offset)
348}
349
350#[inline]
352pub fn effective_draw_text_line_height(font_size: f32, line_height: f32) -> f32 {
353 if line_height <= 0.0 || !line_height.is_finite() {
354 font_size * 1.2
355 } else if line_height <= 4.0 {
356 font_size * line_height
357 } else {
358 line_height
359 }
360}
361
362pub fn draw_text_paint_size(
366 text: &str,
367 bounds_width: Option<f32>,
368 bounds_height: Option<f32>,
369 font_size: f32,
370 line_height: f32,
371 is_monospace: bool,
372) -> (f32, f32) {
373 let fs = if font_size.is_finite() && font_size > 0.0 {
374 font_size
375 } else {
376 14.0
377 };
378 let line_step = effective_draw_text_line_height(fs, line_height).max(fs);
379 let max_w = bounds_width.filter(|w| w.is_finite() && *w > 0.0);
380
381 let ascii_w = if is_monospace { fs * 0.65 } else { fs * 0.64 };
382 let wide_ascii_w = if is_monospace { fs * 0.65 } else { fs * 0.85 };
383 let non_ascii_w = fs * 1.05;
384
385 let mut total_lines = 0usize;
386 let mut max_line_w = 0.0f32;
387 let mut max_para_chars = 0usize;
388 let mut para_count = 0usize;
389
390 for para in text.split('\n') {
391 para_count += 1;
392 let mut para_chars = 0usize;
393 let mut para_w = 0.0f32;
394 for ch in para.chars() {
395 para_chars += 1;
396 para_w += if ch == '\t' {
397 ascii_w * 4.0
398 } else if ch.is_ascii_uppercase() || matches!(ch, 'm' | 'w' | '@' | '%' | '&') {
399 wide_ascii_w
400 } else if ch.is_ascii() {
401 ascii_w
402 } else {
403 non_ascii_w
404 };
405 }
406 max_para_chars = max_para_chars.max(para_chars);
407
408 if let Some(limit) = max_w {
409 max_line_w = max_line_w.max(limit);
410 if para.is_empty() {
411 total_lines += 1;
412 } else {
413 let eff_limit = (limit * 0.78).max(ascii_w);
416 let wrapped = ((para_w / eff_limit).ceil() as usize).max(1);
417 total_lines += wrapped;
418 }
419 } else {
420 max_line_w = max_line_w.max(para_w);
421 total_lines += 1;
422 }
423 }
424
425 let line_count = total_lines.max(para_count).max(1);
426 let est_w = if let Some(limit) = max_w {
427 limit.max(max_line_w)
428 } else {
429 max_line_w.max(max_para_chars as f32 * fs * 0.72)
430 };
431 let est_h = (line_count as f32 * line_step) + (line_step * 0.5);
432 let final_h = bounds_height
433 .filter(|bh| bh.is_finite() && *bh > 0.0)
434 .map_or(est_h, |bh| bh.max(est_h));
435 (est_w, final_h)
436}
437
438#[derive(Debug, Default, Clone, PartialEq)]
440pub struct DisplayList {
441 pub commands: Vec<DrawCommand>,
442}
443
444impl DisplayList {
445 pub fn new() -> Self {
446 Self::default()
447 }
448
449 pub fn push(&mut self, cmd: DrawCommand) {
450 self.commands.push(cmd);
451 }
452
453 pub fn commands(&self) -> &[DrawCommand] {
454 &self.commands
455 }
456
457 pub fn clear(&mut self) {
458 self.commands.clear();
459 }
460
461 pub fn len(&self) -> usize {
462 self.commands.len()
463 }
464
465 pub fn is_empty(&self) -> bool {
466 self.commands.is_empty()
467 }
468}
469
470#[derive(Debug, Default, Clone, PartialEq)]
472pub struct DamageTracker {
473 pub dirty_rects: Vec<Rect>,
474}
475
476impl DamageTracker {
477 pub fn new() -> Self {
478 Self::default()
479 }
480
481 pub fn add_damage(&mut self, rect: Rect) {
482 if rect.width > 0.0 && rect.height > 0.0 {
483 self.dirty_rects.push(rect);
484 }
485 }
486
487 pub fn bounding_damage(&self) -> Option<Rect> {
489 if self.dirty_rects.is_empty() {
490 return None;
491 }
492
493 let mut min_x = f32::MAX;
494 let mut min_y = f32::MAX;
495 let mut max_x = f32::MIN;
496 let mut max_y = f32::MIN;
497
498 for r in &self.dirty_rects {
499 min_x = min_x.min(r.x);
500 min_y = min_y.min(r.y);
501 max_x = max_x.max(r.max_x());
502 max_y = max_y.max(r.max_y());
503 }
504
505 Some(Rect::new(min_x, min_y, max_x - min_x, max_y - min_y))
506 }
507
508 pub fn cluster_damage_rects(&self) -> Vec<Rect> {
513 if self.dirty_rects.is_empty() {
514 return Vec::new();
515 }
516
517 let mut clusters: Vec<Rect> = Vec::new();
518 for &r in &self.dirty_rects {
519 let mut merged = false;
520 for cluster in &mut clusters {
521 let expanded = Rect::new(
523 cluster.x - 16.0,
524 cluster.y - 16.0,
525 cluster.width + 32.0,
526 cluster.height + 32.0,
527 );
528 if expanded.intersect(r).is_some() {
529 let min_x = cluster.x.min(r.x);
530 let min_y = cluster.y.min(r.y);
531 let max_x = cluster.max_x().max(r.max_x());
532 let max_y = cluster.max_y().max(r.max_y());
533 *cluster = Rect::new(min_x, min_y, max_x - min_x, max_y - min_y);
534 merged = true;
535 break;
536 }
537 }
538 if !merged {
539 clusters.push(r);
540 }
541 }
542 clusters
543 }
544
545 pub fn reset(&mut self) {
546 self.dirty_rects.clear();
547 }
548}
549
550#[derive(Debug, Clone, Copy)]
553pub struct ScrollbarOverlay {
554 pub node_ptr: usize,
556 pub clip_bounds: Rect,
558 pub clip_radius: BorderRadius,
560 pub thumb_bounds: Rect,
562 pub color: Color,
564 pub thumb_radius: BorderRadius,
566}
567
568pub struct Compositor;
570
571impl Compositor {
572 pub fn build_display_list(root: &LayoutNode) -> DisplayList {
574 Self::build_display_list_with_viewport(root, None)
575 }
576
577 #[inline]
578 fn cull_rect_for_viewport(viewport: Option<Rect>) -> Option<Rect> {
579 viewport.map(|vp| {
580 let buffer_y = 1200.0;
581 let buffer_x = 300.0;
582 Rect::new(
583 vp.x - buffer_x,
584 vp.y - buffer_y,
585 vp.width + buffer_x * 2.0,
586 vp.height + buffer_y * 2.0,
587 )
588 })
589 }
590
591 #[inline]
592 fn has_scrollbar(node: &LayoutNode, scrollbars: &[ScrollbarOverlay]) -> bool {
593 if scrollbars.is_empty() {
594 return false;
595 }
596 let ptr = node as *const LayoutNode as usize;
597 scrollbars.iter().any(|bar| bar.node_ptr == ptr)
598 }
599
600 #[inline]
601 fn emit_node_scrollbar(
602 node: &LayoutNode,
603 list: &mut DisplayList,
604 scrollbars: &[ScrollbarOverlay],
605 ) {
606 if scrollbars.is_empty() {
607 return;
608 }
609 let ptr = node as *const LayoutNode as usize;
610 for bar in scrollbars {
611 if bar.node_ptr == ptr {
612 list.push(DrawCommand::PushClip {
613 bounds: bar.clip_bounds,
614 radius: bar.clip_radius,
615 });
616 list.push(DrawCommand::DrawRoundedRect {
617 bounds: bar.thumb_bounds,
618 color: bar.color,
619 border_radius: bar.thumb_radius,
620 border_width: EdgeInsets::all(0.0),
621 border_color: None,
622 });
623 list.push(DrawCommand::PopClip);
624 break;
625 }
626 }
627 }
628
629 pub fn build_display_list_with_viewport(
632 root: &LayoutNode,
633 viewport: Option<Rect>,
634 ) -> DisplayList {
635 Self::build_display_list_with_scrollbars(root, viewport, &[])
636 }
637
638 pub fn build_display_list_with_scrollbars(
641 root: &LayoutNode,
642 viewport: Option<Rect>,
643 scrollbars: &[ScrollbarOverlay],
644 ) -> DisplayList {
645 let mut list = DisplayList::new();
646 let cull_rect = Self::cull_rect_for_viewport(viewport);
647 Self::paint_stacking_context_guarded_with_scrollbars(
648 root, &mut list, cull_rect, scrollbars, 0,
649 );
650 list
651 }
652
653 pub fn build_document_display_list_with_viewport(
656 root: &LayoutNode,
657 viewport: Option<Rect>,
658 ) -> DisplayList {
659 Self::build_document_display_list_with_scrollbars(root, viewport, &[])
660 }
661
662 pub fn build_document_display_list_with_scrollbars(
665 root: &LayoutNode,
666 viewport: Option<Rect>,
667 scrollbars: &[ScrollbarOverlay],
668 ) -> DisplayList {
669 let mut list = DisplayList::new();
670 let cull_rect = Self::cull_rect_for_viewport(viewport);
671 Self::paint_stacking_context_inner(
672 root, &mut list, cull_rect, cull_rect, &[], true, scrollbars, 0,
673 );
674 list
675 }
676
677 pub fn append_top_layer_portals(
679 root: &LayoutNode,
680 list: &mut DisplayList,
681 viewport: Option<Rect>,
682 ) {
683 Self::append_top_layer_portals_with_scrollbars(root, list, viewport, &[]);
684 }
685
686 pub fn append_top_layer_portals_with_scrollbars(
689 root: &LayoutNode,
690 list: &mut DisplayList,
691 viewport: Option<Rect>,
692 scrollbars: &[ScrollbarOverlay],
693 ) {
694 let cull_rect = Self::cull_rect_for_viewport(viewport);
695 Self::paint_top_layer_portals(root, list, cull_rect, scrollbars);
696 }
697
698 #[inline]
703 pub fn establishes_stacking_context(node: &LayoutNode, is_root: bool) -> bool {
704 node.establishes_stacking_context_in(None, is_root)
705 }
706
707 fn collect_table_cells<'a>(node: &'a LayoutNode, out: &mut Vec<&'a LayoutNode>) {
709 if node.style.display == Display::TableCell {
710 out.push(node);
711 return;
712 }
713 for child in &node.children {
714 Self::collect_table_cells(child, out);
715 }
716 }
717
718 fn paint_collapsed_table_grid(node: &LayoutNode, list: &mut DisplayList) {
726 if node.style.display != Display::Table
727 || node.style.border_collapse != BorderCollapse::Collapse
728 {
729 return;
730 }
731
732 if let Some(ref grid) = node.table_grid {
733 for r in 0..=grid.num_rows {
735 let y = grid.row_positions[r];
736 for c in 0..grid.num_cols {
737 let edge = &grid.horizontal_edges[r][c];
738 if edge.style == BorderStyle::Hidden
739 || edge.style == BorderStyle::None
740 || edge.width <= 0.0
741 {
742 continue;
743 }
744 let x0 = grid.col_positions[c];
745 let x1 = grid.col_positions[c + 1];
746 let w = (x1 - x0).max(1.0);
747 let color = edge.color.unwrap_or(node.style.color);
748 let thickness = edge.width.round().max(1.0);
749 let draw_y = (y - 0.5 * thickness).round();
750 list.push(DrawCommand::DrawRect {
751 bounds: Rect::new(x0.round(), draw_y, w.round(), thickness),
752 color,
753 });
754 }
755 }
756
757 for r in 0..grid.num_rows {
759 let y0 = grid.row_positions[r];
760 let y1 = grid.row_positions[r + 1];
761 let h = (y1 - y0).max(1.0);
762 for c in 0..=grid.num_cols {
763 let edge = &grid.vertical_edges[r][c];
764 if edge.style == BorderStyle::Hidden
765 || edge.style == BorderStyle::None
766 || edge.width <= 0.0
767 {
768 continue;
769 }
770 let x = grid.col_positions[c];
771 let color = edge.color.unwrap_or(node.style.color);
772 let thickness = edge.width.round().max(1.0);
773 let draw_x = (x - 0.5 * thickness).round();
774 list.push(DrawCommand::DrawRect {
775 bounds: Rect::new(draw_x, y0.round(), thickness, h.round()),
776 color,
777 });
778 }
779 }
780 return;
781 }
782
783 let mut cells: Vec<&LayoutNode> = Vec::new();
784 Self::collect_table_cells(node, &mut cells);
785 cells.retain(|cell| {
786 cell.geometry.border_box.width > 0.0 && cell.geometry.border_box.height > 0.0
787 });
788 if cells.is_empty() {
789 return;
790 }
791
792 let mut stroke_width = 0.0f32;
793 let mut stroke_color: Option<Color> = None;
794 for cell in &cells {
795 let widths = cell.style.border_width;
796 let width = widths
797 .top
798 .max(widths.right)
799 .max(widths.bottom)
800 .max(widths.left);
801 if width > stroke_width {
802 stroke_width = width;
803 stroke_color = cell.style.border_color;
804 }
805 }
806 if stroke_width <= 0.0 {
807 return;
808 }
809 let color = stroke_color.unwrap_or(node.style.color);
810
811 let mut xs: Vec<f32> = Vec::new();
812 let mut ys: Vec<f32> = Vec::new();
813 for cell in &cells {
814 let b = cell.geometry.border_box;
815 xs.push(b.x);
816 xs.push(b.x + b.width);
817 ys.push(b.y);
818 ys.push(b.y + b.height);
819 }
820 let snap = |v: f32| v.round();
821 xs.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
822 xs.dedup_by(|a, b| (*a - *b).abs() < 0.01);
823 ys.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
824 ys.dedup_by(|a, b| (*a - *b).abs() < 0.01);
825
826 let top = snap(*ys.first().unwrap_or(&0.0));
827 let bottom = snap(*ys.last().unwrap_or(&0.0));
828 let line_h = (bottom - top + 1.0).max(1.0);
829 let left = snap(node.geometry.border_box.x);
830 let right = snap(*xs.last().unwrap_or(&0.0));
831 let line_w = (right - left).max(1.0);
832 let thickness = stroke_width.round().max(1.0);
833
834 for x in xs {
835 let snapped = snap(x);
836 let draw_x = if (snapped - right).abs() < 0.01 {
838 snapped - thickness
839 } else {
840 snapped
841 };
842 list.push(DrawCommand::DrawRect {
843 bounds: Rect::new(draw_x, top, thickness, line_h),
844 color,
845 });
846 }
847
848 for y in ys {
849 let snapped = snap(y);
850 list.push(DrawCommand::DrawRect {
851 bounds: Rect::new(left, snapped, line_w, thickness),
852 color,
853 });
854 }
855 }
856
857 fn inline_has_paintable_non_text_content(node: &LayoutNode) -> bool {
859 if !node.svg_items.is_empty()
860 || node.svg_path.is_some()
861 || node.image.is_some()
862 || node.scene_3d.is_some()
863 {
864 return true;
865 }
866 for c in &node.children {
867 if c.style.display != Display::Inline || Self::inline_has_paintable_non_text_content(c)
868 {
869 return true;
870 }
871 }
872 false
873 }
874
875 pub const MAX_COMPOSITOR_DEPTH: usize = 1024;
877
878 pub fn paint_stacking_context(node: &LayoutNode, list: &mut DisplayList) {
880 Self::paint_stacking_context_culled(node, list, None);
881 }
882
883 pub fn paint_stacking_context_culled(
885 node: &LayoutNode,
886 list: &mut DisplayList,
887 cull: Option<Rect>,
888 ) {
889 Self::paint_stacking_context_guarded(node, list, cull, 0);
890 }
891
892 pub fn paint_stacking_context_guarded(
894 node: &LayoutNode,
895 list: &mut DisplayList,
896 cull: Option<Rect>,
897 depth: usize,
898 ) {
899 Self::paint_stacking_context_guarded_with_scrollbars(node, list, cull, &[], depth);
900 }
901
902 fn paint_stacking_context_guarded_with_scrollbars(
903 node: &LayoutNode,
904 list: &mut DisplayList,
905 cull: Option<Rect>,
906 scrollbars: &[ScrollbarOverlay],
907 depth: usize,
908 ) {
909 Self::paint_stacking_context_inner(
910 node,
911 list,
912 cull,
913 cull,
914 &[],
915 depth == 0,
916 scrollbars,
917 depth,
918 );
919 if depth == 0 {
920 Self::paint_top_layer_portals(node, list, cull, scrollbars);
921 }
922 }
923
924 fn collect_top_layer_portals<'a>(node: &'a LayoutNode, out: &mut Vec<&'a LayoutNode>) {
925 let mut stack: Vec<(&'a LayoutNode, usize)> = vec![(node, 0)];
926 while let Some((cur, depth)) = stack.pop() {
927 if depth > 0 && cur.is_top_layer {
928 out.push(cur);
929 }
930 if depth >= Self::MAX_COMPOSITOR_DEPTH {
931 continue;
932 }
933 for child in cur.children.iter().rev() {
934 if child.style.display == Display::None
935 || child.style.content_visibility
936 == strata_style::types::ContentVisibility::Hidden
937 {
938 continue;
939 }
940 stack.push((child, depth + 1));
941 }
942 }
943 }
944
945 fn paint_top_layer_portals(
946 node: &LayoutNode,
947 list: &mut DisplayList,
948 root_cull: Option<Rect>,
949 scrollbars: &[ScrollbarOverlay],
950 ) {
951 let mut portals = Vec::new();
952 Self::collect_top_layer_portals(node, &mut portals);
953 for portal in portals {
954 Self::paint_stacking_context_inner(
955 portal,
956 list,
957 root_cull,
958 root_cull,
959 &[],
960 false,
961 scrollbars,
962 1,
963 );
964 }
965 }
966
967 fn node_clip_scroll_step(node: &LayoutNode) -> Option<ClipScrollStep> {
968 let bounds = node.geometry.border_box;
969 let border_radius = node.style.border_radius;
970 let has_any_radius = border_radius.top_left > 0.0
971 || border_radius.top_right > 0.0
972 || border_radius.bottom_left > 0.0
973 || border_radius.bottom_right > 0.0;
974 let clips_overflow = node.style.overflow_x != Overflow::Visible
975 || node.style.overflow_y != Overflow::Visible
976 || node.transition_layout_width_px.is_some()
977 || node.transition_layout_height_px.is_some();
978 let should_clip =
979 clips_overflow || (has_any_radius && (node.image.is_some() || node.scene_3d.is_some()));
980 let clip = if should_clip {
981 let clip_bounds = if clips_overflow
982 && node.geometry.padding_box.width > 0.0
983 && node.geometry.padding_box.height > 0.0
984 {
985 node.geometry.padding_box
986 } else {
987 bounds
988 };
989 Some((clip_bounds, border_radius))
990 } else {
991 None
992 };
993 let scroll_offset = (node.geometry.scroll_offset.x, node.geometry.scroll_offset.y);
994 let is_fixed_cb = node.style.establishes_fixed_containing_block();
995 let is_abs_cb = node.style.position != Position::Static || is_fixed_cb;
996
997 if clip.is_some()
998 || scroll_offset.0 != 0.0
999 || scroll_offset.1 != 0.0
1000 || is_abs_cb
1001 || is_fixed_cb
1002 {
1003 Some(ClipScrollStep {
1004 clip,
1005 scroll_offset,
1006 is_abs_cb,
1007 is_fixed_cb,
1008 })
1009 } else {
1010 None
1011 }
1012 }
1013
1014 #[inline]
1015 fn effective_steps(position: Position, steps: &[ClipScrollStep]) -> &[ClipScrollStep] {
1016 match position {
1017 Position::Fixed => match steps.iter().rposition(|s| s.is_fixed_cb) {
1018 Some(idx) => &steps[..=idx],
1019 None => &[],
1020 },
1021 Position::Absolute => match steps.iter().rposition(|s| s.is_abs_cb) {
1022 Some(idx) => &steps[..=idx],
1023 None => &[],
1024 },
1025 Position::Static | Position::Relative | Position::Sticky => steps,
1026 }
1027 }
1028
1029 fn push_clip_scroll_steps(steps: &[ClipScrollStep], list: &mut DisplayList) {
1030 for step in steps {
1031 if let Some((bounds, radius)) = step.clip {
1032 list.push(DrawCommand::PushClip { bounds, radius });
1033 }
1034 if step.scroll_offset.0 != 0.0 || step.scroll_offset.1 != 0.0 {
1035 let mat = strata_primitives::geom::Matrix4x4::translation(
1036 -step.scroll_offset.0,
1037 -step.scroll_offset.1,
1038 0.0,
1039 );
1040 list.push(DrawCommand::PushTransform { matrix: mat });
1041 }
1042 }
1043 }
1044
1045 fn pop_clip_scroll_steps(steps: &[ClipScrollStep], list: &mut DisplayList) {
1046 for step in steps.iter().rev() {
1047 if step.scroll_offset.0 != 0.0 || step.scroll_offset.1 != 0.0 {
1048 list.push(DrawCommand::PopTransform);
1049 }
1050 if step.clip.is_some() {
1051 list.push(DrawCommand::PopClip);
1052 }
1053 }
1054 }
1055
1056 fn cull_with_steps(base_cull: Option<Rect>, steps: &[ClipScrollStep]) -> Option<Rect> {
1057 let mut current = base_cull;
1058 for step in steps {
1059 if let Some((clip_bounds, _)) = step.clip {
1060 if clip_bounds.width > 0.0 && clip_bounds.height > 0.0 {
1061 if let Some(c) = current {
1062 current = Some(
1063 clip_bounds
1064 .intersect(c)
1065 .unwrap_or_else(|| Rect::new(0.0, 0.0, -1.0, -1.0)),
1066 );
1067 }
1068 }
1069 }
1070 }
1071 current
1072 }
1073
1074 fn subtree_has_fixed_escape(node: &LayoutNode, depth: usize) -> bool {
1075 if depth >= Self::MAX_COMPOSITOR_DEPTH
1076 || node.style.display == Display::None
1077 || node.is_top_layer
1078 {
1079 return false;
1080 }
1081 if node.style.position == Position::Fixed {
1082 return true;
1083 }
1084 if node.style.establishes_fixed_containing_block() {
1085 return false;
1086 }
1087 node.children
1088 .iter()
1089 .any(|c| Self::subtree_has_fixed_escape(c, depth + 1))
1090 }
1091
1092 fn collect_hoisted_participants<'a>(
1093 parent: &'a LayoutNode,
1094 current_steps: &mut Vec<ClipScrollStep>,
1095 negative_z: &mut Vec<HoistedParticipant<'a>>,
1096 auto_or_zero_z: &mut Vec<HoistedParticipant<'a>>,
1097 positive_z: &mut Vec<HoistedParticipant<'a>>,
1098 scrollbars: &[ScrollbarOverlay],
1099 depth: usize,
1100 ) {
1101 if depth >= Self::MAX_COMPOSITOR_DEPTH {
1102 return;
1103 }
1104 let has_line_boxes = !parent.line_boxes.is_empty();
1105 let parent_display = parent.style.display;
1106
1107 for child in &parent.children {
1108 if child.is_top_layer
1109 || child.style.display == Display::None
1110 || child.style.content_visibility == strata_style::types::ContentVisibility::Hidden
1111 {
1112 continue;
1113 }
1114 if has_line_boxes
1115 && (child.text.is_some()
1116 || (matches!(child.style.display, Display::Inline)
1117 && !Self::inline_has_paintable_non_text_content(child)))
1118 {
1119 continue;
1120 }
1121
1122 if child.establishes_stacking_context_in(Some(parent_display), false) {
1123 let z = child.style.z_index.unwrap_or(0);
1124 let entry = HoistedParticipant {
1125 node: child,
1126 kind: HoistedKind::StackingContext,
1127 steps: current_steps.clone(),
1128 };
1129 if z < 0 {
1130 negative_z.push(entry);
1131 } else if z > 0 {
1132 positive_z.push(entry);
1133 } else {
1134 auto_or_zero_z.push(entry);
1135 }
1136 } else {
1137 if child.style.position != Position::Static {
1138 auto_or_zero_z.push(HoistedParticipant {
1139 node: child,
1140 kind: HoistedKind::PositionedNode,
1141 steps: current_steps.clone(),
1142 });
1143 }
1144 if !child.children.is_empty() {
1145 let step = Self::node_clip_scroll_step(child);
1146 let pushed = step.is_some();
1147 if let Some(s) = step {
1148 current_steps.push(s);
1149 }
1150 Self::collect_hoisted_participants(
1151 child,
1152 current_steps,
1153 negative_z,
1154 auto_or_zero_z,
1155 positive_z,
1156 scrollbars,
1157 depth + 1,
1158 );
1159 if pushed {
1160 current_steps.pop();
1161 }
1162 }
1163 if Self::has_scrollbar(child, scrollbars) {
1164 auto_or_zero_z.push(HoistedParticipant {
1165 node: child,
1166 kind: HoistedKind::Scrollbar,
1167 steps: current_steps.clone(),
1168 });
1169 }
1170 }
1171 }
1172 }
1173
1174 #[allow(clippy::too_many_arguments)]
1175 fn paint_stacking_context_inner(
1176 node: &LayoutNode,
1177 list: &mut DisplayList,
1178 cull: Option<Rect>,
1179 root_cull: Option<Rect>,
1180 inherited_steps: &[ClipScrollStep],
1181 is_root: bool,
1182 scrollbars: &[ScrollbarOverlay],
1183 depth: usize,
1184 ) {
1185 if depth >= Self::MAX_COMPOSITOR_DEPTH {
1186 return;
1187 }
1188 if node.style.display == Display::None {
1189 return;
1190 }
1191 if node.style.content_visibility == strata_style::types::ContentVisibility::Hidden {
1192 return;
1193 }
1194
1195 let node_eff_steps = Self::effective_steps(node.style.position, inherited_steps);
1196 let base_cull = if node.style.position == Position::Fixed
1197 && !inherited_steps.iter().any(|s| s.is_fixed_cb)
1198 {
1199 root_cull
1200 } else {
1201 Self::cull_with_steps(cull, node_eff_steps)
1202 };
1203
1204 if let Some(c) = base_cull {
1205 if (c.width < 0.0 || c.height < 0.0) && !Self::subtree_has_fixed_escape(node, depth) {
1206 return;
1207 }
1208 }
1209
1210 let bounds = node.geometry.border_box;
1211 let border_radius = node.style.border_radius;
1212 let has_any_radius = border_radius.top_left > 0.0
1213 || border_radius.top_right > 0.0
1214 || border_radius.bottom_left > 0.0
1215 || border_radius.bottom_right > 0.0;
1216 let clips_overflow = node.style.overflow_x != Overflow::Visible
1217 || node.style.overflow_y != Overflow::Visible
1218 || node.transition_layout_width_px.is_some()
1219 || node.transition_layout_height_px.is_some();
1220 let should_clip =
1221 clips_overflow || (has_any_radius && (node.image.is_some() || node.scene_3d.is_some()));
1222
1223 let mut static_cull_empty = base_cull.is_some_and(|c| c.width < 0.0 || c.height < 0.0);
1224
1225 let child_cull = if clips_overflow
1226 && bounds.width > 0.0
1227 && bounds.height > 0.0
1228 && node.style.position != Position::Fixed
1229 {
1230 match base_cull {
1231 Some(c) => {
1232 if c.width < 0.0 || c.height < 0.0 {
1233 Some(c)
1234 } else {
1235 match bounds.intersect(c) {
1236 Some(ic) => Some(ic),
1237 None => {
1238 if !Self::subtree_has_fixed_escape(node, depth) {
1239 return;
1240 }
1241 static_cull_empty = true;
1242 Some(Rect::new(0.0, 0.0, -1.0, -1.0))
1243 }
1244 }
1245 }
1246 }
1247 None => None,
1248 }
1249 } else {
1250 base_cull
1251 };
1252
1253 let is_visible = !static_cull_empty
1254 && match base_cull {
1255 Some(c) => {
1256 if node.style.position == Position::Fixed {
1257 true
1258 } else if bounds.width > 0.0 && bounds.height > 0.0 {
1259 bounds.intersect(c).is_some()
1260 } else {
1261 true
1262 }
1263 }
1264 None => true,
1265 };
1266
1267 let has_isolation = node.style.isolation == Isolation::Isolate;
1268 let has_blend_mode = node.style.mix_blend_mode != BlendMode::Normal;
1269 let has_filter_cfg = node.style.filter.as_ref().is_some_and(|f| !f.is_empty());
1270 let has_clip_path_cfg = node
1271 .style
1272 .clip_path
1273 .as_ref()
1274 .is_some_and(|cp| !cp.is_none());
1275 let transform_matrix = if node.style.has_transform() {
1276 Some(
1277 node.style
1278 .compute_transform_matrix(bounds.width, bounds.height),
1279 )
1280 } else {
1281 None
1282 };
1283 let has_opacity = node.style.opacity < 0.999;
1284 let has_backdrop_cfg = node
1285 .style
1286 .backdrop_filter
1287 .as_ref()
1288 .is_some_and(|bf| !bf.is_empty());
1289
1290 let has_group_effect = has_isolation
1291 || has_blend_mode
1292 || has_filter_cfg
1293 || has_clip_path_cfg
1294 || transform_matrix.is_some()
1295 || has_opacity
1296 || has_backdrop_cfg;
1297
1298 let wrap_inherited_outside_group = has_group_effect
1299 && (node.style.establishes_fixed_containing_block()
1300 || !Self::subtree_has_fixed_escape(node, depth));
1301
1302 if wrap_inherited_outside_group {
1303 Self::push_clip_scroll_steps(node_eff_steps, list);
1304 }
1305
1306 if has_isolation {
1307 list.push(DrawCommand::PushIsolation { isolate: true });
1308 }
1309 if has_blend_mode {
1310 list.push(DrawCommand::PushBlendMode {
1311 mode: node.style.mix_blend_mode,
1312 });
1313 }
1314 let has_filter = if let Some(ref f) = node.style.filter {
1315 if !f.is_empty() {
1316 list.push(DrawCommand::PushFilter {
1317 bounds,
1318 filter: f.clone(),
1319 });
1320 true
1321 } else {
1322 false
1323 }
1324 } else {
1325 false
1326 };
1327 let has_clip_path = if let Some(ref cp) = node.style.clip_path {
1328 if !cp.is_none() {
1329 list.push(DrawCommand::PushClipPath {
1330 bounds,
1331 clip_path: cp.clone(),
1332 });
1333 true
1334 } else {
1335 false
1336 }
1337 } else {
1338 false
1339 };
1340 if let Some(mat) = transform_matrix {
1341 list.push(DrawCommand::PushTransform { matrix: mat });
1342 }
1343 if has_opacity {
1344 list.push(DrawCommand::PushOpacity {
1345 alpha: node.style.opacity,
1346 });
1347 }
1348 let has_backdrop_filter = if let Some(ref bf) = node.style.backdrop_filter {
1349 if !bf.is_empty() {
1350 list.push(DrawCommand::PushBackdropFilter {
1351 bounds,
1352 radius: border_radius,
1353 filter: bf.clone(),
1354 });
1355 true
1356 } else {
1357 false
1358 }
1359 } else {
1360 false
1361 };
1362
1363 let mut hoisted_base_steps: Vec<ClipScrollStep> = if wrap_inherited_outside_group {
1365 Vec::new()
1366 } else {
1367 node_eff_steps.to_vec()
1368 };
1369 let own_clip_bounds = if clips_overflow
1370 && node.geometry.padding_box.width > 0.0
1371 && node.geometry.padding_box.height > 0.0
1372 {
1373 node.geometry.padding_box
1374 } else {
1375 bounds
1376 };
1377 let own_is_fixed_cb = node.style.establishes_fixed_containing_block();
1378 let own_is_abs_cb = node.style.position != Position::Static || own_is_fixed_cb || is_root;
1379 let has_scroll_offset =
1380 node.geometry.scroll_offset.x != 0.0 || node.geometry.scroll_offset.y != 0.0;
1381 let own_clip_opt = if should_clip {
1382 Some((own_clip_bounds, border_radius))
1383 } else {
1384 None
1385 };
1386 if own_clip_opt.is_some() || has_scroll_offset || own_is_abs_cb || own_is_fixed_cb {
1387 hoisted_base_steps.push(ClipScrollStep {
1388 clip: own_clip_opt,
1389 scroll_offset: (node.geometry.scroll_offset.x, node.geometry.scroll_offset.y),
1390 is_abs_cb: own_is_abs_cb,
1391 is_fixed_cb: own_is_fixed_cb,
1392 });
1393 }
1394
1395 let mut negative_z: Vec<HoistedParticipant<'_>> = Vec::new();
1397 let mut auto_or_zero_z: Vec<HoistedParticipant<'_>> = Vec::new();
1398 let mut positive_z: Vec<HoistedParticipant<'_>> = Vec::new();
1399 Self::collect_hoisted_participants(
1400 node,
1401 &mut hoisted_base_steps,
1402 &mut negative_z,
1403 &mut auto_or_zero_z,
1404 &mut positive_z,
1405 scrollbars,
1406 depth + 1,
1407 );
1408
1409 negative_z.sort_by_key(|p| p.node.style.z_index.unwrap_or(0));
1411 positive_z.sort_by_key(|p| p.node.style.z_index.unwrap_or(0));
1412
1413 let mut in_flow_blocks: Vec<&LayoutNode> = Vec::new();
1415 let mut floats: Vec<&LayoutNode> = Vec::new();
1416 let mut in_flow_inlines: Vec<&LayoutNode> = Vec::new();
1417
1418 if !static_cull_empty {
1419 let has_line_boxes = !node.line_boxes.is_empty();
1420 let parent_display = node.style.display;
1421 for child in &node.children {
1422 if child.is_top_layer
1423 || child.style.display == Display::None
1424 || child.style.content_visibility
1425 == strata_style::types::ContentVisibility::Hidden
1426 {
1427 continue;
1428 }
1429 if has_line_boxes
1430 && (child.text.is_some()
1431 || (matches!(child.style.display, Display::Inline)
1432 && !Self::inline_has_paintable_non_text_content(child)))
1433 {
1434 continue;
1435 }
1436 if child.establishes_stacking_context_in(Some(parent_display), false)
1437 || child.style.position != Position::Static
1438 {
1439 continue;
1440 }
1441 if let Some(c) = child_cull {
1442 if child.geometry.border_box.y > c.y + c.height {
1443 continue;
1444 }
1445 if child.geometry.border_box.height > 0.0
1446 && child.geometry.border_box.y + child.geometry.border_box.height < c.y
1447 {
1448 continue;
1449 }
1450 }
1451 if child.style.float != strata_style::types::Float::None {
1452 floats.push(child);
1453 } else {
1454 match child.style.display {
1455 Display::Inline
1456 | Display::InlineBlock
1457 | Display::InlineFlex
1458 | Display::InlineGrid => {
1459 in_flow_inlines.push(child);
1460 }
1461 _ => {
1462 in_flow_blocks.push(child);
1463 }
1464 }
1465 }
1466 }
1467 }
1468
1469 let inner_inherited_steps: &[ClipScrollStep] = if wrap_inherited_outside_group {
1470 &[]
1471 } else {
1472 node_eff_steps
1473 };
1474
1475 if !inner_inherited_steps.is_empty() {
1477 Self::push_clip_scroll_steps(inner_inherited_steps, list);
1478 }
1479 if is_visible {
1480 Self::paint_node_box_decorations(node, list);
1481 }
1482 if !negative_z.is_empty() && !inner_inherited_steps.is_empty() {
1483 Self::pop_clip_scroll_steps(inner_inherited_steps, list);
1484 }
1485
1486 let child_root_cull = if own_is_fixed_cb {
1488 child_cull
1489 } else {
1490 root_cull
1491 };
1492 for entry in &negative_z {
1493 Self::paint_stacking_context_inner(
1494 entry.node,
1495 list,
1496 root_cull,
1497 child_root_cull,
1498 &entry.steps,
1499 false,
1500 scrollbars,
1501 depth + 1,
1502 );
1503 }
1504
1505 if !negative_z.is_empty() && !inner_inherited_steps.is_empty() {
1506 Self::push_clip_scroll_steps(inner_inherited_steps, list);
1507 }
1508
1509 if should_clip && is_visible {
1511 list.push(DrawCommand::PushClip {
1512 bounds: own_clip_bounds,
1513 radius: border_radius,
1514 });
1515 }
1516 if is_visible {
1517 Self::paint_node_foreground_content(node, list, base_cull);
1518 }
1519
1520 if has_scroll_offset && !static_cull_empty {
1521 let mat = strata_primitives::geom::Matrix4x4::translation(
1522 -node.geometry.scroll_offset.x,
1523 -node.geometry.scroll_offset.y,
1524 0.0,
1525 );
1526 list.push(DrawCommand::PushTransform { matrix: mat });
1527 }
1528
1529 for child in in_flow_blocks {
1531 Self::paint_node_content_inner(child, list, child_cull, true, scrollbars, depth + 1);
1532 }
1533
1534 for child in floats {
1536 Self::paint_node_content_inner(child, list, child_cull, true, scrollbars, depth + 1);
1537 }
1538
1539 for child in in_flow_inlines {
1541 Self::paint_node_content_inner(child, list, child_cull, true, scrollbars, depth + 1);
1542 }
1543
1544 if !static_cull_empty {
1546 Self::paint_collapsed_table_grid(node, list);
1547 }
1548
1549 if has_scroll_offset && !static_cull_empty {
1550 list.push(DrawCommand::PopTransform);
1551 }
1552 if should_clip && is_visible {
1553 list.push(DrawCommand::PopClip);
1554 }
1555 if !inner_inherited_steps.is_empty() {
1556 Self::pop_clip_scroll_steps(inner_inherited_steps, list);
1557 }
1558
1559 for entry in &auto_or_zero_z {
1562 match entry.kind {
1563 HoistedKind::StackingContext => {
1564 Self::paint_stacking_context_inner(
1565 entry.node,
1566 list,
1567 root_cull,
1568 child_root_cull,
1569 &entry.steps,
1570 false,
1571 scrollbars,
1572 depth + 1,
1573 );
1574 }
1575 HoistedKind::PositionedNode => {
1576 let eff = Self::effective_steps(entry.node.style.position, &entry.steps);
1577 let entry_cull = Self::cull_with_steps(child_root_cull, eff);
1578 if entry_cull.is_none_or(|c| c.width >= 0.0 && c.height >= 0.0) {
1579 Self::push_clip_scroll_steps(eff, list);
1580 Self::paint_node_content_inner(
1581 entry.node,
1582 list,
1583 entry_cull,
1584 true,
1585 scrollbars,
1586 depth + 1,
1587 );
1588 Self::pop_clip_scroll_steps(eff, list);
1589 }
1590 }
1591 HoistedKind::Scrollbar => {
1592 let eff = Self::effective_steps(entry.node.style.position, &entry.steps);
1593 let entry_cull = Self::cull_with_steps(child_root_cull, eff);
1594 if entry_cull.is_none_or(|c| c.width >= 0.0 && c.height >= 0.0) {
1595 Self::push_clip_scroll_steps(eff, list);
1596 Self::emit_node_scrollbar(entry.node, list, scrollbars);
1597 Self::pop_clip_scroll_steps(eff, list);
1598 }
1599 }
1600 }
1601 }
1602
1603 if is_visible && Self::has_scrollbar(node, scrollbars) {
1607 if !inner_inherited_steps.is_empty() {
1608 Self::push_clip_scroll_steps(inner_inherited_steps, list);
1609 }
1610 Self::emit_node_scrollbar(node, list, scrollbars);
1611 if !inner_inherited_steps.is_empty() {
1612 Self::pop_clip_scroll_steps(inner_inherited_steps, list);
1613 }
1614 }
1615
1616 for entry in &positive_z {
1618 Self::paint_stacking_context_inner(
1619 entry.node,
1620 list,
1621 root_cull,
1622 child_root_cull,
1623 &entry.steps,
1624 false,
1625 scrollbars,
1626 depth + 1,
1627 );
1628 }
1629
1630 if has_backdrop_filter {
1631 list.push(DrawCommand::PopBackdropFilter);
1632 }
1633 if transform_matrix.is_some() {
1634 list.push(DrawCommand::PopTransform);
1635 }
1636 if has_clip_path {
1637 list.push(DrawCommand::PopClipPath);
1638 }
1639 if has_filter {
1640 list.push(DrawCommand::PopFilter);
1641 }
1642 if has_blend_mode {
1643 list.push(DrawCommand::PopBlendMode);
1644 }
1645 if has_isolation {
1646 list.push(DrawCommand::PopIsolation);
1647 }
1648 if has_opacity {
1649 list.push(DrawCommand::PopOpacity);
1650 }
1651 if wrap_inherited_outside_group {
1652 Self::pop_clip_scroll_steps(node_eff_steps, list);
1653 }
1654 }
1655
1656 fn paint_node_box_decorations(node: &LayoutNode, list: &mut DisplayList) {
1657 let bounds = node.geometry.border_box;
1658 let border_radius = node.style.border_radius;
1659 let has_any_radius = border_radius.top_left > 0.0
1660 || border_radius.top_right > 0.0
1661 || border_radius.bottom_left > 0.0
1662 || border_radius.bottom_right > 0.0;
1663 let has_any_border_width = node.style.border_width.top > 0.0
1664 || node.style.border_width.right > 0.0
1665 || node.style.border_width.bottom > 0.0
1666 || node.style.border_width.left > 0.0;
1667 let draw_border_separately = node.style.border_style != BorderStyle::None
1668 && node.style.border_style != BorderStyle::Hidden
1669 && has_any_border_width
1670 && node.style.border_color.is_some()
1671 && !(node.style.display == Display::TableCell
1672 && node.style.border_collapse == BorderCollapse::Collapse);
1673 let rounded_border_color = if draw_border_separately
1674 || node.style.border_style == BorderStyle::None
1675 || node.style.border_style == BorderStyle::Hidden
1676 {
1677 None
1678 } else {
1679 node.style.border_color
1680 };
1681
1682 for shadow in &node.style.box_shadow {
1684 if !shadow.inset {
1685 list.push(DrawCommand::DrawShadow {
1686 bounds,
1687 shadow: shadow.clone(),
1688 border_radius,
1689 });
1690 }
1691 }
1692
1693 if let Some(bg_color) = node.style.background_color {
1695 if has_any_radius {
1696 list.push(DrawCommand::DrawRoundedRect {
1697 bounds,
1698 color: bg_color,
1699 border_radius,
1700 border_width: node.style.border_width,
1701 border_color: rounded_border_color,
1702 });
1703 } else if bg_color.a > 0 {
1704 list.push(DrawCommand::DrawRect {
1705 bounds,
1706 color: bg_color,
1707 });
1708 }
1709 }
1710
1711 if let Some(ref grad) = node.style.background_gradient {
1713 match grad {
1714 strata_style::types::Gradient::Linear { angle_deg, stops } => {
1715 list.push(DrawCommand::DrawLinearGradient {
1716 bounds,
1717 angle_deg: *angle_deg,
1718 stops: stops.clone(),
1719 border_radius,
1720 });
1721 }
1722 strata_style::types::Gradient::Radial { center, stops } => {
1723 list.push(DrawCommand::DrawRadialGradient {
1724 bounds,
1725 center: *center,
1726 stops: stops.clone(),
1727 border_radius,
1728 });
1729 }
1730 strata_style::types::Gradient::Conic {
1731 angle_deg,
1732 center: _,
1733 stops,
1734 } => {
1735 list.push(DrawCommand::DrawLinearGradient {
1736 bounds,
1737 angle_deg: *angle_deg,
1738 stops: stops.clone(),
1739 border_radius,
1740 });
1741 }
1742 }
1743 }
1744
1745 for shadow in &node.style.box_shadow {
1747 if shadow.inset {
1748 list.push(DrawCommand::DrawInsetShadow {
1749 bounds,
1750 shadow: shadow.clone(),
1751 border_radius,
1752 });
1753 }
1754 }
1755
1756 if draw_border_separately {
1759 if let Some(border_color) = node.style.border_color {
1760 list.push(DrawCommand::DrawBorder {
1761 bounds,
1762 widths: node.style.border_width,
1763 color: border_color,
1764 border_radius,
1765 style: node.style.border_style,
1766 });
1767 }
1768 }
1769
1770 if node.style.outline_width > 0.0 && node.style.outline_style != BorderStyle::None {
1772 if let Some(outline_color) = node.style.outline_color {
1773 let offset = node.style.outline_offset;
1774 let outline_radius = BorderRadius {
1775 top_left: (border_radius.top_left + offset).max(0.0),
1776 top_right: (border_radius.top_right + offset).max(0.0),
1777 bottom_left: (border_radius.bottom_left + offset).max(0.0),
1778 bottom_right: (border_radius.bottom_right + offset).max(0.0),
1779 };
1780 list.push(DrawCommand::DrawBorder {
1781 bounds: Rect::new(
1782 bounds.x - offset,
1783 bounds.y - offset,
1784 bounds.width + offset * 2.0,
1785 bounds.height + offset * 2.0,
1786 ),
1787 widths: EdgeInsets::all(node.style.outline_width),
1788 color: outline_color,
1789 border_radius: outline_radius,
1790 style: node.style.outline_style,
1791 });
1792 }
1793 }
1794 }
1795
1796 fn paint_node_foreground_content(
1797 node: &LayoutNode,
1798 list: &mut DisplayList,
1799 cull: Option<Rect>,
1800 ) {
1801 let bounds = node.geometry.border_box;
1802
1803 if let Some(ref handle) = node.scene_3d {
1805 let vp_bounds = if node.geometry.content_box.width > 0.0
1806 && node.geometry.content_box.height > 0.0
1807 {
1808 node.geometry.content_box
1809 } else {
1810 bounds
1811 };
1812 if vp_bounds.width > 0.0 && vp_bounds.height > 0.0 {
1813 if let Ok(scene) =
1816 std::sync::Arc::clone(&handle.0).downcast::<crate::scene3d::Scene3D>()
1817 {
1818 list.push(DrawCommand::DrawViewport3D {
1819 bounds: vp_bounds,
1820 scene,
1821 });
1822 } else if let Some(scene_arc) = handle
1823 .0
1824 .downcast_ref::<std::sync::Arc<crate::scene3d::Scene3D>>()
1825 {
1826 list.push(DrawCommand::DrawViewport3D {
1827 bounds: vp_bounds,
1828 scene: std::sync::Arc::clone(scene_arc),
1829 });
1830 } else if let Some(cmds) = handle
1831 .0
1832 .downcast_ref::<Vec<crate::canvas2d::CanvasCommand>>()
1833 {
1834 list.push(DrawCommand::DrawCanvas2D {
1835 bounds: vp_bounds,
1836 commands: cmds.clone(),
1837 });
1838 } else if let Some(cmds_arc) = handle
1839 .0
1840 .downcast_ref::<std::sync::Arc<Vec<crate::canvas2d::CanvasCommand>>>()
1841 {
1842 list.push(DrawCommand::DrawCanvas2D {
1843 bounds: vp_bounds,
1844 commands: (**cmds_arc).clone(),
1845 });
1846 } else if let Some(paint_cb) = handle
1847 .0
1848 .downcast_ref::<crate::canvas2d::Canvas2DPaintCallback>()
1849 {
1850 let commands = paint_cb.paint(vp_bounds.width, vp_bounds.height);
1851 list.push(DrawCommand::DrawCanvas2D {
1852 bounds: vp_bounds,
1853 commands,
1854 });
1855 }
1856 }
1857 }
1858
1859 if let Some(ref image) = node.image {
1861 let image_bounds = if node.geometry.content_box.width > 0.0
1862 && node.geometry.content_box.height > 0.0
1863 {
1864 node.geometry.content_box
1865 } else {
1866 bounds
1867 };
1868 list.push(DrawCommand::DrawImage {
1869 bounds: image_bounds,
1870 image: image.clone(),
1871 });
1872 }
1873
1874 if !node.line_boxes.is_empty() {
1876 let mut fragments = Vec::new();
1877 for line in &node.line_boxes {
1878 if let Some(c) = cull {
1879 if line.bounds.height > 0.0
1880 && (line.bounds.y > c.y + c.height
1881 || line.bounds.y + line.bounds.height < c.y)
1882 {
1883 continue;
1884 }
1885 }
1886 fragments.extend(line.text_fragments.clone());
1887 }
1888 if !fragments.is_empty() {
1889 list.push(DrawCommand::DrawTextFragments { fragments });
1890 }
1891 } else if let Some(ref text) = node.text {
1892 let font_size = node.style.font_size;
1893 let line_height = node.style.line_height;
1894 let font_weight = node.style.font_weight;
1895 let color = node.style.color;
1896 let is_nowrap = matches!(
1897 node.style.white_space,
1898 strata_style::types::WhiteSpace::NoWrap | strata_style::types::WhiteSpace::Pre
1899 );
1900 let is_monospace = strata_layout::is_monospace_family(node.style.font_family);
1901 let text_align = node.style.text_align;
1902 let effective_text_w = node
1903 .transition_content_width()
1904 .map_or(node.geometry.content_box.width, |tw| {
1905 node.geometry.content_box.width.max(tw)
1906 });
1907 let bounds_width = if effective_text_w > 0.0 && !is_nowrap {
1908 Some(effective_text_w)
1909 } else {
1910 None
1911 };
1912 let scroll_x = node.geometry.scroll_offset.x;
1913 let scroll_y = node.geometry.scroll_offset.y;
1914 let is_top_aligned = matches!(
1915 node.style.white_space,
1916 strata_style::types::WhiteSpace::PreWrap
1917 | strata_style::types::WhiteSpace::PreLine
1918 | strata_style::types::WhiteSpace::Pre
1919 ) || scroll_y != 0.0
1920 || text.contains('\n');
1921 let bounds_height = if !is_top_aligned && node.geometry.content_box.height > 0.0 {
1922 Some(node.geometry.content_box.height)
1923 } else {
1924 None
1925 };
1926 let align_offset = if is_nowrap
1927 && node.geometry.content_box.width > 0.0
1928 && scroll_x == 0.0
1929 && !matches!(
1930 text_align,
1931 strata_style::types::TextAlign::Left | strata_style::types::TextAlign::Justify
1932 ) {
1933 let (tw, _) = strata_layout::text::measure_text_bounds_styled_with_family(
1934 text,
1935 font_size,
1936 line_height,
1937 None,
1938 is_monospace,
1939 node.style.font_family,
1940 font_weight,
1941 node.style.font_style,
1942 );
1943 match text_align {
1944 strata_style::types::TextAlign::Center => {
1945 ((node.geometry.content_box.width - tw) / 2.0).max(0.0)
1946 }
1947 strata_style::types::TextAlign::Right => {
1948 (node.geometry.content_box.width - tw).max(0.0)
1949 }
1950 _ => 0.0,
1951 }
1952 } else {
1953 0.0
1954 };
1955
1956 let clip_rect = if node.style.overflow_x != Overflow::Visible
1957 || node.style.overflow_y != Overflow::Visible
1958 || scroll_x != 0.0
1959 || scroll_y != 0.0
1960 {
1961 let c = if node.geometry.content_box.width > 0.0
1962 && node.geometry.content_box.height > 0.0
1963 {
1964 node.geometry.content_box
1965 } else {
1966 bounds
1967 };
1968 if c.width > 0.0 && c.height > 0.0 {
1969 Some(c)
1970 } else {
1971 None
1972 }
1973 } else {
1974 None
1975 };
1976
1977 if let Some(cr) = clip_rect {
1978 list.push(DrawCommand::PushClip {
1979 bounds: cr,
1980 radius: BorderRadius::all(0.0),
1981 });
1982 }
1983 list.push(DrawCommand::DrawText {
1984 origin: (
1985 node.geometry.content_box.x + align_offset - scroll_x,
1986 node.geometry.content_box.y - scroll_y,
1987 ),
1988 bounds_width,
1989 bounds_height,
1990 text_align,
1991 text: text.clone(),
1992 font_size,
1993 line_height,
1994 font_weight,
1995 color,
1996 is_monospace,
1997 font_family: node.style.font_family,
1998 });
1999 if clip_rect.is_some() {
2000 list.push(DrawCommand::PopClip);
2001 }
2002 }
2003
2004 if !node.svg_items.is_empty() {
2006 for item in &node.svg_items {
2007 let fill = if item.fill_is_current_color {
2008 Some(node.style.color)
2009 } else {
2010 item.fill_color
2011 };
2012 let stroke = if item.stroke_is_current_color {
2013 Some(node.style.color)
2014 } else {
2015 item.stroke_color.or_else(|| {
2016 if fill.is_none() {
2017 Some(node.style.color)
2018 } else {
2019 None
2020 }
2021 })
2022 };
2023 if let Some(ref svg_text) = item.text {
2024 if !svg_text.content.is_empty() {
2025 let scale_x = if item.view_box.0 > 0.0 {
2026 bounds.width / item.view_box.0
2027 } else {
2028 1.0
2029 };
2030 let scale_y = if item.view_box.1 > 0.0 {
2031 bounds.height / item.view_box.1
2032 } else {
2033 1.0
2034 };
2035 let avg_scale = ((scale_x + scale_y) * 0.5).max(0.01);
2036 let font_size = (svg_text.font_size * avg_scale).max(1.0);
2037 let text_color = fill.or(stroke).unwrap_or(node.style.color);
2038 let est_w = svg_text.content.chars().count() as f32 * font_size * 0.56;
2039 let anchor_dx = match svg_text.text_anchor {
2040 strata_style::TextAlign::Center => -est_w * 0.5,
2041 strata_style::TextAlign::Right => -est_w,
2042 _ => 0.0,
2043 };
2044 let px = bounds.x + svg_text.x * scale_x + anchor_dx;
2045 let py = bounds.y + svg_text.y * scale_y - font_size * 0.80;
2046 list.push(DrawCommand::DrawText {
2047 origin: (px, py),
2048 bounds_width: None,
2049 bounds_height: None,
2050 text_align: strata_style::TextAlign::Left,
2051 text: svg_text.content.clone(),
2052 font_size,
2053 line_height: font_size * 1.2,
2054 font_weight: svg_text.font_weight,
2055 color: text_color,
2056 is_monospace: strata_layout::is_monospace_family(
2057 node.style.font_family,
2058 ),
2059 font_family: node.style.font_family,
2060 });
2061 }
2062 }
2063 if !item.path_data.is_empty() {
2064 list.push(DrawCommand::DrawSvgPath {
2065 bounds,
2066 path_data: item.path_data.clone(),
2067 stroke_color: stroke,
2068 fill_color: fill,
2069 stroke_width: item.stroke_width,
2070 stroke_linecap: item.stroke_linecap,
2071 stroke_linejoin: item.stroke_linejoin,
2072 stroke_dasharray: item.stroke_dasharray.clone(),
2073 fill_rule: item.fill_rule,
2074 view_box: item.view_box,
2075 });
2076 }
2077 }
2078 } else if let Some(ref path_data) = node.svg_path {
2079 list.push(DrawCommand::DrawSvgPath {
2080 bounds,
2081 path_data: path_data.clone(),
2082 stroke_color: Some(node.style.color),
2083 fill_color: None,
2084 stroke_width: 2.0,
2085 stroke_linecap: strata_layout::StrokeLineCap::Round,
2086 stroke_linejoin: strata_layout::StrokeLineJoin::Round,
2087 stroke_dasharray: Vec::new(),
2088 fill_rule: strata_layout::FillRule::NonZero,
2089 view_box: (24.0, 24.0),
2090 });
2091 }
2092 }
2093
2094 pub fn paint_node_content(node: &LayoutNode, list: &mut DisplayList) {
2096 Self::paint_node_content_culled(node, list, None);
2097 }
2098
2099 pub fn paint_node_content_culled(
2101 node: &LayoutNode,
2102 list: &mut DisplayList,
2103 cull: Option<Rect>,
2104 ) {
2105 Self::paint_node_content_guarded(node, list, cull, 0);
2106 }
2107
2108 pub fn paint_node_content_guarded(
2110 node: &LayoutNode,
2111 list: &mut DisplayList,
2112 cull: Option<Rect>,
2113 depth: usize,
2114 ) {
2115 Self::paint_node_content_inner(node, list, cull, false, &[], depth);
2116 }
2117
2118 fn paint_node_content_inner(
2119 node: &LayoutNode,
2120 list: &mut DisplayList,
2121 cull: Option<Rect>,
2122 skip_hoisted: bool,
2123 scrollbars: &[ScrollbarOverlay],
2124 depth: usize,
2125 ) {
2126 if depth >= Self::MAX_COMPOSITOR_DEPTH {
2127 return;
2128 }
2129 if node.style.display == Display::None {
2130 return;
2131 }
2132 if node.style.content_visibility == strata_style::types::ContentVisibility::Hidden {
2133 return;
2134 }
2135
2136 let bounds = node.geometry.border_box;
2137 let clips_overflow = node.style.overflow_x != Overflow::Visible
2138 || node.style.overflow_y != Overflow::Visible
2139 || node.transition_layout_width_px.is_some()
2140 || node.transition_layout_height_px.is_some();
2141 let border_radius = node.style.border_radius;
2142 let has_any_radius = border_radius.top_left > 0.0
2143 || border_radius.top_right > 0.0
2144 || border_radius.bottom_left > 0.0
2145 || border_radius.bottom_right > 0.0;
2146 let should_clip =
2147 clips_overflow || (has_any_radius && (node.image.is_some() || node.scene_3d.is_some()));
2148
2149 let child_cull = if clips_overflow
2150 && bounds.width > 0.0
2151 && bounds.height > 0.0
2152 && node.style.position != Position::Fixed
2153 {
2154 match cull {
2155 Some(c) => match bounds.intersect(c) {
2156 Some(ic) => Some(ic),
2157 None => return,
2158 },
2159 None => None,
2160 }
2161 } else {
2162 cull
2163 };
2164
2165 let is_visible = match cull {
2166 Some(c) => {
2167 if node.style.position == Position::Fixed {
2168 true
2169 } else if bounds.width > 0.0 && bounds.height > 0.0 {
2170 bounds.intersect(c).is_some()
2171 } else {
2172 true
2173 }
2174 }
2175 None => true,
2176 };
2177
2178 if is_visible {
2179 Self::paint_node_box_decorations(node, list);
2180
2181 if should_clip {
2182 let clip_bounds = if clips_overflow
2183 && node.geometry.padding_box.width > 0.0
2184 && node.geometry.padding_box.height > 0.0
2185 {
2186 node.geometry.padding_box
2187 } else {
2188 bounds
2189 };
2190 list.push(DrawCommand::PushClip {
2191 bounds: clip_bounds,
2192 radius: border_radius,
2193 });
2194 }
2195
2196 Self::paint_node_foreground_content(node, list, cull);
2197 }
2198
2199 let has_scroll_offset =
2200 node.geometry.scroll_offset.x != 0.0 || node.geometry.scroll_offset.y != 0.0;
2201 if has_scroll_offset {
2202 let mat = strata_primitives::geom::Matrix4x4::translation(
2203 -node.geometry.scroll_offset.x,
2204 -node.geometry.scroll_offset.y,
2205 0.0,
2206 );
2207 list.push(DrawCommand::PushTransform { matrix: mat });
2208 }
2209
2210 let has_line_boxes = !node.line_boxes.is_empty();
2211 let parent_display = node.style.display;
2212 for child in &node.children {
2213 if child.is_top_layer || child.style.display == Display::None {
2214 continue;
2215 }
2216 if has_line_boxes
2217 && (child.text.is_some()
2218 || (matches!(child.style.display, Display::Inline)
2219 && !Self::inline_has_paintable_non_text_content(child)))
2220 {
2221 continue;
2222 }
2223
2224 let child_is_sc = child.establishes_stacking_context_in(Some(parent_display), false);
2225 if skip_hoisted && (child_is_sc || child.style.position != Position::Static) {
2226 continue;
2227 }
2228
2229 if let Some(c) = child_cull {
2231 if child.style.position == Position::Static {
2232 if child.geometry.border_box.y > c.y + c.height {
2233 continue;
2234 }
2235 if child.geometry.border_box.height > 0.0
2236 && child.geometry.border_box.y + child.geometry.border_box.height < c.y
2237 {
2238 continue;
2239 }
2240 }
2241 }
2242
2243 if child_is_sc {
2244 Self::paint_stacking_context_guarded_with_scrollbars(
2245 child,
2246 list,
2247 child_cull,
2248 scrollbars,
2249 depth + 1,
2250 );
2251 } else {
2252 Self::paint_node_content_inner(
2253 child,
2254 list,
2255 child_cull,
2256 skip_hoisted,
2257 scrollbars,
2258 depth + 1,
2259 );
2260 }
2261 }
2262
2263 Self::paint_collapsed_table_grid(node, list);
2265
2266 if has_scroll_offset {
2267 list.push(DrawCommand::PopTransform);
2268 }
2269
2270 if should_clip && is_visible {
2271 list.push(DrawCommand::PopClip);
2272 }
2273
2274 if !skip_hoisted && is_visible {
2275 Self::emit_node_scrollbar(node, list, scrollbars);
2276 }
2277 }
2278}
2279
2280#[derive(Clone, Copy)]
2281struct ClipScrollStep {
2282 clip: Option<(Rect, BorderRadius)>,
2283 scroll_offset: (f32, f32),
2284 is_abs_cb: bool,
2285 is_fixed_cb: bool,
2286}
2287
2288#[derive(Clone, Copy, PartialEq, Eq)]
2289enum HoistedKind {
2290 StackingContext,
2291 PositionedNode,
2292 Scrollbar,
2293}
2294
2295struct HoistedParticipant<'a> {
2296 node: &'a LayoutNode,
2297 kind: HoistedKind,
2298 steps: Vec<ClipScrollStep>,
2299}