| 1 | use crate::{ |
| 2 | AnyElement, AppContext as _, Context, ElementId, Entity, Hsla, InteractiveElement, IntoElement, |
| 3 | ParentElement, Render, StatefulInteractiveElement, Styled, Window, div, px, |
| 4 | util::FluentBuilder, |
| 5 | }; |
| 6 | use collections::{HashMap, HashSet}; |
| 7 | use rand::{Rng as _, SeedableRng as _, rngs::StdRng}; |
| 8 | use std::{ |
| 9 | cell::RefCell, |
| 10 | ops::RangeInclusive, |
| 11 | rc::{Rc, Weak}, |
| 12 | }; |
| 13 | |
| 14 | /// Dispatched to no one: the action generated elements register handlers for. Not |
| 15 | /// registered, so builds that enable `bench-support` through feature unification (such as |
| 16 | /// the workspace's tests) don't gain an action namespace. |
| 17 | #[derive(Clone, Default, PartialEq, crate::Action)] |
| 18 | #[action(namespace = randomized_element_tree, no_json, no_register)] |
| 19 | pub struct RandomizedElementTreeAction; |
| 20 | |
| 21 | /// The initial shape generated for a randomized element tree. |
| 22 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 23 | pub enum RandomizedElementTreeTopology { |
| 24 | /// Every generated element is a direct child of the root. |
| 25 | Wide, |
| 26 | /// Every generated element is the child of the previous element. |
| 27 | Deep, |
| 28 | /// Generated elements choose parents throughout the existing tree. |
| 29 | Mixed, |
| 30 | /// Generated elements usually extend one deep branch, with occasional root children. |
| 31 | Narrow, |
| 32 | } |
| 33 | |
| 34 | impl RandomizedElementTreeTopology { |
| 35 | /// Every topology. |
| 36 | pub const ALL: [Self; 4] = [Self::Wide, Self::Deep, Self::Mixed, Self::Narrow]; |
| 37 | |
| 38 | /// Whether the tree's depth grows with its element count. `Deep` nests every element |
| 39 | /// under the previous one and `Narrow` nests four in five, so both recurse once per |
| 40 | /// element through layout and paint; without gpui's `stacker` feature that overflows |
| 41 | /// a 2 MB thread stack somewhere between 384 and 512 elements in a release build. |
| 42 | pub fn is_tall(self) -> bool { |
| 43 | matches!(self, Self::Deep | Self::Narrow) |
| 44 | } |
| 45 | |
| 46 | fn from_seed(seed: u64) -> Self { |
| 47 | match seed % 4 { |
| 48 | 0 => Self::Wide, |
| 49 | 1 => Self::Deep, |
| 50 | 2 => Self::Mixed, |
| 51 | _ => Self::Narrow, |
| 52 | } |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | /// Configuration for a reproducible randomized element-tree workload. |
| 57 | #[derive(Clone, Copy, Debug, PartialEq)] |
| 58 | pub struct RandomizedElementTreeConfig { |
| 59 | seed: u64, |
| 60 | element_count: usize, |
| 61 | topology: RandomizedElementTreeTopology, |
| 62 | entity_density: f64, |
| 63 | handler_density: f64, |
| 64 | } |
| 65 | |
| 66 | impl RandomizedElementTreeConfig { |
| 67 | /// Creates an element-only workload whose topology is selected by `seed`. |
| 68 | pub fn new(seed: u64, element_count: usize) -> Self { |
| 69 | Self { |
| 70 | seed, |
| 71 | element_count, |
| 72 | topology: RandomizedElementTreeTopology::from_seed(seed), |
| 73 | entity_density: 0.0, |
| 74 | handler_density: 0.0, |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | /// Selects the initial tree topology independently of the RNG seed. |
| 79 | pub fn with_topology(mut self, topology: RandomizedElementTreeTopology) -> Self { |
| 80 | self.topology = topology; |
| 81 | self |
| 82 | } |
| 83 | |
| 84 | /// Sets the probability that each generated element is backed by a persistent entity. |
| 85 | pub fn with_entity_density(mut self, density: f64) -> Self { |
| 86 | self.entity_density = normalized_density(density); |
| 87 | self |
| 88 | } |
| 89 | |
| 90 | /// Sets the probability of each generated interaction feature on an element. |
| 91 | pub fn with_handler_density(mut self, density: f64) -> Self { |
| 92 | self.handler_density = normalized_density(density); |
| 93 | self |
| 94 | } |
| 95 | |
| 96 | /// Returns the seed used for generation and subsequent random mutations. |
| 97 | pub fn seed(&self) -> u64 { |
| 98 | self.seed |
| 99 | } |
| 100 | |
| 101 | /// Returns the requested number of initial descendants. |
| 102 | pub fn element_count(&self) -> usize { |
| 103 | self.element_count |
| 104 | } |
| 105 | |
| 106 | /// Returns the selected initial topology. |
| 107 | pub fn topology(&self) -> RandomizedElementTreeTopology { |
| 108 | self.topology |
| 109 | } |
| 110 | |
| 111 | /// Returns the probability that a generated element is backed by an entity. |
| 112 | pub fn entity_density(&self) -> f64 { |
| 113 | self.entity_density |
| 114 | } |
| 115 | |
| 116 | /// Returns the probability of each generated interaction feature. |
| 117 | pub fn handler_density(&self) -> f64 { |
| 118 | self.handler_density |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | /// Bounds an RNG is drawn against to produce a [`RandomizedElementTreeConfig`]: a family |
| 123 | /// of trees, such as "tall trees of 32 to 256 elements with up to half of them entities", |
| 124 | /// from which one draw picks one member. Every field of the resulting config, and the |
| 125 | /// tree built from it, follows from the RNG's state, so an RNG seeded by `#[gpui::bench]` |
| 126 | /// or `#[gpui::test]` samples the family across seeds and any one seed reproduces exactly. |
| 127 | #[derive(Clone, Debug, PartialEq)] |
| 128 | pub struct RandomizedElementTreeBounds { |
| 129 | topologies: Vec<RandomizedElementTreeTopology>, |
| 130 | element_count: RangeInclusive<usize>, |
| 131 | entity_density: RangeInclusive<f64>, |
| 132 | handler_density: RangeInclusive<f64>, |
| 133 | } |
| 134 | |
| 135 | impl RandomizedElementTreeBounds { |
| 136 | /// Trees of any topology with `element_count` elements, no entities and no handlers. |
| 137 | pub fn new(element_count: RangeInclusive<usize>) -> Self { |
| 138 | Self { |
| 139 | topologies: RandomizedElementTreeTopology::ALL.to_vec(), |
| 140 | element_count, |
| 141 | entity_density: 0.0..=0.0, |
| 142 | handler_density: 0.0..=0.0, |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | /// Restricts the topologies a seed may pick. An empty list keeps them all. |
| 147 | pub fn with_topologies( |
| 148 | mut self, |
| 149 | topologies: impl IntoIterator<Item = RandomizedElementTreeTopology>, |
| 150 | ) -> Self { |
| 151 | let topologies: Vec<_> = topologies.into_iter().collect(); |
| 152 | if !topologies.is_empty() { |
| 153 | self.topologies = topologies; |
| 154 | } |
| 155 | self |
| 156 | } |
| 157 | |
| 158 | /// The range a seed draws the share of entity-backed elements from. |
| 159 | pub fn with_entity_density(mut self, density: RangeInclusive<f64>) -> Self { |
| 160 | self.entity_density = |
| 161 | normalized_density(*density.start())..=normalized_density(*density.end()); |
| 162 | self |
| 163 | } |
| 164 | |
| 165 | /// The range a seed draws the per-feature handler probability from. |
| 166 | pub fn with_handler_density(mut self, density: RangeInclusive<f64>) -> Self { |
| 167 | self.handler_density = |
| 168 | normalized_density(*density.start())..=normalized_density(*density.end()); |
| 169 | self |
| 170 | } |
| 171 | |
| 172 | /// Draws one config from these bounds. The config's own seed, which drives the tree's |
| 173 | /// contents and mutation stream, is drawn from `rng` too, so all of it reproduces from |
| 174 | /// the seed `rng` started from. |
| 175 | pub fn sample(&self, rng: &mut StdRng) -> RandomizedElementTreeConfig { |
| 176 | let topology = self.topologies[rng.random_range(0..self.topologies.len())]; |
| 177 | let element_count = rng.random_range(self.element_count.clone()); |
| 178 | RandomizedElementTreeConfig::new(rng.random(), element_count) |
| 179 | .with_topology(topology) |
| 180 | .with_entity_density(sample_range(&self.entity_density, rng)) |
| 181 | .with_handler_density(sample_range(&self.handler_density, rng)) |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | fn sample_range(range: &RangeInclusive<f64>, rng: &mut StdRng) -> f64 { |
| 186 | if range.start() >= range.end() { |
| 187 | *range.start() |
| 188 | } else { |
| 189 | rng.random_range(range.clone()) |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | /// Work performed while converting randomized entities and elements into an element tree. |
| 194 | #[derive(Clone, Debug, Default, Eq, PartialEq)] |
| 195 | pub struct RandomizedElementTreeWorkCounters { |
| 196 | root_render_count: usize, |
| 197 | entity_render_count: usize, |
| 198 | element_render_count: usize, |
| 199 | handler_registration_count: usize, |
| 200 | rendered_entity_ids: Vec<u64>, |
| 201 | } |
| 202 | |
| 203 | impl RandomizedElementTreeWorkCounters { |
| 204 | /// Returns how many times the persistent root's `Render` implementation ran. |
| 205 | pub fn root_render_count(&self) -> usize { |
| 206 | self.root_render_count |
| 207 | } |
| 208 | |
| 209 | /// Returns how many randomized child entities rendered. |
| 210 | pub fn entity_render_count(&self) -> usize { |
| 211 | self.entity_render_count |
| 212 | } |
| 213 | |
| 214 | /// Returns how many randomized descendant elements were reconstructed. |
| 215 | pub fn element_render_count(&self) -> usize { |
| 216 | self.element_render_count |
| 217 | } |
| 218 | |
| 219 | /// Returns how many interaction handlers were registered while rendering. |
| 220 | pub fn handler_registration_count(&self) -> usize { |
| 221 | self.handler_registration_count |
| 222 | } |
| 223 | |
| 224 | /// Returns stable IDs for the randomized child entities that rendered, in render order. |
| 225 | pub fn rendered_entity_ids(&self) -> &[u64] { |
| 226 | &self.rendered_entity_ids |
| 227 | } |
| 228 | |
| 229 | fn reset(&mut self) { |
| 230 | self.root_render_count = 0; |
| 231 | self.entity_render_count = 0; |
| 232 | self.element_render_count = 0; |
| 233 | self.handler_registration_count = 0; |
| 234 | self.rendered_entity_ids.clear(); |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | /// A cloneable description of a randomized element tree's renderable state. |
| 239 | #[derive(Clone, Debug, PartialEq)] |
| 240 | pub struct RandomizedElementTreeSnapshot { |
| 241 | root: RandomizedElementStyle, |
| 242 | children: Vec<RandomizedElementNode>, |
| 243 | next_element_id: u64, |
| 244 | paths_by_element_id: HashMap<u64, Vec<usize>>, |
| 245 | } |
| 246 | |
| 247 | impl RandomizedElementTreeSnapshot { |
| 248 | /// Returns the number of randomized elements below the persistent root. |
| 249 | pub fn descendant_count(&self) -> usize { |
| 250 | let mut count = 0; |
| 251 | let mut stack = self.children.iter().collect::<Vec<_>>(); |
| 252 | while let Some(node) = stack.pop() { |
| 253 | count += 1; |
| 254 | stack.extend(node.children.iter()); |
| 255 | } |
| 256 | count |
| 257 | } |
| 258 | |
| 259 | /// Returns the deepest randomized element below the persistent root. |
| 260 | /// |
| 261 | /// A snapshot with no descendants has depth zero. |
| 262 | pub fn max_depth(&self) -> usize { |
| 263 | let mut max_depth = 0; |
| 264 | let mut stack = self |
| 265 | .children |
| 266 | .iter() |
| 267 | .map(|node| (node, 1)) |
| 268 | .collect::<Vec<_>>(); |
| 269 | while let Some((node, depth)) = stack.pop() { |
| 270 | max_depth = max_depth.max(depth); |
| 271 | stack.extend(node.children.iter().map(|child| (child, depth + 1))); |
| 272 | } |
| 273 | max_depth |
| 274 | } |
| 275 | |
| 276 | /// Returns the stable element IDs in depth-first order. |
| 277 | pub fn element_ids(&self) -> Vec<u64> { |
| 278 | node_paths(&self.children) |
| 279 | .iter() |
| 280 | .filter_map(|path| node_at_path(&self.children, path).map(|node| node.id)) |
| 281 | .collect() |
| 282 | } |
| 283 | |
| 284 | /// Returns the number of descendants backed by persistent child entities. |
| 285 | pub fn entity_count(&self) -> usize { |
| 286 | let mut count = 0; |
| 287 | let mut stack = self.children.iter().collect::<Vec<_>>(); |
| 288 | while let Some(node) = stack.pop() { |
| 289 | count += usize::from(node.is_entity); |
| 290 | stack.extend(node.children.iter()); |
| 291 | } |
| 292 | count |
| 293 | } |
| 294 | |
| 295 | /// Returns the number of interaction handlers in the generated tree. |
| 296 | pub fn handler_count(&self) -> usize { |
| 297 | let mut count = 0; |
| 298 | let mut stack = self.children.iter().collect::<Vec<_>>(); |
| 299 | while let Some(node) = stack.pop() { |
| 300 | count += node.features.handler_count(); |
| 301 | stack.extend(node.children.iter()); |
| 302 | } |
| 303 | count |
| 304 | } |
| 305 | |
| 306 | fn rebuild_element_paths(&mut self) { |
| 307 | self.paths_by_element_id = node_paths(&self.children) |
| 308 | .into_iter() |
| 309 | .filter_map(|path| node_at_path(&self.children, &path).map(|node| (node.id, path))) |
| 310 | .collect(); |
| 311 | } |
| 312 | |
| 313 | fn node(&self, element_id: u64) -> Option<&RandomizedElementNode> { |
| 314 | node_at_path(&self.children, self.paths_by_element_id.get(&element_id)?) |
| 315 | } |
| 316 | } |
| 317 | |
| 318 | /// A requested class of deterministic randomized-tree mutation. |
| 319 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 320 | pub enum RandomizedElementTreeMutationKind { |
| 321 | /// Change the root background color. |
| 322 | RootColor, |
| 323 | /// Change the root opacity. |
| 324 | RootOpacity, |
| 325 | /// Change the root border. |
| 326 | RootBorder, |
| 327 | /// Change the root width and height. |
| 328 | RootBounds, |
| 329 | /// Toggle clipping on the root. |
| 330 | RootClipping, |
| 331 | /// Toggle root visibility. |
| 332 | RootVisibility, |
| 333 | /// Change a seeded random descendant's colors. |
| 334 | ChildColor, |
| 335 | /// Change a seeded random descendant's opacity. |
| 336 | ChildOpacity, |
| 337 | /// Change a seeded random descendant's border. |
| 338 | ChildBorder, |
| 339 | /// Change a seeded random descendant's width and height. |
| 340 | ChildBounds, |
| 341 | /// Toggle clipping on a seeded random descendant. |
| 342 | ChildClipping, |
| 343 | /// Toggle visibility on a seeded random descendant. |
| 344 | ChildVisibility, |
| 345 | /// Reorder a seeded random descendant among its siblings. |
| 346 | Reorder, |
| 347 | /// Insert a generated descendant below a seeded random parent. |
| 348 | Insert, |
| 349 | /// Remove a seeded random descendant and its subtree. |
| 350 | Remove, |
| 351 | /// Remove a seeded random childless descendant. Unlike [`Self::Remove`] this changes |
| 352 | /// the element count by exactly one, so it can alternate with [`Self::Insert`] in a |
| 353 | /// long benchmark loop without the tree collapsing or growing. |
| 354 | RemoveLeaf, |
| 355 | } |
| 356 | |
| 357 | impl RandomizedElementTreeMutationKind { |
| 358 | /// Every supported mutation kind, suitable for parameterized tests and benchmarks. |
| 359 | pub const ALL: [Self; 16] = [ |
| 360 | Self::RootColor, |
| 361 | Self::RootOpacity, |
| 362 | Self::RootBorder, |
| 363 | Self::RootBounds, |
| 364 | Self::RootClipping, |
| 365 | Self::RootVisibility, |
| 366 | Self::ChildColor, |
| 367 | Self::ChildOpacity, |
| 368 | Self::ChildBorder, |
| 369 | Self::ChildBounds, |
| 370 | Self::ChildClipping, |
| 371 | Self::ChildVisibility, |
| 372 | Self::Reorder, |
| 373 | Self::Insert, |
| 374 | Self::Remove, |
| 375 | Self::RemoveLeaf, |
| 376 | ]; |
| 377 | } |
| 378 | |
| 379 | /// A deterministic mutation applied to a [`RandomizedElementTree`]. |
| 380 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 381 | pub enum RandomizedElementTreeMutation { |
| 382 | /// Changed the root background color. |
| 383 | RootColor, |
| 384 | /// Changed the root opacity. |
| 385 | RootOpacity, |
| 386 | /// Changed the root border. |
| 387 | RootBorder, |
| 388 | /// Changed the root width and height. |
| 389 | RootBounds, |
| 390 | /// Toggled clipping on the root. |
| 391 | RootClipping, |
| 392 | /// Toggled root visibility. |
| 393 | RootVisibility, |
| 394 | /// Changed a descendant's colors. |
| 395 | ChildColor { |
| 396 | /// The stable ID of the mutated element. |
| 397 | element_id: u64, |
| 398 | }, |
| 399 | /// Changed a descendant's opacity. |
| 400 | ChildOpacity { |
| 401 | /// The stable ID of the mutated element. |
| 402 | element_id: u64, |
| 403 | }, |
| 404 | /// Changed a descendant's border. |
| 405 | ChildBorder { |
| 406 | /// The stable ID of the mutated element. |
| 407 | element_id: u64, |
| 408 | }, |
| 409 | /// Changed a descendant's width and height. |
| 410 | ChildBounds { |
| 411 | /// The stable ID of the mutated element. |
| 412 | element_id: u64, |
| 413 | }, |
| 414 | /// Toggled clipping on a descendant. |
| 415 | ChildClipping { |
| 416 | /// The stable ID of the mutated element. |
| 417 | element_id: u64, |
| 418 | }, |
| 419 | /// Toggled a descendant's visibility. |
| 420 | ChildVisibility { |
| 421 | /// The stable ID of the mutated element. |
| 422 | element_id: u64, |
| 423 | }, |
| 424 | /// Moved an element to a different position among its siblings. |
| 425 | Reordered { |
| 426 | /// The stable ID of the moved element. |
| 427 | element_id: u64, |
| 428 | /// The stable ID of its parent, or `None` for the persistent root. |
| 429 | parent_id: Option<u64>, |
| 430 | /// The element's previous position. |
| 431 | old_index: usize, |
| 432 | /// The element's new position. |
| 433 | new_index: usize, |
| 434 | }, |
| 435 | /// Inserted a newly generated element. |
| 436 | Inserted { |
| 437 | /// The stable ID of the inserted element. |
| 438 | element_id: u64, |
| 439 | /// The stable ID of its parent, or `None` for the persistent root. |
| 440 | parent_id: Option<u64>, |
| 441 | /// The position of the inserted element. |
| 442 | index: usize, |
| 443 | }, |
| 444 | /// Removed an element and all of its descendants. |
| 445 | Removed { |
| 446 | /// The stable ID of the removed element. |
| 447 | element_id: u64, |
| 448 | /// The stable ID of its parent, or `None` for the persistent root. |
| 449 | parent_id: Option<u64>, |
| 450 | /// The former position of the removed element. |
| 451 | index: usize, |
| 452 | /// The total number of elements removed with the subtree. |
| 453 | removed_element_count: usize, |
| 454 | }, |
| 455 | } |
| 456 | |
| 457 | /// Where the elements changed by one frame sit relative to each other. |
| 458 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 459 | pub enum ChangeLocality { |
| 460 | /// Inside one random entity's subtree, as a user action or one component's state |
| 461 | /// change would be; the change reaches the rest of the tree only if the subtree has |
| 462 | /// fewer elements than are changing (a common ancestor changing). |
| 463 | Localized, |
| 464 | /// Anywhere in the tree, uniformly: the worst case for a renderer that reuses clean |
| 465 | /// subtrees, since every changed element may sit in a different one. |
| 466 | Spread, |
| 467 | } |
| 468 | |
| 469 | /// What [`RandomizedElementTree::recolor_children`] changed. |
| 470 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 471 | pub struct RecoloredChildren { |
| 472 | /// Descendants whose background changed. |
| 473 | pub recolored: usize, |
| 474 | /// Entity boundaries (or the root) notified, each once. |
| 475 | pub notified: usize, |
| 476 | } |
| 477 | |
| 478 | /// A persistent root view for randomized GPUI element-tree tests and benchmarks. |
| 479 | pub struct RandomizedElementTree { |
| 480 | snapshot: Rc<RefCell<RandomizedElementTreeSnapshot>>, |
| 481 | entities: Rc<RefCell<RandomizedElementEntities>>, |
| 482 | work_counters: Rc<RefCell<RandomizedElementTreeWorkCounters>>, |
| 483 | config: RandomizedElementTreeConfig, |
| 484 | rng: StdRng, |
| 485 | } |
| 486 | |
| 487 | impl RandomizedElementTree { |
| 488 | /// Generates a tree with `element_count` descendants and a mutation stream from `seed`. |
| 489 | /// |
| 490 | /// Different seeds deliberately produce wide, deep, mixed, and narrow initial topologies. |
| 491 | pub fn new(seed: u64, element_count: usize) -> Self { |
| 492 | Self::from_config(RandomizedElementTreeConfig::new(seed, element_count)) |
| 493 | } |
| 494 | |
| 495 | /// Generates a configured tree and creates its persistent child entities. |
| 496 | pub fn new_with_config(config: RandomizedElementTreeConfig, cx: &mut Context<Self>) -> Self { |
| 497 | let mut tree = Self::from_config(config); |
| 498 | tree.synchronize_entities(cx); |
| 499 | tree |
| 500 | } |
| 501 | |
| 502 | fn from_config(config: RandomizedElementTreeConfig) -> Self { |
| 503 | let mut rng = StdRng::seed_from_u64(config.seed); |
| 504 | let mut children = Vec::new(); |
| 505 | let mut deepest_path = Vec::new(); |
| 506 | |
| 507 | for element_index in 0..config.element_count { |
| 508 | let mut parent_path = match config.topology { |
| 509 | RandomizedElementTreeTopology::Wide => Vec::new(), |
| 510 | RandomizedElementTreeTopology::Deep => deepest_path.clone(), |
| 511 | RandomizedElementTreeTopology::Mixed => random_parent_path(&children, &mut rng), |
| 512 | RandomizedElementTreeTopology::Narrow => { |
| 513 | if rng.random_bool(0.8) { |
| 514 | deepest_path.clone() |
| 515 | } else { |
| 516 | Vec::new() |
| 517 | } |
| 518 | } |
| 519 | }; |
| 520 | let node = RandomizedElementNode::random( |
| 521 | element_index as u64, |
| 522 | config.entity_density, |
| 523 | config.handler_density, |
| 524 | &mut rng, |
| 525 | ); |
| 526 | let (_, inserted_path) = insert_node(&mut children, &mut parent_path, node); |
| 527 | deepest_path = inserted_path; |
| 528 | } |
| 529 | |
| 530 | let mut snapshot = RandomizedElementTreeSnapshot { |
| 531 | root: RandomizedElementStyle::random_root(&mut rng), |
| 532 | children, |
| 533 | next_element_id: config.element_count as u64, |
| 534 | paths_by_element_id: HashMap::default(), |
| 535 | }; |
| 536 | snapshot.rebuild_element_paths(); |
| 537 | |
| 538 | Self { |
| 539 | snapshot: Rc::new(RefCell::new(snapshot)), |
| 540 | entities: Rc::new(RefCell::new(HashMap::default())), |
| 541 | work_counters: Rc::new(RefCell::new(RandomizedElementTreeWorkCounters::default())), |
| 542 | config, |
| 543 | rng, |
| 544 | } |
| 545 | } |
| 546 | |
| 547 | /// Reconstructs a tree from renderable state captured by [`Self::snapshot`]. |
| 548 | pub fn from_snapshot(snapshot: RandomizedElementTreeSnapshot) -> Self { |
| 549 | Self { |
| 550 | config: RandomizedElementTreeConfig::new(0, snapshot.descendant_count()), |
| 551 | snapshot: Rc::new(RefCell::new(snapshot)), |
| 552 | entities: Rc::new(RefCell::new(HashMap::default())), |
| 553 | work_counters: Rc::new(RefCell::new(RandomizedElementTreeWorkCounters::default())), |
| 554 | rng: StdRng::seed_from_u64(0), |
| 555 | } |
| 556 | } |
| 557 | |
| 558 | /// Reconstructs a snapshot while preserving its randomized entity boundaries. |
| 559 | pub fn from_snapshot_with_entities( |
| 560 | snapshot: RandomizedElementTreeSnapshot, |
| 561 | cx: &mut Context<Self>, |
| 562 | ) -> Self { |
| 563 | let mut tree = Self::from_snapshot(snapshot); |
| 564 | tree.synchronize_entities(cx); |
| 565 | tree |
| 566 | } |
| 567 | |
| 568 | /// Captures all state that affects rendering and future element IDs. |
| 569 | pub fn snapshot(&self) -> RandomizedElementTreeSnapshot { |
| 570 | self.snapshot.borrow().clone() |
| 571 | } |
| 572 | |
| 573 | /// Clears render work accumulated since construction or the previous reset. |
| 574 | pub fn reset_work_counters(&mut self) { |
| 575 | self.work_counters.borrow_mut().reset(); |
| 576 | } |
| 577 | |
| 578 | /// Returns work accumulated since construction or the previous reset. |
| 579 | pub fn work_counters(&self) -> RandomizedElementTreeWorkCounters { |
| 580 | self.work_counters.borrow().clone() |
| 581 | } |
| 582 | |
| 583 | /// Applies one seeded random style or structural mutation. |
| 584 | /// |
| 585 | /// This does not notify persistent child entities. Entity-aware callers should use |
| 586 | /// [`Self::apply_random_mutation`] from an entity update instead. |
| 587 | pub fn mutate(&mut self) -> RandomizedElementTreeMutation { |
| 588 | let kind = RandomizedElementTreeMutationKind::ALL[self |
| 589 | .rng |
| 590 | .random_range(0..RandomizedElementTreeMutationKind::ALL.len())]; |
| 591 | self.apply_mutation_without_notification(kind).mutation |
| 592 | } |
| 593 | |
| 594 | /// Applies one seeded random mutation and notifies its nearest persistent entity boundary. |
| 595 | pub fn apply_random_mutation( |
| 596 | &mut self, |
| 597 | cx: &mut Context<Self>, |
| 598 | ) -> RandomizedElementTreeMutation { |
| 599 | let kind = RandomizedElementTreeMutationKind::ALL[self |
| 600 | .rng |
| 601 | .random_range(0..RandomizedElementTreeMutationKind::ALL.len())]; |
| 602 | self.apply_mutation(kind, cx) |
| 603 | } |
| 604 | |
| 605 | /// Applies a selected mutation kind and notifies its nearest persistent entity boundary. |
| 606 | pub fn apply_mutation( |
| 607 | &mut self, |
| 608 | kind: RandomizedElementTreeMutationKind, |
| 609 | cx: &mut Context<Self>, |
| 610 | ) -> RandomizedElementTreeMutation { |
| 611 | let applied = self.apply_mutation_without_notification(kind); |
| 612 | if applied.synchronize_entities { |
| 613 | self.synchronize_entities(cx); |
| 614 | } |
| 615 | self.notify_owner(applied.owner_entity_id, cx); |
| 616 | applied.mutation |
| 617 | } |
| 618 | |
| 619 | /// Generates and inserts an element below a seeded random parent. |
| 620 | /// |
| 621 | /// This does not synchronize or notify persistent child entities. Entity-aware callers should |
| 622 | /// use [`Self::apply_mutation`] with [`RandomizedElementTreeMutationKind::Insert`]. |
| 623 | pub fn insert_child(&mut self) -> RandomizedElementTreeMutation { |
| 624 | self.insert_child_internal().mutation |
| 625 | } |
| 626 | |
| 627 | /// Removes a seeded random element and its subtree. |
| 628 | /// |
| 629 | /// This does not synchronize or notify persistent child entities. Entity-aware callers should |
| 630 | /// use [`Self::apply_mutation`] with [`RandomizedElementTreeMutationKind::Remove`]. |
| 631 | pub fn remove_child(&mut self) -> Option<RandomizedElementTreeMutation> { |
| 632 | self.remove_child_internal(false) |
| 633 | .map(|applied| applied.mutation) |
| 634 | } |
| 635 | |
| 636 | fn apply_mutation_without_notification( |
| 637 | &mut self, |
| 638 | kind: RandomizedElementTreeMutationKind, |
| 639 | ) -> AppliedRandomizedElementTreeMutation { |
| 640 | match kind { |
| 641 | RandomizedElementTreeMutationKind::RootColor => { |
| 642 | self.snapshot.borrow_mut().root.background = random_color(&mut self.rng); |
| 643 | AppliedRandomizedElementTreeMutation::root(RandomizedElementTreeMutation::RootColor) |
| 644 | } |
| 645 | RandomizedElementTreeMutationKind::RootOpacity => { |
| 646 | self.snapshot.borrow_mut().root.opacity = random_opacity(&mut self.rng); |
| 647 | AppliedRandomizedElementTreeMutation::root( |
| 648 | RandomizedElementTreeMutation::RootOpacity, |
| 649 | ) |
| 650 | } |
| 651 | RandomizedElementTreeMutationKind::RootBorder => { |
| 652 | self.snapshot |
| 653 | .borrow_mut() |
| 654 | .root |
| 655 | .randomize_border(&mut self.rng); |
| 656 | AppliedRandomizedElementTreeMutation::root( |
| 657 | RandomizedElementTreeMutation::RootBorder, |
| 658 | ) |
| 659 | } |
| 660 | RandomizedElementTreeMutationKind::RootBounds => { |
| 661 | let mut snapshot = self.snapshot.borrow_mut(); |
| 662 | snapshot.root.width = self.rng.random_range(520.0..980.0); |
| 663 | snapshot.root.height = self.rng.random_range(360.0..760.0); |
| 664 | AppliedRandomizedElementTreeMutation::root( |
| 665 | RandomizedElementTreeMutation::RootBounds, |
| 666 | ) |
| 667 | } |
| 668 | RandomizedElementTreeMutationKind::RootClipping => { |
| 669 | let mut snapshot = self.snapshot.borrow_mut(); |
| 670 | snapshot.root.clipped = !snapshot.root.clipped; |
| 671 | AppliedRandomizedElementTreeMutation::root( |
| 672 | RandomizedElementTreeMutation::RootClipping, |
| 673 | ) |
| 674 | } |
| 675 | RandomizedElementTreeMutationKind::RootVisibility => { |
| 676 | let mut snapshot = self.snapshot.borrow_mut(); |
| 677 | snapshot.root.visible = !snapshot.root.visible; |
| 678 | AppliedRandomizedElementTreeMutation::root( |
| 679 | RandomizedElementTreeMutation::RootVisibility, |
| 680 | ) |
| 681 | } |
| 682 | RandomizedElementTreeMutationKind::ChildColor => { |
| 683 | self.mutate_random_child(RandomizedChildMutation::Color) |
| 684 | } |
| 685 | RandomizedElementTreeMutationKind::ChildOpacity => { |
| 686 | self.mutate_random_child(RandomizedChildMutation::Opacity) |
| 687 | } |
| 688 | RandomizedElementTreeMutationKind::ChildBorder => { |
| 689 | self.mutate_random_child(RandomizedChildMutation::Border) |
| 690 | } |
| 691 | RandomizedElementTreeMutationKind::ChildBounds => { |
| 692 | self.mutate_random_child(RandomizedChildMutation::Bounds) |
| 693 | } |
| 694 | RandomizedElementTreeMutationKind::ChildClipping => { |
| 695 | self.mutate_random_child(RandomizedChildMutation::Clipping) |
| 696 | } |
| 697 | RandomizedElementTreeMutationKind::ChildVisibility => { |
| 698 | self.mutate_random_child(RandomizedChildMutation::Visibility) |
| 699 | } |
| 700 | RandomizedElementTreeMutationKind::Reorder => self.reorder_child(), |
| 701 | RandomizedElementTreeMutationKind::Insert => self.insert_child_internal(), |
| 702 | RandomizedElementTreeMutationKind::Remove => self |
| 703 | .remove_child_internal(false) |
| 704 | .unwrap_or_else(|| self.insert_child_internal()), |
| 705 | RandomizedElementTreeMutationKind::RemoveLeaf => self |
| 706 | .remove_child_internal(true) |
| 707 | .unwrap_or_else(|| self.insert_child_internal()), |
| 708 | } |
| 709 | } |
| 710 | |
| 711 | fn insert_child_internal(&mut self) -> AppliedRandomizedElementTreeMutation { |
| 712 | let mut snapshot = self.snapshot.borrow_mut(); |
| 713 | let element_id = snapshot.next_element_id; |
| 714 | snapshot.next_element_id += 1; |
| 715 | let mut parent_path = random_parent_path(&snapshot.children, &mut self.rng); |
| 716 | let parent_id = node_at_path(&snapshot.children, &parent_path).map(|node| node.id); |
| 717 | let owner_entity_id = nearest_entity_id(&snapshot.children, &parent_path); |
| 718 | let node = RandomizedElementNode::random( |
| 719 | element_id, |
| 720 | self.config.entity_density, |
| 721 | self.config.handler_density, |
| 722 | &mut self.rng, |
| 723 | ); |
| 724 | let (index, _) = insert_node(&mut snapshot.children, &mut parent_path, node); |
| 725 | snapshot.rebuild_element_paths(); |
| 726 | |
| 727 | AppliedRandomizedElementTreeMutation { |
| 728 | mutation: RandomizedElementTreeMutation::Inserted { |
| 729 | element_id, |
| 730 | parent_id, |
| 731 | index, |
| 732 | }, |
| 733 | owner_entity_id, |
| 734 | synchronize_entities: true, |
| 735 | } |
| 736 | } |
| 737 | |
| 738 | fn remove_child_internal( |
| 739 | &mut self, |
| 740 | leaves_only: bool, |
| 741 | ) -> Option<AppliedRandomizedElementTreeMutation> { |
| 742 | let mut snapshot = self.snapshot.borrow_mut(); |
| 743 | let path = if leaves_only { |
| 744 | random_leaf_path(&snapshot.children, &mut self.rng)? |
| 745 | } else { |
| 746 | random_node_path(&snapshot.children, &mut self.rng)? |
| 747 | }; |
| 748 | let (index, parent_path) = path.split_last()?; |
| 749 | let parent_id = node_at_path(&snapshot.children, parent_path).map(|node| node.id); |
| 750 | let owner_entity_id = nearest_entity_id(&snapshot.children, parent_path); |
| 751 | let siblings = children_at_path_mut(&mut snapshot.children, parent_path)?; |
| 752 | if *index >= siblings.len() { |
| 753 | return None; |
| 754 | } |
| 755 | |
| 756 | let removed = siblings.remove(*index); |
| 757 | let removed_element_count = removed.element_count(); |
| 758 | let element_id = removed.id; |
| 759 | snapshot.rebuild_element_paths(); |
| 760 | Some(AppliedRandomizedElementTreeMutation { |
| 761 | mutation: RandomizedElementTreeMutation::Removed { |
| 762 | element_id, |
| 763 | parent_id, |
| 764 | index: *index, |
| 765 | removed_element_count, |
| 766 | }, |
| 767 | owner_entity_id, |
| 768 | synchronize_entities: true, |
| 769 | }) |
| 770 | } |
| 771 | |
| 772 | /// Recolors `count` distinct seeded random descendants in one pass and notifies each |
| 773 | /// affected entity boundary once (the root, for descendants owned by no entity). |
| 774 | /// Returns how many descendants changed and how many boundaries were notified. |
| 775 | /// |
| 776 | /// This is the "share of the scene changing per frame" knob: `count` calls to |
| 777 | /// [`Self::apply_mutation`] would each walk the tree and notify separately, costing |
| 778 | /// more than the frame being measured once `count` is a fair share of the tree. |
| 779 | pub fn recolor_children( |
| 780 | &mut self, |
| 781 | count: usize, |
| 782 | locality: ChangeLocality, |
| 783 | cx: &mut Context<Self>, |
| 784 | ) -> RecoloredChildren { |
| 785 | let owners = { |
| 786 | let mut snapshot = self.snapshot.borrow_mut(); |
| 787 | let mut paths = node_paths(&snapshot.children); |
| 788 | let count = count.min(paths.len()); |
| 789 | if locality == ChangeLocality::Localized { |
| 790 | // Order the paths so one random entity's subtree comes first: the change |
| 791 | // stays inside that entity unless there is more of it than the subtree. |
| 792 | let entity_paths: Vec<_> = paths |
| 793 | .iter() |
| 794 | .filter(|path| { |
| 795 | node_at_path(&snapshot.children, path).is_some_and(|node| node.is_entity) |
| 796 | }) |
| 797 | .cloned() |
| 798 | .collect(); |
| 799 | if let Some(entity_path) = entity_paths |
| 800 | .get(self.rng.random_range(0..entity_paths.len().max(1))) |
| 801 | .cloned() |
| 802 | { |
| 803 | let (inside, outside): (Vec<_>, Vec<_>) = paths |
| 804 | .into_iter() |
| 805 | .partition(|path| path.starts_with(&entity_path)); |
| 806 | paths = inside; |
| 807 | paths.extend(outside); |
| 808 | } |
| 809 | } |
| 810 | // A partial Fisher–Yates shuffle over the first `count` slots: for `Spread`, a |
| 811 | // uniform sample of the tree; for `Localized`, a uniform sample of the chosen |
| 812 | // subtree, spilling into the rest only once the subtree is exhausted. |
| 813 | let sample_from = match locality { |
| 814 | ChangeLocality::Spread => paths.len(), |
| 815 | ChangeLocality::Localized => count, |
| 816 | }; |
| 817 | for index in 0..count { |
| 818 | let other = self.rng.random_range(index..sample_from.max(index + 1)); |
| 819 | paths.swap(index, other); |
| 820 | } |
| 821 | let mut owners = HashSet::default(); |
| 822 | for path in &paths[..count] { |
| 823 | owners.insert(nearest_entity_id(&snapshot.children, path)); |
| 824 | if let Some(node) = node_at_path_mut(&mut snapshot.children, path) { |
| 825 | node.style.background = random_color(&mut self.rng); |
| 826 | } |
| 827 | } |
| 828 | owners |
| 829 | }; |
| 830 | let notified = owners.len(); |
| 831 | let recolored = count.min(self.snapshot.borrow().descendant_count()); |
| 832 | for owner in owners { |
| 833 | self.notify_owner(owner, cx); |
| 834 | } |
| 835 | RecoloredChildren { |
| 836 | recolored, |
| 837 | notified, |
| 838 | } |
| 839 | } |
| 840 | |
| 841 | fn mutate_random_child( |
| 842 | &mut self, |
| 843 | mutation: RandomizedChildMutation, |
| 844 | ) -> AppliedRandomizedElementTreeMutation { |
| 845 | let mut snapshot = self.snapshot.borrow_mut(); |
| 846 | let Some(path) = random_node_path(&snapshot.children, &mut self.rng) else { |
| 847 | drop(snapshot); |
| 848 | return self.insert_child_internal(); |
| 849 | }; |
| 850 | let owner_entity_id = nearest_entity_id(&snapshot.children, &path); |
| 851 | let Some(node) = node_at_path_mut(&mut snapshot.children, &path) else { |
| 852 | drop(snapshot); |
| 853 | return self.insert_child_internal(); |
| 854 | }; |
| 855 | let element_id = node.id; |
| 856 | |
| 857 | let mutation = match mutation { |
| 858 | RandomizedChildMutation::Color => { |
| 859 | node.style.background = random_color(&mut self.rng); |
| 860 | RandomizedElementTreeMutation::ChildColor { element_id } |
| 861 | } |
| 862 | RandomizedChildMutation::Opacity => { |
| 863 | node.style.opacity = random_opacity(&mut self.rng); |
| 864 | RandomizedElementTreeMutation::ChildOpacity { element_id } |
| 865 | } |
| 866 | RandomizedChildMutation::Border => { |
| 867 | node.style.randomize_border(&mut self.rng); |
| 868 | RandomizedElementTreeMutation::ChildBorder { element_id } |
| 869 | } |
| 870 | RandomizedChildMutation::Bounds => { |
| 871 | node.style.width = self.rng.random_range(36.0..220.0); |
| 872 | node.style.height = self.rng.random_range(28.0..180.0); |
| 873 | RandomizedElementTreeMutation::ChildBounds { element_id } |
| 874 | } |
| 875 | RandomizedChildMutation::Clipping => { |
| 876 | node.style.clipped = !node.style.clipped; |
| 877 | RandomizedElementTreeMutation::ChildClipping { element_id } |
| 878 | } |
| 879 | RandomizedChildMutation::Visibility => { |
| 880 | node.style.visible = !node.style.visible; |
| 881 | RandomizedElementTreeMutation::ChildVisibility { element_id } |
| 882 | } |
| 883 | }; |
| 884 | AppliedRandomizedElementTreeMutation { |
| 885 | mutation, |
| 886 | owner_entity_id, |
| 887 | synchronize_entities: false, |
| 888 | } |
| 889 | } |
| 890 | |
| 891 | fn reorder_child(&mut self) -> AppliedRandomizedElementTreeMutation { |
| 892 | let mut snapshot = self.snapshot.borrow_mut(); |
| 893 | let parent_paths = parent_paths_with_multiple_children(&snapshot.children); |
| 894 | if parent_paths.is_empty() { |
| 895 | drop(snapshot); |
| 896 | return self.insert_child_internal(); |
| 897 | } |
| 898 | |
| 899 | let parent_path_index = self.rng.random_range(0..parent_paths.len()); |
| 900 | let Some(parent_path) = parent_paths.get(parent_path_index) else { |
| 901 | drop(snapshot); |
| 902 | return self.insert_child_internal(); |
| 903 | }; |
| 904 | let parent_id = node_at_path(&snapshot.children, parent_path).map(|node| node.id); |
| 905 | let owner_entity_id = nearest_entity_id(&snapshot.children, parent_path); |
| 906 | let Some(child_count) = |
| 907 | children_at_path(&snapshot.children, parent_path).map(<[RandomizedElementNode]>::len) |
| 908 | else { |
| 909 | drop(snapshot); |
| 910 | return self.insert_child_internal(); |
| 911 | }; |
| 912 | if child_count < 2 { |
| 913 | drop(snapshot); |
| 914 | return self.insert_child_internal(); |
| 915 | } |
| 916 | |
| 917 | let old_index = self.rng.random_range(0..child_count); |
| 918 | let mut new_index = self.rng.random_range(0..child_count - 1); |
| 919 | if new_index >= old_index { |
| 920 | new_index += 1; |
| 921 | } |
| 922 | |
| 923 | let Some(siblings) = children_at_path_mut(&mut snapshot.children, parent_path) else { |
| 924 | drop(snapshot); |
| 925 | return self.insert_child_internal(); |
| 926 | }; |
| 927 | let child = siblings.remove(old_index); |
| 928 | let element_id = child.id; |
| 929 | siblings.insert(new_index, child); |
| 930 | snapshot.rebuild_element_paths(); |
| 931 | AppliedRandomizedElementTreeMutation { |
| 932 | mutation: RandomizedElementTreeMutation::Reordered { |
| 933 | element_id, |
| 934 | parent_id, |
| 935 | old_index, |
| 936 | new_index, |
| 937 | }, |
| 938 | owner_entity_id, |
| 939 | synchronize_entities: false, |
| 940 | } |
| 941 | } |
| 942 | |
| 943 | fn synchronize_entities(&mut self, cx: &mut Context<Self>) { |
| 944 | let entity_ids = { |
| 945 | let snapshot = self.snapshot.borrow(); |
| 946 | snapshot |
| 947 | .element_ids() |
| 948 | .into_iter() |
| 949 | .filter(|element_id| { |
| 950 | snapshot |
| 951 | .node(*element_id) |
| 952 | .is_some_and(|node| node.is_entity) |
| 953 | }) |
| 954 | .collect::<Vec<_>>() |
| 955 | }; |
| 956 | let entity_id_set = entity_ids.iter().copied().collect::<HashSet<_>>(); |
| 957 | |
| 958 | self.entities |
| 959 | .borrow_mut() |
| 960 | .retain(|element_id, _| entity_id_set.contains(element_id)); |
| 961 | |
| 962 | let missing_entity_ids = { |
| 963 | let entities = self.entities.borrow(); |
| 964 | entity_ids |
| 965 | .into_iter() |
| 966 | .filter(|element_id| !entities.contains_key(element_id)) |
| 967 | .collect::<Vec<_>>() |
| 968 | }; |
| 969 | |
| 970 | let weak_entities = Rc::downgrade(&self.entities); |
| 971 | for element_id in missing_entity_ids { |
| 972 | let entity = cx.new(|_| RandomizedElementEntity { |
| 973 | element_id, |
| 974 | snapshot: self.snapshot.clone(), |
| 975 | entities: weak_entities.clone(), |
| 976 | work_counters: self.work_counters.clone(), |
| 977 | }); |
| 978 | self.entities.borrow_mut().insert(element_id, entity); |
| 979 | } |
| 980 | |
| 981 | let entity_count = self.entities.borrow().len(); |
| 982 | let mut work_counters = self.work_counters.borrow_mut(); |
| 983 | let additional_capacity = |
| 984 | entity_count.saturating_sub(work_counters.rendered_entity_ids.len()); |
| 985 | work_counters |
| 986 | .rendered_entity_ids |
| 987 | .reserve(additional_capacity); |
| 988 | } |
| 989 | |
| 990 | fn notify_owner(&self, owner_entity_id: Option<u64>, cx: &mut Context<Self>) { |
| 991 | let owner = |
| 992 | owner_entity_id.and_then(|element_id| self.entities.borrow().get(&element_id).cloned()); |
| 993 | if let Some(owner) = owner { |
| 994 | owner.update(cx, |_, cx| cx.notify()); |
| 995 | } else { |
| 996 | cx.notify(); |
| 997 | } |
| 998 | } |
| 999 | } |
| 1000 | |
| 1001 | impl Render for RandomizedElementTree { |
| 1002 | fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement { |
| 1003 | let snapshot = self.snapshot.borrow(); |
| 1004 | let root = &snapshot.root; |
| 1005 | let entities = self.entities.borrow(); |
| 1006 | let mut work_counters = self.work_counters.borrow_mut(); |
| 1007 | work_counters.root_render_count += 1; |
| 1008 | |
| 1009 | div() |
| 1010 | .flex() |
| 1011 | .when(root.vertical, |element| element.flex_col()) |
| 1012 | .when(root.wrap, |element| element.flex_wrap()) |
| 1013 | .gap(px(root.gap)) |
| 1014 | .p(px(root.padding)) |
| 1015 | .w(px(root.width)) |
| 1016 | .h(px(root.height)) |
| 1017 | .bg(root.background) |
| 1018 | .border(px(root.border_width)) |
| 1019 | .border_color(root.border_color) |
| 1020 | .rounded(px(root.corner_radius)) |
| 1021 | .opacity(root.opacity) |
| 1022 | .when(root.clipped, |element| element.overflow_hidden()) |
| 1023 | .when(!root.visible, |element| element.invisible()) |
| 1024 | .children( |
| 1025 | snapshot |
| 1026 | .children |
| 1027 | .iter() |
| 1028 | .map(|node| render_node(node, &entities, &mut work_counters)), |
| 1029 | ) |
| 1030 | } |
| 1031 | } |
| 1032 | |
| 1033 | type RandomizedElementEntities = HashMap<u64, Entity<RandomizedElementEntity>>; |
| 1034 | |
| 1035 | struct RandomizedElementEntity { |
| 1036 | element_id: u64, |
| 1037 | snapshot: Rc<RefCell<RandomizedElementTreeSnapshot>>, |
| 1038 | entities: Weak<RefCell<RandomizedElementEntities>>, |
| 1039 | work_counters: Rc<RefCell<RandomizedElementTreeWorkCounters>>, |
| 1040 | } |
| 1041 | |
| 1042 | impl Render for RandomizedElementEntity { |
| 1043 | fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement { |
| 1044 | let snapshot = self.snapshot.borrow(); |
| 1045 | let entities = self.entities.upgrade(); |
| 1046 | let entities = entities.as_ref().map(|entities| entities.borrow()); |
| 1047 | let mut work_counters = self.work_counters.borrow_mut(); |
| 1048 | work_counters.entity_render_count += 1; |
| 1049 | work_counters.rendered_entity_ids.push(self.element_id); |
| 1050 | |
| 1051 | snapshot |
| 1052 | .node(self.element_id) |
| 1053 | .map(|node| render_node_body(node, entities.as_deref(), &mut work_counters)) |
| 1054 | .unwrap_or_else(|| div().into_any_element()) |
| 1055 | } |
| 1056 | } |
| 1057 | |
| 1058 | struct AppliedRandomizedElementTreeMutation { |
| 1059 | mutation: RandomizedElementTreeMutation, |
| 1060 | owner_entity_id: Option<u64>, |
| 1061 | synchronize_entities: bool, |
| 1062 | } |
| 1063 | |
| 1064 | impl AppliedRandomizedElementTreeMutation { |
| 1065 | fn root(mutation: RandomizedElementTreeMutation) -> Self { |
| 1066 | Self { |
| 1067 | mutation, |
| 1068 | owner_entity_id: None, |
| 1069 | synchronize_entities: false, |
| 1070 | } |
| 1071 | } |
| 1072 | } |
| 1073 | |
| 1074 | #[derive(Clone, Debug, PartialEq)] |
| 1075 | struct RandomizedElementNode { |
| 1076 | id: u64, |
| 1077 | style: RandomizedElementStyle, |
| 1078 | is_entity: bool, |
| 1079 | features: RandomizedElementFeatures, |
| 1080 | children: Vec<RandomizedElementNode>, |
| 1081 | } |
| 1082 | |
| 1083 | impl RandomizedElementNode { |
| 1084 | fn random(id: u64, entity_density: f64, handler_density: f64, rng: &mut StdRng) -> Self { |
| 1085 | Self { |
| 1086 | id, |
| 1087 | style: RandomizedElementStyle::random_child(rng), |
| 1088 | is_entity: rng.random_bool(entity_density), |
| 1089 | features: RandomizedElementFeatures::random(handler_density, rng), |
| 1090 | children: Vec::new(), |
| 1091 | } |
| 1092 | } |
| 1093 | |
| 1094 | fn element_count(&self) -> usize { |
| 1095 | let mut count = 0; |
| 1096 | let mut stack = vec![self]; |
| 1097 | while let Some(node) = stack.pop() { |
| 1098 | count += 1; |
| 1099 | stack.extend(node.children.iter()); |
| 1100 | } |
| 1101 | count |
| 1102 | } |
| 1103 | } |
| 1104 | |
| 1105 | #[derive(Clone, Debug, PartialEq)] |
| 1106 | struct RandomizedElementFeatures { |
| 1107 | action_handler: bool, |
| 1108 | click_handler: bool, |
| 1109 | key_context: bool, |
| 1110 | } |
| 1111 | |
| 1112 | impl RandomizedElementFeatures { |
| 1113 | fn random(handler_density: f64, rng: &mut StdRng) -> Self { |
| 1114 | Self { |
| 1115 | action_handler: rng.random_bool(handler_density), |
| 1116 | click_handler: rng.random_bool(handler_density), |
| 1117 | key_context: rng.random_bool(handler_density), |
| 1118 | } |
| 1119 | } |
| 1120 | |
| 1121 | fn handler_count(&self) -> usize { |
| 1122 | usize::from(self.action_handler) + usize::from(self.click_handler) |
| 1123 | } |
| 1124 | } |
| 1125 | |
| 1126 | #[derive(Clone, Debug, PartialEq)] |
| 1127 | struct RandomizedElementStyle { |
| 1128 | background: Hsla, |
| 1129 | border_color: Hsla, |
| 1130 | opacity: f32, |
| 1131 | border_width: f32, |
| 1132 | corner_radius: f32, |
| 1133 | width: f32, |
| 1134 | height: f32, |
| 1135 | padding: f32, |
| 1136 | gap: f32, |
| 1137 | clipped: bool, |
| 1138 | visible: bool, |
| 1139 | vertical: bool, |
| 1140 | wrap: bool, |
| 1141 | } |
| 1142 | |
| 1143 | impl RandomizedElementStyle { |
| 1144 | fn random_root(rng: &mut StdRng) -> Self { |
| 1145 | Self { |
| 1146 | background: random_color(rng), |
| 1147 | border_color: random_color(rng), |
| 1148 | opacity: random_opacity(rng), |
| 1149 | border_width: rng.random_range(0.0..4.0), |
| 1150 | corner_radius: rng.random_range(0.0..18.0), |
| 1151 | width: rng.random_range(520.0..980.0), |
| 1152 | height: rng.random_range(360.0..760.0), |
| 1153 | padding: rng.random_range(4.0..18.0), |
| 1154 | gap: rng.random_range(2.0..14.0), |
| 1155 | clipped: rng.random_bool(0.5), |
| 1156 | visible: true, |
| 1157 | vertical: rng.random_bool(0.5), |
| 1158 | wrap: rng.random_bool(0.7), |
| 1159 | } |
| 1160 | } |
| 1161 | |
| 1162 | fn random_child(rng: &mut StdRng) -> Self { |
| 1163 | Self { |
| 1164 | background: random_color(rng), |
| 1165 | border_color: random_color(rng), |
| 1166 | opacity: random_opacity(rng), |
| 1167 | border_width: rng.random_range(0.0..4.0), |
| 1168 | corner_radius: rng.random_range(0.0..14.0), |
| 1169 | width: rng.random_range(36.0..220.0), |
| 1170 | height: rng.random_range(28.0..180.0), |
| 1171 | padding: rng.random_range(1.0..10.0), |
| 1172 | gap: rng.random_range(1.0..8.0), |
| 1173 | clipped: rng.random_bool(0.3), |
| 1174 | visible: rng.random_bool(0.9), |
| 1175 | vertical: rng.random_bool(0.5), |
| 1176 | wrap: rng.random_bool(0.4), |
| 1177 | } |
| 1178 | } |
| 1179 | |
| 1180 | fn randomize_border(&mut self, rng: &mut StdRng) { |
| 1181 | self.border_color = random_color(rng); |
| 1182 | self.border_width = rng.random_range(0.0..5.0); |
| 1183 | self.corner_radius = rng.random_range(0.0..18.0); |
| 1184 | } |
| 1185 | } |
| 1186 | |
| 1187 | #[derive(Clone, Copy)] |
| 1188 | enum RandomizedChildMutation { |
| 1189 | Color, |
| 1190 | Opacity, |
| 1191 | Border, |
| 1192 | Bounds, |
| 1193 | Clipping, |
| 1194 | Visibility, |
| 1195 | } |
| 1196 | |
| 1197 | #[cfg_attr(feature = "stacker", stacksafe::stacksafe)] |
| 1198 | fn render_node( |
| 1199 | node: &RandomizedElementNode, |
| 1200 | entities: &RandomizedElementEntities, |
| 1201 | work_counters: &mut RandomizedElementTreeWorkCounters, |
| 1202 | ) -> AnyElement { |
| 1203 | if node.is_entity |
| 1204 | && let Some(entity) = entities.get(&node.id) |
| 1205 | { |
| 1206 | return entity.clone().into_any_element(); |
| 1207 | } |
| 1208 | |
| 1209 | render_node_body(node, Some(entities), work_counters) |
| 1210 | } |
| 1211 | |
| 1212 | #[cfg_attr(feature = "stacker", stacksafe::stacksafe)] |
| 1213 | fn render_node_body( |
| 1214 | node: &RandomizedElementNode, |
| 1215 | entities: Option<&RandomizedElementEntities>, |
| 1216 | work_counters: &mut RandomizedElementTreeWorkCounters, |
| 1217 | ) -> AnyElement { |
| 1218 | work_counters.element_render_count += 1; |
| 1219 | work_counters.handler_registration_count += node.features.handler_count(); |
| 1220 | let style = &node.style; |
| 1221 | div() |
| 1222 | .id(ElementId::NamedInteger( |
| 1223 | "randomized-element".into(), |
| 1224 | node.id, |
| 1225 | )) |
| 1226 | .flex() |
| 1227 | .when(style.vertical, |element| element.flex_col()) |
| 1228 | .when(style.wrap, |element| element.flex_wrap()) |
| 1229 | .gap(px(style.gap)) |
| 1230 | .p(px(style.padding)) |
| 1231 | .w(px(style.width)) |
| 1232 | .h(px(style.height)) |
| 1233 | .bg(style.background) |
| 1234 | .border(px(style.border_width)) |
| 1235 | .border_color(style.border_color) |
| 1236 | .rounded(px(style.corner_radius)) |
| 1237 | .opacity(style.opacity) |
| 1238 | .when(style.clipped, |element| element.overflow_hidden()) |
| 1239 | .when(!style.visible, |element| element.invisible()) |
| 1240 | .when(node.features.action_handler, |element| { |
| 1241 | element.on_action(|_: &RandomizedElementTreeAction, _window, _cx| {}) |
| 1242 | }) |
| 1243 | .when(node.features.click_handler, |element| { |
| 1244 | element.on_click(|_event, _window, _cx| {}) |
| 1245 | }) |
| 1246 | .when(node.features.key_context, |element| { |
| 1247 | element.key_context("RandomizedElementTree") |
| 1248 | }) |
| 1249 | .children(node.children.iter().map(|child| { |
| 1250 | if let Some(entities) = entities { |
| 1251 | render_node(child, entities, work_counters) |
| 1252 | } else { |
| 1253 | render_node_body(child, None, work_counters) |
| 1254 | } |
| 1255 | })) |
| 1256 | .into_any_element() |
| 1257 | } |
| 1258 | |
| 1259 | fn insert_node( |
| 1260 | root_children: &mut Vec<RandomizedElementNode>, |
| 1261 | parent_path: &mut Vec<usize>, |
| 1262 | node: RandomizedElementNode, |
| 1263 | ) -> (usize, Vec<usize>) { |
| 1264 | let Some(children) = children_at_path_mut(root_children, parent_path) else { |
| 1265 | parent_path.clear(); |
| 1266 | let index = root_children.len(); |
| 1267 | root_children.push(node); |
| 1268 | return (index, vec![index]); |
| 1269 | }; |
| 1270 | |
| 1271 | let index = children.len(); |
| 1272 | children.push(node); |
| 1273 | let mut inserted_path = parent_path.clone(); |
| 1274 | inserted_path.push(index); |
| 1275 | (index, inserted_path) |
| 1276 | } |
| 1277 | |
| 1278 | fn random_parent_path(root_children: &[RandomizedElementNode], rng: &mut StdRng) -> Vec<usize> { |
| 1279 | let paths = node_paths(root_children); |
| 1280 | let index = rng.random_range(0..=paths.len()); |
| 1281 | paths.get(index).cloned().unwrap_or_default() |
| 1282 | } |
| 1283 | |
| 1284 | fn random_node_path( |
| 1285 | root_children: &[RandomizedElementNode], |
| 1286 | rng: &mut StdRng, |
| 1287 | ) -> Option<Vec<usize>> { |
| 1288 | let paths = node_paths(root_children); |
| 1289 | if paths.is_empty() { |
| 1290 | None |
| 1291 | } else { |
| 1292 | paths.get(rng.random_range(0..paths.len())).cloned() |
| 1293 | } |
| 1294 | } |
| 1295 | |
| 1296 | fn random_leaf_path( |
| 1297 | root_children: &[RandomizedElementNode], |
| 1298 | rng: &mut StdRng, |
| 1299 | ) -> Option<Vec<usize>> { |
| 1300 | let leaves = node_paths(root_children) |
| 1301 | .into_iter() |
| 1302 | .filter(|path| { |
| 1303 | node_at_path(root_children, path).is_some_and(|node| node.children.is_empty()) |
| 1304 | }) |
| 1305 | .collect::<Vec<_>>(); |
| 1306 | if leaves.is_empty() { |
| 1307 | None |
| 1308 | } else { |
| 1309 | leaves.get(rng.random_range(0..leaves.len())).cloned() |
| 1310 | } |
| 1311 | } |
| 1312 | |
| 1313 | fn parent_paths_with_multiple_children(root_children: &[RandomizedElementNode]) -> Vec<Vec<usize>> { |
| 1314 | let mut parent_paths = Vec::new(); |
| 1315 | if root_children.len() >= 2 { |
| 1316 | parent_paths.push(Vec::new()); |
| 1317 | } |
| 1318 | parent_paths.extend(node_paths(root_children).into_iter().filter(|path| { |
| 1319 | node_at_path(root_children, path).is_some_and(|node| node.children.len() >= 2) |
| 1320 | })); |
| 1321 | parent_paths |
| 1322 | } |
| 1323 | |
| 1324 | fn node_paths(root_children: &[RandomizedElementNode]) -> Vec<Vec<usize>> { |
| 1325 | let mut paths = Vec::new(); |
| 1326 | let mut stack = root_children |
| 1327 | .iter() |
| 1328 | .enumerate() |
| 1329 | .rev() |
| 1330 | .map(|(index, node)| (vec![index], node)) |
| 1331 | .collect::<Vec<_>>(); |
| 1332 | |
| 1333 | while let Some((path, node)) = stack.pop() { |
| 1334 | for (index, child) in node.children.iter().enumerate().rev() { |
| 1335 | let mut child_path = path.clone(); |
| 1336 | child_path.push(index); |
| 1337 | stack.push((child_path, child)); |
| 1338 | } |
| 1339 | paths.push(path); |
| 1340 | } |
| 1341 | paths |
| 1342 | } |
| 1343 | |
| 1344 | fn node_at_path<'a>( |
| 1345 | root_children: &'a [RandomizedElementNode], |
| 1346 | path: &[usize], |
| 1347 | ) -> Option<&'a RandomizedElementNode> { |
| 1348 | let (index, parent_path) = path.split_last()?; |
| 1349 | children_at_path(root_children, parent_path)?.get(*index) |
| 1350 | } |
| 1351 | |
| 1352 | fn node_at_path_mut<'a>( |
| 1353 | root_children: &'a mut Vec<RandomizedElementNode>, |
| 1354 | path: &[usize], |
| 1355 | ) -> Option<&'a mut RandomizedElementNode> { |
| 1356 | let (index, parent_path) = path.split_last()?; |
| 1357 | children_at_path_mut(root_children, parent_path)?.get_mut(*index) |
| 1358 | } |
| 1359 | |
| 1360 | fn children_at_path<'a>( |
| 1361 | mut children: &'a [RandomizedElementNode], |
| 1362 | path: &[usize], |
| 1363 | ) -> Option<&'a [RandomizedElementNode]> { |
| 1364 | for index in path { |
| 1365 | children = &children.get(*index)?.children; |
| 1366 | } |
| 1367 | Some(children) |
| 1368 | } |
| 1369 | |
| 1370 | fn children_at_path_mut<'a>( |
| 1371 | mut children: &'a mut Vec<RandomizedElementNode>, |
| 1372 | path: &[usize], |
| 1373 | ) -> Option<&'a mut Vec<RandomizedElementNode>> { |
| 1374 | for index in path { |
| 1375 | children = &mut children.get_mut(*index)?.children; |
| 1376 | } |
| 1377 | Some(children) |
| 1378 | } |
| 1379 | |
| 1380 | fn nearest_entity_id(root_children: &[RandomizedElementNode], path: &[usize]) -> Option<u64> { |
| 1381 | let mut children = root_children; |
| 1382 | let mut nearest_entity_id = None; |
| 1383 | for index in path { |
| 1384 | let node = children.get(*index)?; |
| 1385 | if node.is_entity { |
| 1386 | nearest_entity_id = Some(node.id); |
| 1387 | } |
| 1388 | children = &node.children; |
| 1389 | } |
| 1390 | nearest_entity_id |
| 1391 | } |
| 1392 | |
| 1393 | fn normalized_density(density: f64) -> f64 { |
| 1394 | if density.is_nan() { |
| 1395 | 0.0 |
| 1396 | } else { |
| 1397 | density.clamp(0.0, 1.0) |
| 1398 | } |
| 1399 | } |
| 1400 | |
| 1401 | fn random_color(rng: &mut StdRng) -> Hsla { |
| 1402 | Hsla { |
| 1403 | h: rng.random_range(0.0..1.0), |
| 1404 | s: rng.random_range(0.25..0.9), |
| 1405 | l: rng.random_range(0.18..0.82), |
| 1406 | a: 1.0, |
| 1407 | } |
| 1408 | } |
| 1409 | |
| 1410 | fn random_opacity(rng: &mut StdRng) -> f32 { |
| 1411 | rng.random_range(0.25..1.0) |
| 1412 | } |
| 1413 | |
| 1414 | #[cfg(test)] |
| 1415 | mod tests { |
| 1416 | use super::*; |
| 1417 | use crate::{ |
| 1418 | AnyWindowHandle, Background, BorderStyle, Bounds, ContentMask, Corners, Edges, Pixels, |
| 1419 | ScaledPixels, Size, TestAppContext, size, |
| 1420 | }; |
| 1421 | use proptest::prelude::*; |
| 1422 | use std::collections::BTreeSet; |
| 1423 | |
| 1424 | const ELEMENT_COUNT: usize = 64; |
| 1425 | const MUTATION_COUNT: usize = 32; |
| 1426 | const WINDOW_SIZE: Size<Pixels> = size(px(1200.0), px(900.0)); |
| 1427 | |
| 1428 | #[derive(Debug, PartialEq)] |
| 1429 | struct SceneSnapshot { |
| 1430 | quads: Vec<QuadSnapshot>, |
| 1431 | element_ids: BTreeSet<u64>, |
| 1432 | } |
| 1433 | |
| 1434 | impl SceneSnapshot { |
| 1435 | fn from_window(window: &Window) -> Self { |
| 1436 | Self { |
| 1437 | quads: window |
| 1438 | .rendered_frame |
| 1439 | .scene |
| 1440 | .quads |
| 1441 | .iter() |
| 1442 | .map(QuadSnapshot::from) |
| 1443 | .collect(), |
| 1444 | element_ids: window |
| 1445 | .rendered_frame |
| 1446 | .element_states |
| 1447 | .keys() |
| 1448 | .filter_map(|(global_id, _)| { |
| 1449 | let ElementId::NamedInteger(name, element_id) = global_id.0.last()? else { |
| 1450 | return None; |
| 1451 | }; |
| 1452 | (name.as_ref() == "randomized-element").then_some(*element_id) |
| 1453 | }) |
| 1454 | .collect(), |
| 1455 | } |
| 1456 | } |
| 1457 | } |
| 1458 | |
| 1459 | #[derive(Debug, PartialEq)] |
| 1460 | struct QuadSnapshot { |
| 1461 | order: u32, |
| 1462 | border_style: BorderStyle, |
| 1463 | bounds: Bounds<ScaledPixels>, |
| 1464 | content_mask: ContentMask<ScaledPixels>, |
| 1465 | background: Background, |
| 1466 | border_color: Hsla, |
| 1467 | corner_radii: Corners<ScaledPixels>, |
| 1468 | border_widths: Edges<ScaledPixels>, |
| 1469 | } |
| 1470 | |
| 1471 | impl From<&crate::Quad> for QuadSnapshot { |
| 1472 | fn from(quad: &crate::Quad) -> Self { |
| 1473 | Self { |
| 1474 | order: quad.order, |
| 1475 | border_style: quad.border_style, |
| 1476 | bounds: quad.bounds, |
| 1477 | content_mask: quad.content_mask, |
| 1478 | background: quad.background, |
| 1479 | border_color: quad.border_color, |
| 1480 | corner_radii: quad.corner_radii, |
| 1481 | border_widths: quad.border_widths, |
| 1482 | } |
| 1483 | } |
| 1484 | } |
| 1485 | |
| 1486 | #[gpui::test] |
| 1487 | fn localized_recoloring_notifies_one_entity_until_its_subtree_is_exhausted( |
| 1488 | cx: &mut TestAppContext, |
| 1489 | ) { |
| 1490 | // Wide: every element is a root child, so every entity's subtree is exactly one |
| 1491 | // element and localized change of k elements must touch k boundaries only when it |
| 1492 | // spills; a mixed tree has larger subtrees to stay inside. |
| 1493 | let config = RandomizedElementTreeConfig::new(11, 200) |
| 1494 | .with_topology(RandomizedElementTreeTopology::Mixed) |
| 1495 | .with_entity_density(0.1); |
| 1496 | let window = cx.open_window(WINDOW_SIZE, move |_, cx| { |
| 1497 | RandomizedElementTree::new_with_config(config, cx) |
| 1498 | }); |
| 1499 | let root = window.root(cx).expect("window has a root"); |
| 1500 | let (localized, spread) = root.update(cx, |tree, cx| { |
| 1501 | let localized = tree.recolor_children(20, ChangeLocality::Localized, cx); |
| 1502 | let spread = tree.recolor_children(20, ChangeLocality::Spread, cx); |
| 1503 | (localized, spread) |
| 1504 | }); |
| 1505 | assert_eq!(localized.recolored, 20); |
| 1506 | assert_eq!(spread.recolored, 20); |
| 1507 | assert!( |
| 1508 | localized.notified <= spread.notified, |
| 1509 | "localized change touches no more boundaries than spread change: {localized:?} vs {spread:?}" |
| 1510 | ); |
| 1511 | assert!(localized.notified >= 1); |
| 1512 | } |
| 1513 | |
| 1514 | #[test] |
| 1515 | fn bounds_sample_within_range_and_reproduce_from_the_seed() { |
| 1516 | let bounds = RandomizedElementTreeBounds::new(32..=256) |
| 1517 | .with_topologies([ |
| 1518 | RandomizedElementTreeTopology::Deep, |
| 1519 | RandomizedElementTreeTopology::Narrow, |
| 1520 | ]) |
| 1521 | .with_entity_density(0.1..=0.5) |
| 1522 | .with_handler_density(0.25..=0.25); |
| 1523 | let mut topologies = BTreeSet::new(); |
| 1524 | let sample = |seed| bounds.sample(&mut StdRng::seed_from_u64(seed)); |
| 1525 | for seed in 0..64 { |
| 1526 | let config = sample(seed); |
| 1527 | assert!((32..=256).contains(&config.element_count()), "{config:?}"); |
| 1528 | assert!(config.topology().is_tall(), "{config:?}"); |
| 1529 | assert!((0.1..=0.5).contains(&config.entity_density()), "{config:?}"); |
| 1530 | assert_eq!(config.handler_density(), 0.25); |
| 1531 | assert_eq!(sample(seed), config, "a seed draws the same config twice"); |
| 1532 | topologies.insert(format!("{:?}", config.topology())); |
| 1533 | } |
| 1534 | assert_eq!(topologies.len(), 2, "64 seeds pick both allowed topologies"); |
| 1535 | assert_ne!(sample(0), sample(1)); |
| 1536 | } |
| 1537 | |
| 1538 | #[test] |
| 1539 | fn generated_topologies_include_wide_deep_narrow_and_empty_trees() { |
| 1540 | let wide = RandomizedElementTree::new(0, ELEMENT_COUNT).snapshot(); |
| 1541 | assert_eq!(wide.children.len(), ELEMENT_COUNT); |
| 1542 | assert_eq!(wide.max_depth(), 1); |
| 1543 | |
| 1544 | let deep = RandomizedElementTree::new(1, ELEMENT_COUNT).snapshot(); |
| 1545 | assert_eq!(deep.children.len(), 1); |
| 1546 | assert_eq!(deep.max_depth(), ELEMENT_COUNT); |
| 1547 | |
| 1548 | let narrow = RandomizedElementTree::new(3, ELEMENT_COUNT).snapshot(); |
| 1549 | assert_eq!(narrow.descendant_count(), ELEMENT_COUNT); |
| 1550 | assert!(narrow.max_depth() > 1); |
| 1551 | |
| 1552 | let empty = RandomizedElementTree::new(2, 0).snapshot(); |
| 1553 | assert_eq!(empty.descendant_count(), 0); |
| 1554 | assert_eq!(empty.max_depth(), 0); |
| 1555 | } |
| 1556 | |
| 1557 | #[test] |
| 1558 | fn randomized_element_ids_are_unique_and_stable() { |
| 1559 | let mut tree = RandomizedElementTree::new(0, ELEMENT_COUNT); |
| 1560 | let initial_ids = tree.snapshot().element_ids(); |
| 1561 | assert_eq!(initial_ids.len(), ELEMENT_COUNT); |
| 1562 | assert_eq!( |
| 1563 | initial_ids.iter().copied().collect::<BTreeSet<_>>().len(), |
| 1564 | ELEMENT_COUNT |
| 1565 | ); |
| 1566 | |
| 1567 | for mutation in [ |
| 1568 | RandomizedChildMutation::Color, |
| 1569 | RandomizedChildMutation::Opacity, |
| 1570 | RandomizedChildMutation::Border, |
| 1571 | RandomizedChildMutation::Bounds, |
| 1572 | RandomizedChildMutation::Clipping, |
| 1573 | RandomizedChildMutation::Visibility, |
| 1574 | ] { |
| 1575 | tree.mutate_random_child(mutation); |
| 1576 | assert_eq!(tree.snapshot().element_ids(), initial_ids); |
| 1577 | } |
| 1578 | |
| 1579 | tree.reorder_child(); |
| 1580 | let reordered_ids = tree.snapshot().element_ids(); |
| 1581 | assert_eq!( |
| 1582 | reordered_ids.iter().copied().collect::<BTreeSet<_>>(), |
| 1583 | initial_ids.iter().copied().collect() |
| 1584 | ); |
| 1585 | |
| 1586 | tree.insert_child(); |
| 1587 | let inserted_ids = tree.snapshot().element_ids(); |
| 1588 | let inserted_id_set = inserted_ids.iter().copied().collect::<BTreeSet<_>>(); |
| 1589 | assert_eq!(inserted_ids.len(), ELEMENT_COUNT + 1); |
| 1590 | assert!(initial_ids.iter().all(|id| inserted_id_set.contains(id))); |
| 1591 | |
| 1592 | tree.remove_child(); |
| 1593 | let remaining_ids = tree.snapshot().element_ids(); |
| 1594 | assert_eq!( |
| 1595 | remaining_ids.iter().copied().collect::<BTreeSet<_>>().len(), |
| 1596 | remaining_ids.len() |
| 1597 | ); |
| 1598 | assert!(remaining_ids.iter().all(|id| inserted_id_set.contains(id))); |
| 1599 | } |
| 1600 | |
| 1601 | #[gpui::test] |
| 1602 | fn randomized_entities_and_work_counters_support_incremental_benchmarks( |
| 1603 | cx: &mut TestAppContext, |
| 1604 | ) { |
| 1605 | let config = RandomizedElementTreeConfig::new(0, 16) |
| 1606 | .with_topology(RandomizedElementTreeTopology::Wide) |
| 1607 | .with_entity_density(1.0) |
| 1608 | .with_handler_density(1.0); |
| 1609 | let window = cx.open_window(WINDOW_SIZE, move |_, cx| { |
| 1610 | RandomizedElementTree::new_with_config(config, cx) |
| 1611 | }); |
| 1612 | let root = window |
| 1613 | .root(cx) |
| 1614 | .expect("randomized tree window should have a root"); |
| 1615 | let window = AnyWindowHandle::from(window); |
| 1616 | |
| 1617 | draw_window(window, cx); |
| 1618 | let initial_counters = root.read_with(cx, |tree, _| tree.work_counters()); |
| 1619 | assert!(initial_counters.root_render_count() >= 1); |
| 1620 | assert!(initial_counters.entity_render_count() >= 16); |
| 1621 | assert!(initial_counters.element_render_count() >= 16); |
| 1622 | assert!(initial_counters.handler_registration_count() >= 32); |
| 1623 | |
| 1624 | let mutation = root.update(cx, |tree, cx| { |
| 1625 | tree.reset_work_counters(); |
| 1626 | tree.apply_mutation(RandomizedElementTreeMutationKind::ChildColor, cx) |
| 1627 | }); |
| 1628 | let RandomizedElementTreeMutation::ChildColor { element_id } = mutation else { |
| 1629 | panic!("a nonempty tree should apply the requested child-color mutation"); |
| 1630 | }; |
| 1631 | draw_window(window, cx); |
| 1632 | |
| 1633 | let incremental_counters = root.read_with(cx, |tree, _| tree.work_counters()); |
| 1634 | assert!(incremental_counters.root_render_count() >= 1); |
| 1635 | assert!(incremental_counters.entity_render_count() >= 1); |
| 1636 | assert!(incremental_counters.element_render_count() >= 1); |
| 1637 | assert!(incremental_counters.handler_registration_count() >= 2); |
| 1638 | assert!( |
| 1639 | incremental_counters |
| 1640 | .rendered_entity_ids() |
| 1641 | .contains(&element_id) |
| 1642 | ); |
| 1643 | |
| 1644 | cx.update_window(window, |_, window, _| window.remove_window()) |
| 1645 | .expect("randomized tree window should remain open until the case completes"); |
| 1646 | } |
| 1647 | |
| 1648 | #[gpui::property_test(config = ProptestConfig { |
| 1649 | cases: 4, |
| 1650 | ..Default::default() |
| 1651 | })] |
| 1652 | fn randomized_element_tree_matches_full_render(cx: &mut TestAppContext, seed: u64) { |
| 1653 | for topology in 0..4 { |
| 1654 | let topology_seed = (seed & !3) | topology; |
| 1655 | let config = RandomizedElementTreeConfig::new(topology_seed, ELEMENT_COUNT) |
| 1656 | .with_entity_density(0.2) |
| 1657 | .with_handler_density(0.2); |
| 1658 | run_render_equivalence_case(cx, config); |
| 1659 | } |
| 1660 | run_render_equivalence_case( |
| 1661 | cx, |
| 1662 | RandomizedElementTreeConfig::new(seed, 0) |
| 1663 | .with_entity_density(0.2) |
| 1664 | .with_handler_density(0.2), |
| 1665 | ); |
| 1666 | } |
| 1667 | |
| 1668 | fn run_render_equivalence_case(cx: &mut TestAppContext, config: RandomizedElementTreeConfig) { |
| 1669 | let persistent_window = cx.open_window(WINDOW_SIZE, move |_, cx| { |
| 1670 | RandomizedElementTree::new_with_config(config, cx) |
| 1671 | }); |
| 1672 | let persistent_root = persistent_window |
| 1673 | .root(cx) |
| 1674 | .expect("randomized tree window should have a root"); |
| 1675 | let persistent_window = AnyWindowHandle::from(persistent_window); |
| 1676 | |
| 1677 | assert_matches_reference(&persistent_root, persistent_window, cx, config, None); |
| 1678 | |
| 1679 | for mutation_index in 0..MUTATION_COUNT { |
| 1680 | let mutation = persistent_root.update(cx, |tree, cx| match mutation_index { |
| 1681 | 0 => tree.apply_mutation(RandomizedElementTreeMutationKind::Insert, cx), |
| 1682 | 1 => tree.apply_mutation(RandomizedElementTreeMutationKind::Remove, cx), |
| 1683 | _ => tree.apply_random_mutation(cx), |
| 1684 | }); |
| 1685 | |
| 1686 | assert_matches_reference( |
| 1687 | &persistent_root, |
| 1688 | persistent_window, |
| 1689 | cx, |
| 1690 | config, |
| 1691 | Some((mutation_index, mutation)), |
| 1692 | ); |
| 1693 | } |
| 1694 | |
| 1695 | cx.update_window(persistent_window, |_, window, _| window.remove_window()) |
| 1696 | .expect("persistent window should remain open until the case completes"); |
| 1697 | } |
| 1698 | |
| 1699 | fn assert_matches_reference( |
| 1700 | persistent_root: &crate::Entity<RandomizedElementTree>, |
| 1701 | persistent_window: AnyWindowHandle, |
| 1702 | cx: &mut TestAppContext, |
| 1703 | config: RandomizedElementTreeConfig, |
| 1704 | mutation: Option<(usize, RandomizedElementTreeMutation)>, |
| 1705 | ) { |
| 1706 | let snapshot = persistent_root.read_with(cx, |tree, _| tree.snapshot()); |
| 1707 | let expected_element_ids = snapshot.element_ids().into_iter().collect::<BTreeSet<_>>(); |
| 1708 | let persistent_scene = draw_window(persistent_window, cx); |
| 1709 | assert_eq!( |
| 1710 | persistent_scene.element_ids, expected_element_ids, |
| 1711 | "persistent frame element IDs diverged from the model for config {config:?}, after \ |
| 1712 | mutation {mutation:?}" |
| 1713 | ); |
| 1714 | let reference_scene = draw_fresh_reference(snapshot, cx); |
| 1715 | |
| 1716 | assert_eq!( |
| 1717 | persistent_scene, reference_scene, |
| 1718 | "rendered scene diverged for config {config:?}, after mutation {mutation:?}" |
| 1719 | ); |
| 1720 | } |
| 1721 | |
| 1722 | fn draw_fresh_reference( |
| 1723 | snapshot: RandomizedElementTreeSnapshot, |
| 1724 | cx: &mut TestAppContext, |
| 1725 | ) -> SceneSnapshot { |
| 1726 | let reference_window = cx.open_window(WINDOW_SIZE, move |_, cx| { |
| 1727 | RandomizedElementTree::from_snapshot_with_entities(snapshot, cx) |
| 1728 | }); |
| 1729 | let reference_window = AnyWindowHandle::from(reference_window); |
| 1730 | let scene = draw_window(reference_window, cx); |
| 1731 | cx.update_window(reference_window, |_, window, _| window.remove_window()) |
| 1732 | .expect("reference window should remain open until its frame is captured"); |
| 1733 | scene |
| 1734 | } |
| 1735 | |
| 1736 | fn draw_window(window: AnyWindowHandle, cx: &mut TestAppContext) -> SceneSnapshot { |
| 1737 | cx.update_window(window, |_, window, cx| { |
| 1738 | let arena_clear_needed = window.draw(cx); |
| 1739 | let scene = SceneSnapshot::from_window(window); |
| 1740 | arena_clear_needed.clear(cx); |
| 1741 | scene |
| 1742 | }) |
| 1743 | .expect("randomized element tree window should remain open while drawing") |
| 1744 | } |
| 1745 | } |