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