{"owner":"linebender","repo":"xilem","hasSkills":true,"totalSkillsCount":3,"totalTokensCount":5020,"categories":["project-spec"],"hasMcp":false,"mcpConfig":null,"found":["ARCHITECTURE.md","xilem/ARCHITECTURE.md","masonry/ARCHITECTURE.md"],"skills":{"ARCHITECTURE.md":"# ARCHITECTURE\n\nThis repository holds the source code for the Xilem project and the Masonry project, including their sub-crates.\n\n- Xilem is a family of high-level GUI frameworks. Xilem apps are written with idiomatic Rust code, with little to no reliance on macros and DSLs.\n    - **`xilem_core`** includes the traits that define Xilem.\n    - **`xilem_masonry`** is the natively compiled framework, built on Masonry.\n    - **`xilem`** is a batteries-included wrapper for `xilem_masonry` using `winit` for platform support.\n    - **`xilem_web`** is the web framework, built on the DOM.\n- Masonry is a foundational framework for building high-level Rust GUI libraries.\n    - **`masonry_core`** includes the base GUI engine.\n    - **`masonry_testing`** includes a harness, helper macros and functions, etc, for testing apps built with Masonry.\n    - **`masonry`** includes a baseline set of widgets and properties, a default theme, unit tests for widgets, and unit tests for `masonry_core`.\n    - **`masonry_winit`** is the winit backend.\n\nSee [xilem/ARCHITECTURE.md](./xilem/ARCHITECTURE.md) and [masonry/ARCHITECTURE.md](./masonry/ARCHITECTURE.md) for more details on each project.\n\nThis repo also holds `tree_arena`, a crate which implements a hierarchical container, which has some properties of a tree (given a mutable reference to a node, you can get disjoint references to its value and children), while allowing `O(1)` (in unsafe mode) access to any element.\n\n```mermaid\ngraph TD\n%%   subgraph Masonry\n    masonry[Masonry]\n    masonry_core[Masonry Core]\n%%   end\n    %% subgraph Masonry Drivers\n        masonry_testing[Masonry Testing]\n        masonry_winit[Masonry Winit]\n        masonry_android_view[Masonry Android View]\n    %% end\n%%   subgraph Xilem\n    xilem[Xilem]\n    xilem_masonry[Xilem Masonry]\n    xilem_core[Xilem Core]\n    xilem_web[Xilem Web]\n%%   end\n%%   subgraph Vello\n        vello[Vello]\n        vello_encoding[Vello Encoding]\n        vello_shaders[Vello Shaders]\n        peniko[Peniko]\n%%   end\n%%   subgraph Parley\n    parley[Parley]\n    fontique[Fontique]\n%%   end\ntree_arena[Tree Arena]\n%%   subgraph Font Infrastructure\n    linebender_resource_handle[Linebender Resource Handle]\n    skrifa[\"Skrifa (Google Fonts)\"]\n    swash[Swash]\n    harfrust[\"HarfRust (HarfBuzz)\"]\n%%   end\n\ncolor[Color]\nkurbo[Kurbo]\nweb_sys[\"web-sys (wasm-bindgen)\"]\n\nwgpu[\"Wgpu (gfx-rs)\"]\n\nfontique --> linebender_resource_handle\nmasonry-->masonry_core\nmasonry-- (dev) -->masonry_testing\nmasonry_testing-->masonry_core\n\nmasonry_android_view --> masonry_core\nmasonry_winit --> masonry_core\nharfrust --> skrifa\nswash --> skrifa\nparley --> swash\nparley --> harfrust\nparley --> fontique\n\npeniko --> color\npeniko --> kurbo\n\nvello --> vello_shaders\nvello_shaders --> vello_encoding\nvello --> vello_encoding\nvello_encoding --> skrifa\nvello --> wgpu\n\nvello --> peniko\nvello --> linebender_resource_handle\n\nxilem_web --> web_sys\nxilem_web --> xilem_core\nmasonry_core -->  vello\nmasonry_core -->  parley\nmasonry_core -->  tree_arena\n\nxilem_masonry --> xilem_core\nxilem_masonry --> masonry\n\nxilem --> xilem_masonry\nxilem --> masonry_winit\n```","xilem/ARCHITECTURE.md":"# ARCHITECTURE\n\nXilem is a family of high-level GUI frameworks.\nXilem apps are written with idiomatic Rust code, with little to no reliance on macros and DSLs.\n\n\n## General architecture\n\nThe most important thing about Xilem is that it is a *reactive* architecture:\n\n- After every change, user-provided functions are called to generate a **view tree**, a lightweight representation of the app's UI.\n- The new view tree is compared against the previous view tree.\n- Based on the differences, the back-end creates an updates a retained **element tree**.\n  Elements are added, removed or mutated to match the current view tree.\n    - In `xilem`, the element tree is the Masonry widget tree.\n    - in `xilem_web`, the element tree is the DOM.\n\nThis architecture is strongly inspired by React, Elm and SwiftUI, which work on similar principles.\n\nA Xilem app's code will usually be made of functions called **components** that create and return subsets of the view tree.\nA component function might look like this pseudo-code:\n\n```rust\nfn list_item(item: &ItemData) -> impl View<...> {\n    row((\n        image(item.image_url),\n        text(item.text),\n        button(\"Do thing\").on_click(|...| do_thing(item.id)),\n    ))\n}\n```\n\n\n## High-level Goals\n\n- **Good Performance:** Xilem aims for the \"performant by default\" class of Rust software. \n  Everything isn't always optimized, but it uses sober data structures and high-performance dependencies (Vello, Parley, wgpu).\n  Static typing gives us very efficient diffing of view trees by default.\n- **Productive:** Xilem offers a high-level API, designed to bypass the borrowing and state management issues that retained GUIs suffer from in Rust.\n- **Idiomatic:** Xilem apps are low on macros or DSLs.\n  Writing a component is about creating and composing view objects, no special syntax needed.\n- **Batteries-included:** Through Masonry, Xilem includes advanced text layout, IME, accessibility trees and styling.\n- **Wide platform support:** Xilem supports the web through `xilem_web` and desktop/mobile platforms through `masonry` and `winit`.\n\n\n## Code layout\n\nThe Xilem project includes these crates:\n\n- **`xilem_core`:** Includes the core traits such as `View`, `ViewElement`, `ViewSequence`, `ElementSlice`, and many others. Also include some generic implementations for these traits (e.g. for Box, Arc, tuples, etc).\n- **`xilem_web`:** Web backend for Xilem. Depends on `xilem_core` and `wasm-bindgen`.\n- **`xilem_masonry`:** Natively compiled backend for Xilem. Depends on `xilem_core` and `masonry`.\n- **`xilem`:** Wrapper crate for `xilem_masonry`, which provides a batteries-included experience for new users. Depends on `xilem_masonry` and `masonry_winit`.\n\n\n## Doc examples\n\nCode snippets in docs comments in both `xilem` and `xilem_masonry` should be as self-contained as possible.\n\nThere should only be a single (visible) import statement at the beginning, listing all the needed imports.\n\nThat import statement should start with `use xilem::`; in other words, all examples should assume that Xilem is the only available dependency (aside from the standard library).\n\nIt should be possible for users to copy-paste the example code into an empty module and have it compile.\nAs such, we should avoid `# ` prefixes when possible.\nView examples should include the whole `fn view() -> impl View<...> {` and `}` parts.\n\n*Note:* Some examples in `xilem` don't currently respect these guidelines.\nWe should fix those examples, and make sure future examples do.\n\n\n## Writing Xilem code\n\n**TODO - This section needs a rewrite.**\n\nYour main interaction with the framework is through the `app_logic()`. Like Elm, the `app_logic()` contains centralized state. On each cycle (meaning, roughly, on each high-level UI interaction such as a button click), the framework calls a closure, giving it mutable access to the `AppData`, and the return value is a `View` tree. This `View` tree is fairly short-lived; it is used to render the UI, possibly dispatch some events, and be used as a reference for diffing by the next cycle, at which point it is dropped. You pass the `app_logic()` to the framework (represented by `Xilem`) and then use it to create the window and run the UI.\n\n```rust\nstruct AppData {\n    count: u32,\n}\n\nfn app_logic(data: &mut AppData) -> impl View<AppData, (), Element = impl Widget> {\n    let count = data.count\n    let button_label = if count == 1 {\n        \"clicked 1 time\".to_string()\n    } else {\n        format!(\"clicked {count} times\")\n    };\n    button(button_label, |data: &mut AppData| data.count +=1)\n}\n\nfn main() {\n    let data = AppData {\n      count: 0\n    }\n    let app = Xilem::new(data, app_logic);\n    app.run_windowed(\"Application Example\".into()).unwrap();\n}\n```\nThe most important construct at the reactive layer is the `View` trait. `View` implementations need to assign the associated `State` and `Element` and implement `build()`, `rebuild()` and `message()`. The `build()` is run only once (first run) to initialize the associated `State` create the associated `Element`of the view. The `rebuild()` is used to update the associated `State` and `Element` and it is what enables Xilem's reactivity. It is worth noting three special types of views the `lens`, `Memoize` and `AnyView` views. \n\nThe `lens` view is used to adapt/convert from the parent data (often the `AppData`) to the child data (some subset of the `AppData`).\n\nThe `View` trees are always eagerly evaluated when the `app_logic()` is called. Even though the `View`'s are very lightweight when the tree becomes large it can create performance issues; the `Memoize` node prunes the `View` tree to improve performance. The generation of the subtree is postponed until the `build()`/`rebuild()` are executed. If none of the `AppData` dependencies change during a UI cycle neither the `View` subtree will be constructed nor the `rebuild()` will be called. The `View` subtree will only be constructed if any of the `AppData` dependencies change. The `Memoize` node should be used when the subtree is a pure function of the `AppData`.\n\nGenerally the Xilem `View` tree is statically typed. `AnyView` allows for the tree to be type erased to enable easy dynamic reconfiguration of the UI. \n","masonry/ARCHITECTURE.md":"# ARCHITECTURE\n\nMasonry is a framework that aims to provide the foundation for Rust GUI libraries.\n\nDevelopers trying to write immediate-mode GUIs, Elm-architecture GUIs, functional reactive GUIs, etc, can import Masonry and get a platform to create windows (often using Winit as a backend) each with a tree of widgets.\nEach widget has to implement the `Widget` trait that Masonry provides.\n\n\n## High-level goals\n\nMasonry has some opinionated design goals:\n\n- **Be dumb.** As a general rule, Masonry doesn't do \"algorithms\".\n  It has no reconciliation logic, no behind-the-scenes dataflow, no clever optimizations, etc.\n  It tries to be efficient, but that efficiency comes from well-designed interfaces and well-placed abstraction boundaries.\n  High-level logic should be implemented in downstream crates.\n- **No mutability tricks.** Masonry uses no unsafe code and as few cells/mutexes as possible.\n  It's designed to work within Rust's ownership system, not to bypass it.\n  While it relies on the `tree_arena` crate in this repository which *does* perform some mutability tricks, the resulting usage patterns are still very rust-like.\n- **Facilitate testing.** The `masonry_testing` crate provides a `TestHarness` type that helps users write unit tests, including tests with simulated user interactions and screenshot tests.\n  In general, every feature should be designed with easy-to-write high-reliability tests in mind.\n- **Facilitate debugging.** GUI app bugs are often easy to fix, but extremely painful to track down.\n  GUI framework bugs are worse.\n  Masonry should facilitate reproducing bugs and pinpointing which bit of code they come from.\n- **Provide reflection.** Masonry should help developers surface some of the inherent structure in GUI programs.\n  It should provide tools out-of-the-box to get information about the widget tree, performance indicators, etc.\n  It should also provide accessibility data out-of-the-box.\n- **Be well-tested:** Masonry doesn't just provide lots of testing tools, it also has a lot of tests.\n  These are a core part of the Masonry development experience.\n\n\n## Code layout\n\nThe Masonry project includes these crates in the Xilem repository:\n\n- **`masonry_core`:** includes the core traits, types and abstractions.\n- **`masonry_testing`:** includes a harness, helper macros and functions, etc, for testing apps built with Masonry.\n- **`masonry`:** includes a baseline set of widgets and properties, a default theme, unit tests for widgets, and unit tests for `masonry_core`.\n- **`masonry_winit`:** the winit backend.\n\n### `masonry_core/src/core/`\n\nMost widget-related code, including the `Widget` trait, its context types, event types, and the `WidgetRef`, `WidgetMut`, and `WidgetPod` types.\n\n#### `masonry_core/src/core/widget_state.rs`\n\nContains the WidgetState type, around which a lot of internal code is based.\n\n`WidgetState` is one of the most important internal types in Masonry.\nUnderstanding Masonry pass code will likely be easier if you read `WidgetState` documentation first.\n\n### `masonry_core/src/app/tracing_backend.rs`\n\nCode for setting up a default configuration of the `tracing` crate.\n\n### `masonry_core/src/app/render_root.rs`\n\nMasonry's composition root. See **General architecture** section.\n\n### `masonry_core/src/layout/`\n\nLayout specific core types.\n\n### `masonry_core/src/passes/`\n\nMasonry's passes are computations that run on the entire widget tree (iff invalidation flags are set) once per frame.\n\n`event.rs` and `update.rs` include a bunch of related passes.\nEvery other file only includes one pass.\n`mod.rs` has utility functions shared between multiple passes.\n\n### `masonry_core/src/properties`\n\nCore properties that every widget has.\n\n### `masonry_core/src/doc/`\n\nLow-level documentation for masonry's cross-cutting concepts.\nIncludes documentation for the pass system, and definitions for various terms used in other places.\n\n### `masonry_core/src/`\n\nContains the TestHarness type, various helper widgets for writing tests, and the snapshot testing code.\n\n### `masonry/src/widgets/`\n\nA list of basic widgets, each defined in a single file.\n\n### `masonry/src/properties/`\n\nA list of properties, which are small plain-old-data types used to customize a widget's look and behavior.\n\n#### `masonry/src/properties/types/`\n\nA list of vocabulary types used in multiple properties.\n\n### `masonry/src/doc/`\n\nHigh-level tutorial for Masonry.\nIn other projects, this would be an `mdbook` doc, but we choose to directly inline the doc, so that `cargo test` runs on it directly.\n\n### `masonry_winit/src/event_loop_runner.rs`\n\nThe bulk of the integration between Masonry and winit.\n\n\n## Module organization principles\n\n### Module structure\n\nThe public module hierarchy should be relatively flat.\nThis makes documentation more readable; readers don't need to click on multiple modules to find the item they're looking for, and maintainers don't need to open multiple layers of folders to find a file.\n\n### Imports\n\nWe should avoid `use super::xxx` imports, except for specific cases like unit tests.\n\nMost imports in the code base should use the canonical top-level import.\n\n### Avoid glob imports\n\nWe should avoid `use foo::*` imports, because they make it harder for people reading the code outside an IDE to track where a given import comes from.\n\nGlob re-exports (e.g. `pub use my_module::*`) are fine and encouraged from `mod.rs` files.\n\n### No prelude\n\nMasonry should have no prelude.\nExamples and documentation should deliberately have a list of imports that cover everything users will need, so users can copy-paste these lists.\n\n\n## General architecture\n\n### Platform handlers\n\nThe composition roots of Masonry are:\n\n- **RenderRoot**, which owns the widget tree.\n- The **AppDriver** trait, which owns the business logic.\n- The **run_with** function in `event_loop_runner.rs`.\n\nThe high-level control flow of a Masonry app's render loop is usually:\n\n- The platform library (windows, macos, x11, etc) runs some callbacks written in Winit in response to user interactions, timers, or other events.\n- Winit calls some RenderRoot method.\n- RenderRoot runs a series of passes (events, updates, paint, accessibility, etc).\n- Throughout those passes, RenderRootSignal values are pushed to a queue which winit can query.\n- winit may change its internals or schedule another frame based on those signals.\n\n\n### Widget hierarchy and passes\n\nThe **Widget** trait is defined in `src/widget/widget.rs`.\nMost of the widget-related bookkeeping is done in the passes defined in `src/passes`.\n\nA **WidgetPod** is the main way to store a child for container widgets.\nIn general, the widget hierarchy looks like a tree of container widgets, with each container owning a `WidgetPod` or a `Vec` of `WidgetPod` or something similar.\n\nWhen RenderRoot runs a pass (on_xxx_event/update_xxx/paint), it iterates over the widget tree, usually in depth-first pre-order, and calls the matching method on each concerned widget.\n\nThere is one exception to this pattern: the layout pass requires widgets to \"manually\" recurse to their children.\n\nThe current passes are:\n\n- **mutate:** Runs a list of callbacks with mutable access to the widget tree. These callbacks can either be passed by the event loop, or pushed to a queue by widgets during the other passes.\n- **on_xxx_event:** Handles UX-related events, e.g. clicks, text entered, IME updates and accessibility input. Widgets can declare these events as \"handled\" which has a bunch of semantic implications.\n- **anim:** Do updates related to an animation frame.\n- **update:** Handles internal changes to some widgets, e.g. when the widget is marked as \"disabled\" or Masonry detects that a widget is hovered by a pointer.\n- **layout:** Container widgets measure their children with `LayoutCtx::compute_size` and then lay them out with `LayoutCtx::run_layout`, finally giving them a position with `LayoutCtx::place_child`.\n- **compose:** Computes the global transform/origin for every widget.\n- **paint** Paint every widget.\n- **accessibility:** Compute every widget's node in the accessibility tree.\n\nSee [masonry_core/src/doc/pass_system.md] for details.\n\n\n### WidgetMut\n\nIn Masonry, widgets can't be mutated directly.\nAll mutations go through a `WidgetMut` wrapper.\nSo, to change a label's text, you might call `WidgetMut<Label>::set_text()`.\nThis helps Masonry make sure that internal metadata is propagated after every widget change.\n\nIn general, there's three ways to get a `WidgetMut`:\n\n- From a `WidgetMut` to a parent widget.\n- As an argument to the callback passed to `RenderRoot::edit_widget()`.\n- As an argument to a callback pushed to the mutate pass.\n\nIn most cases, the `WidgetMut` holds a reference to a WidgetState that will be updated when the `WidgetMut` is dropped.\n\n`WidgetMut` gives direct mutable access to the widget tree.\nThis can be used by GUI frameworks in their tree update methods, and it can be used in tests to make specific local modifications and test their result.\n\n\n### Properties\n\nProperties (often abbreviated to props) are values of arbitrary static types stored alongside each widget.\n\nProperties are a way for widgets to store arbitrary state, not behavior; they're similar to the \"Component\" part of ECS.\n\nThey can be things like Background, BorderColor, BorderWidth, Padding, ContentColor, etc.\n\nAlmost all widget methods take a `PropertiesRef` or `PropertiesMut` parameter that lets them access their properties.\n\nSee [masonry/src/doc/widget_properties.md] for details.\n\n\n### Tests\n\nMasonry is designed to make unit tests easy to write, as if the test function were a mouse-and-keyboard user.\n\nTesting is provided by the **TestHarness** type implemented in the `masonry_testing` crate.\n\nIdeally, the harness should provide ways to emulate absolutely every feature that Masonry apps can use.\nBesides the widget tree, that means keyboard events, mouse events, IME, timers, communication with background threads, animations, accessibility info, etc.\n\n(TODO - Some of that emulation support is not implemented yet. See <https://github.com/linebender/xilem/issues/369>.)\n\nEach widget has unit tests in its module and major features have modules with dedicated unit test suites.\nIdeally, we would like to achieve complete coverage within the crate.\n\n#### Screenshot tests\n\nTODO - mention kompari\n\nTestHarness can render a widget tree, save the result to an image, and compare the image to a stored snapshot.\nThis lets us check that (1) our widgets' paint methods don't panic and (2) changes don't introduce accidental regression in their visual appearance.\n\nTo avoid accumulating large files in the repository, we optimize screenshots with the `oxipng` tool.\nScreenshots tests will fail by default if the saved screenshot is larger than 8KiB.\n\n#### Tests Are Important\n\nTesting is a core element of Masonry.\n\nWhile we don't follow TDD, we have a lot of tests, and *that matters*.\nExtensive testing has helped us catch bugs, find corner cases in our features, and lets us do complex refactors without worrying about breaking something without anyone realizing for years.\n\nWe test individual widgets, Masonry internals, and we even include a screenshot test in most examples.\n\n\n## VS Code markers\n\nMasonry uses VS Code markers to help users browse code with the minimap:\n\nhttps://code.visualstudio.com/docs/getstarted/userinterface#_minimap\n\nThese markers look like this:\n\n```rust\n// --- MARK: MARKER NAME\n```\n\nBy convention, we write them in all caps with three dashes.\nMarkers don't need to follow strict naming conventions, but their names should be a shorthand for the area of the code they're in.\nNames should be short enough not to overflow the VS Code minimap.\n\nSmall files shouldn't have markers, except for files following a general template (widget implementations, view implementations).\nGenerally files should have between 50 and 200 lines between markers.\nIf a file has any markers, it should have enough to split the file into distinct regions.\n"},"files":{"ARCHITECTURE.md":"# ARCHITECTURE\n\nThis repository holds the source code for the Xilem project and the Masonry project, including their sub-crates.\n\n- Xilem is a family of high-level GUI frameworks. Xilem apps are written with idiomatic Rust code, with little to no reliance on macros and DSLs.\n    - **`xilem_core`** includes the traits that define Xilem.\n    - **`xilem_masonry`** is the natively compiled framework, built on Masonry.\n    - **`xilem`** is a batteries-included wrapper for `xilem_masonry` using `winit` for platform support.\n    - **`xilem_web`** is the web framework, built on the DOM.\n- Masonry is a foundational framework for building high-level Rust GUI libraries.\n    - **`masonry_core`** includes the base GUI engine.\n    - **`masonry_testing`** includes a harness, helper macros and functions, etc, for testing apps built with Masonry.\n    - **`masonry`** includes a baseline set of widgets and properties, a default theme, unit tests for widgets, and unit tests for `masonry_core`.\n    - **`masonry_winit`** is the winit backend.\n\nSee [xilem/ARCHITECTURE.md](./xilem/ARCHITECTURE.md) and [masonry/ARCHITECTURE.md](./masonry/ARCHITECTURE.md) for more details on each project.\n\nThis repo also holds `tree_arena`, a crate which implements a hierarchical container, which has some properties of a tree (given a mutable reference to a node, you can get disjoint references to its value and children), while allowing `O(1)` (in unsafe mode) access to any element.\n\n```mermaid\ngraph TD\n%%   subgraph Masonry\n    masonry[Masonry]\n    masonry_core[Masonry Core]\n%%   end\n    %% subgraph Masonry Drivers\n        masonry_testing[Masonry Testing]\n        masonry_winit[Masonry Winit]\n        masonry_android_view[Masonry Android View]\n    %% end\n%%   subgraph Xilem\n    xilem[Xilem]\n    xilem_masonry[Xilem Masonry]\n    xilem_core[Xilem Core]\n    xilem_web[Xilem Web]\n%%   end\n%%   subgraph Vello\n        vello[Vello]\n        vello_encoding[Vello Encoding]\n        vello_shaders[Vello Shaders]\n        peniko[Peniko]\n%%   end\n%%   subgraph Parley\n    parley[Parley]\n    fontique[Fontique]\n%%   end\ntree_arena[Tree Arena]\n%%   subgraph Font Infrastructure\n    linebender_resource_handle[Linebender Resource Handle]\n    skrifa[\"Skrifa (Google Fonts)\"]\n    swash[Swash]\n    harfrust[\"HarfRust (HarfBuzz)\"]\n%%   end\n\ncolor[Color]\nkurbo[Kurbo]\nweb_sys[\"web-sys (wasm-bindgen)\"]\n\nwgpu[\"Wgpu (gfx-rs)\"]\n\nfontique --> linebender_resource_handle\nmasonry-->masonry_core\nmasonry-- (dev) -->masonry_testing\nmasonry_testing-->masonry_core\n\nmasonry_android_view --> masonry_core\nmasonry_winit --> masonry_core\nharfrust --> skrifa\nswash --> skrifa\nparley --> swash\nparley --> harfrust\nparley --> fontique\n\npeniko --> color\npeniko --> kurbo\n\nvello --> vello_shaders\nvello_shaders --> vello_encoding\nvello --> vello_encoding\nvello_encoding --> skrifa\nvello --> wgpu\n\nvello --> peniko\nvello --> linebender_resource_handle\n\nxilem_web --> web_sys\nxilem_web --> xilem_core\nmasonry_core -->  vello\nmasonry_core -->  parley\nmasonry_core -->  tree_arena\n\nxilem_masonry --> xilem_core\nxilem_masonry --> masonry\n\nxilem --> xilem_masonry\nxilem --> masonry_winit\n```","xilem/ARCHITECTURE.md":"# ARCHITECTURE\n\nXilem is a family of high-level GUI frameworks.\nXilem apps are written with idiomatic Rust code, with little to no reliance on macros and DSLs.\n\n\n## General architecture\n\nThe most important thing about Xilem is that it is a *reactive* architecture:\n\n- After every change, user-provided functions are called to generate a **view tree**, a lightweight representation of the app's UI.\n- The new view tree is compared against the previous view tree.\n- Based on the differences, the back-end creates an updates a retained **element tree**.\n  Elements are added, removed or mutated to match the current view tree.\n    - In `xilem`, the element tree is the Masonry widget tree.\n    - in `xilem_web`, the element tree is the DOM.\n\nThis architecture is strongly inspired by React, Elm and SwiftUI, which work on similar principles.\n\nA Xilem app's code will usually be made of functions called **components** that create and return subsets of the view tree.\nA component function might look like this pseudo-code:\n\n```rust\nfn list_item(item: &ItemData) -> impl View<...> {\n    row((\n        image(item.image_url),\n        text(item.text),\n        button(\"Do thing\").on_click(|...| do_thing(item.id)),\n    ))\n}\n```\n\n\n## High-level Goals\n\n- **Good Performance:** Xilem aims for the \"performant by default\" class of Rust software. \n  Everything isn't always optimized, but it uses sober data structures and high-performance dependencies (Vello, Parley, wgpu).\n  Static typing gives us very efficient diffing of view trees by default.\n- **Productive:** Xilem offers a high-level API, designed to bypass the borrowing and state management issues that retained GUIs suffer from in Rust.\n- **Idiomatic:** Xilem apps are low on macros or DSLs.\n  Writing a component is about creating and composing view objects, no special syntax needed.\n- **Batteries-included:** Through Masonry, Xilem includes advanced text layout, IME, accessibility trees and styling.\n- **Wide platform support:** Xilem supports the web through `xilem_web` and desktop/mobile platforms through `masonry` and `winit`.\n\n\n## Code layout\n\nThe Xilem project includes these crates:\n\n- **`xilem_core`:** Includes the core traits such as `View`, `ViewElement`, `ViewSequence`, `ElementSlice`, and many others. Also include some generic implementations for these traits (e.g. for Box, Arc, tuples, etc).\n- **`xilem_web`:** Web backend for Xilem. Depends on `xilem_core` and `wasm-bindgen`.\n- **`xilem_masonry`:** Natively compiled backend for Xilem. Depends on `xilem_core` and `masonry`.\n- **`xilem`:** Wrapper crate for `xilem_masonry`, which provides a batteries-included experience for new users. Depends on `xilem_masonry` and `masonry_winit`.\n\n\n## Doc examples\n\nCode snippets in docs comments in both `xilem` and `xilem_masonry` should be as self-contained as possible.\n\nThere should only be a single (visible) import statement at the beginning, listing all the needed imports.\n\nThat import statement should start with `use xilem::`; in other words, all examples should assume that Xilem is the only available dependency (aside from the standard library).\n\nIt should be possible for users to copy-paste the example code into an empty module and have it compile.\nAs such, we should avoid `# ` prefixes when possible.\nView examples should include the whole `fn view() -> impl View<...> {` and `}` parts.\n\n*Note:* Some examples in `xilem` don't currently respect these guidelines.\nWe should fix those examples, and make sure future examples do.\n\n\n## Writing Xilem code\n\n**TODO - This section needs a rewrite.**\n\nYour main interaction with the framework is through the `app_logic()`. Like Elm, the `app_logic()` contains centralized state. On each cycle (meaning, roughly, on each high-level UI interaction such as a button click), the framework calls a closure, giving it mutable access to the `AppData`, and the return value is a `View` tree. This `View` tree is fairly short-lived; it is used to render the UI, possibly dispatch some events, and be used as a reference for diffing by the next cycle, at which point it is dropped. You pass the `app_logic()` to the framework (represented by `Xilem`) and then use it to create the window and run the UI.\n\n```rust\nstruct AppData {\n    count: u32,\n}\n\nfn app_logic(data: &mut AppData) -> impl View<AppData, (), Element = impl Widget> {\n    let count = data.count\n    let button_label = if count == 1 {\n        \"clicked 1 time\".to_string()\n    } else {\n        format!(\"clicked {count} times\")\n    };\n    button(button_label, |data: &mut AppData| data.count +=1)\n}\n\nfn main() {\n    let data = AppData {\n      count: 0\n    }\n    let app = Xilem::new(data, app_logic);\n    app.run_windowed(\"Application Example\".into()).unwrap();\n}\n```\nThe most important construct at the reactive layer is the `View` trait. `View` implementations need to assign the associated `State` and `Element` and implement `build()`, `rebuild()` and `message()`. The `build()` is run only once (first run) to initialize the associated `State` create the associated `Element`of the view. The `rebuild()` is used to update the associated `State` and `Element` and it is what enables Xilem's reactivity. It is worth noting three special types of views the `lens`, `Memoize` and `AnyView` views. \n\nThe `lens` view is used to adapt/convert from the parent data (often the `AppData`) to the child data (some subset of the `AppData`).\n\nThe `View` trees are always eagerly evaluated when the `app_logic()` is called. Even though the `View`'s are very lightweight when the tree becomes large it can create performance issues; the `Memoize` node prunes the `View` tree to improve performance. The generation of the subtree is postponed until the `build()`/`rebuild()` are executed. If none of the `AppData` dependencies change during a UI cycle neither the `View` subtree will be constructed nor the `rebuild()` will be called. The `View` subtree will only be constructed if any of the `AppData` dependencies change. The `Memoize` node should be used when the subtree is a pure function of the `AppData`.\n\nGenerally the Xilem `View` tree is statically typed. `AnyView` allows for the tree to be type erased to enable easy dynamic reconfiguration of the UI. \n","masonry/ARCHITECTURE.md":"# ARCHITECTURE\n\nMasonry is a framework that aims to provide the foundation for Rust GUI libraries.\n\nDevelopers trying to write immediate-mode GUIs, Elm-architecture GUIs, functional reactive GUIs, etc, can import Masonry and get a platform to create windows (often using Winit as a backend) each with a tree of widgets.\nEach widget has to implement the `Widget` trait that Masonry provides.\n\n\n## High-level goals\n\nMasonry has some opinionated design goals:\n\n- **Be dumb.** As a general rule, Masonry doesn't do \"algorithms\".\n  It has no reconciliation logic, no behind-the-scenes dataflow, no clever optimizations, etc.\n  It tries to be efficient, but that efficiency comes from well-designed interfaces and well-placed abstraction boundaries.\n  High-level logic should be implemented in downstream crates.\n- **No mutability tricks.** Masonry uses no unsafe code and as few cells/mutexes as possible.\n  It's designed to work within Rust's ownership system, not to bypass it.\n  While it relies on the `tree_arena` crate in this repository which *does* perform some mutability tricks, the resulting usage patterns are still very rust-like.\n- **Facilitate testing.** The `masonry_testing` crate provides a `TestHarness` type that helps users write unit tests, including tests with simulated user interactions and screenshot tests.\n  In general, every feature should be designed with easy-to-write high-reliability tests in mind.\n- **Facilitate debugging.** GUI app bugs are often easy to fix, but extremely painful to track down.\n  GUI framework bugs are worse.\n  Masonry should facilitate reproducing bugs and pinpointing which bit of code they come from.\n- **Provide reflection.** Masonry should help developers surface some of the inherent structure in GUI programs.\n  It should provide tools out-of-the-box to get information about the widget tree, performance indicators, etc.\n  It should also provide accessibility data out-of-the-box.\n- **Be well-tested:** Masonry doesn't just provide lots of testing tools, it also has a lot of tests.\n  These are a core part of the Masonry development experience.\n\n\n## Code layout\n\nThe Masonry project includes these crates in the Xilem repository:\n\n- **`masonry_core`:** includes the core traits, types and abstractions.\n- **`masonry_testing`:** includes a harness, helper macros and functions, etc, for testing apps built with Masonry.\n- **`masonry`:** includes a baseline set of widgets and properties, a default theme, unit tests for widgets, and unit tests for `masonry_core`.\n- **`masonry_winit`:** the winit backend.\n\n### `masonry_core/src/core/`\n\nMost widget-related code, including the `Widget` trait, its context types, event types, and the `WidgetRef`, `WidgetMut`, and `WidgetPod` types.\n\n#### `masonry_core/src/core/widget_state.rs`\n\nContains the WidgetState type, around which a lot of internal code is based.\n\n`WidgetState` is one of the most important internal types in Masonry.\nUnderstanding Masonry pass code will likely be easier if you read `WidgetState` documentation first.\n\n### `masonry_core/src/app/tracing_backend.rs`\n\nCode for setting up a default configuration of the `tracing` crate.\n\n### `masonry_core/src/app/render_root.rs`\n\nMasonry's composition root. See **General architecture** section.\n\n### `masonry_core/src/layout/`\n\nLayout specific core types.\n\n### `masonry_core/src/passes/`\n\nMasonry's passes are computations that run on the entire widget tree (iff invalidation flags are set) once per frame.\n\n`event.rs` and `update.rs` include a bunch of related passes.\nEvery other file only includes one pass.\n`mod.rs` has utility functions shared between multiple passes.\n\n### `masonry_core/src/properties`\n\nCore properties that every widget has.\n\n### `masonry_core/src/doc/`\n\nLow-level documentation for masonry's cross-cutting concepts.\nIncludes documentation for the pass system, and definitions for various terms used in other places.\n\n### `masonry_core/src/`\n\nContains the TestHarness type, various helper widgets for writing tests, and the snapshot testing code.\n\n### `masonry/src/widgets/`\n\nA list of basic widgets, each defined in a single file.\n\n### `masonry/src/properties/`\n\nA list of properties, which are small plain-old-data types used to customize a widget's look and behavior.\n\n#### `masonry/src/properties/types/`\n\nA list of vocabulary types used in multiple properties.\n\n### `masonry/src/doc/`\n\nHigh-level tutorial for Masonry.\nIn other projects, this would be an `mdbook` doc, but we choose to directly inline the doc, so that `cargo test` runs on it directly.\n\n### `masonry_winit/src/event_loop_runner.rs`\n\nThe bulk of the integration between Masonry and winit.\n\n\n## Module organization principles\n\n### Module structure\n\nThe public module hierarchy should be relatively flat.\nThis makes documentation more readable; readers don't need to click on multiple modules to find the item they're looking for, and maintainers don't need to open multiple layers of folders to find a file.\n\n### Imports\n\nWe should avoid `use super::xxx` imports, except for specific cases like unit tests.\n\nMost imports in the code base should use the canonical top-level import.\n\n### Avoid glob imports\n\nWe should avoid `use foo::*` imports, because they make it harder for people reading the code outside an IDE to track where a given import comes from.\n\nGlob re-exports (e.g. `pub use my_module::*`) are fine and encouraged from `mod.rs` files.\n\n### No prelude\n\nMasonry should have no prelude.\nExamples and documentation should deliberately have a list of imports that cover everything users will need, so users can copy-paste these lists.\n\n\n## General architecture\n\n### Platform handlers\n\nThe composition roots of Masonry are:\n\n- **RenderRoot**, which owns the widget tree.\n- The **AppDriver** trait, which owns the business logic.\n- The **run_with** function in `event_loop_runner.rs`.\n\nThe high-level control flow of a Masonry app's render loop is usually:\n\n- The platform library (windows, macos, x11, etc) runs some callbacks written in Winit in response to user interactions, timers, or other events.\n- Winit calls some RenderRoot method.\n- RenderRoot runs a series of passes (events, updates, paint, accessibility, etc).\n- Throughout those passes, RenderRootSignal values are pushed to a queue which winit can query.\n- winit may change its internals or schedule another frame based on those signals.\n\n\n### Widget hierarchy and passes\n\nThe **Widget** trait is defined in `src/widget/widget.rs`.\nMost of the widget-related bookkeeping is done in the passes defined in `src/passes`.\n\nA **WidgetPod** is the main way to store a child for container widgets.\nIn general, the widget hierarchy looks like a tree of container widgets, with each container owning a `WidgetPod` or a `Vec` of `WidgetPod` or something similar.\n\nWhen RenderRoot runs a pass (on_xxx_event/update_xxx/paint), it iterates over the widget tree, usually in depth-first pre-order, and calls the matching method on each concerned widget.\n\nThere is one exception to this pattern: the layout pass requires widgets to \"manually\" recurse to their children.\n\nThe current passes are:\n\n- **mutate:** Runs a list of callbacks with mutable access to the widget tree. These callbacks can either be passed by the event loop, or pushed to a queue by widgets during the other passes.\n- **on_xxx_event:** Handles UX-related events, e.g. clicks, text entered, IME updates and accessibility input. Widgets can declare these events as \"handled\" which has a bunch of semantic implications.\n- **anim:** Do updates related to an animation frame.\n- **update:** Handles internal changes to some widgets, e.g. when the widget is marked as \"disabled\" or Masonry detects that a widget is hovered by a pointer.\n- **layout:** Container widgets measure their children with `LayoutCtx::compute_size` and then lay them out with `LayoutCtx::run_layout`, finally giving them a position with `LayoutCtx::place_child`.\n- **compose:** Computes the global transform/origin for every widget.\n- **paint** Paint every widget.\n- **accessibility:** Compute every widget's node in the accessibility tree.\n\nSee [masonry_core/src/doc/pass_system.md] for details.\n\n\n### WidgetMut\n\nIn Masonry, widgets can't be mutated directly.\nAll mutations go through a `WidgetMut` wrapper.\nSo, to change a label's text, you might call `WidgetMut<Label>::set_text()`.\nThis helps Masonry make sure that internal metadata is propagated after every widget change.\n\nIn general, there's three ways to get a `WidgetMut`:\n\n- From a `WidgetMut` to a parent widget.\n- As an argument to the callback passed to `RenderRoot::edit_widget()`.\n- As an argument to a callback pushed to the mutate pass.\n\nIn most cases, the `WidgetMut` holds a reference to a WidgetState that will be updated when the `WidgetMut` is dropped.\n\n`WidgetMut` gives direct mutable access to the widget tree.\nThis can be used by GUI frameworks in their tree update methods, and it can be used in tests to make specific local modifications and test their result.\n\n\n### Properties\n\nProperties (often abbreviated to props) are values of arbitrary static types stored alongside each widget.\n\nProperties are a way for widgets to store arbitrary state, not behavior; they're similar to the \"Component\" part of ECS.\n\nThey can be things like Background, BorderColor, BorderWidth, Padding, ContentColor, etc.\n\nAlmost all widget methods take a `PropertiesRef` or `PropertiesMut` parameter that lets them access their properties.\n\nSee [masonry/src/doc/widget_properties.md] for details.\n\n\n### Tests\n\nMasonry is designed to make unit tests easy to write, as if the test function were a mouse-and-keyboard user.\n\nTesting is provided by the **TestHarness** type implemented in the `masonry_testing` crate.\n\nIdeally, the harness should provide ways to emulate absolutely every feature that Masonry apps can use.\nBesides the widget tree, that means keyboard events, mouse events, IME, timers, communication with background threads, animations, accessibility info, etc.\n\n(TODO - Some of that emulation support is not implemented yet. See <https://github.com/linebender/xilem/issues/369>.)\n\nEach widget has unit tests in its module and major features have modules with dedicated unit test suites.\nIdeally, we would like to achieve complete coverage within the crate.\n\n#### Screenshot tests\n\nTODO - mention kompari\n\nTestHarness can render a widget tree, save the result to an image, and compare the image to a stored snapshot.\nThis lets us check that (1) our widgets' paint methods don't panic and (2) changes don't introduce accidental regression in their visual appearance.\n\nTo avoid accumulating large files in the repository, we optimize screenshots with the `oxipng` tool.\nScreenshots tests will fail by default if the saved screenshot is larger than 8KiB.\n\n#### Tests Are Important\n\nTesting is a core element of Masonry.\n\nWhile we don't follow TDD, we have a lot of tests, and *that matters*.\nExtensive testing has helped us catch bugs, find corner cases in our features, and lets us do complex refactors without worrying about breaking something without anyone realizing for years.\n\nWe test individual widgets, Masonry internals, and we even include a screenshot test in most examples.\n\n\n## VS Code markers\n\nMasonry uses VS Code markers to help users browse code with the minimap:\n\nhttps://code.visualstudio.com/docs/getstarted/userinterface#_minimap\n\nThese markers look like this:\n\n```rust\n// --- MARK: MARKER NAME\n```\n\nBy convention, we write them in all caps with three dashes.\nMarkers don't need to follow strict naming conventions, but their names should be a shorthand for the area of the code they're in.\nNames should be short enough not to overflow the VS Code minimap.\n\nSmall files shouldn't have markers, except for files following a general template (widget implementations, view implementations).\nGenerally files should have between 50 and 200 lines between markers.\nIf a file has any markers, it should have enough to split the file into distinct regions.\n"},"items":[{"name":"ARCHITECTURE.md","path":"ARCHITECTURE.md","rawUrl":"https://raw.githubusercontent.com/linebender/xilem/HEAD/ARCHITECTURE.md","title":"System Architecture & Module Boundaries","category":"project-spec","format":"markdown","content":"# ARCHITECTURE\n\nThis repository holds the source code for the Xilem project and the Masonry project, including their sub-crates.\n\n- Xilem is a family of high-level GUI frameworks. Xilem apps are written with idiomatic Rust code, with little to no reliance on macros and DSLs.\n    - **`xilem_core`** includes the traits that define Xilem.\n    - **`xilem_masonry`** is the natively compiled framework, built on Masonry.\n    - **`xilem`** is a batteries-included wrapper for `xilem_masonry` using `winit` for platform support.\n    - **`xilem_web`** is the web framework, built on the DOM.\n- Masonry is a foundational framework for building high-level Rust GUI libraries.\n    - **`masonry_core`** includes the base GUI engine.\n    - **`masonry_testing`** includes a harness, helper macros and functions, etc, for testing apps built with Masonry.\n    - **`masonry`** includes a baseline set of widgets and properties, a default theme, unit tests for widgets, and unit tests for `masonry_core`.\n    - **`masonry_winit`** is the winit backend.\n\nSee [xilem/ARCHITECTURE.md](./xilem/ARCHITECTURE.md) and [masonry/ARCHITECTURE.md](./masonry/ARCHITECTURE.md) for more details on each project.\n\nThis repo also holds `tree_arena`, a crate which implements a hierarchical container, which has some properties of a tree (given a mutable reference to a node, you can get disjoint references to its value and children), while allowing `O(1)` (in unsafe mode) access to any element.\n\n```mermaid\ngraph TD\n%%   subgraph Masonry\n    masonry[Masonry]\n    masonry_core[Masonry Core]\n%%   end\n    %% subgraph Masonry Drivers\n        masonry_testing[Masonry Testing]\n        masonry_winit[Masonry Winit]\n        masonry_android_view[Masonry Android View]\n    %% end\n%%   subgraph Xilem\n    xilem[Xilem]\n    xilem_masonry[Xilem Masonry]\n    xilem_core[Xilem Core]\n    xilem_web[Xilem Web]\n%%   end\n%%   subgraph Vello\n        vello[Vello]\n        vello_encoding[Vello Encoding]\n        vello_shaders[Vello Shaders]\n        peniko[Peniko]\n%%   end\n%%   subgraph Parley\n    parley[Parley]\n    fontique[Fontique]\n%%   end\ntree_arena[Tree Arena]\n%%   subgraph Font Infrastructure\n    linebender_resource_handle[Linebender Resource Handle]\n    skrifa[\"Skrifa (Google Fonts)\"]\n    swash[Swash]\n    harfrust[\"HarfRust (HarfBuzz)\"]\n%%   end\n\ncolor[Color]\nkurbo[Kurbo]\nweb_sys[\"web-sys (wasm-bindgen)\"]\n\nwgpu[\"Wgpu (gfx-rs)\"]\n\nfontique --> linebender_resource_handle\nmasonry-->masonry_core\nmasonry-- (dev) -->masonry_testing\nmasonry_testing-->masonry_core\n\nmasonry_android_view --> masonry_core\nmasonry_winit --> masonry_core\nharfrust --> skrifa\nswash --> skrifa\nparley --> swash\nparley --> harfrust\nparley --> fontique\n\npeniko --> color\npeniko --> kurbo\n\nvello --> vello_shaders\nvello_shaders --> vello_encoding\nvello --> vello_encoding\nvello_encoding --> skrifa\nvello --> wgpu\n\nvello --> peniko\nvello --> linebender_resource_handle\n\nxilem_web --> web_sys\nxilem_web --> xilem_core\nmasonry_core -->  vello\nmasonry_core -->  parley\nmasonry_core -->  tree_arena\n\nxilem_masonry --> xilem_core\nxilem_masonry --> masonry\n\nxilem --> xilem_masonry\nxilem --> masonry_winit\n```","isInternal":false,"tokens":906,"sizeBytes":3133},{"name":"ARCHITECTURE.md","path":"masonry/ARCHITECTURE.md","rawUrl":"https://raw.githubusercontent.com/linebender/xilem/HEAD/masonry/ARCHITECTURE.md","title":"masonry - System Architecture & Module Boundaries","category":"project-spec","format":"markdown","content":"# ARCHITECTURE\n\nMasonry is a framework that aims to provide the foundation for Rust GUI libraries.\n\nDevelopers trying to write immediate-mode GUIs, Elm-architecture GUIs, functional reactive GUIs, etc, can import Masonry and get a platform to create windows (often using Winit as a backend) each with a tree of widgets.\nEach widget has to implement the `Widget` trait that Masonry provides.\n\n\n## High-level goals\n\nMasonry has some opinionated design goals:\n\n- **Be dumb.** As a general rule, Masonry doesn't do \"algorithms\".\n  It has no reconciliation logic, no behind-the-scenes dataflow, no clever optimizations, etc.\n  It tries to be efficient, but that efficiency comes from well-designed interfaces and well-placed abstraction boundaries.\n  High-level logic should be implemented in downstream crates.\n- **No mutability tricks.** Masonry uses no unsafe code and as few cells/mutexes as possible.\n  It's designed to work within Rust's ownership system, not to bypass it.\n  While it relies on the `tree_arena` crate in this repository which *does* perform some mutability tricks, the resulting usage patterns are still very rust-like.\n- **Facilitate testing.** The `masonry_testing` crate provides a `TestHarness` type that helps users write unit tests, including tests with simulated user interactions and screenshot tests.\n  In general, every feature should be designed with easy-to-write high-reliability tests in mind.\n- **Facilitate debugging.** GUI app bugs are often easy to fix, but extremely painful to track down.\n  GUI framework bugs are worse.\n  Masonry should facilitate reproducing bugs and pinpointing which bit of code they come from.\n- **Provide reflection.** Masonry should help developers surface some of the inherent structure in GUI programs.\n  It should provide tools out-of-the-box to get information about the widget tree, performance indicators, etc.\n  It should also provide accessibility data out-of-the-box.\n- **Be well-tested:** Masonry doesn't just provide lots of testing tools, it also has a lot of tests.\n  These are a core part of the Masonry development experience.\n\n\n## Code layout\n\nThe Masonry project includes these crates in the Xilem repository:\n\n- **`masonry_core`:** includes the core traits, types and abstractions.\n- **`masonry_testing`:** includes a harness, helper macros and functions, etc, for testing apps built with Masonry.\n- **`masonry`:** includes a baseline set of widgets and properties, a default theme, unit tests for widgets, and unit tests for `masonry_core`.\n- **`masonry_winit`:** the winit backend.\n\n### `masonry_core/src/core/`\n\nMost widget-related code, including the `Widget` trait, its context types, event types, and the `WidgetRef`, `WidgetMut`, and `WidgetPod` types.\n\n#### `masonry_core/src/core/widget_state.rs`\n\nContains the WidgetState type, around which a lot of internal code is based.\n\n`WidgetState` is one of the most important internal types in Masonry.\nUnderstanding Masonry pass code will likely be easier if you read `WidgetState` documentation first.\n\n### `masonry_core/src/app/tracing_backend.rs`\n\nCode for setting up a default configuration of the `tracing` crate.\n\n### `masonry_core/src/app/render_root.rs`\n\nMasonry's composition root. See **General architecture** section.\n\n### `masonry_core/src/layout/`\n\nLayout specific core types.\n\n### `masonry_core/src/passes/`\n\nMasonry's passes are computations that run on the entire widget tree (iff invalidation flags are set) once per frame.\n\n`event.rs` and `update.rs` include a bunch of related passes.\nEvery other file only includes one pass.\n`mod.rs` has utility functions shared between multiple passes.\n\n### `masonry_core/src/properties`\n\nCore properties that every widget has.\n\n### `masonry_core/src/doc/`\n\nLow-level documentation for masonry's cross-cutting concepts.\nIncludes documentation for the pass system, and definitions for various terms used in other places.\n\n### `masonry_core/src/`\n\nContains the TestHarness type, various helper widgets for writing tests, and the snapshot testing code.\n\n### `masonry/src/widgets/`\n\nA list of basic widgets, each defined in a single file.\n\n### `masonry/src/properties/`\n\nA list of properties, which are small plain-old-data types used to customize a widget's look and behavior.\n\n#### `masonry/src/properties/types/`\n\nA list of vocabulary types used in multiple properties.\n\n### `masonry/src/doc/`\n\nHigh-level tutorial for Masonry.\nIn other projects, this would be an `mdbook` doc, but we choose to directly inline the doc, so that `cargo test` runs on it directly.\n\n### `masonry_winit/src/event_loop_runner.rs`\n\nThe bulk of the integration between Masonry and winit.\n\n\n## Module organization principles\n\n### Module structure\n\nThe public module hierarchy should be relatively flat.\nThis makes documentation more readable; readers don't need to click on multiple modules to find the item they're looking for, and maintainers don't need to open multiple layers of folders to find a file.\n\n### Imports\n\nWe should avoid `use super::xxx` imports, except for specific cases like unit tests.\n\nMost imports in the code base should use the canonical top-level import.\n\n### Avoid glob imports\n\nWe should avoid `use foo::*` imports, because they make it harder for people reading the code outside an IDE to track where a given import comes from.\n\nGlob re-exports (e.g. `pub use my_module::*`) are fine and encouraged from `mod.rs` files.\n\n### No prelude\n\nMasonry should have no prelude.\nExamples and documentation should deliberately have a list of imports that cover everything users will need, so users can copy-paste these lists.\n\n\n## General architecture\n\n### Platform handlers\n\nThe composition roots of Masonry are:\n\n- **RenderRoot**, which owns the widget tree.\n- The **AppDriver** trait, which owns the business logic.\n- The **run_with** function in `event_loop_runner.rs`.\n\nThe high-level control flow of a Masonry app's render loop is usually:\n\n- The platform library (windows, macos, x11, etc) runs some callbacks written in Winit in response to user interactions, timers, or other events.\n- Winit calls some RenderRoot method.\n- RenderRoot runs a series of passes (events, updates, paint, accessibility, etc).\n- Throughout those passes, RenderRootSignal values are pushed to a queue which winit can query.\n- winit may change its internals or schedule another frame based on those signals.\n\n\n### Widget hierarchy and passes\n\nThe **Widget** trait is defined in `src/widget/widget.rs`.\nMost of the widget-related bookkeeping is done in the passes defined in `src/passes`.\n\nA **WidgetPod** is the main way to store a child for container widgets.\nIn general, the widget hierarchy looks like a tree of container widgets, with each container owning a `WidgetPod` or a `Vec` of `WidgetPod` or something similar.\n\nWhen RenderRoot runs a pass (on_xxx_event/update_xxx/paint), it iterates over the widget tree, usually in depth-first pre-order, and calls the matching method on each concerned widget.\n\nThere is one exception to this pattern: the layout pass requires widgets to \"manually\" recurse to their children.\n\nThe current passes are:\n\n- **mutate:** Runs a list of callbacks with mutable access to the widget tree. These callbacks can either be passed by the event loop, or pushed to a queue by widgets during the other passes.\n- **on_xxx_event:** Handles UX-related events, e.g. clicks, text entered, IME updates and accessibility input. Widgets can declare these events as \"handled\" which has a bunch of semantic implications.\n- **anim:** Do updates related to an animation frame.\n- **update:** Handles internal changes to some widgets, e.g. when the widget is marked as \"disabled\" or Masonry detects that a widget is hovered by a pointer.\n- **layout:** Container widgets measure their children with `LayoutCtx::compute_size` and then lay them out with `LayoutCtx::run_layout`, finally giving them a position with `LayoutCtx::place_child`.\n- **compose:** Computes the global transform/origin for every widget.\n- **paint** Paint every widget.\n- **accessibility:** Compute every widget's node in the accessibility tree.\n\nSee [masonry_core/src/doc/pass_system.md] for details.\n\n\n### WidgetMut\n\nIn Masonry, widgets can't be mutated directly.\nAll mutations go through a `WidgetMut` wrapper.\nSo, to change a label's text, you might call `WidgetMut<Label>::set_text()`.\nThis helps Masonry make sure that internal metadata is propagated after every widget change.\n\nIn general, there's three ways to get a `WidgetMut`:\n\n- From a `WidgetMut` to a parent widget.\n- As an argument to the callback passed to `RenderRoot::edit_widget()`.\n- As an argument to a callback pushed to the mutate pass.\n\nIn most cases, the `WidgetMut` holds a reference to a WidgetState that will be updated when the `WidgetMut` is dropped.\n\n`WidgetMut` gives direct mutable access to the widget tree.\nThis can be used by GUI frameworks in their tree update methods, and it can be used in tests to make specific local modifications and test their result.\n\n\n### Properties\n\nProperties (often abbreviated to props) are values of arbitrary static types stored alongside each widget.\n\nProperties are a way for widgets to store arbitrary state, not behavior; they're similar to the \"Component\" part of ECS.\n\nThey can be things like Background, BorderColor, BorderWidth, Padding, ContentColor, etc.\n\nAlmost all widget methods take a `PropertiesRef` or `PropertiesMut` parameter that lets them access their properties.\n\nSee [masonry/src/doc/widget_properties.md] for details.\n\n\n### Tests\n\nMasonry is designed to make unit tests easy to write, as if the test function were a mouse-and-keyboard user.\n\nTesting is provided by the **TestHarness** type implemented in the `masonry_testing` crate.\n\nIdeally, the harness should provide ways to emulate absolutely every feature that Masonry apps can use.\nBesides the widget tree, that means keyboard events, mouse events, IME, timers, communication with background threads, animations, accessibility info, etc.\n\n(TODO - Some of that emulation support is not implemented yet. See <https://github.com/linebender/xilem/issues/369>.)\n\nEach widget has unit tests in its module and major features have modules with dedicated unit test suites.\nIdeally, we would like to achieve complete coverage within the crate.\n\n#### Screenshot tests\n\nTODO - mention kompari\n\nTestHarness can render a widget tree, save the result to an image, and compare the image to a stored snapshot.\nThis lets us check that (1) our widgets' paint methods don't panic and (2) changes don't introduce accidental regression in their visual appearance.\n\nTo avoid accumulating large files in the repository, we optimize screenshots with the `oxipng` tool.\nScreenshots tests will fail by default if the saved screenshot is larger than 8KiB.\n\n#### Tests Are Important\n\nTesting is a core element of Masonry.\n\nWhile we don't follow TDD, we have a lot of tests, and *that matters*.\nExtensive testing has helped us catch bugs, find corner cases in our features, and lets us do complex refactors without worrying about breaking something without anyone realizing for years.\n\nWe test individual widgets, Masonry internals, and we even include a screenshot test in most examples.\n\n\n## VS Code markers\n\nMasonry uses VS Code markers to help users browse code with the minimap:\n\nhttps://code.visualstudio.com/docs/getstarted/userinterface#_minimap\n\nThese markers look like this:\n\n```rust\n// --- MARK: MARKER NAME\n```\n\nBy convention, we write them in all caps with three dashes.\nMarkers don't need to follow strict naming conventions, but their names should be a shorthand for the area of the code they're in.\nNames should be short enough not to overflow the VS Code minimap.\n\nSmall files shouldn't have markers, except for files following a general template (widget implementations, view implementations).\nGenerally files should have between 50 and 200 lines between markers.\nIf a file has any markers, it should have enough to split the file into distinct regions.\n","isInternal":false,"tokens":2608,"sizeBytes":11992},{"name":"ARCHITECTURE.md","path":"xilem/ARCHITECTURE.md","rawUrl":"https://raw.githubusercontent.com/linebender/xilem/HEAD/xilem/ARCHITECTURE.md","title":"xilem - System Architecture & Module Boundaries","category":"project-spec","format":"markdown","content":"# ARCHITECTURE\n\nXilem is a family of high-level GUI frameworks.\nXilem apps are written with idiomatic Rust code, with little to no reliance on macros and DSLs.\n\n\n## General architecture\n\nThe most important thing about Xilem is that it is a *reactive* architecture:\n\n- After every change, user-provided functions are called to generate a **view tree**, a lightweight representation of the app's UI.\n- The new view tree is compared against the previous view tree.\n- Based on the differences, the back-end creates an updates a retained **element tree**.\n  Elements are added, removed or mutated to match the current view tree.\n    - In `xilem`, the element tree is the Masonry widget tree.\n    - in `xilem_web`, the element tree is the DOM.\n\nThis architecture is strongly inspired by React, Elm and SwiftUI, which work on similar principles.\n\nA Xilem app's code will usually be made of functions called **components** that create and return subsets of the view tree.\nA component function might look like this pseudo-code:\n\n```rust\nfn list_item(item: &ItemData) -> impl View<...> {\n    row((\n        image(item.image_url),\n        text(item.text),\n        button(\"Do thing\").on_click(|...| do_thing(item.id)),\n    ))\n}\n```\n\n\n## High-level Goals\n\n- **Good Performance:** Xilem aims for the \"performant by default\" class of Rust software. \n  Everything isn't always optimized, but it uses sober data structures and high-performance dependencies (Vello, Parley, wgpu).\n  Static typing gives us very efficient diffing of view trees by default.\n- **Productive:** Xilem offers a high-level API, designed to bypass the borrowing and state management issues that retained GUIs suffer from in Rust.\n- **Idiomatic:** Xilem apps are low on macros or DSLs.\n  Writing a component is about creating and composing view objects, no special syntax needed.\n- **Batteries-included:** Through Masonry, Xilem includes advanced text layout, IME, accessibility trees and styling.\n- **Wide platform support:** Xilem supports the web through `xilem_web` and desktop/mobile platforms through `masonry` and `winit`.\n\n\n## Code layout\n\nThe Xilem project includes these crates:\n\n- **`xilem_core`:** Includes the core traits such as `View`, `ViewElement`, `ViewSequence`, `ElementSlice`, and many others. Also include some generic implementations for these traits (e.g. for Box, Arc, tuples, etc).\n- **`xilem_web`:** Web backend for Xilem. Depends on `xilem_core` and `wasm-bindgen`.\n- **`xilem_masonry`:** Natively compiled backend for Xilem. Depends on `xilem_core` and `masonry`.\n- **`xilem`:** Wrapper crate for `xilem_masonry`, which provides a batteries-included experience for new users. Depends on `xilem_masonry` and `masonry_winit`.\n\n\n## Doc examples\n\nCode snippets in docs comments in both `xilem` and `xilem_masonry` should be as self-contained as possible.\n\nThere should only be a single (visible) import statement at the beginning, listing all the needed imports.\n\nThat import statement should start with `use xilem::`; in other words, all examples should assume that Xilem is the only available dependency (aside from the standard library).\n\nIt should be possible for users to copy-paste the example code into an empty module and have it compile.\nAs such, we should avoid `# ` prefixes when possible.\nView examples should include the whole `fn view() -> impl View<...> {` and `}` parts.\n\n*Note:* Some examples in `xilem` don't currently respect these guidelines.\nWe should fix those examples, and make sure future examples do.\n\n\n## Writing Xilem code\n\n**TODO - This section needs a rewrite.**\n\nYour main interaction with the framework is through the `app_logic()`. Like Elm, the `app_logic()` contains centralized state. On each cycle (meaning, roughly, on each high-level UI interaction such as a button click), the framework calls a closure, giving it mutable access to the `AppData`, and the return value is a `View` tree. This `View` tree is fairly short-lived; it is used to render the UI, possibly dispatch some events, and be used as a reference for diffing by the next cycle, at which point it is dropped. You pass the `app_logic()` to the framework (represented by `Xilem`) and then use it to create the window and run the UI.\n\n```rust\nstruct AppData {\n    count: u32,\n}\n\nfn app_logic(data: &mut AppData) -> impl View<AppData, (), Element = impl Widget> {\n    let count = data.count\n    let button_label = if count == 1 {\n        \"clicked 1 time\".to_string()\n    } else {\n        format!(\"clicked {count} times\")\n    };\n    button(button_label, |data: &mut AppData| data.count +=1)\n}\n\nfn main() {\n    let data = AppData {\n      count: 0\n    }\n    let app = Xilem::new(data, app_logic);\n    app.run_windowed(\"Application Example\".into()).unwrap();\n}\n```\nThe most important construct at the reactive layer is the `View` trait. `View` implementations need to assign the associated `State` and `Element` and implement `build()`, `rebuild()` and `message()`. The `build()` is run only once (first run) to initialize the associated `State` create the associated `Element`of the view. The `rebuild()` is used to update the associated `State` and `Element` and it is what enables Xilem's reactivity. It is worth noting three special types of views the `lens`, `Memoize` and `AnyView` views. \n\nThe `lens` view is used to adapt/convert from the parent data (often the `AppData`) to the child data (some subset of the `AppData`).\n\nThe `View` trees are always eagerly evaluated when the `app_logic()` is called. Even though the `View`'s are very lightweight when the tree becomes large it can create performance issues; the `Memoize` node prunes the `View` tree to improve performance. The generation of the subtree is postponed until the `build()`/`rebuild()` are executed. If none of the `AppData` dependencies change during a UI cycle neither the `View` subtree will be constructed nor the `rebuild()` will be called. The `View` subtree will only be constructed if any of the `AppData` dependencies change. The `Memoize` node should be used when the subtree is a pure function of the `AppData`.\n\nGenerally the Xilem `View` tree is statically typed. `AnyView` allows for the tree to be type erased to enable easy dynamic reconfiguration of the UI. \n","isInternal":false,"tokens":1506,"sizeBytes":6228}],"systemPromptSnippet":"<yakaai_skills repo=\"linebender/xilem\">\n<!-- File: ARCHITECTURE.md (Tokens: ~906 | Category: project-spec) -->\n# ARCHITECTURE\n\nThis repository holds the source code for the Xilem project and the Masonry project, including their sub-crates.\n\n- Xilem is a family of high-level GUI frameworks. Xilem apps are written with idiomatic Rust code, with little to no reliance on macros and DSLs.\n    - **`xilem_core`** includes the traits that define Xilem.\n    - **`xilem_masonry`** is the natively compiled framework, built on Masonry.\n    - **`xilem`** is a batteries-included wrapper for `xilem_masonry` using `winit` for platform support.\n    - **`xilem_web`** is the web framework, built on the DOM.\n- Masonry is a foundational framework for building high-level Rust GUI libraries.\n    - **`masonry_core`** includes the base GUI engine.\n    - **`masonry_testing`** includes a harness, helper macros and functions, etc, for testing apps built with Masonry.\n    - **`masonry`** includes a baseline set of widgets and properties, a default theme, unit tests for widgets, and unit tests for `masonry_core`.\n    - **`masonry_winit`** is the winit backend.\n\nSee [xilem/ARCHITECTURE.md](./xilem/ARCHITECTURE.md) and [masonry/ARCHITECTURE.md](./masonry/ARCHITECTURE.md) for more details on each project.\n\nThis repo also holds `tree_arena`, a crate which implements a hierarchical container, which has some properties of a tree (given a mutable reference to a node, you can get disjoint references to its value and children), while allowing `O(1)` (in unsafe mode) access to any element.\n\n```mermaid\ngraph TD\n%%   subgraph Masonry\n    masonry[Masonry]\n    masonry_core[Masonry Core]\n%%   end\n    %% subgraph Masonry Drivers\n        masonry_testing[Masonry Testing]\n        masonry_winit[Masonry Winit]\n        masonry_android_view[Masonry Android View]\n    %% end\n%%   subgraph Xilem\n    xilem[Xilem]\n    xilem_masonry[Xilem Masonry]\n    xilem_core[Xilem Core]\n    xilem_web[Xilem Web]\n%%   end\n%%   subgraph Vello\n        vello[Vello]\n        vello_encoding[Vello Encoding]\n        vello_shaders[Vello Shaders]\n        peniko[Peniko]\n%%   end\n%%   subgraph Parley\n    parley[Parley]\n    fontique[Fontique]\n%%   end\ntree_arena[Tree Arena]\n%%   subgraph Font Infrastructure\n    linebender_resource_handle[Linebender Resource Handle]\n    skrifa[\"Skrifa (Google Fonts)\"]\n    swash[Swash]\n    harfrust[\"HarfRust (HarfBuzz)\"]\n%%   end\n\ncolor[Color]\nkurbo[Kurbo]\nweb_sys[\"web-sys (wasm-bindgen)\"]\n\nwgpu[\"Wgpu (gfx-rs)\"]\n\nfontique --> linebender_resource_handle\nmasonry-->masonry_core\nmasonry-- (dev) -->masonry_testing\nmasonry_testing-->masonry_core\n\nmasonry_android_view --> masonry_core\nmasonry_winit --> masonry_core\nharfrust --> skrifa\nswash --> skrifa\nparley --> swash\nparley --> harfrust\nparley --> fontique\n\npeniko --> color\npeniko --> kurbo\n\nvello --> vello_shaders\nvello_shaders --> vello_encoding\nvello --> vello_encoding\nvello_encoding --> skrifa\nvello --> wgpu\n\nvello --> peniko\nvello --> linebender_resource_handle\n\nxilem_web --> web_sys\nxilem_web --> xilem_core\nmasonry_core -->  vello\nmasonry_core -->  parley\nmasonry_core -->  tree_arena\n\nxilem_masonry --> xilem_core\nxilem_masonry --> masonry\n\nxilem --> xilem_masonry\nxilem --> masonry_winit\n```\n\n<!-- File: masonry/ARCHITECTURE.md (Tokens: ~2608 | Category: project-spec) -->\n# ARCHITECTURE\n\nMasonry is a framework that aims to provide the foundation for Rust GUI libraries.\n\nDevelopers trying to write immediate-mode GUIs, Elm-architecture GUIs, functional reactive GUIs, etc, can import Masonry and get a platform to create windows (often using Winit as a backend) each with a tree of widgets.\nEach widget has to implement the `Widget` trait that Masonry provides.\n\n\n## High-level goals\n\nMasonry has some opinionated design goals:\n\n- **Be dumb.** As a general rule, Masonry doesn't do \"algorithms\".\n  It has no reconciliation logic, no behind-the-scenes dataflow, no clever optimizations, etc.\n  It tries to be efficient, but that efficiency comes from well-designed interfaces and well-placed abstraction boundaries.\n  High-level logic should be implemented in downstream crates.\n- **No mutability tricks.** Masonry uses no unsafe code and as few cells/mutexes as possible.\n  It's designed to work within Rust's ownership system, not to bypass it.\n  While it relies on the `tree_arena` crate in this repository which *does* perform some mutability tricks, the resulting usage patterns are still very rust-like.\n- **Facilitate testing.** The `masonry_testing` crate provides a `TestHarness` type that helps users write unit tests, including tests with simulated user interactions and screenshot tests.\n  In general, every feature should be designed with easy-to-write high-reliability tests in mind.\n- **Facilitate debugging.** GUI app bugs are often easy to fix, but extremely painful to track down.\n  GUI framework bugs are worse.\n  Masonry should facilitate reproducing bugs and pinpointing which bit of code they come from.\n- **Provide reflection.** Masonry should help developers surface some of the inherent structure in GUI programs.\n  It should provide tools out-of-the-box to get information about the widget tree, performance indicators, etc.\n  It should also provide accessibility data out-of-the-box.\n- **Be well-tested:** Masonry doesn't just provide lots of testing tools, it also has a lot of tests.\n  These are a core part of the Masonry development experience.\n\n\n## Code layout\n\nThe Masonry project includes these crates in the Xilem repository:\n\n- **`masonry_core`:** includes the core traits, types and abstractions.\n- **`masonry_testing`:** includes a harness, helper macros and functions, etc, for testing apps built with Masonry.\n- **`masonry`:** includes a baseline set of widgets and properties, a default theme, unit tests for widgets, and unit tests for `masonry_core`.\n- **`masonry_winit`:** the winit backend.\n\n### `masonry_core/src/core/`\n\nMost widget-related code, including the `Widget` trait, its context types, event types, and the `WidgetRef`, `WidgetMut`, and `WidgetPod` types.\n\n#### `masonry_core/src/core/widget_state.rs`\n\nContains the WidgetState type, around which a lot of internal code is based.\n\n`WidgetState` is one of the most important internal types in Masonry.\nUnderstanding Masonry pass code will likely be easier if you read `WidgetState` documentation first.\n\n### `masonry_core/src/app/tracing_backend.rs`\n\nCode for setting up a default configuration of the `tracing` crate.\n\n### `masonry_core/src/app/render_root.rs`\n\nMasonry's composition root. See **General architecture** section.\n\n### `masonry_core/src/layout/`\n\nLayout specific core types.\n\n### `masonry_core/src/passes/`\n\nMasonry's passes are computations that run on the entire widget tree (iff invalidation flags are set) once per frame.\n\n`event.rs` and `update.rs` include a bunch of related passes.\nEvery other file only includes one pass.\n`mod.rs` has utility functions shared between multiple passes.\n\n### `masonry_core/src/properties`\n\nCore properties that every widget has.\n\n### `masonry_core/src/doc/`\n\nLow-level documentation for masonry's cross-cutting concepts.\nIncludes documentation for the pass system, and definitions for various terms used in other places.\n\n### `masonry_core/src/`\n\nContains the TestHarness type, various helper widgets for writing tests, and the snapshot testing code.\n\n### `masonry/src/widgets/`\n\nA list of basic widgets, each defined in a single file.\n\n### `masonry/src/properties/`\n\nA list of properties, which are small plain-old-data types used to customize a widget's look and behavior.\n\n#### `masonry/src/properties/types/`\n\nA list of vocabulary types used in multiple properties.\n\n### `masonry/src/doc/`\n\nHigh-level tutorial for Masonry.\nIn other projects, this would be an `mdbook` doc, but we choose to directly inline the doc, so that `cargo test` runs on it directly.\n\n### `masonry_winit/src/event_loop_runner.rs`\n\nThe bulk of the integration between Masonry and winit.\n\n\n## Module organization principles\n\n### Module structure\n\nThe public module hierarchy should be relatively flat.\nThis makes documentation more readable; readers don't need to click on multiple modules to find the item they're looking for, and maintainers don't need to open multiple layers of folders to find a file.\n\n### Imports\n\nWe should avoid `use super::xxx` imports, except for specific cases like unit tests.\n\nMost imports in the code base should use the canonical top-level import.\n\n### Avoid glob imports\n\nWe should avoid `use foo::*` imports, because they make it harder for people reading the code outside an IDE to track where a given import comes from.\n\nGlob re-exports (e.g. `pub use my_module::*`) are fine and encouraged from `mod.rs` files.\n\n### No prelude\n\nMasonry should have no prelude.\nExamples and documentation should deliberately have a list of imports that cover everything users will need, so users can copy-paste these lists.\n\n\n## General architecture\n\n### Platform handlers\n\nThe composition roots of Masonry are:\n\n- **RenderRoot**, which owns the widget tree.\n- The **AppDriver** trait, which owns the business logic.\n- The **run_with** function in `event_loop_runner.rs`.\n\nThe high-level control flow of a Masonry app's render loop is usually:\n\n- The platform library (windows, macos, x11, etc) runs some callbacks written in Winit in response to user interactions, timers, or other events.\n- Winit calls some RenderRoot method.\n- RenderRoot runs a series of passes (events, updates, paint, accessibility, etc).\n- Throughout those passes, RenderRootSignal values are pushed to a queue which winit can query.\n- winit may change its internals or schedule another frame based on those signals.\n\n\n### Widget hierarchy and passes\n\nThe **Widget** trait is defined in `src/widget/widget.rs`.\nMost of the widget-related bookkeeping is done in the passes defined in `src/passes`.\n\nA **WidgetPod** is the main way to store a child for container widgets.\nIn general, the widget hierarchy looks like a tree of container widgets, with each container owning a `WidgetPod` or a `Vec` of `WidgetPod` or something similar.\n\nWhen RenderRoot runs a pass (on_xxx_event/update_xxx/paint), it iterates over the widget tree, usually in depth-first pre-order, and calls the matching method on each concerned widget.\n\nThere is one exception to this pattern: the layout pass requires widgets to \"manually\" recurse to their children.\n\nThe current passes are:\n\n- **mutate:** Runs a list of callbacks with mutable access to the widget tree. These callbacks can either be passed by the event loop, or pushed to a queue by widgets during the other passes.\n- **on_xxx_event:** Handles UX-related events, e.g. clicks, text entered, IME updates and accessibility input. Widgets can declare these events as \"handled\" which has a bunch of semantic implications.\n- **anim:** Do updates related to an animation frame.\n- **update:** Handles internal changes to some widgets, e.g. when the widget is marked as \"disabled\" or Masonry detects that a widget is hovered by a pointer.\n- **layout:** Container widgets measure their children with `LayoutCtx::compute_size` and then lay them out with `LayoutCtx::run_layout`, finally giving them a position with `LayoutCtx::place_child`.\n- **compose:** Computes the global transform/origin for every widget.\n- **paint** Paint every widget.\n- **accessibility:** Compute every widget's node in the accessibility tree.\n\nSee [masonry_core/src/doc/pass_system.md] for details.\n\n\n### WidgetMut\n\nIn Masonry, widgets can't be mutated directly.\nAll mutations go through a `WidgetMut` wrapper.\nSo, to change a label's text, you might call `WidgetMut<Label>::set_text()`.\nThis helps Masonry make sure that internal metadata is propagated after every widget change.\n\nIn general, there's three ways to get a `WidgetMut`:\n\n- From a `WidgetMut` to a parent widget.\n- As an argument to the callback passed to `RenderRoot::edit_widget()`.\n- As an argument to a callback pushed to the mutate pass.\n\nIn most cases, the `WidgetMut` holds a reference to a WidgetState that will be updated when the `WidgetMut` is dropped.\n\n`WidgetMut` gives direct mutable access to the widget tree.\nThis can be used by GUI frameworks in their tree update methods, and it can be used in tests to make specific local modifications and test their result.\n\n\n### Properties\n\nProperties (often abbreviated to props) are values of arbitrary static types stored alongside each widget.\n\nProperties are a way for widgets to store arbitrary state, not behavior; they're similar to the \"Component\" part of ECS.\n\nThey can be things like Background, BorderColor, BorderWidth, Padding, ContentColor, etc.\n\nAlmost all widget methods take a `PropertiesRef` or `PropertiesMut` parameter that lets them access their properties.\n\nSee [masonry/src/doc/widget_properties.md] for details.\n\n\n### Tests\n\nMasonry is designed to make unit tests easy to write, as if the test function were a mouse-and-keyboard user.\n\nTesting is provided by the **TestHarness** type implemented in the `masonry_testing` crate.\n\nIdeally, the harness should provide ways to emulate absolutely every feature that Masonry apps can use.\nBesides the widget tree, that means keyboard events, mouse events, IME, timers, communication with background threads, animations, accessibility info, etc.\n\n(TODO - Some of that emulation support is not implemented yet. See <https://github.com/linebender/xilem/issues/369>.)\n\nEach widget has unit tests in its module and major features have modules with dedicated unit test suites.\nIdeally, we would like to achieve complete coverage within the crate.\n\n#### Screenshot tests\n\nTODO - mention kompari\n\nTestHarness can render a widget tree, save the result to an image, and compare the image to a stored snapshot.\nThis lets us check that (1) our widgets' paint methods don't panic and (2) changes don't introduce accidental regression in their visual appearance.\n\nTo avoid accumulating large files in the repository, we optimize screenshots with the `oxipng` tool.\nScreenshots tests will fail by default if the saved screenshot is larger than 8KiB.\n\n#### Tests Are Important\n\nTesting is a core element of Masonry.\n\nWhile we don't follow TDD, we have a lot of tests, and *that matters*.\nExtensive testing has helped us catch bugs, find corner cases in our features, and lets us do complex refactors without worrying about breaking something without anyone realizing for years.\n\nWe test individual widgets, Masonry internals, and we even include a screenshot test in most examples.\n\n\n## VS Code markers\n\nMasonry uses VS Code markers to help users browse code with the minimap:\n\nhttps://code.visualstudio.com/docs/getstarted/userinterface#_minimap\n\nThese markers look like this:\n\n```rust\n// --- MARK: MARKER NAME\n```\n\nBy convention, we write them in all caps with three dashes.\nMarkers don't need to follow strict naming conventions, but their names should be a shorthand for the area of the code they're in.\nNames should be short enough not to overflow the VS Code minimap.\n\nSmall files shouldn't have markers, except for files following a general template (widget implementations, view implementations).\nGenerally files should have between 50 and 200 lines between markers.\nIf a file has any markers, it should have enough to split the file into distinct regions.\n\n<!-- File: xilem/ARCHITECTURE.md (Tokens: ~1506 | Category: project-spec) -->\n# ARCHITECTURE\n\nXilem is a family of high-level GUI frameworks.\nXilem apps are written with idiomatic Rust code, with little to no reliance on macros and DSLs.\n\n\n## General architecture\n\nThe most important thing about Xilem is that it is a *reactive* architecture:\n\n- After every change, user-provided functions are called to generate a **view tree**, a lightweight representation of the app's UI.\n- The new view tree is compared against the previous view tree.\n- Based on the differences, the back-end creates an updates a retained **element tree**.\n  Elements are added, removed or mutated to match the current view tree.\n    - In `xilem`, the element tree is the Masonry widget tree.\n    - in `xilem_web`, the element tree is the DOM.\n\nThis architecture is strongly inspired by React, Elm and SwiftUI, which work on similar principles.\n\nA Xilem app's code will usually be made of functions called **components** that create and return subsets of the view tree.\nA component function might look like this pseudo-code:\n\n```rust\nfn list_item(item: &ItemData) -> impl View<...> {\n    row((\n        image(item.image_url),\n        text(item.text),\n        button(\"Do thing\").on_click(|...| do_thing(item.id)),\n    ))\n}\n```\n\n\n## High-level Goals\n\n- **Good Performance:** Xilem aims for the \"performant by default\" class of Rust software. \n  Everything isn't always optimized, but it uses sober data structures and high-performance dependencies (Vello, Parley, wgpu).\n  Static typing gives us very efficient diffing of view trees by default.\n- **Productive:** Xilem offers a high-level API, designed to bypass the borrowing and state management issues that retained GUIs suffer from in Rust.\n- **Idiomatic:** Xilem apps are low on macros or DSLs.\n  Writing a component is about creating and composing view objects, no special syntax needed.\n- **Batteries-included:** Through Masonry, Xilem includes advanced text layout, IME, accessibility trees and styling.\n- **Wide platform support:** Xilem supports the web through `xilem_web` and desktop/mobile platforms through `masonry` and `winit`.\n\n\n## Code layout\n\nThe Xilem project includes these crates:\n\n- **`xilem_core`:** Includes the core traits such as `View`, `ViewElement`, `ViewSequence`, `ElementSlice`, and many others. Also include some generic implementations for these traits (e.g. for Box, Arc, tuples, etc).\n- **`xilem_web`:** Web backend for Xilem. Depends on `xilem_core` and `wasm-bindgen`.\n- **`xilem_masonry`:** Natively compiled backend for Xilem. Depends on `xilem_core` and `masonry`.\n- **`xilem`:** Wrapper crate for `xilem_masonry`, which provides a batteries-included experience for new users. Depends on `xilem_masonry` and `masonry_winit`.\n\n\n## Doc examples\n\nCode snippets in docs comments in both `xilem` and `xilem_masonry` should be as self-contained as possible.\n\nThere should only be a single (visible) import statement at the beginning, listing all the needed imports.\n\nThat import statement should start with `use xilem::`; in other words, all examples should assume that Xilem is the only available dependency (aside from the standard library).\n\nIt should be possible for users to copy-paste the example code into an empty module and have it compile.\nAs such, we should avoid `# ` prefixes when possible.\nView examples should include the whole `fn view() -> impl View<...> {` and `}` parts.\n\n*Note:* Some examples in `xilem` don't currently respect these guidelines.\nWe should fix those examples, and make sure future examples do.\n\n\n## Writing Xilem code\n\n**TODO - This section needs a rewrite.**\n\nYour main interaction with the framework is through the `app_logic()`. Like Elm, the `app_logic()` contains centralized state. On each cycle (meaning, roughly, on each high-level UI interaction such as a button click), the framework calls a closure, giving it mutable access to the `AppData`, and the return value is a `View` tree. This `View` tree is fairly short-lived; it is used to render the UI, possibly dispatch some events, and be used as a reference for diffing by the next cycle, at which point it is dropped. You pass the `app_logic()` to the framework (represented by `Xilem`) and then use it to create the window and run the UI.\n\n```rust\nstruct AppData {\n    count: u32,\n}\n\nfn app_logic(data: &mut AppData) -> impl View<AppData, (), Element = impl Widget> {\n    let count = data.count\n    let button_label = if count == 1 {\n        \"clicked 1 time\".to_string()\n    } else {\n        format!(\"clicked {count} times\")\n    };\n    button(button_label, |data: &mut AppData| data.count +=1)\n}\n\nfn main() {\n    let data = AppData {\n      count: 0\n    }\n    let app = Xilem::new(data, app_logic);\n    app.run_windowed(\"Application Example\".into()).unwrap();\n}\n```\nThe most important construct at the reactive layer is the `View` trait. `View` implementations need to assign the associated `State` and `Element` and implement `build()`, `rebuild()` and `message()`. The `build()` is run only once (first run) to initialize the associated `State` create the associated `Element`of the view. The `rebuild()` is used to update the associated `State` and `Element` and it is what enables Xilem's reactivity. It is worth noting three special types of views the `lens`, `Memoize` and `AnyView` views. \n\nThe `lens` view is used to adapt/convert from the parent data (often the `AppData`) to the child data (some subset of the `AppData`).\n\nThe `View` trees are always eagerly evaluated when the `app_logic()` is called. Even though the `View`'s are very lightweight when the tree becomes large it can create performance issues; the `Memoize` node prunes the `View` tree to improve performance. The generation of the subtree is postponed until the `build()`/`rebuild()` are executed. If none of the `AppData` dependencies change during a UI cycle neither the `View` subtree will be constructed nor the `rebuild()` will be called. The `View` subtree will only be constructed if any of the `AppData` dependencies change. The `Memoize` node should be used when the subtree is a pure function of the `AppData`.\n\nGenerally the Xilem `View` tree is statically typed. `AnyView` allows for the tree to be type erased to enable easy dynamic reconfiguration of the UI.\n</yakaai_skills>"}