1use std::cell::{Cell, RefCell};
5use std::collections::HashMap;
6
7pub const EV_CLICK: u32 = 1;
9pub const EV_MOUSEDOWN: u32 = 2;
10pub const EV_MOUSEUP: u32 = 3;
11pub const EV_WHEEL: u32 = 4;
12pub const EV_KEYDOWN: u32 = 5;
13pub const EV_KEYUP: u32 = 6;
14pub const EV_FOCUS: u32 = 7;
15pub const EV_BLUR: u32 = 8;
16pub const EV_INPUT: u32 = 9;
17pub const EV_SCROLL: u32 = 10;
18pub const EV_COMPLETE: u32 = 11;
20pub const EV_LOOPCOMPLETE: u32 = 12;
21pub const EV_ENTERFRAME: u32 = 13;
22pub const EV_MOUSEMOVE: u32 = 14;
23pub const EV_MOUSEENTER: u32 = 15;
25pub const EV_MOUSELEAVE: u32 = 16;
26pub const EV_LOADSTART: u32 = 17;
27pub const EV_LOADEDMETADATA: u32 = 18;
28pub const EV_LOADEDDATA: u32 = 19;
29pub const EV_CANPLAY: u32 = 20;
30pub const EV_CANPLAYTHROUGH: u32 = 21;
31pub const EV_PLAY: u32 = 22;
32pub const EV_PLAYING: u32 = 23;
33pub const EV_PAUSE: u32 = 24;
34pub const EV_SEEKING: u32 = 25;
35pub const EV_SEEKED: u32 = 26;
36pub const EV_TIMEUPDATE: u32 = 27;
38pub const EV_DURATIONCHANGE: u32 = 28;
39pub const EV_RATECHANGE: u32 = 29;
40pub const EV_VOLUMECHANGE: u32 = 30;
41pub const EV_WAITING: u32 = 31;
42pub const EV_ENDED: u32 = 32;
43pub const EV_ERROR: u32 = 33;
45pub const EV_EMPTIED: u32 = 34;
46
47pub const EV_TRANSITIONEND: u32 = 35;
48pub const EV_ANIMATIONSTART: u32 = 36;
49pub const EV_ANIMATIONEND: u32 = 37;
50pub const EV_ANIMATIONCANCEL: u32 = 38;
51
52pub const EV_PASTE: u32 = 39;
53pub const EV_COPY: u32 = 40;
54pub const EV_CUT: u32 = 41;
55
56pub const EV_CONTEXTMENU: u32 = 42;
59pub const EV_LOAD: u32 = 43;
62pub const EV_POINTERCANCEL: u32 = 44;
64pub const EV_SELECTSTART: u32 = 45;
67pub const EV_SELECTIONCHANGE: u32 = 46;
68pub const EV_AUXCLICK: u32 = 47;
71pub const EV_BEFOREINPUT: u32 = 48;
73pub const EV_COMPOSITIONSTART: u32 = 49;
76pub const EV_COMPOSITIONUPDATE: u32 = 50;
77pub const EV_COMPOSITIONEND: u32 = 51;
78pub const EV_MESSAGE: u32 = 52;
81pub const EV_POINTERLOCKCHANGE: u32 = 53;
84pub const EV_POINTERLOCKERROR: u32 = 54;
85pub const EV_SURFACERESIZE: u32 = 55;
90pub const EV_SURFACEREADY: u32 = 56;
91pub const EV_SURFACELOST: u32 = 57;
92pub const EV_SURFACEDISPLAYCHANGE: u32 = 58;
93
94pub const EVENT_NAMES: &[(u32, &str)] = &[
96 (EV_CLICK, "click"),
97 (EV_MOUSEDOWN, "mousedown"),
98 (EV_MOUSEUP, "mouseup"),
99 (EV_WHEEL, "wheel"),
100 (EV_KEYDOWN, "keydown"),
101 (EV_KEYUP, "keyup"),
102 (EV_FOCUS, "focus"),
103 (EV_BLUR, "blur"),
104 (EV_INPUT, "input"),
105 (EV_SCROLL, "scroll"),
106 (EV_COMPLETE, "complete"),
107 (EV_LOOPCOMPLETE, "loopComplete"),
108 (EV_ENTERFRAME, "enterFrame"),
109 (EV_MOUSEMOVE, "mousemove"),
110 (EV_MOUSEENTER, "mouseenter"),
111 (EV_MOUSELEAVE, "mouseleave"),
112 (EV_LOADSTART, "loadstart"),
113 (EV_LOADEDMETADATA, "loadedmetadata"),
114 (EV_LOADEDDATA, "loadeddata"),
115 (EV_CANPLAY, "canplay"),
116 (EV_CANPLAYTHROUGH, "canplaythrough"),
117 (EV_PLAY, "play"),
118 (EV_PLAYING, "playing"),
119 (EV_PAUSE, "pause"),
120 (EV_SEEKING, "seeking"),
121 (EV_SEEKED, "seeked"),
122 (EV_TIMEUPDATE, "timeupdate"),
123 (EV_DURATIONCHANGE, "durationchange"),
124 (EV_RATECHANGE, "ratechange"),
125 (EV_VOLUMECHANGE, "volumechange"),
126 (EV_WAITING, "waiting"),
127 (EV_ENDED, "ended"),
128 (EV_ERROR, "error"),
129 (EV_EMPTIED, "emptied"),
130 (EV_TRANSITIONEND, "transitionend"),
131 (EV_ANIMATIONSTART, "animationstart"),
132 (EV_ANIMATIONEND, "animationend"),
133 (EV_ANIMATIONCANCEL, "animationcancel"),
134 (EV_PASTE, "paste"),
135 (EV_COPY, "copy"),
136 (EV_CUT, "cut"),
137 (EV_CONTEXTMENU, "contextmenu"),
138 (EV_LOAD, "load"),
139 (EV_POINTERCANCEL, "pointercancel"),
140 (EV_SELECTSTART, "selectstart"),
141 (EV_SELECTIONCHANGE, "selectionchange"),
142 (EV_AUXCLICK, "auxclick"),
143 (EV_BEFOREINPUT, "beforeinput"),
144 (EV_COMPOSITIONSTART, "compositionstart"),
145 (EV_COMPOSITIONUPDATE, "compositionupdate"),
146 (EV_COMPOSITIONEND, "compositionend"),
147 (EV_MESSAGE, "message"),
148 (EV_POINTERLOCKCHANGE, "pointerlockchange"),
149 (EV_POINTERLOCKERROR, "pointerlockerror"),
150 (EV_SURFACERESIZE, "surfaceresize"),
151 (EV_SURFACEREADY, "surfaceready"),
152 (EV_SURFACELOST, "surfacelost"),
153 (EV_SURFACEDISPLAYCHANGE, "surfacedisplaychange"),
154];
155
156#[derive(Debug, Clone, Copy, PartialEq, Eq)]
157pub enum Kind {
158 Element,
159 Text,
160 Anchor,
161}
162
163pub struct Node {
164 pub kind: Kind,
165 pub tag: u32,
166 pub parent: u32,
167 pub children: Vec<u32>,
168 pub text: String,
170 pub style: Vec<(u32, String)>,
172 pub classes: Vec<String>,
173 pub class_attr: String,
175 pub props: Vec<(u32, String, u32)>,
179 pub scopes: Vec<String>,
181 pub listeners: u64,
182 pub(crate) inline_dirty: bool,
183 pub style_present: bool,
185 pub style_raw: Option<String>,
187 pub(crate) sub_rev: u64,
190 pub(crate) mark_gen: u32,
193 pub(crate) desc_gen: u32,
194 pub(crate) sel_flags: Cell<u8>,
196 pub(crate) inline: Option<std::rc::Rc<sk_css::InlineStyle>>,
197 pub computed: Option<sk_css::ComputedStates>,
198}
199
200pub(crate) mod sel {
206 pub const PREV_EDGE: u8 = 1;
207 pub const PREV_WALK: u8 = 2;
208 pub const NEXT_EDGE: u8 = 4;
209 pub const NEXT_WALK: u8 = 8;
210 pub const SIBLINGS: u8 = PREV_EDGE | PREV_WALK | NEXT_EDGE | NEXT_WALK;
211 pub const EMPTY: u8 = 16;
212 pub const HAS_SELF: u8 = 32;
213 pub const HAS_DESC: u8 = 64;
214 pub const HAS: u8 = HAS_SELF | HAS_DESC;
215 pub const HAS_NEXT: u8 = 128;
216}
217
218thread_local! {
219 static CASCADE_SUBJECT: Cell<u32> = const { Cell::new(0) };
220 static HAS_DEPTH: Cell<u32> = const { Cell::new(0) };
223 static READ_ON_OTHERS: RefCell<ReadOnOthers> = RefCell::new(ReadOnOthers::default());
224 static READ_CACHE: [Cell<(usize, usize, u32)>; 128] = [const { Cell::new((0, 0, 0)) }; 128];
227}
228
229#[derive(Default)]
235struct ReadOnOthers {
236 names: [HashMap<Box<str>, Readers>; 4],
237}
238
239#[derive(Default)]
240struct Readers {
241 tags: Vec<u32>,
242 all: bool,
243}
244
245const MAX_READER_TAGS: usize = 8;
247
248#[derive(Clone, Copy)]
249enum NameKind {
250 Class = 0,
251 Attr = 1,
252 Scope = 2,
253 Position = 3,
256}
257
258const POSITION: &str = "position";
259
260#[derive(Debug, PartialEq)]
261enum Reach {
262 Own,
263 Tags(Vec<u32>),
265 Subtree,
266}
267
268fn note_name_read(asked: u32, subject: u32, subject_tag: u32, name: &str, kind: NameKind) {
269 if subject == 0 || subject == asked {
270 return;
271 }
272 let key = (
273 name.as_ptr() as usize,
274 name.len() * 4 + kind as usize,
275 subject_tag,
276 );
277 let slot = ((key.0 >> 3) ^ key.2 as usize) & 127;
278 if READ_CACHE.with(|c| c[slot].get()) == key {
279 return;
280 }
281 READ_ON_OTHERS.with(|r| {
282 let mut r = r.borrow_mut();
283 let map = &mut r.names[kind as usize];
284 let readers = match map.get_mut(name) {
285 Some(readers) => readers,
286 None => map.entry(name.into()).or_default(),
287 };
288 if !readers.all && !readers.tags.contains(&subject_tag) {
289 readers.tags.push(subject_tag);
290 if readers.tags.len() > MAX_READER_TAGS {
291 readers.all = true;
292 readers.tags = Vec::new();
293 }
294 }
295 });
296 READ_CACHE.with(|c| c[slot].set(key));
297}
298
299fn reach_of<'a>(names: impl IntoIterator<Item = (&'a str, NameKind)>) -> Reach {
300 READ_ON_OTHERS.with(|r| {
301 let r = r.borrow();
302 let mut tags: Vec<u32> = Vec::new();
303 for (name, kind) in names {
304 let Some(readers) = r.names[kind as usize].get(name) else {
305 continue;
306 };
307 if readers.all {
308 return Reach::Subtree;
309 }
310 for &t in &readers.tags {
311 if !tags.contains(&t) {
312 tags.push(t);
313 }
314 }
315 }
316 match tags.len() {
317 0 => Reach::Own,
318 n if n > MAX_READER_TAGS => Reach::Subtree,
319 _ => Reach::Tags(tags),
320 }
321 })
322}
323
324#[derive(Default, Debug, Clone)]
325pub struct TreeMem {
326 pub slots: usize,
327 pub nodes: usize,
328 pub elements: usize,
329 pub texts: usize,
330 pub anchors: usize,
331 pub computed: usize,
332 pub slot_bytes: usize,
333 pub owned_bytes: usize,
334 pub computed_bytes: usize,
335 pub refinements: usize,
336 pub refinement_bytes: usize,
337 pub vars_maps: usize,
338 pub var_entries: usize,
339 pub vars_bytes: usize,
340 pub inlines: usize,
341 pub inline_bytes: usize,
342 pub names: usize,
343 pub total_bytes: usize,
344}
345
346#[derive(Default)]
347pub struct Tree {
348 nodes: Vec<Option<Node>>,
349 free: Vec<u32>,
350 freed: Vec<u32>,
351 pub root: u32,
352 dirty: bool,
353 restyle_gen: u32,
354 detached_marks: Vec<u32>,
357 has_anchors: Cell<bool>,
358 self_marks: Vec<u32>,
359 sibling_combinators: bool,
360 prop_writes: u32,
363 dirty_all: bool,
364 inline_dirty_nodes: Vec<u32>,
365 style_flushed: bool,
366 inline_container_units: bool,
369 style_nodes: std::collections::BTreeSet<u32>,
372 group_anchors: std::collections::HashSet<u32>,
376 group_hover_deps: HashMap<u32, Vec<u32>>,
379 group_focus_deps: HashMap<u32, Vec<u32>>,
381 names: Vec<String>,
382 name_ids: HashMap<String, u32>,
383}
384
385thread_local! {
386 static TREE: RefCell<Tree> = RefCell::new(Tree::new());
387 static DISPATCHER: Cell<u64> = const { Cell::new(0) };
388}
389
390pub fn with_tree<R>(f: impl FnOnce(&mut Tree) -> R) -> R {
393 TREE.with(|t| f(&mut t.borrow_mut()))
394}
395
396pub fn read_tree<R>(f: impl FnOnce(&Tree) -> R) -> R {
397 TREE.with(|t| f(&t.borrow()))
398}
399
400fn warn_css(msg: &str) {
402 let msg = crate::log::one_line(msg);
404 let fresh = CSS_WARNED.with(|w| w.borrow_mut().insert(msg.clone()));
405 if fresh {
406 eprintln!("{msg}");
407 crate::log::record("css", msg);
408 }
409}
410
411pub(crate) fn set_dispatcher(f: u64) {
412 DISPATCHER.with(|d| d.set(f));
413}
414
415pub(crate) fn dispatcher() -> u64 {
416 DISPATCHER.with(|d| d.get())
417}
418
419impl Tree {
420 fn new() -> Self {
421 Tree {
422 nodes: vec![None],
423 names: vec![String::new()],
426 name_ids: HashMap::from([(String::new(), 0)]),
427 restyle_gen: 1,
428 ..Default::default()
429 }
430 }
431
432 pub fn intern(&mut self, name: &str) -> u32 {
433 if let Some(&id) = self.name_ids.get(name) {
434 return id;
435 }
436 let id = self.names.len() as u32;
437 self.names.push(name.to_string());
438 self.name_ids.insert(name.to_string(), id);
439 id
440 }
441
442 pub fn name(&self, id: u32) -> &str {
443 self.names
444 .get(id as usize)
445 .map(String::as_str)
446 .unwrap_or("")
447 }
448
449 pub fn is_group_anchor(&self, id: u32) -> bool {
450 self.group_anchors.contains(&id)
451 }
452
453 pub(crate) fn touch_hover_styled(&mut self, id: u32) -> bool {
456 let own = self
457 .node(id)
458 .and_then(|n| n.computed.as_ref())
459 .is_some_and(|cs| cs.hover.is_some() || cs.control_state(1));
460 if own {
461 self.touch(id);
462 }
463 let deps = self.group_hover_deps.get(&id).cloned().unwrap_or_default();
464 for &dep in &deps {
465 self.touch(dep);
466 }
467 own || !deps.is_empty()
468 }
469
470 pub(crate) fn touch_focus_watchers(&mut self, old: u32, new: u32) {
473 if self.group_focus_deps.is_empty() {
474 return;
475 }
476 let mut deps = Vec::new();
477 for start in [old, new] {
478 let mut at = start;
479 for _ in 0..4096 {
480 let Some(n) = self.node(at) else { break };
481 if let Some(watchers) = self.group_focus_deps.get(&at) {
482 deps.extend_from_slice(watchers);
483 }
484 if n.parent == 0 || n.parent == at {
485 break;
486 }
487 at = n.parent;
488 }
489 }
490 for dep in deps {
491 self.touch(dep);
492 }
493 }
494
495 fn alloc(&mut self, node: Node) -> u32 {
496 if let Some(id) = self.free.pop() {
497 self.nodes[id as usize] = Some(node);
498 id
499 } else {
500 self.nodes.push(Some(node));
501 (self.nodes.len() - 1) as u32
502 }
503 }
504
505 pub fn node(&self, id: u32) -> Option<&Node> {
506 self.nodes.get(id as usize).and_then(Option::as_ref)
507 }
508
509 pub(crate) fn node_mut(&mut self, id: u32) -> Option<&mut Node> {
510 self.nodes.get_mut(id as usize).and_then(Option::as_mut)
511 }
512
513 fn fresh(&mut self, kind: Kind, tag: u32) -> u32 {
514 self.dirty = true;
515 let id = self.alloc(Node {
516 kind,
517 tag,
518 parent: 0,
519 children: Vec::new(),
520 text: String::new(),
521 style: Vec::new(),
522 classes: Vec::new(),
523 class_attr: String::new(),
524 props: Vec::new(),
525 scopes: Vec::new(),
526 listeners: 0,
527 inline_dirty: false,
528 style_present: false,
529 style_raw: None,
530 sub_rev: 0,
531 mark_gen: 0,
532 desc_gen: 0,
533 sel_flags: Cell::new(0),
534 inline: None,
535 computed: None,
536 });
537 self.mark_restyle(id);
538 id
539 }
540
541 pub fn create_element(&mut self, tag: u32) -> u32 {
542 let id = self.fresh(Kind::Element, tag);
543 if self.name(tag).eq_ignore_ascii_case("style") {
544 self.style_nodes.insert(id);
545 }
546 id
547 }
548
549 pub fn create_text(&mut self) -> u32 {
550 self.fresh(Kind::Text, 0)
551 }
552
553 pub fn create_anchor(&mut self) -> u32 {
554 self.fresh(Kind::Anchor, 0)
555 }
556
557 pub fn create_root(&mut self) -> u32 {
558 let tag = self.intern("root");
559 let id = self.fresh(Kind::Element, tag);
560 self.root = id;
561 id
562 }
563
564 pub fn set_text(&mut self, id: u32, text: String) {
565 if let Some(n) = self.node_mut(id) {
566 let flips = n.kind == Kind::Text && n.text.is_empty() != text.is_empty();
569 let mut parent = n.parent;
570 n.text = text;
571 self.dirty = true;
572 self.mark_restyle(id);
573 if flips {
574 while let Some(p) = self.node(parent).filter(|p| p.kind == Kind::Anchor) {
575 parent = p.parent;
576 }
577 if self
578 .node(parent)
579 .is_some_and(|p| p.sel_flags.get() & sel::EMPTY != 0)
580 {
581 self.mark_with_followers(parent);
582 }
583 self.touch_mutated(id, false);
584 return;
585 }
586 self.touch(id);
587 }
588 }
589
590 pub fn set_element_text(&mut self, id: u32, text: String) {
591 let children = match self.node_mut(id) {
592 Some(n) => std::mem::take(&mut n.children),
593 None => return,
594 };
595 for c in children {
596 self.free_subtree(c);
597 }
598 if let Some(n) = self.node_mut(id) {
599 n.text = text;
600 }
601 self.dirty = true;
602 if self
603 .node(id)
604 .is_some_and(|n| n.sel_flags.get() & sel::EMPTY != 0)
605 {
606 self.mark_with_followers(id);
607 } else {
608 self.mark_restyle(id);
609 }
610 self.touch_mutated(id, true);
611 }
612
613 pub fn insert(&mut self, child: u32, parent: u32, anchor: u32) {
616 if child == 0 || parent == 0 || child == anchor || self.node(parent).is_none() {
617 return;
618 }
619 let old_parent = self.node(child).map(|n| n.parent).unwrap_or(0);
620 if old_parent != 0 {
621 let was_bare = self.bare_if_asked(old_parent);
622 let at = self.detach(child);
623 self.child_list_changed(old_parent, at, false, was_bare);
624 }
625 let was_bare = self.bare_if_asked(parent);
626 let idx = {
629 let Some(p) = self.node_mut(parent) else {
630 return;
631 };
632 p.text.clear();
633 match p.children.iter().position(|&c| c == anchor) {
634 Some(i) => i,
635 None => p.children.len(),
636 }
637 };
638 if let Some(p) = self.node_mut(parent) {
639 p.children.insert(idx, child);
640 }
641 if let Some(c) = self.node_mut(child) {
642 c.parent = parent;
643 }
644 self.mark_restyle(child);
645 if self
646 .node(child)
647 .is_some_and(|c| c.desc_gen == self.restyle_gen)
648 {
649 self.flag_path(parent);
650 }
651 self.child_list_changed(parent, idx, true, was_bare);
652 self.dirty = true;
653 if old_parent != 0 {
655 self.touch_mutated(old_parent, true);
656 }
657 self.touch_mutated(child, false);
658 }
659
660 fn detach(&mut self, id: u32) -> usize {
661 let parent = self.node(id).map(|n| n.parent).unwrap_or(0);
662 let mut at = 0;
663 if parent != 0 {
664 if let Some(p) = self.node_mut(parent) {
665 if let Some(i) = p.children.iter().position(|&c| c == id) {
666 p.children.remove(i);
667 at = i;
668 }
669 }
670 if let Some(n) = self.node_mut(id) {
671 n.parent = 0;
672 }
673 }
674 at
675 }
676
677 pub fn remove(&mut self, id: u32) {
680 let parent = self.node(id).map(|n| n.parent).unwrap_or(0);
681 let was_bare = self.bare_if_asked(parent);
682 let at = self.detach(id);
683 self.free_subtree(id);
684 if parent != 0 {
685 self.child_list_changed(parent, at, false, was_bare);
686 }
687 self.dirty = true;
688 if parent != 0 {
689 self.touch_mutated(parent, true);
690 }
691 }
692
693 fn child_list_changed(&mut self, parent: u32, at: usize, inserted: bool, was_bare: bool) {
696 let Some(p) = self.node(parent) else { return };
697 let flags = p.sel_flags.get();
698 if flags & sel::EMPTY != 0 && self.is_bare(parent) != was_bare {
699 self.mark_with_followers(parent);
700 }
701 if flags & sel::SIBLINGS == 0 {
702 return;
703 }
704 let marks: Vec<u32> = {
705 let children = &self.node(parent).map_or(&[][..], |p| &p.children[..]);
706 let is_element = |c: &u32| self.node(*c).is_some_and(|n| n.kind == Kind::Element);
707 let after = if inserted { at + 1 } else { at };
708 let mut marks = Vec::new();
709 if flags & sel::PREV_WALK != 0 {
710 marks.extend(children.iter().skip(after).copied());
711 } else if flags & sel::PREV_EDGE != 0 {
712 marks.extend(children.iter().skip(after).find(|c| is_element(c)).copied());
713 }
714 if flags & sel::NEXT_WALK != 0 {
715 marks.extend(children.iter().take(at).copied());
716 } else if flags & sel::NEXT_EDGE != 0 {
717 marks.extend(
718 children
719 .iter()
720 .take(at)
721 .rev()
722 .find(|c| is_element(c))
723 .copied(),
724 );
725 }
726 marks
727 };
728 if marks.is_empty() {
729 return;
730 }
731 let reach = reach_of([(POSITION, NameKind::Position)]);
732 for c in marks {
733 self.mark_reach(c, &reach, false);
734 }
735 }
736
737 fn bare_if_asked(&self, id: u32) -> bool {
740 self.node(id)
741 .is_some_and(|n| n.sel_flags.get() & sel::EMPTY != 0)
742 && self.is_bare(id)
743 }
744
745 fn is_bare(&self, id: u32) -> bool {
746 let Some(n) = self.node(id) else { return true };
747 n.text.is_empty()
748 && n.children.iter().all(|&c| match self.node(c) {
749 Some(child) => match child.kind {
750 Kind::Element => false,
751 Kind::Text => child.text.is_empty(),
752 Kind::Anchor => self.is_bare(c),
753 },
754 None => true,
755 })
756 }
757
758 fn free_subtree(&mut self, id: u32) {
759 let Some(node) = self.nodes.get_mut(id as usize).and_then(Option::take) else {
760 return;
761 };
762 self.style_nodes.remove(&id);
763 for c in node.children {
764 self.free_subtree(c);
765 }
766 if self.root == id {
767 self.root = 0;
768 }
769 self.freed.push(id);
770 }
771
772 pub(crate) fn hidden_above(&self, id: u32) -> bool {
773 let mut cur = self.node(id).map_or(0, |n| n.parent);
774 while cur != 0 {
775 let Some(n) = self.node(cur) else {
776 return false;
777 };
778 if n.computed
779 .as_ref()
780 .is_some_and(|c| c.base.display == Some(gpui::Display::None))
781 {
782 return true;
783 }
784 cur = n.parent;
785 }
786 false
787 }
788
789 pub(crate) fn release_freed(&mut self) {
792 self.free.append(&mut self.freed);
793 }
794
795 pub fn set_style(&mut self, id: u32, key: u32, value: String) {
796 if let Some(n) = self.node_mut(id) {
797 if value.is_empty() {
798 n.style.retain(|(k, _)| *k != key);
799 } else if let Some(slot) = n.style.iter_mut().find(|(k, _)| *k == key) {
800 slot.1 = value;
801 } else {
802 n.style.push((key, value));
803 }
804 n.inline_dirty = true;
805 self.dirty = true;
806 self.inline_dirty_nodes.push(id);
807 self.mark_self(id);
808 self.touch(id);
809 }
810 }
811
812 pub fn set_prop(&mut self, id: u32, key: u32, value: Option<String>) {
813 let reach = reach_of([(self.name(key), NameKind::Attr)]);
814 self.prop_writes = self.prop_writes.wrapping_add(1);
815 let write = self.prop_writes;
816 if let Some(n) = self.node_mut(id) {
817 match value {
818 None => n.props.retain(|(k, _, _)| *k != key),
819 Some(v) => {
820 if let Some(slot) = n.props.iter_mut().find(|(k, _, _)| *k == key) {
821 slot.1 = v;
822 slot.2 = write;
823 } else {
824 n.props.push((key, v, write));
825 }
826 }
827 }
828 self.dirty = true;
829 self.mark_own_inputs(id, reach);
830 self.touch_mutated(id, false);
831 }
832 }
833
834 pub fn prop<'a>(&'a self, id: u32, name: &str) -> Option<&'a str> {
835 self.prop_write(id, name).map(|(v, _)| v)
836 }
837
838 pub fn prop_write<'a>(&'a self, id: u32, name: &str) -> Option<(&'a str, u32)> {
841 let key = *self.name_ids.get(name)?;
842 self.node(id)?
843 .props
844 .iter()
845 .find(|(k, _, _)| *k == key)
846 .map(|(_, v, write)| (v.as_str(), *write))
847 }
848
849 pub fn add_scope(&mut self, id: u32, scope: String) {
850 let reach = reach_of([(scope.as_str(), NameKind::Scope)]);
851 if let Some(n) = self.node_mut(id) {
852 if !n.scopes.contains(&scope) {
853 n.scopes.push(scope);
854 self.dirty = true;
855 self.mark_own_inputs(id, reach);
856 self.touch_mutated(id, false);
857 }
858 }
859 }
860
861 pub fn copy_scopes(&mut self, from: u32, to: u32) {
863 let scopes = self
864 .node(from)
865 .map(|n| n.scopes.clone())
866 .unwrap_or_default();
867 for scope in scopes {
868 self.add_scope(to, scope);
869 }
870 }
871
872 pub fn set_class(&mut self, id: u32, classes: &str) {
873 if let Some(n) = self.node_mut(id) {
874 if n.class_attr == classes {
875 return; }
877 let mut next: Vec<String> = Vec::new();
880 for c in classes.split_whitespace() {
881 if !next.iter().any(|x| x == c) {
882 next.push(c.to_string());
883 }
884 }
885 let reach = {
886 let gone = n.classes.iter().filter(|c| !next.contains(c));
887 let came = next.iter().filter(|c| !n.classes.contains(c));
888 let names = gone.chain(came).map(|c| (c.as_str(), NameKind::Class));
889 reach_of(std::iter::once(("class", NameKind::Attr)).chain(names))
890 };
891 n.classes = next;
892 n.class_attr = classes.to_string();
893 self.dirty = true;
894 self.mark_own_inputs(id, reach);
895 self.touch_mutated(id, false);
896 }
897 }
898
899 fn mark_own_inputs(&mut self, id: u32, reach: Reach) {
902 self.mark_reach(id, &reach, self.sibling_combinators);
903 }
904
905 fn mark_reach(&mut self, id: u32, reach: &Reach, later_siblings: bool) {
906 let tags = match reach {
907 Reach::Subtree if later_siblings => return self.mark_with_followers(id),
908 Reach::Subtree => return self.mark_restyle(id),
909 Reach::Own => return self.mark_self(id),
910 Reach::Tags(tags) => tags,
911 };
912 self.mark_self(id);
913 let mut stack: Vec<u32> = self
914 .node(id)
915 .map(|n| n.children.clone())
916 .unwrap_or_default();
917 if later_siblings {
918 if let Some(siblings) = self
919 .node(id)
920 .and_then(|n| self.node(n.parent))
921 .map(|p| &p.children)
922 {
923 if let Some(at) = siblings.iter().position(|&c| c == id) {
924 stack.extend_from_slice(&siblings[at + 1..]);
925 }
926 }
927 }
928 let mut hits: Vec<u32> = Vec::new();
929 while let Some(c) = stack.pop() {
930 let Some(n) = self.node(c) else { continue };
931 if n.kind == Kind::Element && tags.contains(&n.tag) {
932 hits.push(c);
933 continue;
934 }
935 stack.extend_from_slice(&n.children);
936 }
937 for c in hits {
938 self.mark_restyle(c);
939 }
940 }
941
942 fn mark_self(&mut self, id: u32) {
943 if self.dirty_all || id == 0 || self.node(id).is_none_or(|n| n.mark_gen == self.restyle_gen)
944 {
945 return;
946 }
947 self.self_marks.push(id);
948 }
949
950 pub fn set_listener(&mut self, id: u32, event: u32, on: bool) {
951 if let Some(n) = self.node_mut(id) {
952 if event >= u64::BITS {
955 return;
956 }
957 let bit = 1u64 << event;
958 if on {
959 n.listeners |= bit;
960 } else {
961 n.listeners &= !bit;
962 }
963 self.dirty = true;
964 self.touch(id);
965 }
966 }
967
968 pub fn is_dirty(&self) -> bool {
969 self.dirty || self.style_flushed
970 }
971
972 pub fn take_dirty(&mut self) -> bool {
973 let flushed = std::mem::take(&mut self.style_flushed);
975 std::mem::take(&mut self.dirty) || flushed
976 }
977
978 pub fn live_count(&self) -> u32 {
980 self.nodes.iter().filter(|n| n.is_some()).count() as u32
981 }
982
983 pub(crate) fn mem_estimate(&self) -> TreeMem {
984 use std::collections::HashSet;
985 use std::mem::size_of;
986 let mut m = TreeMem {
987 slots: self.nodes.len(),
988 slot_bytes: self.nodes.capacity() * size_of::<Option<Node>>(),
989 ..TreeMem::default()
990 };
991 let mut refinements: HashSet<*const gpui::StyleRefinement> = HashSet::new();
992 let mut vars: HashSet<*const sk_css::Vars> = HashSet::new();
993 let mut inlines: HashSet<*const sk_css::InlineStyle> = HashSet::new();
994 let note_ref = |r: &std::rc::Rc<gpui::StyleRefinement>,
995 set: &mut HashSet<*const gpui::StyleRefinement>| {
996 set.insert(std::rc::Rc::as_ptr(r));
997 };
998 for n in self.nodes.iter().flatten() {
999 m.nodes += 1;
1000 match n.kind {
1001 Kind::Element => m.elements += 1,
1002 Kind::Text => m.texts += 1,
1003 Kind::Anchor => m.anchors += 1,
1004 }
1005 let mut own = n.children.capacity() * 4 + n.text.capacity() + n.class_attr.capacity();
1006 own += n.style.capacity() * size_of::<(u32, String)>()
1007 + n.style.iter().map(|(_, v)| v.capacity()).sum::<usize>();
1008 own += n.classes.capacity() * size_of::<String>()
1009 + n.classes.iter().map(|c| c.capacity()).sum::<usize>();
1010 own += n.props.capacity() * size_of::<(u32, String, u32)>()
1011 + n.props.iter().map(|(_, v, _)| v.capacity()).sum::<usize>();
1012 own += n.scopes.capacity() * size_of::<String>()
1013 + n.scopes.iter().map(|s| s.capacity()).sum::<usize>();
1014 m.owned_bytes += own;
1015 if let Some(i) = &n.inline {
1016 inlines.insert(std::rc::Rc::as_ptr(i));
1017 }
1018 if let Some(cs) = &n.computed {
1019 m.computed += 1;
1020 note_ref(&cs.base, &mut refinements);
1021 for r in [
1022 &cs.hover,
1023 &cs.active,
1024 &cs.focus,
1025 &cs.focus_visible,
1026 &cs.focus_within,
1027 &cs.placeholder,
1028 &cs.selection,
1029 &cs.file_selector_button,
1030 ]
1031 .into_iter()
1032 .flatten()
1033 {
1034 note_ref(r, &mut refinements);
1035 }
1036 for (_, r) in [&cs.group_hover, &cs.group_active].into_iter().flatten() {
1037 note_ref(r, &mut refinements);
1038 }
1039 if let Some(g) = &cs.group_focus {
1040 for (_, r) in [&g.focus, &g.focus_visible, &g.focus_within]
1041 .into_iter()
1042 .flatten()
1043 {
1044 note_ref(r, &mut refinements);
1045 }
1046 }
1047 if vars.insert(std::rc::Rc::as_ptr(&cs.vars)) {
1048 m.var_entries += cs.vars.len();
1049 }
1050 }
1051 }
1052 m.computed_bytes = m.computed * size_of::<sk_css::ComputedStates>();
1053 m.refinements = refinements.len();
1054 m.refinement_bytes = refinements.len() * (size_of::<gpui::StyleRefinement>() + 16);
1055 m.vars_maps = vars.len();
1056 m.vars_bytes = vars.len() * (size_of::<sk_css::Vars>() + 16)
1058 + m.var_entries * 2 * size_of::<std::rc::Rc<str>>();
1059 m.inlines = inlines.len();
1060 m.inline_bytes = inlines.len() * (size_of::<sk_css::InlineStyle>() + 16);
1061 m.names = self.names.len();
1062 m.total_bytes = m.slot_bytes
1063 + m.owned_bytes
1064 + m.computed_bytes
1065 + m.refinement_bytes
1066 + m.vars_bytes
1067 + m.inline_bytes;
1068 m
1069 }
1070
1071 pub fn mark_restyle_subtree(&mut self, id: u32) {
1074 self.dirty = true;
1075 self.mark_restyle(id);
1076 }
1077
1078 pub fn mark_dirty(&mut self) {
1079 self.dirty = true;
1080 self.dirty_all = true;
1081 }
1082
1083 pub(crate) fn touch(&mut self, id: u32) {
1086 let mut cur = id;
1087 for _ in 0..4096 {
1089 let Some(n) = self.node_mut(cur) else { return };
1090 n.sub_rev = n.sub_rev.wrapping_add(1);
1091 match n.parent {
1092 0 => return,
1093 p => cur = p,
1094 }
1095 }
1096 }
1097
1098 pub(crate) fn touch_mutated(&mut self, id: u32, include_self: bool) {
1104 if !self.has_anchors.get() {
1105 self.touch(id);
1106 return;
1107 }
1108 let mut whole: Vec<u32> = Vec::new();
1109 let mut cur = id;
1110 let mut first = true;
1111 for _ in 0..4096 {
1112 let Some(n) = self.node_mut(cur) else { break };
1113 n.sub_rev = n.sub_rev.wrapping_add(1);
1114 let flags = n.sel_flags.get();
1115 let parent = n.parent;
1116 if include_self || !first {
1117 if flags & sel::HAS_DESC != 0 {
1118 whole.push(cur);
1119 } else if flags & sel::HAS_SELF != 0 {
1120 self.self_marks.push(cur);
1121 }
1122 }
1123 first = false;
1124 let earlier: Vec<u32> = match self.node(parent) {
1127 Some(p) if p.sel_flags.get() & sel::HAS_NEXT != 0 => p
1128 .children
1129 .iter()
1130 .take_while(|&&c| c != cur)
1131 .copied()
1132 .collect(),
1133 _ => Vec::new(),
1134 };
1135 for sibling in earlier {
1136 let flags = self.node(sibling).map_or(0, |n| n.sel_flags.get());
1137 if flags & sel::HAS_DESC != 0 {
1138 whole.push(sibling);
1139 } else if flags & sel::HAS_SELF != 0 {
1140 self.self_marks.push(sibling);
1141 }
1142 }
1143 match parent {
1144 0 => break,
1145 p => cur = p,
1146 }
1147 }
1148 for a in whole {
1149 self.mark_with_followers(a);
1150 }
1151 }
1152
1153 pub fn sub_rev(&self, id: u32) -> u64 {
1156 self.node(id).map(|n| n.sub_rev).unwrap_or(0)
1157 }
1158
1159 fn mark_restyle(&mut self, id: u32) {
1164 if self.dirty_all || id == 0 {
1165 return;
1166 }
1167 let gen = self.restyle_gen;
1168 match self.node_mut(id) {
1169 Some(n) if n.mark_gen != gen => n.mark_gen = gen,
1170 _ => return,
1171 }
1172 self.flag_path(id);
1173 }
1174
1175 fn mark_with_followers(&mut self, id: u32) {
1178 self.mark_restyle(id);
1179 if !self.sibling_combinators {
1180 return;
1181 }
1182 let later: Vec<u32> = self
1183 .node(id)
1184 .and_then(|n| self.node(n.parent))
1185 .map(|p| {
1186 p.children
1187 .iter()
1188 .skip_while(|&&c| c != id)
1189 .skip(1)
1190 .copied()
1191 .collect()
1192 })
1193 .unwrap_or_default();
1194 for s in later {
1195 self.mark_restyle(s);
1196 }
1197 }
1198
1199 fn flag_path(&mut self, id: u32) {
1202 let gen = self.restyle_gen;
1203 let root = self.root;
1204 let mut cur = id;
1205 for _ in 0..4096 {
1207 let Some(n) = self.node_mut(cur) else { return };
1208 if n.desc_gen == gen {
1209 return;
1210 }
1211 n.desc_gen = gen;
1212 match n.parent {
1213 0 => {
1214 if cur != root {
1215 self.detached_marks.push(cur);
1216 }
1217 return;
1218 }
1219 p => cur = p,
1220 }
1221 }
1222 }
1223
1224 pub(crate) fn invalidate_viewport_inline(&mut self) -> usize {
1229 self.invalidate_inline_where(has_viewport_unit)
1230 }
1231
1232 pub(crate) fn invalidate_rem_inline(&mut self) -> usize {
1233 self.invalidate_inline_where(has_rem_unit)
1234 }
1235
1236 fn invalidate_inline_where(&mut self, names_the_unit: fn(&str) -> bool) -> usize {
1237 let hits: Vec<u32> = self
1238 .nodes
1239 .iter()
1240 .enumerate()
1241 .filter_map(|(i, n)| {
1242 let n = n.as_ref()?;
1243 n.style
1244 .iter()
1245 .any(|(_, v)| names_the_unit(v))
1246 .then_some(i as u32)
1247 })
1248 .collect();
1249 for &id in &hits {
1250 if let Some(n) = self.node_mut(id) {
1251 n.inline_dirty = true;
1252 }
1253 self.inline_dirty_nodes.push(id);
1254 self.mark_restyle(id);
1255 self.touch(id);
1256 }
1257 if !hits.is_empty() {
1258 self.dirty = true;
1259 }
1260 hits.len()
1261 }
1262
1263 pub(crate) fn invalidate_font_inline(&mut self) -> usize {
1266 self.invalidate_inline_named(&["font", "font-family"])
1267 }
1268
1269 fn invalidate_inline_named(&mut self, names: &[&str]) -> usize {
1271 let keys: Vec<u32> = names
1272 .iter()
1273 .filter_map(|k| self.name_ids.get(*k).copied())
1274 .collect();
1275 if keys.is_empty() {
1276 return 0;
1277 }
1278 let hits: Vec<u32> = self
1279 .nodes
1280 .iter()
1281 .enumerate()
1282 .filter_map(|(i, n)| {
1283 let n = n.as_ref()?;
1284 n.style
1285 .iter()
1286 .any(|(k, _)| keys.contains(k))
1287 .then_some(i as u32)
1288 })
1289 .collect();
1290 for &id in &hits {
1291 if let Some(n) = self.node_mut(id) {
1292 n.inline_dirty = true;
1293 }
1294 self.inline_dirty_nodes.push(id);
1295 self.mark_restyle(id);
1296 self.touch(id);
1297 }
1298 if !hits.is_empty() {
1299 self.dirty = true;
1300 }
1301 hits.len()
1302 }
1303
1304 pub fn restyle(&mut self, engine: Option<&sk_css::Engine>, env: &sk_css::Env) {
1306 match engine {
1307 Some(e) => self.restyle_with(e, env),
1308 None => NO_SHEET.with(|e| self.restyle_with(e, env)),
1311 }
1312 }
1313
1314 fn restyle_roots(&mut self) -> Vec<u32> {
1318 let gen = self.restyle_gen;
1319 self.restyle_gen = self.restyle_gen.wrapping_add(1).max(1);
1320 let detached = std::mem::take(&mut self.detached_marks);
1321 if std::mem::take(&mut self.dirty_all) {
1322 let mut roots: Vec<u32> = Vec::new();
1323 if self.root != 0 && self.node(self.root).is_some() {
1324 roots.push(self.root);
1325 }
1326 roots.extend(
1327 (1..self.nodes.len() as u32)
1328 .filter(|&id| id != self.root)
1329 .filter(|&id| self.node(id).is_some_and(|n| n.parent == 0)),
1330 );
1331 return roots;
1332 }
1333
1334 let mut roots: Vec<u32> = Vec::new();
1335 let mut tops: Vec<u32> = Vec::new();
1338 for top in std::iter::once(self.root).chain(detached) {
1339 let Some(n) = self.node(top) else { continue };
1340 if n.desc_gen != gen || (top != self.root && n.parent != 0) || tops.contains(&top) {
1341 continue;
1342 }
1343 tops.push(top);
1344 }
1345 for top in tops {
1346 if self.collect_roots(top, gen, &mut roots, 0) {
1347 roots.push(top);
1348 }
1349 }
1350 roots
1351 }
1352
1353 fn collect_roots(&self, id: u32, gen: u32, roots: &mut Vec<u32>, depth: u32) -> bool {
1354 let Some(n) = self.node(id) else { return false };
1355 if n.mark_gen == gen || (n.kind == Kind::Element && n.computed.is_none()) || depth > 1024 {
1356 return true;
1357 }
1358 let start = roots.len();
1359 let element = n.kind == Kind::Element;
1360 for &c in &n.children {
1361 let Some(child) = self.node(c) else { continue };
1362 let whole = child.desc_gen == gen && self.collect_roots(c, gen, roots, depth + 1);
1363 if !whole {
1364 continue;
1365 }
1366 if !element {
1367 roots.truncate(start);
1370 return true;
1371 }
1372 roots.push(c);
1373 }
1374 false
1375 }
1376
1377 pub(crate) fn probe_root_font_size(
1381 &self,
1382 engine: Option<&sk_css::Engine>,
1383 env: &sk_css::Env,
1384 ) -> Option<f32> {
1385 let engine = engine?;
1386 let n = self.node(self.root)?;
1387 let parsed;
1388 let inline: Option<&sk_css::InlineStyle> = if n.inline_dirty {
1389 let body = n
1390 .style
1391 .iter()
1392 .map(|(k, v)| format!("{}: {}", self.name(*k), v))
1393 .collect::<Vec<_>>()
1394 .join("; ");
1395 parsed = (!body.is_empty())
1396 .then(|| sk_css::parse_inline_style(&body, &mut Vec::new()))
1397 .filter(|s| !s.is_empty());
1398 parsed.as_ref()
1399 } else {
1400 n.inline.as_deref()
1401 };
1402 let states = engine.compute_node_at(
1403 NodeRef {
1404 tree: self,
1405 id: self.root,
1406 },
1407 inline,
1408 &std::rc::Rc::new(sk_css::Vars::default()),
1409 None,
1410 ROOT_PARENT_FONT_SIZE,
1411 env,
1412 &mut Vec::new(),
1413 );
1414 match states.base.text.font_size? {
1415 gpui::AbsoluteLength::Pixels(p) => Some(f32::from(p)),
1416 gpui::AbsoluteLength::Rems(r) => Some(r.0 * sk_css::rem_basis()),
1419 }
1420 }
1421
1422 #[allow(clippy::type_complexity)]
1425 fn walk_inputs(
1426 &self,
1427 r: u32,
1428 env: &sk_css::Env,
1429 root_vars: &std::rc::Rc<sk_css::Vars>,
1430 ) -> (
1431 std::rc::Rc<sk_css::Vars>,
1432 bool,
1433 Inherited,
1434 sk_css::InheritedRadii,
1435 sk_css::Env,
1436 ) {
1437 let root_env = crate::windows::env_for_node(self, r, env);
1438 let mut cur = self.node(r).map_or(0, |n| n.parent);
1439 let mut parent_computed = None;
1440 for _ in 0..4096 {
1441 let Some(p) = self.node(cur) else { break };
1442 if let Some(c) = p.computed.as_ref() {
1443 parent_computed = Some(c);
1444 break;
1445 }
1446 if p.kind == Kind::Element {
1447 break;
1448 }
1449 cur = p.parent;
1450 }
1451 let inherited = parent_computed
1452 .map(|c| c.vars.clone())
1453 .unwrap_or_else(|| root_vars.clone());
1454 let inherited_inert =
1455 parent_computed.is_some_and(|c| c.extras.pointer_events_none == Some(true));
1456 let inherited_text = Inherited {
1459 color: parent_computed.and_then(|c| c.color),
1460 font_size: parent_computed.map_or(ROOT_PARENT_FONT_SIZE, |c| c.font_size),
1461 font: parent_computed
1462 .map(|c| c.computed_font.clone())
1463 .unwrap_or_default(),
1464 };
1465 let inherited_radii = parent_computed
1466 .map(|c| sk_css::InheritedRadii::of(&c.base))
1467 .unwrap_or_default();
1468 (
1469 inherited,
1470 inherited_inert,
1471 inherited_text,
1472 inherited_radii,
1473 root_env,
1474 )
1475 }
1476
1477 fn cascade_one(
1478 &self,
1479 engine: &sk_css::Engine,
1480 id: u32,
1481 (parent_vars, parent_inert, parent_text, parent_radii): (
1482 &std::rc::Rc<sk_css::Vars>,
1483 bool,
1484 Inherited,
1485 sk_css::InheritedRadii,
1486 ),
1487 env: &sk_css::Env,
1488 chain: &sk_css::container::Chain,
1489 diagnostics: &mut Vec<String>,
1490 ) -> (sk_css::ComputedStates, sk_css::InheritedRadii) {
1491 let n = self.node(id).expect("cascade_one on a live node");
1492 CASCADE_SUBJECT.with(|c| c.set(id));
1493 let mut states = sk_css::container::with_chain(chain, || {
1494 engine.compute_node_with_font(
1495 NodeRef { tree: self, id },
1496 n.inline.as_deref(),
1497 parent_vars,
1498 parent_text.color,
1499 parent_text.font_size,
1500 &parent_text.font,
1501 env,
1502 diagnostics,
1503 )
1504 });
1505 CASCADE_SUBJECT.with(|c| c.set(0));
1506 let inert = states.extras.pointer_events_none.unwrap_or(parent_inert);
1509 states.extras.pointer_events_none = Some(inert);
1510 let radii = sk_css::resolve_inherited_radii(&mut states, parent_radii);
1511 (states, radii)
1512 }
1513
1514 fn container_chain(&self, id: u32, active: bool) -> sk_css::container::Chain {
1517 if !active {
1518 return None;
1519 }
1520 let mut above = Vec::new();
1521 let mut cur = self.node(id).map_or(0, |n| n.parent);
1522 for _ in 0..4096 {
1523 let Some(n) = self.node(cur) else { break };
1524 if n.computed.is_some() {
1525 above.push(cur);
1526 }
1527 cur = n.parent;
1528 }
1529 let mut chain = None;
1530 for &a in above.iter().rev() {
1531 if let Some(cs) = self.node(a).and_then(|n| n.computed.as_ref()) {
1532 chain = sk_css::container::Container::link(
1533 a,
1534 &cs.extras,
1535 &cs.vars,
1536 cs.font_size,
1537 &chain,
1538 );
1539 }
1540 }
1541 chain
1542 }
1543
1544 fn containers_active(&self, engine: &sk_css::Engine) -> bool {
1545 engine.uses_containers() || self.inline_container_units
1546 }
1547
1548 fn settle_self_marks(
1552 &mut self,
1553 engine: &sk_css::Engine,
1554 env: &sk_css::Env,
1555 ) -> Vec<(u32, sk_css::ComputedStates)> {
1556 let mut marks = std::mem::take(&mut self.self_marks);
1557 if marks.is_empty() || self.dirty_all {
1558 return Vec::new();
1559 }
1560 marks.sort_unstable();
1561 marks.dedup();
1562 let root_vars = std::rc::Rc::new(sk_css::Vars::default());
1563 let mut diagnostics = Vec::new();
1564 let mut stored = Vec::new();
1565 let mut whole = Vec::new();
1566 let containers = self.containers_active(engine);
1567 for id in marks {
1568 let Some(n) = self.node(id) else { continue };
1569 if n.kind != Kind::Element || n.mark_gen == self.restyle_gen || n.computed.is_none() {
1570 continue;
1571 }
1572 let (vars, inert, text, radii, here_env) = self.walk_inputs(id, env, &root_vars);
1573 let (states, child_radii) = self.cascade_one(
1574 engine,
1575 id,
1576 (&vars, inert, text, radii),
1577 &here_env,
1578 &self.container_chain(id, containers),
1579 &mut diagnostics,
1580 );
1581 let Some(old) = n.computed.as_ref() else {
1582 continue;
1583 };
1584 if *old == states {
1585 continue;
1586 }
1587 let hands_down_the_same = old.vars == states.vars
1588 && old.color == states.color
1589 && old.font_size == states.font_size
1590 && old.computed_font == states.computed_font
1591 && old.extras.pointer_events_none == states.extras.pointer_events_none
1592 && old.extras.container_type == states.extras.container_type
1593 && old.extras.container_name == states.extras.container_name
1594 && sk_css::InheritedRadii::of(&old.base) == child_radii;
1595 if hands_down_the_same {
1596 stored.push((id, states));
1597 } else {
1598 whole.push(id);
1599 }
1600 }
1601 for id in whole {
1602 self.mark_restyle(id);
1603 }
1604 stored
1605 }
1606
1607 fn restyle_with(&mut self, engine: &sk_css::Engine, env: &sk_css::Env) {
1608 let _profile = sk_runtime::redjs::profiling::span("style", "Restyle DOM");
1609 thread_local! { static CACHE_ENGINE: Cell<usize> = const { Cell::new(0) }; }
1612 let addr = engine as *const sk_css::Engine as usize;
1613 if CACHE_ENGINE.with(|c| c.replace(addr)) != addr {
1614 forget_read_cache();
1615 note_parent_keys(engine);
1616 }
1617 let sheet_changed = REBIND_ANIMATIONS.with(|pending| pending.replace(false));
1618 self.sibling_combinators = engine.uses_sibling_combinators();
1619 let pass = crate::perf::Span::start();
1620 let phase = crate::perf::Span::start();
1621 let dirty_inline = std::mem::take(&mut self.inline_dirty_nodes);
1624 for id in dirty_inline {
1625 if !self.node(id).is_some_and(|n| n.inline_dirty) {
1626 continue; }
1628 let body = {
1629 let n = self.node(id).unwrap();
1630 n.style
1631 .iter()
1632 .map(|(k, v)| format!("{}: {}", self.name(*k), v))
1633 .collect::<Vec<_>>()
1634 .join("; ")
1635 };
1636 let mut diags = Vec::new();
1637 let parsed = if body.is_empty() {
1638 None
1639 } else {
1640 let style = sk_css::parse_inline_style(&body, &mut diags);
1641 (!style.is_empty()).then(|| std::rc::Rc::new(style))
1642 };
1643 for d in diags {
1644 warn_css(&format!("[css inline] {d}"));
1645 }
1646 self.inline_container_units |= parsed.is_some() && body.contains("cq");
1647 let n = self.node_mut(id).unwrap();
1648 n.inline = parsed;
1649 n.inline_dirty = false;
1650 }
1651
1652 let inline_ms = phase.ms();
1653 let phase = crate::perf::Span::start();
1654
1655 let mut diagnostics: Vec<String> = Vec::new();
1656 let full = self.dirty_all;
1657 let containers = self.containers_active(engine);
1658 if containers {
1659 crate::containers::install();
1660 }
1661 if full {
1662 crate::containers::forget_all();
1663 }
1664 let settled = self.settle_self_marks(engine, env);
1665 let roots = self.restyle_roots();
1666 let cascaded_anything = !roots.is_empty() || !settled.is_empty();
1667 let computed: Vec<(u32, sk_css::ComputedStates)> = {
1668 let this: &Tree = self;
1669 let root_vars = std::rc::Rc::new(sk_css::Vars::default());
1670 let mut out = Vec::new();
1671 let mut stack: Vec<(
1675 u32,
1676 std::rc::Rc<sk_css::Vars>,
1677 bool,
1678 Inherited,
1679 sk_css::InheritedRadii,
1680 sk_css::Env,
1681 sk_css::container::Chain,
1682 )> = Vec::new();
1683 let multiwindow = crate::windows::any_secondary();
1684 for r in roots {
1685 let (inherited, inherited_inert, inherited_text, inherited_radii, root_env) =
1688 this.walk_inputs(r, env, &root_vars);
1689 stack.push((
1690 r,
1691 inherited,
1692 inherited_inert,
1693 inherited_text,
1694 inherited_radii,
1695 root_env,
1696 this.container_chain(r, containers),
1697 ));
1698 while let Some((
1699 id,
1700 parent_vars,
1701 parent_inert,
1702 parent_text,
1703 parent_radii,
1704 here_env,
1705 chain,
1706 )) = stack.pop()
1707 {
1708 let Some(n) = this.node(id) else { continue };
1709 let (child_vars, child_inert, child_text, child_radii, child_chain) =
1710 if n.kind == Kind::Element {
1711 let (states, radii) = this.cascade_one(
1712 engine,
1713 id,
1714 (
1715 &parent_vars,
1716 parent_inert,
1717 parent_text.clone(),
1718 parent_radii,
1719 ),
1720 &here_env,
1721 &chain,
1722 &mut diagnostics,
1723 );
1724 let inert = states.extras.pointer_events_none == Some(true);
1725 let vars = states.vars.clone();
1726 let text = Inherited {
1727 color: states.color,
1728 font_size: states.font_size,
1729 font: states.computed_font.clone(),
1730 };
1731 let child_chain = if containers {
1732 sk_css::container::Container::link(
1733 id,
1734 &states.extras,
1735 &states.vars,
1736 states.font_size,
1737 &chain,
1738 )
1739 } else {
1740 None
1741 };
1742 out.push((id, states));
1743 (vars, inert, text, radii, child_chain)
1744 } else {
1745 (parent_vars, parent_inert, parent_text, parent_radii, chain)
1746 };
1747 for &c in n.children.iter().rev() {
1748 let child_env = if multiwindow {
1752 crate::windows::env_at_root(c, env).unwrap_or(here_env)
1753 } else {
1754 here_env
1755 };
1756 stack.push((
1757 c,
1758 child_vars.clone(),
1759 child_inert,
1760 child_text.clone(),
1761 child_radii,
1762 child_env,
1763 child_chain.clone(),
1764 ));
1765 }
1766 }
1767 }
1768 out
1769 };
1770 let computed = if settled.is_empty() {
1773 computed
1774 } else {
1775 let walked: std::collections::HashSet<u32> =
1776 computed.iter().map(|(id, _)| *id).collect();
1777 let mut computed = computed;
1778 computed.extend(settled.into_iter().filter(|(id, _)| !walked.contains(id)));
1779 computed
1780 };
1781 let cascade_ms = phase.ms();
1782 let cascaded = computed.len() as u64;
1783 let phase = crate::perf::Span::start();
1784 for d in diagnostics {
1785 warn_css(&format!("[css] {d}"));
1786 }
1787 let now = std::time::Instant::now();
1788 let has_keyframes = engine.has_keyframes();
1789 let keyframe_diagnostics = std::cell::RefCell::new(Vec::<String>::new());
1792 let mut restyled: Vec<u32> = Vec::new();
1793 let multiwindow = crate::windows::any_secondary();
1797 let mut display_flips: Vec<(u32, bool)> = Vec::new();
1798 ANIMATOR.with(|a| {
1799 let mut animator = a.borrow_mut();
1800 for (id, states) in computed {
1801 let node_env = if multiwindow && (has_keyframes || !states.animations.is_empty()) {
1802 crate::windows::env_for_node(self, id, env)
1803 } else {
1804 *env
1805 };
1806 let rebind = (sheet_changed || node_env != *env) && !states.animations.is_empty();
1809 let self_none = states.base.display == Some(gpui::Display::None);
1812 let animated = !states.animations.is_empty() || animator.has_animations(id);
1813 let hidden = animated && (self_none || self.hidden_above(id));
1814 let keywords = (animated
1815 || !states.transitions.is_empty()
1816 || animator.has_script_animations(id))
1817 && crate::inherit::interpolate_keywords(
1818 self,
1819 id,
1820 states.extras.interpolate_size,
1821 );
1822 animator.set_interpolate_keywords(id, keywords);
1823 if let Some(n) = self.node_mut(id) {
1824 let was_none = n
1825 .computed
1826 .as_ref()
1827 .map(|c| c.base.display == Some(gpui::Display::None));
1828 if was_none.is_some_and(|was| was != self_none) {
1829 display_flips.push((id, self_none));
1830 }
1831 if hidden {
1832 animator.cancel_animations(id, now);
1833 }
1834 if containers {
1835 crate::containers::note_committed(
1836 id,
1837 n.parent,
1838 n.computed.is_none(),
1839 &states,
1840 );
1841 }
1842 if n.computed.as_ref() != Some(&states) {
1843 let before = if containers && crate::containers::born_this_frame(id) {
1844 None
1845 } else {
1846 n.computed.as_ref()
1847 };
1848 animator.on_computed(id, before, &states, now);
1849 if !hidden
1853 && (has_keyframes
1854 || !states.animations.is_empty()
1855 || animator.has_animations(id))
1856 {
1857 animator.on_computed_animations(id, &states, now, &|name| {
1858 engine.keyframes_for(
1859 name,
1860 &states.vars,
1861 &node_env,
1862 &mut keyframe_diagnostics.borrow_mut(),
1863 )
1864 });
1865 }
1866 if states.hover_transitions() {
1869 let target = fold_hover_target(id, &states);
1870 if target.is_some() || animator.holds_state(id) {
1871 animator.on_state(id, &states, target.as_ref(), now);
1872 }
1873 }
1874 n.computed = Some(states);
1875 restyled.push(id);
1876 } else if rebind && !hidden {
1877 animator.on_computed_animations(id, &states, now, &|name| {
1878 engine.keyframes_for(
1879 name,
1880 &states.vars,
1881 &node_env,
1882 &mut keyframe_diagnostics.borrow_mut(),
1883 )
1884 });
1885 }
1886 }
1887 }
1888 for (id, none) in std::mem::take(&mut display_flips) {
1891 if !none && self.hidden_above(id) {
1892 continue; }
1894 let mut stack: Vec<u32> = self
1895 .node(id)
1896 .map(|n| n.children.clone())
1897 .unwrap_or_default();
1898 while let Some(c) = stack.pop() {
1899 let Some(node) = self.node(c) else { continue };
1900 if none {
1901 if animator.has_animations(c) {
1902 animator.cancel_animations(c, now);
1903 }
1904 } else {
1905 let Some(cs) = node.computed.as_ref() else {
1906 continue;
1907 };
1908 if cs.base.display == Some(gpui::Display::None) {
1909 continue; }
1911 if !cs.animations.is_empty() {
1912 let node_env = if multiwindow {
1913 crate::windows::env_for_node(self, c, env)
1914 } else {
1915 *env
1916 };
1917 animator.on_computed_animations(c, cs, now, &|name| {
1918 engine.keyframes_for(
1919 name,
1920 &cs.vars,
1921 &node_env,
1922 &mut keyframe_diagnostics.borrow_mut(),
1923 )
1924 });
1925 }
1926 }
1927 stack.extend(node.children.iter().copied());
1928 }
1929 }
1930 for d in animator.take_diagnostics() {
1931 warn_css(&format!("[css transition] {d}"));
1932 }
1933 });
1934 for d in keyframe_diagnostics.into_inner() {
1935 warn_css(&format!("[css] {d}"));
1936 }
1937 crate::perf::note_restyle_shape(full, restyled.len() as u64);
1938 for id in restyled {
1939 self.touch(id);
1940 }
1941 if !cascaded_anything {
1942 crate::perf::note_restyle(pass.ms(), inline_ms, cascade_ms, phase.ms(), cascaded);
1943 return;
1944 }
1945 self.group_anchors.clear();
1946 self.group_hover_deps.clear();
1947 self.group_focus_deps.clear();
1948 if engine.uses_group_states() {
1949 for (i, slot) in self.nodes.iter().enumerate() {
1950 let Some(slot) = slot else { continue };
1951 if let Some(cs) = &slot.computed {
1952 if let Some((key, _)) = &cs.group_hover {
1953 self.group_anchors.insert(*key as u32);
1954 self.group_hover_deps
1955 .entry(*key as u32)
1956 .or_default()
1957 .push(i as u32);
1958 }
1959 if let Some((key, _)) = &cs.group_active {
1960 self.group_anchors.insert(*key as u32);
1961 }
1962 for key in cs.group_focus.iter().flat_map(|g| g.anchors()) {
1963 self.group_focus_deps
1964 .entry(key as u32)
1965 .or_default()
1966 .push(i as u32);
1967 }
1968 }
1969 }
1970 }
1971 crate::perf::note_restyle(pass.ms(), inline_ms, cascade_ms, phase.ms(), cascaded);
1972 }
1973}
1974
1975thread_local! {
1976 static NO_SHEET: sk_css::Engine = sk_css::Engine::compile("");
1977 static RUNTIME_CSS: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
1978 static CSS_WARNED: RefCell<std::collections::HashSet<String>> =
1979 RefCell::new(std::collections::HashSet::new());
1980 static ENGINE: RefCell<Option<sk_css::Engine>> = const { RefCell::new(None) };
1981 static REM_SETTLED: Cell<Option<(f32, f32)>> = const { Cell::new(None) };
1984 static SHEET_SOURCE: RefCell<String> = const { RefCell::new(String::new()) };
1985 static HEAD_SHEETS: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
1988 static ANIMATOR: RefCell<sk_css::Animator> = RefCell::new(sk_css::Animator::new());
1989 static REBIND_ANIMATIONS: Cell<bool> = const { Cell::new(false) };
1990 static ENV: Cell<sk_css::Env> = Cell::new(sk_css::Env::default());
1994}
1995
1996pub fn set_env(env: sk_css::Env) -> bool {
1999 set_reduce_motion(env.reduce_motion);
2000 let primary = crate::windows::primary();
2001 let env = sk_css::Env {
2002 dynamic_range_high: crate::surface::dynamic_range_high(primary),
2003 ..env
2004 };
2005 crate::windows::set_env(primary, env);
2006 ENV.with(|e| {
2007 if e.get() == env {
2008 return false;
2009 }
2010 e.set(env);
2011 true
2012 })
2013}
2014
2015pub fn set_window_env(k: crate::windows::WinKey, env: sk_css::Env) -> bool {
2016 let env = sk_css::Env {
2017 dynamic_range_high: crate::surface::dynamic_range_high(k),
2018 ..env
2019 };
2020 if !crate::windows::set_env(k, env) {
2021 return false;
2022 }
2023 let root = crate::windows::root_of(k);
2024 if root != 0 {
2025 with_tree(|t| t.mark_restyle_subtree(root));
2026 }
2027 true
2028}
2029
2030pub fn env() -> sk_css::Env {
2031 ENV.with(|e| e.get())
2032}
2033
2034pub fn animation_overlay(
2035 id: u32,
2036 base: &gpui::StyleRefinement,
2037 now: std::time::Instant,
2038) -> Option<gpui::StyleRefinement> {
2039 ANIMATOR.with(|a| a.borrow().overlay(id, base, now))
2040}
2041
2042pub fn animated_extras(id: u32, now: std::time::Instant) -> Option<sk_css::Extras> {
2043 ANIMATOR.with(|animator| animator.borrow().animated_extras(id, now))
2044}
2045
2046thread_local! {
2047 static HOVERED: RefCell<std::collections::HashSet<u32>> =
2050 RefCell::new(std::collections::HashSet::new());
2051}
2052
2053pub fn note_hover(id: u32, hovered: bool) {
2058 let changed = HOVERED.with(|h| {
2059 let mut h = h.borrow_mut();
2060 if hovered {
2061 h.insert(id)
2062 } else {
2063 h.remove(&id)
2064 }
2065 });
2066 if !changed {
2067 return;
2068 }
2069 let now = std::time::Instant::now();
2070 retarget_state(id, now);
2071 let deps = read_tree(|t| t.group_hover_deps.get(&id).cloned());
2072 for dep in deps.into_iter().flatten() {
2073 retarget_state(dep, now);
2074 }
2075}
2076
2077pub fn is_hovered(id: u32) -> bool {
2079 HOVERED.with(|h| h.borrow().contains(&id))
2080}
2081
2082pub fn live_style(id: u32) -> Option<gpui::StyleRefinement> {
2085 use gpui::Refineable as _;
2086 let cs = read_tree(|t| t.node(id).and_then(|n| n.computed.clone()))?;
2087 let mut live = (*cs.base).clone();
2088 if let Some(overlay) = animation_overlay(id, &cs.base, std::time::Instant::now()) {
2089 live.refine(&overlay);
2090 }
2091 if let Some(group) = &cs.group_focus {
2092 read_tree(|t| {
2093 group.fold(&mut live, |key, state| {
2094 crate::live_state::focus_holds(t, key as u32, state)
2095 })
2096 });
2097 }
2098 if let Some(rung) = fold_hover_target(id, &cs) {
2099 match sk_css::strip_transitioned(&rung, &cs.transitions) {
2100 Some(stripped) => live.refine(&stripped),
2101 None => live.refine(&rung),
2102 }
2103 }
2104 Some(live)
2105}
2106
2107fn fold_hover_target(id: u32, cs: &sk_css::ComputedStates) -> Option<gpui::StyleRefinement> {
2108 HOVERED.with(|h| {
2109 let h = h.borrow();
2110 let own = h.contains(&id);
2111 let group = cs
2112 .group_hover
2113 .as_ref()
2114 .is_some_and(|(key, _)| h.contains(&(*key as u32)));
2115 cs.hovered(own, group)
2116 })
2117}
2118
2119fn retarget_state(id: u32, now: std::time::Instant) {
2120 let Some(cs) = read_tree(|t| t.node(id).and_then(|n| n.computed.clone())) else {
2121 return;
2122 };
2123 if !cs.hover_transitions() {
2124 return;
2125 }
2126 let target = fold_hover_target(id, &cs);
2127 ANIMATOR.with(|a| a.borrow_mut().on_state(id, &cs, target.as_ref(), now));
2128}
2129
2130pub fn animating() -> bool {
2132 let now = std::time::Instant::now();
2133 ANIMATOR.with(|a| {
2134 let a = a.borrow();
2135 a.any_active(now) || a.any_animation(now)
2136 })
2137}
2138
2139pub(crate) fn moving_paths(now: std::time::Instant, out: &mut std::collections::HashSet<u32>) {
2142 ANIMATOR.with(|a| {
2143 let a = a.borrow();
2144 read_tree(|t| {
2145 for id in a.moving_nodes(now) {
2146 let mut cur = id;
2147 while cur != 0 && out.insert(cur) {
2148 cur = t.node(cur).map_or(0, |n| n.parent);
2149 }
2150 }
2151 });
2152 });
2153}
2154
2155pub(crate) fn moving_nodes(now: std::time::Instant, out: &mut std::collections::HashSet<u32>) {
2158 ANIMATOR.with(|a| out.extend(a.borrow().moving_nodes(now)));
2159}
2160
2161pub fn advance_animations() -> bool {
2165 let now = std::time::Instant::now();
2166 ANIMATOR.with(|a| {
2167 let mut a = a.borrow_mut();
2168 a.tick(now);
2171 a.finish_settled(now)
2172 })
2173}
2174
2175pub fn take_anim_events() -> Vec<sk_css::AnimEvent> {
2176 ANIMATOR.with(|a| a.borrow_mut().take_events())
2177}
2178
2179thread_local! {
2180 static SCRIPT_DIRTY: Cell<bool> = const { Cell::new(false) };
2181 static TIMELINE_ORIGIN: Cell<Option<std::time::Instant>> = const { Cell::new(None) };
2182}
2183
2184fn ensure_timeline_origin(animator: &mut sk_css::Animator) {
2187 if TIMELINE_ORIGIN.with(|o| o.get()).is_some() {
2188 return;
2189 }
2190 let now = std::time::Instant::now();
2191 let ms = unsafe { sk_runtime::redjs::ffi::redjs_now() };
2192 let origin = now
2193 .checked_sub(std::time::Duration::from_secs_f64(ms.max(0.0) / 1000.0))
2194 .unwrap_or(now);
2195 TIMELINE_ORIGIN.with(|o| o.set(Some(origin)));
2196 animator.set_timeline_origin(origin);
2197}
2198
2199fn script_touched(node: Option<u32>) {
2200 if let Some(node) = node {
2201 with_tree(|t| t.touch(node));
2202 }
2203 SCRIPT_DIRTY.with(|d| d.set(true));
2204}
2205
2206pub(crate) fn script_anim_set(
2209 id: u32,
2210 node: u32,
2211 frames: &[sk_css::ScriptFrame],
2212 timing: sk_css::ScriptTiming,
2213) -> sk_css::ScriptKeyframeNotes {
2214 let (vars, keywords) = read_tree(|t| {
2215 let own = t.node(node).and_then(|n| n.computed.as_ref());
2216 (
2217 own.map(|c| c.vars.clone()),
2218 crate::inherit::interpolate_keywords(
2219 t,
2220 node,
2221 own.and_then(|c| c.extras.interpolate_size),
2222 ),
2223 )
2224 });
2225 let vars = vars.unwrap_or_default();
2226 let (keyframes, notes) = with_engine(|engine| {
2227 let compile = || sk_css::script_keyframes(frames, &vars, &env());
2228 match engine {
2229 Some(engine) => engine.with_functions(compile),
2230 None => compile(),
2231 }
2232 });
2233 let previous = ANIMATOR.with(|a| {
2234 let mut a = a.borrow_mut();
2235 ensure_timeline_origin(&mut a);
2236 a.set_interpolate_keywords(node, keywords);
2237 let previous = a.script_node(id);
2238 a.script_set(id, node, keyframes, timing);
2239 previous
2240 });
2241 if previous.is_some_and(|p| p != node) {
2243 script_touched(previous);
2244 }
2245 script_touched(Some(node));
2246 notes
2247}
2248
2249pub(crate) fn script_anim_clock(id: u32, clock: sk_css::ScriptClock) {
2250 let node = ANIMATOR.with(|a| a.borrow_mut().script_clock(id, clock));
2251 script_touched(node);
2252}
2253
2254pub(crate) fn script_anim_drop(id: u32) {
2255 let node = ANIMATOR.with(|a| a.borrow_mut().script_drop(id));
2256 script_touched(node);
2257}
2258
2259pub(crate) fn script_anim_values(id: u32) -> Option<Vec<(String, String)>> {
2260 let now = std::time::Instant::now();
2261 ANIMATOR.with(|a| {
2262 let a = a.borrow();
2263 let node = a.script_node(id)?;
2264 let base = read_tree(|t| {
2265 t.node(node)
2266 .and_then(|n| n.computed.as_ref().map(|c| c.base.clone()))
2267 })
2268 .unwrap_or_default();
2269 a.script_values(id, &base, now)
2270 })
2271}
2272
2273pub(crate) fn take_script_dirty() -> bool {
2278 SCRIPT_DIRTY.with(|d| d.replace(false))
2279}
2280
2281pub(crate) fn with_sheet<R>(f: impl FnOnce(&sk_css::Engine) -> R) -> R {
2283 ENGINE.with(|e| match e.borrow().as_ref() {
2284 Some(engine) => f(engine),
2285 None => NO_SHEET.with(|engine| f(engine)),
2286 })
2287}
2288
2289pub(crate) fn animate_detached(id: u32, states: &sk_css::ComputedStates, now: std::time::Instant) {
2292 let env = env();
2293 let diagnostics = std::cell::RefCell::new(Vec::new());
2294 with_sheet(|engine| {
2295 ANIMATOR.with(|a| {
2296 a.borrow_mut()
2297 .on_computed_animations(id, states, now, &|name| {
2298 engine.keyframes_for(name, &states.vars, &env, &mut diagnostics.borrow_mut())
2299 });
2300 });
2301 });
2302 for d in diagnostics.into_inner() {
2303 warn_css(&format!("[css] {d}"));
2304 }
2305}
2306
2307pub(crate) fn animations_finished(id: u32, now: std::time::Instant) -> bool {
2308 ANIMATOR.with(|a| a.borrow().animations_finished(id, now))
2309}
2310
2311pub(crate) fn cancel_detached(id: u32) {
2312 let now = std::time::Instant::now();
2313 ANIMATOR.with(|a| a.borrow_mut().cancel_animations(id, now));
2314}
2315
2316pub fn animator_gc() {
2317 ANIMATOR.with(|a| {
2318 a.borrow_mut()
2319 .gc(&|id| crate::view_transition::is_pseudo(id) || read_tree(|t| t.node(id).is_some()));
2320 });
2321 HOVERED.with(|h| {
2324 let mut h = h.borrow_mut();
2325 if !h.is_empty() {
2326 read_tree(|t| h.retain(|&id| t.node(id).is_some()));
2327 }
2328 });
2329}
2330
2331pub fn set_reduce_motion(on: bool) {
2332 ANIMATOR.with(|a| a.borrow_mut().set_reduce_motion(on));
2333}
2334
2335fn sheet_sources() -> Vec<String> {
2340 let mut out = vec![SHEET_SOURCE.with(|s| s.borrow().clone())];
2341 HEAD_SHEETS.with(|h| out.extend(h.borrow().iter().cloned()));
2342 RUNTIME_CSS.with(|r| out.extend(r.borrow().iter().cloned()));
2343 out
2344}
2345
2346fn sync_runtime_sheets() {
2347 let next = with_tree(|t| {
2348 let mut placed: Vec<((bool, u32, Vec<usize>), u32)> = Vec::new();
2349 for &id in t.style_nodes.iter() {
2350 let mut ancestor = id;
2354 let mut path = Vec::new();
2355 let mut top = None;
2356 for _ in 0..4096 {
2357 if ancestor == t.root || crate::windows::window_of_root(ancestor).is_some() {
2358 top = Some(ancestor);
2359 break;
2360 }
2361 let Some(node) = t.node(ancestor) else { break };
2362 let Some(parent) = t.node(node.parent) else {
2363 break;
2364 };
2365 path.push(
2366 parent
2367 .children
2368 .iter()
2369 .position(|&c| c == ancestor)
2370 .unwrap_or(usize::MAX),
2371 );
2372 ancestor = node.parent;
2373 }
2374 let Some(top) = top else { continue };
2375 path.reverse();
2376 placed.push(((top != t.root, top, path), id));
2377 }
2378 placed.sort();
2379 let mut sheets = Vec::new();
2380 for (_, id) in placed {
2381 fn walk(t: &Tree, id: u32, out: &mut String) {
2382 let Some(n) = t.node(id) else { return };
2383 out.push_str(&n.text);
2384 for &c in &n.children {
2385 walk(t, c, out);
2386 }
2387 }
2388 let mut out = String::new();
2389 walk(t, id, &mut out);
2390 sheets.push(out);
2391 }
2392 sheets
2393 });
2394 if RUNTIME_CSS.with(|r| *r.borrow() == next) {
2395 return;
2396 }
2397 RUNTIME_CSS.with(|r| *r.borrow_mut() = next);
2398 recompile_sheet(
2401 crate::perf::FullReason::StyleElement,
2402 "a <style> element in the tree changed — recompiling the stylesheet",
2403 );
2404}
2405
2406#[cfg(test)]
2407pub(crate) fn set_stylesheet(css: String) {
2408 set_stylesheet_with_head(css, Vec::new());
2409}
2410
2411pub fn set_stylesheet_with_head(css: String, head: Vec<String>) -> bool {
2415 let same = ENGINE.with(|e| e.borrow().is_some())
2416 && SHEET_SOURCE.with(|s| *s.borrow() == css)
2417 && HEAD_SHEETS.with(|h| *h.borrow() == head);
2418 if same {
2419 return false;
2420 }
2421 let fresh = SHEET_SOURCE.with(|s| *s.borrow() != css);
2424 if fresh {
2425 CSS_WARNED.with(|w| w.borrow_mut().clear());
2426 }
2427 let before = crate::perf::live_bytes();
2428 SHEET_SOURCE.with(|s| *s.borrow_mut() = css);
2429 HEAD_SHEETS.with(|h| *h.borrow_mut() = head);
2430 let span = crate::perf::Span::start();
2431 let took = std::time::Instant::now();
2432 let sources = sheet_sources();
2433 let engine = compile(&sources);
2434 crate::perf::note_recompile(span.ms());
2435 set_engine(engine);
2436 let len = sources.iter().map(String::len).sum();
2437 drop(sources);
2438 crate::perf::note_sheet_compile(
2439 took.elapsed().as_secs_f32() * 1000.0,
2440 len,
2441 before,
2442 crate::perf::live_bytes(),
2443 );
2444 true
2445}
2446
2447fn compile(sources: &[String]) -> sk_css::Engine {
2450 crate::fonts::note_sheet(&sources.join("\n"));
2451 let sheets: Vec<&str> = sources.iter().map(String::as_str).collect();
2452 sk_css::Engine::compile_sheets(&sheets)
2453}
2454
2455pub(crate) fn recompile_for_fonts() {
2458 recompile_sheet(
2459 crate::perf::FullReason::Fonts,
2460 "web fonts were registered — recompiling the stylesheet",
2461 );
2462 with_tree(|t| {
2463 t.invalidate_font_inline();
2464 t.mark_dirty();
2465 });
2466}
2467
2468pub fn effects_changed() {
2473 recompile_sheet(
2474 crate::perf::FullReason::Stylesheet,
2475 "the app's `--shading` effects were rebuilt — recompiling the stylesheet",
2476 );
2477 with_tree(|t| {
2478 t.invalidate_inline_named(&["--shading"]);
2479 t.mark_dirty();
2480 });
2481}
2482
2483pub(crate) fn set_engine(engine: sk_css::Engine) {
2484 REBIND_ANIMATIONS.with(|pending| pending.set(true));
2487 for d in &engine.diagnostics {
2488 warn_css(&format!("[css] {d}"));
2489 }
2490 note_parent_keys(&engine);
2491 ENGINE.with(|c| *c.borrow_mut() = Some(engine));
2492 forget_read_cache();
2495}
2496
2497fn forget_read_cache() {
2498 READ_CACHE.with(|c| c.iter().for_each(|s| s.set((0, 0, 0))));
2499}
2500
2501fn note_parent_keys(engine: &sk_css::Engine) {
2505 READ_ON_OTHERS.with(|r| {
2506 let mut r = r.borrow_mut();
2507 let map = &mut r.names[NameKind::Class as usize];
2508 for name in engine.classes_keyed_on_the_parent() {
2509 let readers = match map.get_mut(name) {
2510 Some(readers) => readers,
2511 None => map.entry(name.into()).or_default(),
2512 };
2513 readers.all = true;
2514 readers.tags = Vec::new();
2515 }
2516 });
2517}
2518
2519pub(crate) fn with_engine<R>(f: impl FnOnce(Option<&sk_css::Engine>) -> R) -> R {
2520 ENGINE.with(|e| f(e.borrow().as_ref()))
2521}
2522
2523pub fn restyle_all() {
2527 let pending = read_tree(|t| t.dirty);
2528 sync_runtime_sheets();
2529 let env = env();
2530 let basis_moved = sk_css::set_viewport_basis(env.viewport_width, env.viewport_height);
2536 if basis_moved && sk_css::uses_viewport_units() {
2537 rebase_viewport(env.viewport_width, env.viewport_height);
2538 }
2539 if basis_moved {
2541 with_tree(|t| t.invalidate_viewport_inline());
2542 }
2543 if sk_css::uses_viewport_units() && crate::windows::any_secondary() {
2544 crate::render::warn_compat(
2545 "multiwindow-viewport-units",
2546 "A-M05: this stylesheet uses `vw`/`vh`/`rem`, which Skathi flattens to px when \
2547 the sheet is COMPILED — so those lengths resolve against the PRIMARY window's \
2548 viewport in every window, including pop-outs. `@media` conditions, `env()` and \
2549 `prefers-color-scheme` are already per-window.",
2550 );
2551 }
2552 let probe = || {
2560 ENGINE.with(|eng| {
2561 let eng = eng.borrow();
2562 read_tree(|t| t.probe_root_font_size(eng.as_ref(), &env))
2563 })
2564 };
2565 let mut earlier: Option<(f32, f32)> = None;
2566 for _ in 0..REM_BASIS_PASSES {
2567 let Some(root_font_size) = probe() else {
2568 break;
2569 };
2570 let basis = sk_css::rem_basis();
2571 if REM_SETTLED.with(Cell::get) == Some((basis, root_font_size)) {
2572 break;
2573 }
2574 let at_initial = earlier.and_then(|(b0, p0)| {
2575 let moved = (root_font_size - p0).abs() > 1e-3 && (basis - b0).abs() > 1e-3;
2576 moved.then(|| p0 + (root_font_size - p0) / (basis - b0) * (ROOT_PARENT_FONT_SIZE - b0))
2577 });
2578 earlier = Some((basis, root_font_size));
2579 let next = at_initial.unwrap_or(root_font_size);
2580 let moved = sk_css::set_rem_basis(next);
2581 if moved {
2582 with_tree(|t| t.invalidate_rem_inline());
2583 }
2584 let recompiled = moved
2585 && recompile_sheet(crate::perf::FullReason::RemBasis, &format!(
2586 "rem basis is now {next}px (the root element's font-size) — recompiling \n the stylesheet"
2587 ));
2588 if at_initial.is_some() {
2589 let settled = if recompiled {
2590 probe()
2591 } else {
2592 Some(root_font_size)
2593 };
2594 REM_SETTLED.with(|c| c.set(settled.map(|size| (sk_css::rem_basis(), size))));
2595 break;
2596 }
2597 REM_SETTLED.with(|c| c.set(None));
2598 if !recompiled {
2599 break;
2600 }
2601 }
2602 with_tree(|t| t.dirty = pending);
2605 ENGINE.with(|eng| {
2606 let eng = eng.borrow();
2607 with_tree(|t| t.restyle(eng.as_ref(), &env));
2608 });
2609}
2610
2611fn has_viewport_unit(value: &str) -> bool {
2612 const UNITS: [&str; 24] = [
2613 "vw", "vh", "vi", "vb", "vmin", "vmax", "svw", "svh", "svi", "svb", "svmin", "svmax",
2614 "lvw", "lvh", "lvi", "lvb", "lvmin", "lvmax", "dvw", "dvh", "dvi", "dvb", "dvmin", "dvmax",
2615 ];
2616 has_unit(value, &UNITS)
2617}
2618
2619fn has_rem_unit(value: &str) -> bool {
2620 has_unit(value, &["rem"])
2621}
2622
2623fn has_unit(value: &str, units: &[&str]) -> bool {
2624 let b = value.as_bytes();
2625 let mut i = 0;
2626 while i < b.len() {
2627 if b[i].is_ascii_digit() || (b[i] == b'.' && b.get(i + 1).is_some_and(u8::is_ascii_digit)) {
2628 while i < b.len() && (b[i].is_ascii_digit() || b[i] == b'.') {
2629 i += 1;
2630 }
2631 let start = i;
2632 while i < b.len() && b[i].is_ascii_alphabetic() {
2633 i += 1;
2634 }
2635 let unit = value[start..i].to_ascii_lowercase();
2636 if units.contains(&unit.as_str()) {
2637 return true;
2638 }
2639 } else if b[i].is_ascii_alphabetic()
2640 || b[i] == b'_'
2641 || (b[i] == b'-'
2642 && b.get(i + 1)
2643 .is_some_and(|c| c.is_ascii_alphabetic() || *c == b'-' || *c == b'_'))
2644 {
2645 while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'-' || b[i] == b'_') {
2647 i += 1;
2648 }
2649 } else {
2650 i += 1;
2651 }
2652 }
2653 false
2654}
2655
2656pub fn flush_pending_style() {
2661 let pending = with_tree(|t| {
2662 if !t.dirty {
2663 return false;
2664 }
2665 t.dirty = false;
2666 t.style_flushed = true;
2667 true
2668 });
2669 if pending {
2670 crate::perf::note_style_flush();
2671 restyle_all();
2672 crate::render::gc_node_state();
2673 animator_gc();
2674 }
2675}
2676
2677fn recompile_sheet(reason: crate::perf::FullReason, why: &str) -> bool {
2678 crate::log::record("dev", format!("[css] {why}"));
2681 let sources = sheet_sources();
2682 if sources.iter().all(|s| s.trim().is_empty()) {
2683 return false;
2684 }
2685 let before = crate::perf::live_bytes();
2686 let span = crate::perf::Span::start();
2687 let took = std::time::Instant::now();
2688 let engine = compile(&sources);
2689 crate::perf::note_recompile(span.ms());
2690 crate::perf::note_full(reason);
2691 set_engine(engine);
2692 let len = sources.iter().map(String::len).sum();
2693 drop(sources);
2694 crate::perf::note_sheet_compile(
2695 took.elapsed().as_secs_f32() * 1000.0,
2696 len,
2697 before,
2698 crate::perf::live_bytes(),
2699 );
2700 with_tree(|t| t.mark_dirty());
2701 true
2702}
2703
2704fn rebase_viewport(width: f32, height: f32) {
2708 let took = std::time::Instant::now();
2709 let rebased = ENGINE.with(|e| e.borrow_mut().as_mut().is_some_and(|e| e.rebase_viewport()));
2710 if !rebased {
2711 recompile_sheet(crate::perf::FullReason::ViewportBasis, &format!(
2712 "viewport basis is now {width}x{height}px — recompiling the stylesheet (it uses vh/vw units)"
2713 ));
2714 return;
2715 }
2716 crate::log::record("dev", format!(
2717 "[css] viewport basis is now {width}x{height}px — re-resolved the stylesheet's vh/vw rules ({:.1} ms)",
2718 took.elapsed().as_secs_f32() * 1000.0
2719 ));
2720 crate::perf::note_full(crate::perf::FullReason::ViewportBasis);
2721 with_tree(|t| t.mark_dirty());
2722}
2723
2724const REM_BASIS_PASSES: usize = 3;
2727
2728const ROOT_PARENT_FONT_SIZE: f32 = 16.0;
2729
2730#[derive(Clone, Debug, PartialEq)]
2731struct Inherited {
2732 color: Option<gpui::Hsla>,
2733 font_size: f32,
2734 font: gpui::Font,
2735}
2736
2737#[derive(Clone, Copy)]
2738pub struct NodeRef<'t> {
2739 pub tree: &'t Tree,
2740 pub id: u32,
2741}
2742
2743impl<'t> NodeRef<'t> {
2744 fn node(&self) -> &'t Node {
2745 self.tree
2746 .node(self.id)
2747 .expect("NodeRef points at a live node")
2748 }
2749
2750 fn element_sibling(&self, forward: bool) -> Option<NodeRef<'t>> {
2751 let parent = self.node().parent;
2752 if parent == 0 {
2753 return None;
2754 }
2755 let siblings = &self.tree.node(parent)?.children;
2756 let pos = siblings.iter().position(|&c| c == self.id)?;
2757 let range: Box<dyn Iterator<Item = u32>> = if forward {
2758 Box::new(siblings[pos + 1..].iter().copied())
2759 } else {
2760 Box::new(siblings[..pos].iter().rev().copied())
2761 };
2762 for id in range {
2763 if self.tree.node(id).is_some_and(|n| n.kind == Kind::Element) {
2764 return Some(NodeRef {
2765 tree: self.tree,
2766 id,
2767 });
2768 }
2769 }
2770 None
2771 }
2772
2773 fn note_sibling_question(&self, edge: u8, walk: u8) {
2774 let subject = CASCADE_SUBJECT.with(Cell::get);
2775 if subject == 0 {
2776 return;
2777 }
2778 let parent = self.node().parent;
2779 if let Some(p) = self.tree.node(parent) {
2780 let flag = if self.id == subject { edge } else { walk };
2781 p.sel_flags.set(p.sel_flags.get() | flag);
2782 }
2783 if self.id != subject {
2784 if let Some(s) = self.tree.node(subject) {
2785 if s.parent != parent {
2786 note_name_read(self.id, subject, s.tag, POSITION, NameKind::Position);
2787 }
2788 }
2789 }
2790 }
2791
2792 fn note_read(&self, name: &str, kind: NameKind) {
2793 let subject = CASCADE_SUBJECT.with(Cell::get);
2794 if subject == 0 || subject == self.id {
2795 return;
2796 }
2797 let tag = self.tree.node(subject).map_or(0, |n| n.tag);
2798 note_name_read(self.id, subject, tag, name, kind);
2799 }
2800
2801 fn note_content_question(&self, flag: u8) {
2807 let subject = CASCADE_SUBJECT.with(Cell::get);
2808 if subject == 0 {
2809 return;
2810 }
2811 let flag = match flag {
2812 sel::HAS if self.id == subject => sel::HAS_SELF,
2813 sel::HAS => sel::HAS_DESC,
2814 other => other,
2815 };
2816 let n = self.node();
2817 n.sel_flags.set(n.sel_flags.get() | flag);
2818 if flag & sel::HAS != 0 {
2819 self.tree.has_anchors.set(true);
2820 }
2821 }
2822}
2823
2824impl<'t> sk_css::MatchDom for NodeRef<'t> {
2825 fn key(&self) -> u64 {
2826 self.id as u64
2827 }
2828 fn parent(&self) -> Option<Self> {
2829 let p = self.node().parent;
2830 (p != 0).then(|| NodeRef {
2831 tree: self.tree,
2832 id: p,
2833 })
2834 }
2835 fn prev_sibling(&self) -> Option<Self> {
2836 self.note_sibling_question(sel::PREV_EDGE, sel::PREV_WALK);
2837 self.element_sibling(false)
2838 }
2839 fn next_sibling(&self) -> Option<Self> {
2840 self.note_sibling_question(sel::NEXT_EDGE, sel::NEXT_WALK);
2841 self.element_sibling(true)
2842 }
2843 fn note_following_sibling_anchor(&self) {
2846 if CASCADE_SUBJECT.with(Cell::get) == 0 {
2847 return;
2848 }
2849 self.note_content_question(sel::HAS);
2850 if let Some(p) = self.tree.node(self.node().parent) {
2851 p.sel_flags.set(p.sel_flags.get() | sel::HAS_NEXT);
2852 }
2853 }
2854 fn each_child(&self, f: &mut dyn FnMut(Self)) {
2855 fn walk<'t>(tree: &'t Tree, id: u32, f: &mut dyn FnMut(NodeRef<'t>)) {
2856 let Some(node) = tree.node(id) else { return };
2857 for &child in &node.children {
2858 match tree.node(child).map(|n| n.kind) {
2859 Some(Kind::Element) => f(NodeRef { tree, id: child }),
2860 Some(_) => walk(tree, child, f),
2861 None => {}
2862 }
2863 }
2864 }
2865 struct Restore(u32);
2866 impl Drop for Restore {
2867 fn drop(&mut self) {
2868 HAS_DEPTH.with(|d| d.set(self.0));
2869 }
2870 }
2871 let depth = HAS_DEPTH.with(|d| d.replace(d.get() + 1));
2872 let _restore = Restore(depth);
2873 if depth == 0 {
2874 self.note_content_question(sel::HAS);
2875 }
2876 walk(self.tree, self.id, f);
2877 }
2878 fn has_tag(&self, name: &str) -> bool {
2879 self.tree.name(self.node().tag) == name
2882 }
2883 fn tag_eq(&self, other: &Self) -> bool {
2884 self.node().tag == other.node().tag
2885 }
2886 fn has_class(&self, name: &str) -> bool {
2887 self.note_read(name, NameKind::Class);
2888 self.node().classes.iter().any(|c| c == name)
2889 }
2890 fn tag_name(&self) -> &str {
2891 self.tree.name(self.node().tag)
2892 }
2893 fn each_class(&self, f: &mut dyn FnMut(&str)) {
2894 for c in &self.node().classes {
2895 f(c);
2896 }
2897 }
2898 fn has_scope(&self, name: &str) -> bool {
2899 self.note_read(name, NameKind::Scope);
2900 self.node().scopes.iter().any(|s| s == name)
2901 }
2902 fn attr(&self, name: &str) -> Option<&str> {
2904 self.note_read(name, NameKind::Attr);
2905 if name == "class" {
2907 let raw = self.node().class_attr.as_str();
2908 return (!raw.is_empty()).then_some(raw);
2909 }
2910 let key = *self.tree.name_ids.get(name)?;
2911 self.node()
2912 .props
2913 .iter()
2914 .find(|(k, _, _)| *k == key)
2915 .map(|(_, v, _)| v.as_str())
2916 }
2917 fn is_empty(&self) -> bool {
2922 self.note_content_question(sel::EMPTY);
2923 self.tree.is_bare(self.id)
2924 }
2925 fn is_root(&self) -> bool {
2926 self.node().parent == 0
2927 }
2928}
2929
2930#[cfg(test)]
2931mod tests {
2932 use super::*;
2933
2934 #[test]
2935 fn a_mutation_bumps_the_subtree_revision_of_every_ancestor_and_of_nothing_else() {
2936 let (root, left, leaf, right) = with_tree(|t| {
2937 let root = t.create_root();
2938 let div = t.intern("div");
2939 let left = t.create_element(div);
2940 let leaf = t.create_element(div);
2941 let right = t.create_element(div);
2942 t.insert(left, root, 0);
2943 t.insert(leaf, left, 0);
2944 t.insert(right, root, 0);
2945 (root, left, leaf, right)
2946 });
2947 let before = read_tree(|t| {
2948 (
2949 t.sub_rev(root),
2950 t.sub_rev(left),
2951 t.sub_rev(leaf),
2952 t.sub_rev(right),
2953 )
2954 });
2955
2956 with_tree(|t| t.set_class(leaf, "hot"));
2957
2958 let after = read_tree(|t| {
2959 (
2960 t.sub_rev(root),
2961 t.sub_rev(left),
2962 t.sub_rev(leaf),
2963 t.sub_rev(right),
2964 )
2965 });
2966 assert!(after.0 > before.0, "the root is an ancestor of the change");
2967 assert!(after.1 > before.1, "so is the parent");
2968 assert!(after.2 > before.2, "and the node itself");
2969 assert_eq!(after.3, before.3, "the sibling subtree did not move");
2970 }
2971
2972 #[test]
2973 fn removing_a_child_bumps_the_parent() {
2974 let (parent, child) = with_tree(|t| {
2975 let root = t.create_root();
2976 let div = t.intern("div");
2977 let parent = t.create_element(div);
2978 let child = t.create_element(div);
2979 t.insert(parent, root, 0);
2980 t.insert(child, parent, 0);
2981 (parent, child)
2982 });
2983 let before = read_tree(|t| t.sub_rev(parent));
2984 with_tree(|t| t.remove(child));
2985 assert!(read_tree(|t| t.sub_rev(parent)) > before);
2986 }
2987
2988 #[test]
2989 fn the_cascade_touches_every_node_whose_fold_moved() {
2990 set_stylesheet(".on .leaf { opacity: 0.5 }".into());
2991 let (wrap, leaf, bystander) = with_tree(|t| {
2992 let root = t.create_root();
2993 let div = t.intern("div");
2994 let wrap = t.create_element(div);
2995 let leaf = t.create_element(div);
2996 let bystander = t.create_element(div);
2997 t.set_class(leaf, "leaf");
2998 t.insert(wrap, root, 0);
2999 t.insert(leaf, wrap, 0);
3000 t.insert(bystander, root, 0);
3001 (wrap, leaf, bystander)
3002 });
3003 restyle_all();
3004 let before = read_tree(|t| (t.sub_rev(leaf), t.sub_rev(bystander)));
3005
3006 with_tree(|t| t.set_class(wrap, "on"));
3007 restyle_all();
3008
3009 let after = read_tree(|t| (t.sub_rev(leaf), t.sub_rev(bystander)));
3010 assert_eq!(
3011 read_tree(|t| t
3012 .node(leaf)
3013 .and_then(|n| n.computed.as_ref())
3014 .and_then(|c| c.base.opacity)),
3015 Some(0.5),
3016 "the descendant combinator reached the leaf",
3017 );
3018 assert!(
3019 after.0 > before.0,
3020 "…so the leaf's subtree revision moved with it"
3021 );
3022 assert_eq!(after.1, before.1, "the bystander's fold did not move");
3023 }
3024
3025 #[test]
3029 fn a_runtime_style_element_reaches_the_cascade_and_recompiles_when_its_text_moves() {
3030 let opacity = |id: u32| {
3031 read_tree(|t| {
3032 t.node(id)
3033 .and_then(|n| n.computed.as_ref())
3034 .and_then(|c| c.base.opacity)
3035 })
3036 };
3037
3038 set_stylesheet(".probe { opacity: 0.25 }".into());
3039 let (probe, sheet) = with_tree(|t| {
3040 let root = t.create_root();
3041 let div = t.intern("div");
3042 let probe = t.create_element(div);
3043 t.set_class(probe, "probe");
3044 t.insert(probe, root, 0);
3045 let style_tag = t.intern("style");
3046 let sheet = t.create_element(style_tag);
3047 t.insert(sheet, root, 1);
3048 (probe, sheet)
3049 });
3050 restyle_all();
3051 assert_eq!(
3052 opacity(probe),
3053 Some(0.25),
3054 "the build's sheet, with an empty <style>"
3055 );
3056
3057 with_tree(|t| t.set_element_text(sheet, ".probe { opacity: 0.5 }".into()));
3059 restyle_all();
3060 assert_eq!(
3061 opacity(probe),
3062 Some(0.5),
3063 "a runtime <style> installs its rules"
3064 );
3065
3066 with_tree(|t| t.set_element_text(sheet, ".probe { opacity: 0.75 }".into()));
3067 restyle_all();
3068 assert_eq!(opacity(probe), Some(0.75), "changed text re-installs");
3069
3070 restyle_all();
3071 assert_eq!(
3072 opacity(probe),
3073 Some(0.75),
3074 "an unchanged sheet is not recompiled away"
3075 );
3076
3077 with_tree(|t| t.set_element_text(sheet, String::new()));
3078 restyle_all();
3079 assert_eq!(
3080 opacity(probe),
3081 Some(0.25),
3082 "removing the rules restores the build's sheet"
3083 );
3084 }
3085
3086 #[test]
3087 fn runtime_sheets_are_in_document_order() {
3088 set_stylesheet(String::new());
3089 with_tree(|t| {
3090 let root = t.create_root();
3091 let style = t.intern("style");
3092 let older = t.create_element(style);
3093 t.set_element_text(older, ".a { opacity: 0.5 }".into());
3094 t.insert(older, root, 0);
3095 let newer = t.create_element(style);
3096 t.set_element_text(newer, ".b { opacity: 0.5 }".into());
3097 t.insert(newer, root, older);
3098 });
3099 restyle_all();
3100 let sheets = RUNTIME_CSS.with(|r| r.borrow().clone());
3101 assert_eq!(
3102 sheets,
3103 vec![
3104 ".b { opacity: 0.5 }".to_string(),
3105 ".a { opacity: 0.5 }".to_string()
3106 ]
3107 );
3108 }
3109
3110 fn runtime_sheet_probe() -> (u32, u32, u32, u32) {
3111 set_stylesheet(".probe { opacity: 0.25 }".into());
3112 with_tree(|t| {
3113 let root = t.create_root();
3114 let div = t.intern("div");
3115 let probe = t.create_element(div);
3116 t.set_class(probe, "probe");
3117 t.insert(probe, root, 0);
3118 let detached = t.create_anchor();
3119 let style = t.intern("style");
3120 let sheet = t.create_element(style);
3121 t.set_element_text(sheet, ".probe { opacity: 0.75 }".into());
3122 t.insert(sheet, detached, 0);
3123 (root, probe, detached, sheet)
3124 })
3125 }
3126
3127 fn runtime_sheet_opacity(node: u32) -> Option<f32> {
3128 read_tree(|t| {
3129 t.node(node)
3130 .unwrap()
3131 .computed
3132 .as_ref()
3133 .unwrap()
3134 .base
3135 .opacity
3136 })
3137 }
3138
3139 #[test]
3140 fn detached_fragment_styles_are_inert_until_connected_and_stop_on_detach() {
3141 let (root, probe, fragment, sheet) = runtime_sheet_probe();
3142 restyle_all();
3143 assert_eq!(
3144 runtime_sheet_opacity(probe),
3145 Some(0.25),
3146 "closed Select fragments install no rules"
3147 );
3148
3149 with_tree(|t| t.insert(fragment, root, 0));
3150 restyle_all();
3151 assert_eq!(
3152 runtime_sheet_opacity(probe),
3153 Some(0.75),
3154 "connecting the fragment activates its style"
3155 );
3156
3157 with_tree(|t| {
3158 let other_fragment = t.create_anchor();
3159 t.insert(fragment, other_fragment, 0);
3160 });
3161 restyle_all();
3162 assert_eq!(
3163 runtime_sheet_opacity(probe),
3164 Some(0.25),
3165 "detaching removes its rules without freeing the style"
3166 );
3167
3168 with_tree(|t| t.set_element_text(sheet, ".probe { opacity: 0.9 }".into()));
3169 restyle_all();
3170 assert_eq!(
3171 runtime_sheet_opacity(probe),
3172 Some(0.25),
3173 "editing detached CSS remains inert"
3174 );
3175 }
3176
3177 #[test]
3178 fn runtime_styles_in_a_painted_secondary_root_remain_connected() {
3179 let (_, probe, secondary_root, _) = runtime_sheet_probe();
3180 restyle_all();
3181 assert_eq!(runtime_sheet_opacity(probe), Some(0.25));
3182
3183 crate::windows::set_painted_root(9001, secondary_root);
3184 restyle_all();
3185 assert_eq!(
3186 runtime_sheet_opacity(probe),
3187 Some(0.75),
3188 "SkWindow styles share the live document cascade"
3189 );
3190
3191 crate::windows::set_painted_root(9001, 0);
3192 restyle_all();
3193 assert_eq!(
3194 runtime_sheet_opacity(probe),
3195 Some(0.25),
3196 "unpainting a detached root deactivates its style"
3197 );
3198 crate::windows::forget(9001);
3199 }
3200
3201 #[test]
3202 fn empty_ignores_vue_anchors_and_empty_text() {
3203 let opacity = |id: u32| {
3204 read_tree(|t| {
3205 t.node(id)
3206 .and_then(|n| n.computed.as_ref())
3207 .and_then(|c| c.base.opacity)
3208 })
3209 };
3210 set_stylesheet(".box:empty { opacity: 0.5 }".into());
3211 let (bare, anchored, texted, text) = with_tree(|t| {
3212 let root = t.create_root();
3213 let div = t.intern("div");
3214 let mut boxed = || {
3215 let b = t.create_element(div);
3216 t.set_class(b, "box");
3217 t.insert(b, root, 0);
3218 b
3219 };
3220 let (bare, anchored, texted) = (boxed(), boxed(), boxed());
3221 for _ in 0..2 {
3222 let a = t.create_anchor();
3223 t.insert(a, anchored, 0);
3224 }
3225 let start = t.create_text();
3226 t.insert(start, anchored, 0);
3227 let text = t.create_text();
3228 t.insert(text, texted, 0);
3229 (bare, anchored, texted, text)
3230 });
3231 restyle_all();
3232 assert_eq!(opacity(bare), Some(0.5), "no children");
3233 assert_eq!(
3234 opacity(anchored),
3235 Some(0.5),
3236 "anchors and an empty text node only"
3237 );
3238 assert_eq!(opacity(texted), Some(0.5), "a text node with no data");
3239
3240 with_tree(|t| t.set_text(text, " ".into()));
3241 restyle_all();
3242 assert_eq!(opacity(texted), None, "text with data, whitespace included");
3243 with_tree(|t| t.set_text(text, String::new()));
3244 restyle_all();
3245 assert_eq!(opacity(texted), Some(0.5), "and empty again");
3246
3247 with_tree(|t| {
3248 let span = t.intern("span");
3249 let child = t.create_element(span);
3250 t.insert(child, anchored, 0);
3251 });
3252 restyle_all();
3253 assert_eq!(opacity(anchored), None, "an element child");
3254 }
3255
3256 #[test]
3257 fn a_viewport_unit_is_a_dimension_token_not_a_substring() {
3258 for yes in [
3259 "100vw",
3260 "100svh",
3261 "calc(100vh - 2rem)",
3262 "-5vh",
3263 "-.5vmin",
3264 "85DVH",
3265 "min(50vw, 40rem)",
3266 "1.5lvmax",
3267 ] {
3268 assert!(has_viewport_unit(yes), "{yes:?}");
3269 }
3270 for no in [
3271 "10px",
3272 "var(--x9vw)",
3273 "abc12vh",
3274 "2rem",
3275 "",
3276 "50%",
3277 "url(a1vw.png)",
3278 "100v",
3279 "3vws",
3280 ] {
3281 assert!(!has_viewport_unit(no), "{no:?}");
3282 }
3283 }
3284
3285 #[test]
3286 fn inline_viewport_units_and_var_composed_ones_follow_the_viewport() {
3287 fn px(l: Option<gpui::Length>) -> Option<f32> {
3288 match l? {
3289 gpui::Length::Definite(gpui::DefiniteLength::Absolute(
3290 gpui::AbsoluteLength::Pixels(p),
3291 )) => Some(f32::from(p)),
3292 _ => None,
3293 }
3294 }
3295 let size = |id: u32| {
3296 read_tree(|t| {
3297 let cs = t.node(id)?.computed.as_ref()?;
3298 Some((px(cs.base.size.width), px(cs.base.size.height)))
3299 })
3300 };
3301 let resize = |w: f32, h: f32| {
3302 if set_env(sk_css::Env {
3303 viewport_width: w,
3304 viewport_height: h,
3305 ..sk_css::Env::default()
3306 }) {
3307 with_tree(|t| t.mark_dirty());
3308 }
3309 restyle_all();
3310 };
3311 resize(1652.0, 633.0);
3312 let (shell, child, plain) = with_tree(|t| {
3313 let root = t.create_root();
3314 let div = t.intern("div");
3315 let (width, height, var) = (t.intern("width"), t.intern("height"), t.intern("--w"));
3316 let shell = t.create_element(div);
3317 t.insert(shell, root, 0);
3318 t.set_style(shell, width, "100svw".into());
3319 t.set_style(shell, height, "100svh".into());
3320 let parent = t.create_element(div);
3321 t.insert(parent, root, 1);
3322 t.set_style(parent, var, "50vw".into());
3323 let child = t.create_element(div);
3324 t.insert(child, parent, 0);
3325 t.set_style(child, width, "var(--w)".into());
3326 let plain = t.create_element(div);
3327 t.insert(plain, root, 2);
3328 t.set_style(plain, width, "40px".into());
3329 (shell, child, plain)
3330 });
3331 restyle_all();
3332 assert_eq!(size(shell), Some((Some(1652.0), Some(633.0))));
3333 assert_eq!(size(child).and_then(|s| s.0), Some(826.0));
3334
3335 resize(1700.0, 800.0);
3336 assert_eq!(
3337 size(shell),
3338 Some((Some(1700.0), Some(800.0))),
3339 "the inline svw/svh re-resolved"
3340 );
3341 assert_eq!(
3342 size(child).and_then(|s| s.0),
3343 Some(850.0),
3344 "and the var()-composed vw with it"
3345 );
3346 assert_eq!(size(plain).and_then(|s| s.0), Some(40.0));
3347
3348 assert!(sk_css::set_viewport_basis(1000.0, 500.0));
3350 let marked = with_tree(|t| t.invalidate_viewport_inline());
3351 assert_eq!(
3352 marked, 2,
3353 "the shell and the --w parent; never the px-only node"
3354 );
3355 ENGINE.with(|eng| with_tree(|t| t.restyle(eng.borrow().as_ref(), &env())));
3356 assert_eq!(size(shell), Some((Some(1000.0), Some(500.0))));
3357 assert_eq!(size(child).and_then(|s| s.0), Some(500.0));
3358 }
3359
3360 #[test]
3361 fn sheet_viewport_units_follow_the_viewport() {
3362 let width = |id: u32| {
3363 read_tree(|t| match t.node(id)?.computed.as_ref()?.base.size.width? {
3364 gpui::Length::Definite(gpui::DefiniteLength::Absolute(
3365 gpui::AbsoluteLength::Pixels(p),
3366 )) => Some(f32::from(p)),
3367 _ => None,
3368 })
3369 };
3370 let resize = |w: f32, h: f32| {
3371 if set_env(sk_css::Env {
3372 viewport_width: w,
3373 viewport_height: h,
3374 ..sk_css::Env::default()
3375 }) {
3376 with_tree(|t| t.mark_dirty());
3377 }
3378 restyle_all();
3379 };
3380 resize(1000.0, 800.0);
3381 assert!(set_stylesheet_with_head(
3382 ".box, .wide { width: 50vw } .wide { min-height: 10vh }".into(),
3383 vec![]
3384 ));
3385 let (bx, wide) = with_tree(|t| {
3386 let root = t.create_root();
3387 let div = t.intern("div");
3388 let bx = t.create_element(div);
3389 t.insert(bx, root, 0);
3390 t.set_class(bx, "box");
3391 let wide = t.create_element(div);
3392 t.insert(wide, root, 1);
3393 t.set_class(wide, "wide");
3394 t.mark_dirty();
3395 (bx, wide)
3396 });
3397 restyle_all();
3398 assert_eq!((width(bx), width(wide)), (Some(500.0), Some(500.0)));
3399 resize(1200.0, 800.0);
3400 assert_eq!(
3401 (width(bx), width(wide)),
3402 (Some(600.0), Some(600.0)),
3403 "rebased"
3404 );
3405
3406 assert!(set_stylesheet_with_head(
3407 ".box, .wide { width: 50vw } @keyframes k { from { height: 10vh } }".into(),
3408 vec![]
3409 ));
3410 with_tree(|t| t.mark_dirty());
3411 restyle_all();
3412 resize(800.0, 800.0);
3413 assert_eq!(
3414 (width(bx), width(wide)),
3415 (Some(400.0), Some(400.0)),
3416 "recompiled"
3417 );
3418 sk_css::set_viewport_basis(
3419 sk_css::INITIAL_VIEWPORT_BASIS.0,
3420 sk_css::INITIAL_VIEWPORT_BASIS.1,
3421 );
3422 }
3423
3424 #[test]
3425 fn an_unchanged_sheet_resent_compiles_nothing() {
3426 assert!(set_stylesheet_with_head(
3427 ".a { opacity: 0.5 }".into(),
3428 vec![".b {}".into()]
3429 ));
3430 assert!(!set_stylesheet_with_head(
3431 ".a { opacity: 0.5 }".into(),
3432 vec![".b {}".into()]
3433 ));
3434 assert!(set_stylesheet_with_head(
3435 ".a { opacity: 0.5 }".into(),
3436 vec![".b {}".into(), ".c {}".into()]
3437 ));
3438 assert!(set_stylesheet_with_head(
3439 ".a { opacity: 0.6 }".into(),
3440 vec![".b {}".into(), ".c {}".into()]
3441 ));
3442 assert_eq!(
3443 sheet_sources(),
3444 vec![
3445 ".a { opacity: 0.6 }".to_string(),
3446 ".b {}".into(),
3447 ".c {}".into()
3448 ],
3449 "the build's sheet, then each head text on its own"
3450 );
3451 }
3452
3453 fn flush_motion_styles() {
3454 with_tree(|t| t.mark_dirty());
3455 restyle_all();
3456 }
3457
3458 fn motion_probe(sheet: &str) -> (u32, std::time::Instant) {
3459 set_stylesheet(sheet.into());
3460 let node = with_tree(|t| {
3461 let root = t.create_root();
3462 let div = t.intern("div");
3463 let node = t.create_element(div);
3464 t.set_class(node, "motion");
3465 t.insert(node, root, 0);
3466 node
3467 });
3468 flush_motion_styles();
3469 let start = std::time::Instant::now();
3470 ANIMATOR.with(|a| a.borrow_mut().tick(start));
3471 let _ = take_anim_events();
3472 (node, start)
3473 }
3474
3475 fn motion_opacity_at(node: u32, at: std::time::Instant) -> Option<f32> {
3476 let base = read_tree(|t| {
3477 t.node(node)
3478 .unwrap()
3479 .computed
3480 .as_ref()
3481 .unwrap()
3482 .base
3483 .clone()
3484 });
3485 animation_overlay(node, &base, at).and_then(|style| style.opacity)
3486 }
3487
3488 #[test]
3489 fn late_stylesheet_and_font_recompile_preserve_a_running_animation_clock() {
3490 let sheet = "@keyframes enter { from { opacity: 0 } to { opacity: 1 } } \
3491 .motion { animation: enter 500ms linear }";
3492 let (node, start) = motion_probe(sheet);
3493 let at = start + std::time::Duration::from_millis(200);
3494 assert!((motion_opacity_at(node, at).unwrap() - 0.4).abs() < 1e-5);
3495
3496 assert!(set_stylesheet_with_head(
3497 sheet.into(),
3498 vec![".late-panel { color: red }".into()]
3499 ));
3500 flush_motion_styles();
3501 assert!(
3502 (motion_opacity_at(node, at).unwrap() - 0.4).abs() < 1e-5,
3503 "unrelated CSS must retain the elapsed clock, not drop/restart the run"
3504 );
3505
3506 recompile_for_fonts();
3507 flush_motion_styles();
3508 assert!(
3509 (motion_opacity_at(node, at).unwrap() - 0.4).abs() < 1e-5,
3510 "registering a font must not erase the running animation"
3511 );
3512 }
3513
3514 #[test]
3515 fn changed_keyframes_rebind_at_the_existing_clock_and_deleted_keyframes_cancel() {
3516 let sheet = "@keyframes enter { from { opacity: 0 } to { opacity: 1 } } \
3517 .motion { animation: enter 500ms linear }";
3518 let (node, start) = motion_probe(sheet);
3519 let at = start + std::time::Duration::from_millis(200);
3520 set_stylesheet(sheet.replace("opacity: 1", "opacity: 0.5"));
3521 flush_motion_styles();
3522 assert!(
3523 (motion_opacity_at(node, at).unwrap() - 0.2).abs() < 1e-5,
3524 "same-name definition changes sample new frames on the existing timeline"
3525 );
3526
3527 set_stylesheet(".motion { animation: enter 500ms linear }".into());
3528 flush_motion_styles();
3529 assert!(
3530 motion_opacity_at(node, at).is_none(),
3531 "deleted frames must not keep painting"
3532 );
3533 let events = take_anim_events();
3534 assert_eq!(
3535 events
3536 .iter()
3537 .filter(|event| event.node == node
3538 && event.kind == sk_css::AnimEventKind::AnimationCancel)
3539 .count(),
3540 1
3541 );
3542 }
3543
3544 #[test]
3545 fn removing_the_animation_and_last_keyframes_cancels_the_old_run() {
3546 let (node, start) = motion_probe(
3547 "@keyframes enter { from { opacity: 0 } to { opacity: 1 } } \
3548 .motion { animation: enter 500ms linear }",
3549 );
3550 set_stylesheet(".motion { opacity: 1 }".into());
3551 flush_motion_styles();
3552 assert!(motion_opacity_at(node, start).is_none());
3553 assert!(take_anim_events().iter().any(
3554 |event| event.node == node && event.kind == sk_css::AnimEventKind::AnimationCancel
3555 ));
3556 }
3557
3558 #[test]
3559 fn unrelated_stylesheet_preserves_a_running_transition_clock() {
3560 let sheet = ".motion { opacity: 0; transition: opacity 500ms linear } \
3561 .motion.open { opacity: 1 }";
3562 let (node, _) = motion_probe(sheet);
3563 with_tree(|t| t.set_class(node, "motion open"));
3564 flush_motion_styles();
3565 let start = std::time::Instant::now();
3566 let at = start + std::time::Duration::from_millis(200);
3567 let before = motion_opacity_at(node, at).unwrap();
3568 assert!(before > 0.39 && before < 0.42, "{before}");
3569 assert!(set_stylesheet_with_head(
3570 sheet.into(),
3571 vec![".late-panel { color: red }".into()]
3572 ));
3573 flush_motion_styles();
3574 assert!(
3575 (motion_opacity_at(node, at).unwrap() - before).abs() < 1e-5,
3576 "a late sheet must not snap or restart an unrelated transition"
3577 );
3578 }
3579
3580 #[test]
3583 fn a_rem_recompile_at_boot_starts_no_transition() {
3584 set_stylesheet(".card { padding: 1.5rem; transition: all 300ms }".into());
3585 let card = with_tree(|t| {
3586 let root = t.create_root();
3587 let font_size = t.intern("font-size");
3590 t.set_style(root, font_size, "14px".into());
3591 let div = t.intern("div");
3592 let card = t.create_element(div);
3593 t.set_class(card, "card");
3594 t.insert(card, root, 0);
3595 card
3596 });
3597
3598 let probed = ENGINE.with(|eng| {
3599 let eng = eng.borrow();
3600 read_tree(|t| t.probe_root_font_size(eng.as_ref(), &env()))
3601 });
3602 assert_eq!(
3603 probed,
3604 Some(14.0),
3605 "the root's own inline font-size, without a cascade"
3606 );
3607 assert!(
3608 read_tree(|t| t.node(t.root).is_some_and(|n| n.computed.is_none())),
3609 "probing the basis must not commit a computed style"
3610 );
3611
3612 restyle_all();
3613 assert_eq!(
3614 sk_css::rem_basis(),
3615 14.0,
3616 "the sheet was recompiled against the root"
3617 );
3618
3619 let padding = read_tree(|t| {
3620 t.node(card)
3621 .and_then(|n| n.computed.as_ref())
3622 .and_then(|c| c.base.padding.top)
3623 });
3624 assert_eq!(
3625 padding,
3626 Some(gpui::DefiniteLength::Absolute(
3627 gpui::AbsoluteLength::Pixels(gpui::px(21.0))
3628 )),
3629 "the ONE committed cascade ran under the settled basis"
3630 );
3631
3632 let base = read_tree(|t| {
3633 t.node(card)
3634 .and_then(|n| n.computed.as_ref())
3635 .map(|c| c.base.clone())
3636 })
3637 .expect("the card is cascaded");
3638 assert!(
3639 animation_overlay(card, &base, std::time::Instant::now()).is_none(),
3640 "a basis recompile is not a style change, so no transition runs across it"
3641 );
3642 }
3643
3644 #[test]
3645 fn several_style_elements_concatenate_in_document_order() {
3646 let opacity = |id: u32| {
3647 read_tree(|t| {
3648 t.node(id)
3649 .and_then(|n| n.computed.as_ref())
3650 .and_then(|c| c.base.opacity)
3651 })
3652 };
3653 set_stylesheet(String::new());
3654 let probe = with_tree(|t| {
3655 let root = t.create_root();
3656 let div = t.intern("div");
3657 let probe = t.create_element(div);
3658 t.set_class(probe, "probe");
3659 t.insert(probe, root, 0);
3660 let style_tag = t.intern("style");
3661 for css in [".probe { opacity: 0.1 }", ".probe { opacity: 0.9 }"] {
3662 let sheet = t.create_element(style_tag);
3663 t.set_element_text(sheet, css.into());
3664 t.insert(sheet, root, 0);
3665 }
3666 probe
3667 });
3668 restyle_all();
3669 assert_eq!(
3670 opacity(probe),
3671 Some(0.9),
3672 "the later sheet wins at equal specificity"
3673 );
3674 }
3675
3676 fn cascaded_comb(n: usize) -> (u32, Vec<u32>, Vec<u32>) {
3677 let ids = with_tree(|t| {
3678 let root = t.create_root();
3679 let div = t.intern("div");
3680 let mut kids = Vec::new();
3681 let mut grandkids = Vec::new();
3682 for _ in 0..n {
3683 let kid = t.create_element(div);
3684 let grandkid = t.create_element(div);
3685 t.insert(grandkid, kid, 0);
3686 t.insert(kid, root, 0);
3687 kids.push(kid);
3688 grandkids.push(grandkid);
3689 }
3690 (root, kids, grandkids)
3691 });
3692 restyle_all();
3693 ids
3694 }
3695
3696 fn roots_of() -> Vec<u32> {
3697 let mut roots = with_tree(|t| t.restyle_roots());
3698 roots.sort_unstable();
3699 roots
3700 }
3701
3702 #[test]
3703 fn hundreds_of_separate_marks_stay_a_scoped_pass() {
3704 let (_, _, grandkids) = cascaded_comb(300);
3705 with_tree(|t| {
3706 for &g in &grandkids {
3707 t.mark_restyle_subtree(g);
3708 }
3709 });
3710 let mut want = grandkids.clone();
3711 want.sort_unstable();
3712 assert_eq!(roots_of(), want);
3713 assert!(roots_of().is_empty());
3714 }
3715
3716 #[test]
3717 fn a_mark_under_a_marked_ancestor_is_not_walked_twice() {
3718 let (_, kids, grandkids) = cascaded_comb(3);
3719 with_tree(|t| {
3720 t.mark_restyle_subtree(grandkids[1]);
3721 t.mark_restyle_subtree(kids[1]);
3722 });
3723 assert_eq!(roots_of(), vec![kids[1]]);
3724 }
3725
3726 #[test]
3727 fn marks_in_a_parentless_container_are_found_and_follow_a_move() {
3728 let (_, kids, _) = cascaded_comb(2);
3729 let (cache, kept) = with_tree(|t| {
3730 let div = t.intern("div");
3731 let cache = t.create_element(div);
3732 let kept = t.create_element(div);
3733 t.insert(kept, cache, 0);
3734 (cache, kept)
3735 });
3736 restyle_all();
3737 with_tree(|t| t.mark_restyle_subtree(kept));
3738 assert_eq!(roots_of(), vec![kept]);
3739
3740 with_tree(|t| {
3741 t.mark_restyle_subtree(kept);
3742 t.insert(kept, kids[0], 0);
3743 });
3744 assert_eq!(roots_of(), vec![kept]);
3745 let _ = cache;
3746 }
3747
3748 #[test]
3749 fn an_append_walks_the_new_child_and_not_its_siblings() {
3750 let (root, kids, _) = cascaded_comb(50);
3751 let added = with_tree(|t| {
3752 let div = t.intern("div");
3753 let added = t.create_element(div);
3754 t.insert(added, root, 0);
3755 added
3756 });
3757 assert_eq!(roots_of(), vec![added]);
3758 let _ = kids;
3759 }
3760
3761 #[test]
3764 fn a_root_has_anchor_is_rechecked_not_walked() {
3765 let sheet = "body:has([data-x]) { opacity: 0.5 }";
3766 set_engine(sk_css::Engine::compile(sheet));
3767 let (root, _, grandkids) = cascaded_comb(3);
3768 assert!(
3769 read_tree(|t| t.node(root).unwrap().sel_flags.get() & sel::HAS_SELF != 0),
3770 "the root asked `:has()` of itself"
3771 );
3772 let engine = sk_css::Engine::compile(sheet);
3773 let env = env();
3774
3775 let settled_ids = |engine: &sk_css::Engine| {
3776 with_tree(|t| t.settle_self_marks(engine, &env))
3777 .into_iter()
3778 .map(|(id, _)| id)
3779 .collect::<Vec<_>>()
3780 };
3781
3782 with_tree(|t| t.set_class(grandkids[1], "x"));
3783 assert!(settled_ids(&engine).is_empty());
3784 assert!(roots_of().is_empty(), "no walk at all");
3785
3786 let x = with_tree(|t| t.intern("data-x"));
3787 with_tree(|t| t.set_prop(grandkids[0], x, Some(String::new())));
3788 assert_eq!(settled_ids(&engine), vec![root]);
3789 assert!(roots_of().is_empty(), "no walk at all");
3790 }
3791
3792 #[test]
3793 fn a_following_sibling_has_anchor_is_rechecked_when_that_sibling_changes() {
3794 let sheet = "div:has(+ [data-x]) { opacity: 0.5 }";
3795 set_engine(sk_css::Engine::compile(sheet));
3796 let (root, kids, _) = cascaded_comb(2);
3797 assert!(
3798 read_tree(|t| t.node(root).unwrap().sel_flags.get() & sel::HAS_NEXT != 0),
3799 "a child asked `:has(+ …)`"
3800 );
3801 let engine = sk_css::Engine::compile(sheet);
3802 let env = env();
3803 let x = with_tree(|t| t.intern("data-x"));
3804 with_tree(|t| t.set_prop(kids[1], x, Some(String::new())));
3805 let settled: Vec<u32> = with_tree(|t| t.settle_self_marks(&engine, &env))
3806 .into_iter()
3807 .map(|(id, _)| id)
3808 .collect();
3809 assert!(
3810 settled.contains(&kids[0]),
3811 "the earlier sibling's answer moved: {settled:?}"
3812 );
3813 }
3814
3815 #[test]
3816 fn a_text_node_filling_up_rechecks_the_has_anchor_that_reads_empty() {
3817 let sheet = ".card:has(span:empty) { opacity: 0.5 }";
3818 set_engine(sk_css::Engine::compile(sheet));
3819 let (card, text) = with_tree(|t| {
3820 let root = t.create_root();
3821 let (div, span) = (t.intern("div"), t.intern("span"));
3822 let card = t.create_element(div);
3823 t.set_class(card, "card");
3824 let badge = t.create_element(span);
3825 let text = t.create_text();
3826 t.insert(text, badge, 0);
3827 t.insert(badge, card, 0);
3828 t.insert(card, root, 0);
3829 (card, text)
3830 });
3831 restyle_all();
3832 let engine = sk_css::Engine::compile(sheet);
3833 let env = env();
3834 with_tree(|t| t.set_text(text, "3".into()));
3835 let settled = with_tree(|t| t.settle_self_marks(&engine, &env));
3836 let card_now = settled
3837 .iter()
3838 .find(|(id, _)| *id == card)
3839 .map(|(_, s)| s.base.opacity);
3840 assert_eq!(
3841 card_now,
3842 Some(None),
3843 "the badge has text now: {:?}",
3844 settled.iter().map(|s| s.0).collect::<Vec<_>>()
3845 );
3846 }
3847
3848 #[test]
3849 fn a_prop_set_again_after_a_removal_has_a_new_write_count() {
3850 let (id, value) = with_tree(|t| {
3851 t.create_root();
3852 let input = t.intern("input");
3853 let id = t.create_element(input);
3854 (id, t.intern("value"))
3855 });
3856 let write = |v: Option<&str>| {
3857 with_tree(|t| t.set_prop(id, value, v.map(str::to_string)));
3858 read_tree(|t| t.prop_write(id, "value").map(|(_, write)| write))
3859 };
3860 let first = write(Some("a")).unwrap();
3861 assert_ne!(
3862 write(Some("a")).unwrap(),
3863 first,
3864 "the same string again is still a write"
3865 );
3866 assert_eq!(write(None), None);
3867 assert_ne!(write(Some("a")).unwrap(), first);
3868 }
3869
3870 #[test]
3871 fn a_class_read_only_by_its_own_element_restyles_that_element_alone() {
3872 let sheet = ".hot { opacity: 0.5 } .on .leaf { opacity: 0.25 }";
3873 set_engine(sk_css::Engine::compile(sheet));
3874 let (root, kids, grandkids) = with_tree(|t| {
3875 let root = t.create_root();
3876 let div = t.intern("div");
3877 let kid = t.create_element(div);
3878 let leaf = t.create_element(div);
3879 t.set_class(leaf, "leaf");
3880 t.insert(leaf, kid, 0);
3881 t.insert(kid, root, 0);
3882 (root, vec![kid], vec![leaf])
3883 });
3884 restyle_all();
3885 let engine = sk_css::Engine::compile(sheet);
3886 let env = env();
3887
3888 with_tree(|t| t.set_class(kids[0], "hot"));
3889 let settled = with_tree(|t| t.settle_self_marks(&engine, &env));
3890 assert_eq!(settled.len(), 1);
3891 assert_eq!(settled[0].0, kids[0]);
3892 assert_eq!(settled[0].1.base.opacity, Some(0.5));
3893 assert!(roots_of().is_empty(), "the subtree is not walked");
3894
3895 with_tree(|t| t.set_class(kids[0], "hot on"));
3896 let settled = with_tree(|t| t.settle_self_marks(&engine, &env));
3897 assert_eq!(
3898 settled.iter().map(|s| s.0).collect::<Vec<_>>(),
3899 vec![kids[0]]
3900 );
3901 assert_eq!(roots_of(), vec![grandkids[0]]);
3902 let _ = root;
3903 }
3904
3905 #[test]
3906 fn a_moved_sibling_is_restyled_alone_with_the_elements_that_read_its_place() {
3907 let sheet = ".row:nth-child(2) { opacity: 0.5 } .row:first-child .cell { opacity: 0.25 }";
3908 set_engine(sk_css::Engine::compile(sheet));
3909 let (list, rows, cells) = with_tree(|t| {
3910 let root = t.create_root();
3911 let div = t.intern("div");
3912 let span = t.intern("span");
3913 let list = t.create_element(div);
3914 let (mut rows, mut cells) = (Vec::new(), Vec::new());
3915 for _ in 0..3 {
3916 let row = t.create_element(div);
3917 t.set_class(row, "row");
3918 let other = t.create_element(div);
3919 let cell = t.create_element(span);
3920 t.set_class(cell, "cell");
3921 t.insert(other, row, 0);
3922 t.insert(cell, row, 0);
3923 t.insert(row, list, 0);
3924 rows.push(row);
3925 cells.push(cell);
3926 }
3927 t.insert(list, root, 0);
3928 (list, rows, cells)
3929 });
3930 restyle_all();
3931 let opacity = |id: u32| {
3932 read_tree(|t| {
3933 t.node(id)
3934 .and_then(|n| n.computed.as_ref())
3935 .and_then(|c| c.base.opacity)
3936 })
3937 };
3938 assert_eq!(
3939 (opacity(rows[1]), opacity(cells[0])),
3940 (Some(0.5), Some(0.25))
3941 );
3942
3943 let engine = sk_css::Engine::compile(sheet);
3944 let env = env();
3945 let added = with_tree(|t| {
3946 let div = t.intern("div");
3947 let added = t.create_element(div);
3948 t.set_class(added, "row");
3949 t.insert(added, list, rows[0]);
3950 added
3951 });
3952 let settled = with_tree(|t| t.settle_self_marks(&engine, &env));
3953 assert_eq!(
3954 settled.iter().map(|s| s.0).collect::<Vec<_>>(),
3955 vec![rows[0], rows[1]]
3956 );
3957 let mut want = vec![added, cells[0], cells[1], cells[2]];
3958 want.sort_unstable();
3959 assert_eq!(
3960 roots_of(),
3961 want,
3962 "the new row and the cells, none of the rows' other children"
3963 );
3964
3965 with_tree(|t| t.remove(added));
3966 restyle_all();
3967 with_tree(|t| {
3968 let div = t.intern("div");
3969 let added = t.create_element(div);
3970 t.set_class(added, "row");
3971 t.insert(added, list, rows[0]);
3972 });
3973 restyle_all();
3974 assert_eq!(
3975 [rows[0], rows[1], cells[0], cells[1]].map(opacity),
3976 [Some(0.5), None, None, None],
3977 "the old first row is the second now, and no cell is under the first row"
3978 );
3979 }
3980
3981 #[test]
3982 fn a_name_read_by_a_few_tags_walks_only_those_elements() {
3983 let sheet = "[class*=\"submit\"] button { opacity: 0.5 }";
3984 set_engine(sk_css::Engine::compile(sheet));
3985 let (panel, buttons) = with_tree(|t| {
3986 let root = t.create_root();
3987 let div = t.intern("div");
3988 let button = t.intern("button");
3989 let panel = t.create_element(div);
3990 let mut buttons = Vec::new();
3991 for _ in 0..3 {
3992 let row = t.create_element(div);
3993 let b = t.create_element(button);
3994 let label = t.create_element(div);
3995 t.insert(label, b, 0);
3996 t.insert(b, row, 0);
3997 t.insert(row, panel, 0);
3998 buttons.push(b);
3999 }
4000 t.insert(panel, root, 0);
4001 (panel, buttons)
4002 });
4003 restyle_all();
4004 let opacity = |id: u32| {
4005 read_tree(|t| {
4006 t.node(id)
4007 .and_then(|n| n.computed.as_ref())
4008 .and_then(|c| c.base.opacity)
4009 })
4010 };
4011 assert_eq!(opacity(buttons[0]), None);
4012
4013 let engine = sk_css::Engine::compile(sheet);
4014 let env = env();
4015 with_tree(|t| t.set_class(panel, "submit-row"));
4016 assert!(
4017 with_tree(|t| t.settle_self_marks(&engine, &env)).is_empty(),
4018 "the panel's own style did not move"
4019 );
4020 let mut want = buttons.clone();
4021 want.sort_unstable();
4022 assert_eq!(
4023 roots_of(),
4024 want,
4025 "the buttons, and none of the divs around them"
4026 );
4027
4028 with_tree(|t| t.set_class(panel, "submit-row wide"));
4029 restyle_all();
4030 assert!(buttons.iter().all(|&b| opacity(b) == Some(0.5)));
4031 with_tree(|t| t.set_class(panel, "wide"));
4032 restyle_all();
4033 assert!(buttons.iter().all(|&b| opacity(b).is_none()));
4034 }
4035
4036 #[test]
4037 fn an_insert_marks_the_siblings_the_cascade_said_it_read() {
4038 let (root, kids, _) = cascaded_comb(5);
4039 let take_self_marks = || {
4040 with_tree(|t| {
4041 let mut marks = std::mem::take(&mut t.self_marks);
4042 marks.sort_unstable();
4043 marks.dedup();
4044 marks
4045 })
4046 };
4047 with_tree(|t| t.node(root).unwrap().sel_flags.set(sel::NEXT_EDGE));
4048 let added = with_tree(|t| {
4049 let div = t.intern("div");
4050 let added = t.create_element(div);
4051 t.insert(added, root, 0);
4052 added
4053 });
4054 assert_eq!(take_self_marks(), vec![kids[4]], "the old last child");
4055 assert_eq!(roots_of(), vec![added], "and the new one");
4056
4057 with_tree(|t| t.node(root).unwrap().sel_flags.set(sel::PREV_WALK));
4058 let middle = with_tree(|t| {
4059 let div = t.intern("div");
4060 let middle = t.create_element(div);
4061 t.insert(middle, root, kids[3]);
4062 middle
4063 });
4064 let mut want = vec![kids[3], kids[4], added];
4065 want.sort_unstable();
4066 assert_eq!(take_self_marks(), want);
4067 assert_eq!(roots_of(), vec![middle]);
4068 }
4069
4070 #[test]
4071 fn a_root_under_an_anchor_is_promoted_to_the_anchor() {
4072 let (anchor, inner) = with_tree(|t| {
4073 let root = t.create_root();
4074 let div = t.intern("div");
4075 let anchor = t.create_anchor();
4076 let a = t.create_element(div);
4077 let b = t.create_element(div);
4078 t.insert(a, anchor, 0);
4079 t.insert(b, anchor, 0);
4080 t.insert(anchor, root, 0);
4081 (anchor, b)
4082 });
4083 restyle_all();
4084 with_tree(|t| t.mark_restyle_subtree(inner));
4085 assert_eq!(roots_of(), vec![anchor]);
4086 }
4087
4088 #[test]
4089 fn a_sibling_combinator_reaches_later_siblings_where_they_read() {
4090 let sheet = ".a + .b { opacity: 0.5 }";
4091 set_engine(sk_css::Engine::compile(sheet));
4092 let (root, kids, grandkids) = cascaded_comb(5);
4093 let opacity = |id: u32| {
4094 read_tree(|t| {
4095 t.node(id)
4096 .and_then(|n| n.computed.as_ref())
4097 .and_then(|c| c.base.opacity)
4098 })
4099 };
4100 with_tree(|t| kids.iter().for_each(|&k| t.set_class(k, "b")));
4101 restyle_all();
4102 let order: Vec<u32> = read_tree(|t| t.node(root).unwrap().children.clone());
4103 let (first, second, third) = (order[0], order[1], order[2]);
4104
4105 with_tree(|t| t.set_class(first, "a b"));
4106 let mut want: Vec<u32> = order[1..].to_vec();
4107 want.push(grandkids[kids.iter().position(|&k| k == first).unwrap()]);
4108 want.sort_unstable();
4109 assert_eq!(roots_of(), want, "the divs after it, and the one under it");
4110
4111 let added = with_tree(|t| {
4112 let div = t.intern("div");
4113 let added = t.create_element(div);
4114 t.insert(added, root, third);
4115 added
4116 });
4117 assert_eq!(roots_of(), vec![added], "only the new node is walked");
4118 let mut marked = with_tree(|t| std::mem::take(&mut t.self_marks));
4119 marked.sort_unstable();
4120 marked.dedup();
4121 assert_eq!(
4122 marked,
4123 vec![first, third],
4124 "the class change, and the one whose `+` steps across"
4125 );
4126
4127 with_tree(|t| t.set_class(first, "b"));
4128 restyle_all();
4129 assert_eq!(opacity(second), None);
4130 with_tree(|t| t.set_class(first, "a b"));
4131 restyle_all();
4132 assert_eq!(opacity(second), Some(0.5), ".a + .b");
4133 with_tree(|t| t.set_class(first, "b"));
4134 restyle_all();
4135 assert_eq!(opacity(second), None);
4136 }
4137
4138 #[test]
4139 fn an_uncascaded_element_on_the_trail_is_a_walk_root() {
4140 let (_, kids, _) = cascaded_comb(2);
4141 let fresh = with_tree(|t| {
4142 let div = t.intern("div");
4143 let fresh = t.create_element(div);
4144 let inner = t.create_element(div);
4145 t.insert(inner, fresh, 0);
4146 t.node_mut(fresh).unwrap().parent = kids[0];
4149 t.node_mut(fresh).unwrap().mark_gen = 0;
4150 t.node_mut(kids[0]).unwrap().children.push(fresh);
4151 t.flag_path(kids[0]);
4152 fresh
4153 });
4154 assert_eq!(roots_of(), vec![fresh]);
4155 }
4156
4157 fn font_size_of(id: u32) -> f32 {
4158 read_tree(|t| {
4159 t.node(id)
4160 .and_then(|n| n.computed.as_ref())
4161 .map(|c| c.font_size)
4162 })
4163 .expect("cascaded")
4164 }
4165
4166 fn padding_top_of(id: u32) -> Option<gpui::DefiniteLength> {
4167 read_tree(|t| {
4168 t.node(id)
4169 .and_then(|n| n.computed.as_ref())
4170 .and_then(|c| c.base.padding.top)
4171 })
4172 }
4173
4174 fn px_len(v: f32) -> Option<gpui::DefiniteLength> {
4175 Some(gpui::px(v).into())
4176 }
4177
4178 #[test]
4181 fn a_root_font_size_in_rem_settles_on_the_initial_size() {
4182 set_stylesheet(":root { font-size: 0.875rem } .w { width: 2rem }".into());
4183 let w = with_tree(|t| {
4184 let root = t.create_root();
4185 let div = t.intern("div");
4186 let w = t.create_element(div);
4187 t.set_class(w, "w");
4188 let height = t.intern("height");
4189 t.set_style(w, height, "2rem".to_string());
4190 t.insert(w, root, 0);
4191 w
4192 });
4193 for pass in 0..4 {
4194 with_tree(|t| t.take_dirty());
4195 restyle_all();
4196 assert_eq!(sk_css::rem_basis(), 14.0, "pass {pass}");
4197 assert!(
4198 !read_tree(|t| t.dirty),
4199 "pass {pass} left a restyle pending"
4200 );
4201 let computed = read_tree(|t| {
4202 t.node(w)
4203 .and_then(|n| n.computed.as_ref())
4204 .map(|c| c.base.clone())
4205 })
4206 .expect("cascaded");
4207 let rem2 = Some(gpui::Length::Definite(gpui::px(28.0).into()));
4208 assert_eq!(computed.size.width, rem2, "the sheet's 2rem, pass {pass}");
4209 assert_eq!(computed.size.height, rem2, "the inline 2rem, pass {pass}");
4210 }
4211 }
4212
4213 #[test]
4214 fn em_follows_the_computed_font_size_down_the_walk() {
4215 set_stylesheet(
4216 ":root { font-size: 62.5% } \
4217 .a { font-size: 2em } \
4218 .b { font-size: 75%; padding: .5em } \
4219 .c { margin-top: 1em; width: 2rem; line-height: 1.5em } \
4220 .n { line-height: 1.5 }"
4221 .into(),
4222 );
4223 let (root, a, b, c, n) = with_tree(|t| {
4224 let root = t.create_root();
4225 let div = t.intern("div");
4226 let mut make = |class: &str, parent: u32| {
4227 let e = t.create_element(div);
4228 t.set_class(e, class);
4229 t.insert(e, parent, 0);
4230 e
4231 };
4232 let a = make("a", root);
4233 let b = make("b", a);
4234 let c = make("c", b);
4235 let n = make("n", c);
4236 (root, a, b, c, n)
4237 });
4238 restyle_all();
4239 assert_eq!(
4240 sk_css::rem_basis(),
4241 10.0,
4242 "the root's 62.5% of 16px is the rem basis"
4243 );
4244 assert_eq!(
4245 [root, a, b, c, n].map(font_size_of),
4246 [10.0, 20.0, 15.0, 15.0, 15.0],
4247 "each size of its parent's, and inherited as px"
4248 );
4249 assert_eq!(padding_top_of(b), px_len(7.5), "`.5em` of its own 15px");
4250 let computed = read_tree(|t| {
4251 t.node(c)
4252 .and_then(|n| n.computed.as_ref())
4253 .map(|c| c.base.clone())
4254 })
4255 .expect("cascaded");
4256 assert_eq!(
4257 computed.margin.top,
4258 Some(gpui::Length::Definite(gpui::px(15.0).into()))
4259 );
4260 assert_eq!(
4261 computed.size.width,
4262 Some(gpui::Length::Definite(gpui::px(20.0).into())),
4263 "2rem"
4264 );
4265 assert_eq!(
4266 computed.text.line_height,
4267 px_len(22.5),
4268 "an em line-height is px"
4269 );
4270 let number = read_tree(|t| {
4271 t.node(n)
4272 .and_then(|n| n.computed.as_ref())
4273 .and_then(|c| c.base.text.line_height)
4274 });
4275 assert_eq!(
4276 number,
4277 Some(gpui::relative(1.5)),
4278 "a number line-height stays a number"
4279 );
4280 let reported = crate::dom::computed_style(c).unwrap_or_default();
4281 assert!(
4282 reported.lines().any(|l| l == "font-size=15px"),
4283 "getComputedStyle: {reported}"
4284 );
4285 }
4286
4287 #[test]
4288 fn a_new_parent_font_size_reaches_the_em_below_it() {
4289 set_stylesheet(".big { font-size: 20px } .leaf { padding: 1em }".into());
4290 let (big, plain, leaves) = with_tree(|t| {
4291 let root = t.create_root();
4292 let div = t.intern("div");
4293 let big = t.create_element(div);
4294 t.set_class(big, "big");
4295 t.insert(big, root, 0);
4296 let plain = t.create_element(div);
4297 t.insert(plain, root, 1);
4298 let mut leaves = Vec::new();
4299 for parent in [big, plain] {
4300 let leaf = t.create_element(div);
4301 t.set_class(leaf, "leaf");
4302 t.insert(leaf, parent, 0);
4303 leaves.push(leaf);
4304 }
4305 (big, plain, leaves)
4306 });
4307 restyle_all();
4308 assert_eq!(
4309 leaves
4310 .iter()
4311 .map(|&l| padding_top_of(l))
4312 .collect::<Vec<_>>(),
4313 vec![px_len(20.0), px_len(16.0)]
4314 );
4315
4316 with_tree(|t| {
4317 t.set_class(plain, "big");
4318 t.set_class(big, "");
4319 });
4320 restyle_all();
4321 assert_eq!(
4322 leaves
4323 .iter()
4324 .map(|&l| padding_top_of(l))
4325 .collect::<Vec<_>>(),
4326 vec![px_len(16.0), px_len(20.0)]
4327 );
4328 assert_eq!(font_size_of(leaves[1]), 20.0);
4329 }
4330 #[test]
4331 fn character_width_follows_inherited_face_and_restyles_descendants() {
4332 sk_css::set_font_source(|| vec!["SK Metric Narrow".into(), "SK Metric Wide".into()]);
4333 sk_css::set_font_metric_source(|font, size| {
4334 Some(sk_css::FontRelativeMetrics {
4335 zero_advance: size
4336 * if font.family.as_ref() == "SK Metric Wide" {
4337 0.8
4338 } else {
4339 0.6
4340 },
4341 x_height: size * 0.4,
4342 })
4343 });
4344 struct Reset;
4345 impl Drop for Reset {
4346 fn drop(&mut self) {
4347 sk_css::set_font_metric_source(|_, _| None);
4348 }
4349 }
4350 let _reset = Reset;
4351 set_stylesheet(".narrow {font-family:'SK Metric Narrow';font-size:10px} .wide {font-family:'SK Metric Wide';font-size:10px} .leaf{width:1ch}".into());
4352 let (parent, leaves) = with_tree(|tree| {
4353 let root = tree.create_root();
4354 let tag = tree.intern("div");
4355 let mut parents = Vec::new();
4356 let mut leaves = Vec::new();
4357 for class in ["narrow", "wide"] {
4358 let parent = tree.create_element(tag);
4359 tree.set_class(parent, class);
4360 tree.insert(parent, root, 0);
4361 parents.push(parent);
4362 let leaf = tree.create_element(tag);
4363 tree.set_class(leaf, "leaf");
4364 tree.insert(leaf, parent, 0);
4365 leaves.push(leaf);
4366 }
4367 (parents[0], leaves)
4368 });
4369 let widths = || {
4370 read_tree(|tree| {
4371 leaves
4372 .iter()
4373 .map(|&id| {
4374 tree.node(id)
4375 .and_then(|node| node.computed.as_ref())
4376 .and_then(|computed| computed.base.size.width)
4377 })
4378 .collect::<Vec<_>>()
4379 })
4380 };
4381 restyle_all();
4382 assert_eq!(
4383 widths(),
4384 vec![Some(gpui::px(6.0).into()), Some(gpui::px(8.0).into())]
4385 );
4386 with_tree(|tree| tree.set_class(parent, "wide"));
4387 restyle_all();
4388 assert_eq!(
4389 widths(),
4390 vec![Some(gpui::px(8.0).into()), Some(gpui::px(8.0).into())]
4391 );
4392 }
4393}