// Generated API outline. Implementation bodies omitted. #nullable enable using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using System.Threading; using System; using nfloat = System.Runtime.InteropServices.NFloat; using static Xui.Core.Math2D.Constants; namespace Xui.Core.Abstract { using Xui.Core.Actual; using Xui.Core.Debug; /// /// Represents an abstract base class for Xui applications. /// This class is paired at runtime with a platform-specific counterpart, /// which delegates to actual system APIs on macOS, Windows, Android, etc. /// /// Users should subclass , override the method, /// and call to launch the application. /// public abstract class Application : IServiceProvider { /// The service provider for this application. public IServiceProvider Context { get; } /// Gets the service object of the specified type. /// An object that specifies the type of service object to get. /// A service object of type . /// /// -or- /// /// if there is no service object of type . public virtual object? GetService(Type serviceType); /// The platform runtime used by this application. public IRuntime Runtime { get; } /// A list of disposables that are disposed when the application exits. public List DisposeQueue { get; } /// /// Initializes a new instance of the class. /// public Application(IServiceProvider context); /// /// Starts the main application loop by delegating to the platform-specific run loop. /// This method may block until the application exits, /// or may return immediately if the platform bootstraps a runtime loop before instantiating the app delegate. /// /// The application’s exit code. public virtual int Run(); /// /// Requests graceful shutdown of the application's run loop. /// On platforms without a blocking run loop (iOS, Browser) this is a no-op. /// public virtual void Quit(); /// /// Called by the runtime after initialization. /// Override this method to set up application state and display the initial UI. /// public abstract void Start(); /// /// Raised when the application exits on platforms with a definite exit point. /// See for the same constraint on when this fires. /// public event Action? Exit; /// /// Called by run loops that have a definite exit point (e.g. Win32, macOS) just before /// their returns. Not called on platforms whose run loop never /// exits (iOS, Browser canvas), so do not rely on this for cleanup that must always run. /// public virtual void OnExit(); } } namespace Xui.Core.Abstract { /// /// Mutable clock implementation used for deterministic scenarios such as tests. /// public sealed class FixedClock : IClock { /// /// Initializes a new fixed clock with an initial time value. /// /// The initial local time. public FixedClock(DateTime now); /// /// Gets the current fixed local time. /// public DateTime Now { get; } /// /// Sets the current fixed time. /// /// The new local time. public void Set(DateTime now); /// /// Advances the current fixed time by a delta. /// /// The time delta to add. public void Advance(TimeSpan delta); } /// /// Provides access to the current clock time. /// public interface IClock { /// /// Gets the current local time. /// DateTime Now { get; } } /// /// Describes the macOS-specific chrome treatment for a desktop window. /// Implementing this interface is safe on every target; non-macOS runtimes /// ignore it. /// public interface IMacOSWindowStyle { /// /// Controls whether AppKit displays the native window title. /// public MacOSWindowTitle Title { get; } /// /// Selects the native title and toolbar height. /// public MacOSWindowTitleHeight TitleHeight { get; } /// /// Selects the window background treatment. /// public MacOSWindowBackground Background { get; } } /// /// Provides random value generation. /// public interface IRandom { /// /// Returns a random integer within the specified range. /// /// Inclusive lower bound of the random number. /// Exclusive upper bound of the random number. /// A random integer in the specified range. int Next(int minValue, int maxValue); /// /// Returns a random floating-point number in the range [0.0, 1.0). /// /// A random floating-point number. double NextDouble(); } /// /// Defines the abstract interface for a platform window in Xui. /// This surface hosts rendering, input handling, and layout updates. /// /// /// Implementations of this interface bridge platform-specific Actual windowing /// with the framework’s abstract layer. It is used both for physical windows (e.g. desktop apps) /// and virtual windows (e.g. emulator windows). /// public partial interface IWindow { /// /// Provides optional desktop-specific window styling hints for platforms /// that support multiple top-level windows (e.g., Windows, macOS, Linux). /// /// /// On mobile platforms, applications typically run in a single full-screen window, /// and this interface has no effect. On desktop, implementing this interface allows /// apps to influence window chrome, border visibility, and initial sizing. /// public partial interface IDesktopStyle { /// /// Controls the window backdrop and chrome style. /// /// /// /// Windows: Default creates a standard WS_TILEDWINDOW. /// Chromeless uses WS_POPUP with no system chrome. /// Mica and Acrylic use DWM system backdrop APIs (Windows 11+) /// with system caption buttons but no icon or title text. /// /// /// macOS: Chromeless maps to FullSizeContentView | Borderless /// with a transparent title bar and empty toolbar (traffic-light buttons remain, no chrome visible). /// Acrylic uses NSVisualEffectView with the same transparent-titlebar + empty-toolbar treatment. /// Mica falls back to this Acrylic treatment because macOS has no native Mica material. /// /// public enum WindowBackdrop { /// /// Standard opaque window with full system chrome (title bar, icon, buttons). /// Default = 0, /// /// No system chrome. The entire surface is client area and the app draws everything. /// Chromeless = 1, /// /// Translucent blurred backdrop using the Windows 11 Mica material. System caption /// buttons are kept, but icon and title text are removed. On macOS this falls back to /// the same visual-effect treatment as , because macOS has no /// native Mica material. /// Mica = 2, /// /// Blur-behind backdrop. On Windows 11 uses the Acrylic DWM material (more translucent /// than Mica). On macOS uses NSVisualEffectView with a transparent title bar and /// empty toolbar so traffic-light buttons are visible without any other chrome. /// Acrylic = 3, } } } /// /// Defines the abstract interface for a platform window in Xui. /// This surface hosts rendering, input handling, and layout updates. /// /// /// Implementations of this interface bridge platform-specific Actual windowing /// with the framework’s abstract layer. It is used both for physical windows (e.g. desktop apps) /// and virtual windows (e.g. emulator windows). /// public partial interface IWindow { /// /// Provides optional desktop-specific window styling hints for platforms /// that support multiple top-level windows (e.g., Windows, macOS, Linux). /// /// /// On mobile platforms, applications typically run in a single full-screen window, /// and this interface has no effect. On desktop, implementing this interface allows /// apps to influence window chrome, border visibility, and initial sizing. /// public partial interface IDesktopStyle { /// Controls how much of the window area is available for application drawing. public enum WindowClientArea { /// System-managed non-client area (title bar + borders behave normally). Default, /// /// Extend the client area into the title bar region (app draws background/title area). /// Extended, } } } /// /// The native macOS window background treatment. /// public enum MacOSWindowBackground { /// The standard opaque AppKit window background. Default, /// The standard Acrylic background material. Acrylic, /// /// The dynamic macOS glass material. On macOS releases that do not provide /// it, this falls back to the Acrylic background material. /// Glass, /// /// A transparent borderless window background. The native title is hidden /// when this background is selected. /// Transparent, /// /// A transparent, application-drawn window surface intended for custom tools /// and widgets. The application provides its own drag and resize hit testing. /// Borderless, } /// /// The visibility of the native macOS window title. /// public enum MacOSWindowTitle { /// The native title is visible. Visible, /// The native title is hidden. Hidden, } /// /// The native macOS title and toolbar height. /// public enum MacOSWindowTitleHeight { /// The standard AppKit title-bar height. Default, /// The compact unified toolbar height. Medium, /// The unified toolbar height. Large, } /// /// Random implementation that uses a fixed seed for deterministic output. /// public sealed class SeededRandom : IRandom { /// /// Initializes a new seeded random instance. /// /// The deterministic seed value. public SeededRandom(int seed); /// /// Returns a random integer within the specified range. /// /// Inclusive lower bound of the random number. /// Exclusive upper bound of the random number. /// A random integer in the specified range. public int Next(int minValue, int maxValue); /// /// Returns a random floating-point number in the range [0.0, 1.0). /// /// A random floating-point number. public double NextDouble(); } /// /// Default clock implementation backed by . /// public sealed class SystemClock : IClock { /// /// Gets the shared default system clock instance. /// public static SystemClock Default { get; } /// /// Gets the current local time. /// public DateTime Now { get; } } /// /// Default random implementation backed by . /// public sealed class SystemRandom : IRandom { /// /// Gets the shared default system random instance. /// public static SystemRandom Default { get; } /// /// Returns a random integer within the specified range. /// /// Inclusive lower bound of the random number. /// Exclusive upper bound of the random number. /// A random integer in the specified range. public int Next(int minValue, int maxValue); /// /// Returns a random floating-point number in the range [0.0, 1.0). /// /// A random floating-point number. public double NextDouble(); } } namespace Xui.Core.Abstract { using Xui.Core.Actual; /// /// Internal integration point for .NET's MetadataUpdateHandler, enabling partial support /// for Hot Reload during development. This is not a stable API and should not be used /// by application developers. /// /// /// This type is invoked automatically by the runtime when types are updated via /// Edit and Continue or Hot Reload. However, Hot Reload support in Xui is limited, /// and application developers should rely on full rebuilds for consistent behavior. /// /// The current implementation simply invalidates open windows and clears transient caches, /// without attempting to rehydrate or diff application state. /// public static class HotReload { /// /// Raised on the UI thread when a hot reload occurs. /// Windows subscribe to this event to invalidate themselves. /// public static event Action? OnReload; /// /// Called by the runtime to clear any cached data after a hot reload. /// Not intended for use by application developers. /// /// The list of updated types, if available. public static void ClearCache(Type[]? updatedTypes); /// /// Posts a request to the main UI dispatcher to refresh application state. /// /// The list of updated types, if available. public static void UpdateApplication(Type[]? updatedTypes); /// /// Performs a synchronous application update on the main thread. /// Invokes the event so subscribers (windows) can invalidate. /// /// The list of updated types, if available. public static void MainThreadUpdateApplication(Type[]? updatedTypes); } } namespace Xui.Core.Abstract { using Xui.Core.Abstract.Events; using Xui.Core.Math2D; /// /// Defines the contract for UI content that participates in layout, rendering, and input dispatch. /// public partial interface IContent { /// Requests a visual redraw of this content. void Invalidate(); /// Invoked when a mouse button is pressed within this content's area. void OnMouseDown(ref MouseDownEventRef e); /// Invoked when the mouse pointer moves within this content's area. void OnMouseMove(ref MouseMoveEventRef e); /// Invoked when a mouse button is released. void OnMouseUp(ref MouseUpEventRef e); /// Invoked when the scroll wheel is used over this content. void OnScrollWheel(ref ScrollWheelEventRef e); /// Invoked when a platform magnification gesture occurs over this content. void OnZoom(ref ZoomEventRef e); /// Invoked when a touch event occurs. void OnTouch(ref TouchEventRef e); /// Invoked on each animation frame tick. void OnAnimationFrame(ref FrameEventRef e); /// Performs layout and renders this content into . void Update(ref RenderEventRef @event); /// Invoked when a keyboard key is pressed. void OnKeyDown(ref KeyEventRef e); /// Invoked when a character is typed. void OnChar(ref KeyEventRef e); } /// /// Defines the abstract interface for a platform window in Xui. /// This surface hosts rendering, input handling, and layout updates. /// /// /// Implementations of this interface bridge platform-specific Actual windowing /// with the framework’s abstract layer. It is used both for physical windows (e.g. desktop apps) /// and virtual windows (e.g. emulator windows). /// public partial interface IWindow { /// /// Represents a handler for software keyboard input. /// /// /// This interface allows focused views to receive input from the system's software keyboard, /// typically used on mobile platforms and the emulator. It handles character insertion /// and backward deletion commands. /// /// This is not meant to expose full IME or keyboard layout logic—just basic input dispatch. /// public interface ISoftKeyboard { /// Whether the focused text client contains text. bool HasText { get; } /// Whether the focused text client requires password entry. bool IsSecureTextEntry { get; } /// /// Requests insertion of one or more characters into the current input context. /// /// The input event containing the text to insert. public void InsertText(ref InsertTextEventRef eventRef); /// /// Requests deletion of content preceding the caret or selection. /// /// The input event representing a backspace action. public void DeleteBackwards(ref DeleteBackwardsEventRef eventRef); } } } namespace Xui.Core.Abstract { using Xui.Core.Math2D; /// /// Defines the abstract interface for a platform window in Xui. /// This surface hosts rendering, input handling, and layout updates. /// /// /// Implementations of this interface bridge platform-specific Actual windowing /// with the framework’s abstract layer. It is used both for physical windows (e.g. desktop apps) /// and virtual windows (e.g. emulator windows). /// public partial interface IWindow { /// /// Provides optional desktop-specific window styling hints for platforms /// that support multiple top-level windows (e.g., Windows, macOS, Linux). /// /// /// On mobile platforms, applications typically run in a single full-screen window, /// and this interface has no effect. On desktop, implementing this interface allows /// apps to influence window chrome, border visibility, and initial sizing. /// public partial interface IDesktopStyle { /// /// Cross-platform window stacking level (Z-order abstraction). /// /// /// /// macOS: Maps to NSWindow.Level values such as .normal, .floating, /// .statusBar, and .modalPanel. /// /// /// Windows: Maps primarily to Win32 Z-order using HWND_TOPMOST / /// HWND_NOTOPMOST. Higher levels may be approximated, as Windows exposes fewer /// public layering tiers than macOS. /// /// public enum DesktopWindowLevel : int { /// /// Standard application window. /// /// /// macOS: NSWindow.Level.normal.
/// Windows: normal (non-topmost) window. ///
Normal = 0, /// /// Floating utility window above normal windows. /// /// /// macOS: NSWindow.Level.floating.
/// Windows: implemented via HWND_TOPMOST. ///
Floating = 100, /// /// High-floating level for small status or utility UI. /// /// /// macOS: NSWindow.Level.statusBar.
/// Windows: approximated as topmost, often with utility window styles. ///
StatusBar = 200, /// /// Modal dialog level that blocks interaction with other app windows. /// /// /// macOS: NSWindow.Level.modalPanel or sheets.
/// Windows: enforced via window ownership and modality, not a unique Z-order tier. ///
Modal = 300, } } } /// /// Defines the abstract interface for a platform window in Xui. /// This surface hosts rendering, input handling, and layout updates. /// /// /// Implementations of this interface bridge platform-specific Actual windowing /// with the framework’s abstract layer. It is used both for physical windows (e.g. desktop apps) /// and virtual windows (e.g. emulator windows). /// public partial interface IWindow { /// /// Provides optional desktop-specific window styling hints for platforms /// that support multiple top-level windows (e.g., Windows, macOS, Linux). /// /// /// On mobile platforms, applications typically run in a single full-screen window, /// and this interface has no effect. On desktop, implementing this interface allows /// apps to influence window chrome, border visibility, and initial sizing. /// public partial interface IDesktopStyle { /// /// Controls the window backdrop and chrome style. /// public WindowBackdrop Backdrop { get; } /// /// Optional startup size hint for the window. /// If null, the platform will decide the initial size. /// public Size? StartupSize { get; } /// /// Controls the window stacking level (Z-order) relative to other windows. /// public DesktopWindowLevel Level { get; } /// /// Enables AppKit zoom when Xui receives a double-click in a region that /// reports as Title. Use this /// for extended client areas, where the native title bar is not handling /// the double-click itself. This setting applies only on macOS. /// public bool MacOSDoubleTapSoftwareMaximize { get; } /// /// Controls whether the client area includes the title bar region. /// /// /// Default: System-managed non-client area (title bar + borders behave normally).
Extended: Extends the client area into the title bar region so the app can draw its own /// title bar content/background while still allowing native window behaviors via hit testing.

Windows: Uses DwmExtendFrameIntoClientArea (and relies on WM_NCHITTEST returning /// HTCAPTION for draggable regions). This is the recommended way to hide title text/icon reliably, /// especially with Mica/Acrylic backdrops.
macOS: Uses full-size content view / transparent title bar with title visibility hidden. ///
public WindowClientArea ClientArea { get; } } } } namespace Xui.Core.Abstract { using Xui.Core.Abstract.Events; using Xui.Core.Canvas; using Xui.Core.Math2D; /// /// Defines the abstract interface for a platform window in Xui. /// This surface hosts rendering, input handling, and layout updates. /// /// /// Implementations of this interface bridge platform-specific Actual windowing /// with the framework’s abstract layer. It is used both for physical windows (e.g. desktop apps) /// and virtual windows (e.g. emulator windows). /// public partial interface IWindow { /// /// Gets the actual window immediately downstream of this abstract window. /// Together with , this forms the /// bidirectional composed-window chain. /// Actual.IWindow? Actual { get; } /// /// Gets or sets the total visible area of the window, including content that may /// be obscured by hardware cutouts, rounded corners, or system UI overlays. /// /// /// Used by the layout system to determine the full available size. /// public Rect DisplayArea { get; set; } /// /// Gets or sets the "safe" area of the window, excluding obstructions like notches /// or status bars. Important UI elements should be placed within this area. /// /// /// Especially relevant on mobile devices and in emulator scenarios. /// public Rect SafeArea { get; set; } /// /// Gets or sets the corner radius of the physical screen, in logical pixels. /// Used to offset UI elements (such as scrollbar indicators) away from rounded screen edges. /// Zero on desktop platforms where the window has sharp corners. /// public nfloat ScreenCornerRadius { get; set; } /// /// Invoked when the window is closed and cleanup should occur. /// void Closed(); /// /// Invoked before the window closes. Returning false can cancel the closure. /// /// /// true if the window may close; otherwise, false. bool Closing(); /// /// Invoked once per frame to propagate animation timing information. /// /// Timing details for the current animation frame. void OnAnimationFrame(ref FrameEventRef animationFrame); /// /// Invoked when the mouse is moved within the window. /// /// The mouse movement event data. void OnMouseMove(ref MouseMoveEventRef evRef); /// /// Invoked when a mouse button is pressed within the window. /// /// The mouse down event data. void OnMouseDown(ref MouseDownEventRef evRef); /// /// Invoked when a mouse button is released within the window. /// /// The mouse up event data. void OnMouseUp(ref MouseUpEventRef evRef); /// /// Invoked when the scroll wheel is used within the window. /// /// The scroll wheel event data. void OnScrollWheel(ref ScrollWheelEventRef evRef); /// Invoked when a platform magnification gesture occurs within the window. void OnZoom(ref ZoomEventRef evRef); /// /// Invoked when touch input occurs within the window. /// /// The touch event data. void OnTouch(ref TouchEventRef touchEventRef); /// /// Invoked during the render phase of the UI lifecycle. /// Responsible for triggering layout and visual updates. /// /// The render event data, including target rect and frame info. void Render(ref RenderEventRef render); /// /// Invoked when the system requests a hit test for window interaction. /// Allows the app to indicate whether a region is draggable, resizable, etc. /// /// The hit test event containing pointer position and window bounds. void WindowHitTest(ref WindowHitTestEventRef evRef); /// /// Invoked when a key is pressed. /// /// The keyboard event data. void OnKeyDown(ref KeyEventRef e); /// /// Invoked when a character is input (after keyboard translation). /// /// The keyboard event data with the translated character. void OnChar(ref KeyEventRef e); } } namespace Xui.Core.Abstract { using Xui.Core.Abstract.Events; using Xui.Core.Actual; using Xui.Core.Canvas; using Xui.Core.DI; using Xui.Core.Debug; using Xui.Core.Math2D; using Xui.Core.UI; /// /// Represents an abstract cross-platform application window in Xui. /// Handles input, rendering, layout, and software keyboard integration. /// /// /// This class connects the abstract UI framework with the underlying platform window, /// acting as a root container for layout and visual composition. Subclasses may override /// specific input or rendering behaviors as needed. /// public class Window : Abstract.IWindow, Abstract.IWindow.ISoftKeyboard, IServiceProvider, IDisposable { /// The service provider for this window. public IServiceProvider Context { get; } /// Gets the service object of the specified type. /// An object that specifies the type of service object to get. /// A service object of type . /// /// -or- /// /// if there is no service object of type . /// /// Resolves platform and middleware services through the actual-window chain, then /// falls back to this window's DI scope. The chain is strictly forward: actual /// windows must never consult their abstract event receiver for services. /// /// /// belongs to this window's root rather than a middleware host window. /// public virtual object? GetService(Type serviceType); /// A list of disposables disposed when the window closes. public List DisposeQueue { get; } /// /// When true (the default), closing the window calls . /// Set to false for windows that survive being closed and reopened. /// public bool DestroyOnClose { get; set; } /// The platform runtime used by this window. public IRuntime Runtime { get; } /// /// Gets the underlying platform-specific window instance. /// public Actual.IWindow Actual { get; } /// /// Gets or sets the total visible area of the window, including content that may /// be obscured by hardware cutouts, rounded corners, or system UI overlays. /// /// /// Used by the layout system to determine the full available size. /// public virtual Rect DisplayArea { get; set; } /// /// Gets or sets the "safe" area of the window, excluding obstructions like notches /// or status bars. Important UI elements should be placed within this area. /// /// /// Especially relevant on mobile devices and in emulator scenarios. /// public virtual Rect SafeArea { get; set; } /// /// Gets or sets the corner radius of the physical screen, in logical pixels. /// Used to offset UI elements (such as scrollbar indicators) away from rounded screen edges. /// Zero on desktop platforms where the window has sharp corners. /// public virtual nfloat ScreenCornerRadius { get; set; } /// /// Gets the text measure context for this window, used for hit-testing text /// positions during pointer events. Null on platforms that do not provide one. /// public virtual ITextMeasureContext? TextMeasureContext { get; } /// The root view that hosts the window's content hierarchy. public RootView RootView { get; } /// /// Stable name used to identify this window's render surface in instrumentation. /// public string InstrumentationName { get; } /// The instrumentation sink created for this window's render surface, if enabled. public IRenderSurfaceInstrumentsSink? RenderSurfaceInstruments { get; } /// Sets the root content view of this window. public View Content { init; } /// /// Initializes a new instance of the class. /// This creates the backing platform window. /// /// /// An optional scoped for this window. /// If it implements , it will be disposed when the window closes. /// public Window(IServiceProvider context); /// /// Gets or sets the window title (where supported by the platform). /// public string Title { get; set; } /// /// Requests that the soft keyboard be shown or hidden (on supported platforms). /// public bool RequireKeyboard { get; set; } /// /// Makes the window visible and adds it to the list of open windows. /// public void Show(); /// /// Invoked during the render phase of the UI lifecycle. /// Responsible for triggering layout and visual updates. /// /// The render event data, including target rect and frame info. public virtual void Render(ref RenderEventRef renderEventRef); /// /// Invoked when the system requests a hit test for window interaction. /// Allows the app to indicate whether a region is draggable, resizable, etc. /// /// The hit test event containing pointer position and window bounds. public virtual void WindowHitTest(ref WindowHitTestEventRef evRef); /// /// Invoked before the window closes. Returning false can cancel the closure. /// /// /// true if the window may close; otherwise, false. public virtual bool Closing(); /// /// Invoked when the window is closed and cleanup should occur. /// public virtual void Closed(); /// /// Releases all managed resources owned by this window. /// If the platform window is still open, it is closed first. /// Items in are disposed in order. /// public void Dispose(); /// /// true when called from ; false from a finalizer. /// protected virtual void Dispose(bool disposing); /// /// Creates the platform-specific window for this abstract window. /// /// The platform implementation of . protected virtual Actual.IWindow CreateActualWindow(); /// /// Requests a visual invalidation/redraw of this window. /// public virtual void Invalidate(); /// /// Invoked when a mouse button is pressed within the window. /// /// The mouse down event data. public virtual void OnMouseDown(ref MouseDownEventRef e); /// /// Invoked when the mouse is moved within the window. /// /// The mouse movement event data. public virtual void OnMouseMove(ref MouseMoveEventRef e); /// /// Invoked when a mouse button is released within the window. /// /// The mouse up event data. public virtual void OnMouseUp(ref MouseUpEventRef e); /// /// Invoked when the scroll wheel is used within the window. /// /// The scroll wheel event data. public virtual void OnScrollWheel(ref ScrollWheelEventRef e); /// Routes a platform magnification gesture through the view tree. public virtual void OnZoom(ref ZoomEventRef e); /// /// Invoked when touch input occurs within the window. /// /// The touch event data. public virtual void OnTouch(ref TouchEventRef e); /// /// Invoked when a key is pressed. /// /// The keyboard event data. public virtual void OnKeyDown(ref KeyEventRef e); /// /// Invoked when a character is input (after keyboard translation). /// /// The keyboard event data with the translated character. public virtual void OnChar(ref KeyEventRef e); /// /// Invoked once per frame to propagate animation timing information. /// /// Timing details for the current animation frame. public virtual void OnAnimationFrame(ref FrameEventRef e); /// Whether the focused text client contains text. public virtual bool HasText { get; } /// Whether the focused text client requires password entry. public virtual bool IsSecureTextEntry { get; } /// /// Requests insertion of one or more characters into the current input context. /// /// The input event containing the text to insert. public virtual void InsertText(ref InsertTextEventRef eventRef); /// /// Requests deletion of content preceding the caret or selection. /// /// The input event representing a backspace action. public virtual void DeleteBackwards(ref DeleteBackwardsEventRef eventRef); } } namespace Xui.Core.Abstract.Events { /// /// Represents a platform-level input event requesting deletion of content /// positioned logically before the caret or selection range. /// Typically triggered by a "Backspace" key press or an equivalent gesture. /// /// /// This event originates from the Actual window layer and is forwarded /// to the Abstract window for dispatching through the view hierarchy. /// It is intended to be routed to the appropriate focused or editable view. /// public ref struct DeleteBackwardsEventRef { /// /// Initializes a new instance of the struct. /// public DeleteBackwardsEventRef(); } /// /// Represents a platform-level event dispatched once per frame, /// providing timing information used for driving animations and visual updates. /// /// /// This event is emitted from the Actual window and forwarded /// to the Abstract window, typically during the animation phase /// of the UI lifecycle. It provides both the previous and next frame times, /// along with the time delta between them. Consumers can use this data /// to advance animations or perform time-based layout updates. /// public ref struct FrameEventRef { /// /// The timestamp of the previous frame. /// public TimeSpan Previous; /// /// The timestamp of the upcoming frame. /// public TimeSpan Next; /// /// The time elapsed between the previous and next frames. /// public TimeSpan Delta; /// /// Initializes a new instance of the struct /// with the given previous and next frame timestamps. /// /// The timestamp of the previous frame. /// The timestamp of the upcoming frame. public FrameEventRef(TimeSpan previous, TimeSpan next); } /// /// Represents a platform-level input event requesting insertion of text /// at the current caret or selection position. /// /// /// This event originates from the Actual window and is forwarded /// to the Abstract layer for dispatch through the view hierarchy. /// It is typically triggered by user input such as typing characters, /// pasting from the clipboard, or text input from IMEs. /// public ref struct InsertTextEventRef { /// /// The text to be inserted into the current input context. /// public readonly string Text; /// /// Initializes a new instance of the struct /// with the specified text to insert. /// /// The string of text to be inserted. public InsertTextEventRef(string text); } /// /// Represents a keyboard input event. /// Used for both key down (Key is set) and character input (Character is set) events. /// public ref struct KeyEventRef { /// /// The virtual key code for key down/up events. /// public VirtualKey Key; /// /// The Unicode character for character input events (e.g. WM_CHAR). /// Zero when this is a key down/up event without character translation. /// public char Character; /// /// True if the Shift key is held during this event. /// public bool Shift; /// /// True if this is an auto-repeat event (key held down). /// public bool IsRepeat; /// /// Set to true by the handler to indicate the event was consumed. /// public bool Handled; } /// /// Identifies a specific mouse button involved in a pointer event. /// public enum MouseButton { /// /// The left mouse button, typically used for primary actions like selection or dragging. /// Left, /// /// The right mouse button, typically used for context menus or alternate actions. /// Right, /// /// Any other mouse button, such as middle-click or additional buttons on advanced mice. /// Other } /// /// Represents a platform-level input event containing one or more touch points, /// typically originating from a touchscreen or trackpad gesture. /// /// /// This event is dispatched by the Actual window and forwarded /// to the Abstract layer for routing through the view hierarchy. /// It includes all active touch points for the current frame, allowing /// gesture recognition, hit testing, and view interaction logic. /// public ref struct TouchEventRef { /// /// A span of all current touch points involved in this event. /// public readonly ReadOnlySpan Touches; /// Text measurement supplied by the window for precision caret hit-testing. public Xui.Core.Canvas.ITextMeasureContext? TextMeasure; /// /// Initializes a new instance of the struct /// with the provided set of touch points. /// /// A span of active touch data. public TouchEventRef(ReadOnlySpan touches); } /// /// Describes the phase of an individual touch point during a touch event. /// public enum TouchPhase { /// /// The touch has just started (finger or stylus contacted the surface). /// Start, /// /// The touch is actively moving across the surface. /// Move, /// /// The touch has ended (finger or stylus lifted off the surface). /// End, /// The system interrupted the contact; it must not complete a tap. Cancel } /// /// Platform-agnostic virtual key codes for keyboard input. /// Values intentionally match Win32 VK_* codes for zero-cost mapping on Windows. /// public enum VirtualKey : ushort { /// No key pressed. None = 0x00, /// Backspace key. Back = 0x08, /// Tab key. Tab = 0x09, /// Enter/Return key. Return = 0x0D, /// Shift modifier key. Shift = 0x10, /// Control modifier key. Control = 0x11, /// Alt modifier key. Alt = 0x12, /// Escape key. Escape = 0x1B, /// Space bar. Space = 0x20, /// Page Up key. Prior = 0x21, /// Page Down key. Next = 0x22, /// End key. End = 0x23, /// Home key. Home = 0x24, /// Left arrow key. Left = 0x25, /// Up arrow key. Up = 0x26, /// Right arrow key. Right = 0x27, /// Down arrow key. Down = 0x28, /// Insert key. Insert = 0x2D, /// Delete key. Delete = 0x2E, /// Digit key 0. D0 = 0x30, /// Digit key 1. D1 = 0x31, /// Digit key 2. D2 = 0x32, /// Digit key 3. D3 = 0x33, /// Digit key 4. D4 = 0x34, /// Digit key 5. D5 = 0x35, /// Digit key 6. D6 = 0x36, /// Digit key 7. D7 = 0x37, /// Digit key 8. D8 = 0x38, /// Digit key 9. D9 = 0x39, /// Letter key A. A = 0x41, /// Letter key B. B = 0x42, /// Letter key C. C = 0x43, /// Letter key D. D = 0x44, /// Letter key E. E = 0x45, /// Letter key F. F = 0x46, /// Letter key G. G = 0x47, /// Letter key H. H = 0x48, /// Letter key I. I = 0x49, /// Letter key J. J = 0x4A, /// Letter key K. K = 0x4B, /// Letter key L. L = 0x4C, /// Letter key M. M = 0x4D, /// Letter key N. N = 0x4E, /// Letter key O. O = 0x4F, /// Letter key P. P = 0x50, /// Letter key Q. Q = 0x51, /// Letter key R. R = 0x52, /// Letter key S. S = 0x53, /// Letter key T. T = 0x54, /// Letter key U. U = 0x55, /// Letter key V. V = 0x56, /// Letter key W. W = 0x57, /// Letter key X. X = 0x58, /// Letter key Y. Y = 0x59, /// Letter key Z. Z = 0x5A, } } namespace Xui.Core.Abstract.Events { using Xui.Core.Canvas; using Xui.Core.Math2D; /// /// Represents a platform-level input event indicating that a mouse button /// was pressed at a given position. /// /// /// This event is dispatched by the Actual window and forwarded /// to the Abstract layer for routing through the view hierarchy. /// It may be used to initiate focus, dragging, selection, or other pointer interactions. /// public ref struct MouseDownEventRef { /// /// The position of the mouse pointer at the time of the event, /// in logical window coordinates. /// public Point Position; /// Normalized device pressure, from 0 to 1, when HasPressure is true. public System.Runtime.InteropServices.NFloat Pressure; /// Whether the source supplied a real pressure measurement. public bool HasPressure; /// /// The mouse button that was pressed. /// public MouseButton Button; /// /// Optional text measure context for hit-testing text positions. /// May be null on platforms that do not provide one. /// public ITextMeasureContext? TextMeasure; } /// /// Represents a platform-level input event indicating that the mouse pointer /// has moved to a new position. /// /// /// This event is dispatched by the Actual window and forwarded /// to the Abstract layer for routing through the view hierarchy. /// It is typically used to trigger hover effects, cursor updates, /// or to track dragging or gesture movement. /// public ref struct MouseMoveEventRef { /// /// The current position of the mouse pointer in logical window coordinates. /// public Point Position; /// Normalized device pressure, from 0 to 1, when HasPressure is true. public System.Runtime.InteropServices.NFloat Pressure; /// Whether the source supplied a real pressure measurement. public bool HasPressure; /// /// Optional text measure context for hit-testing text positions. /// May be null on platforms that do not provide one. /// public ITextMeasureContext? TextMeasure; } /// /// Represents a platform-level input event indicating that a mouse button /// was released at a given position. /// /// /// This event is dispatched by the Actual window and forwarded /// to the Abstract layer for routing through the view hierarchy. /// It is typically used to complete interactions such as clicks, drags, /// or other pointer-driven gestures. /// public ref struct MouseUpEventRef { /// /// The position of the mouse pointer at the time of the event, /// in logical window coordinates. /// public Point Position; /// Normalized device pressure, from 0 to 1, when HasPressure is true. public System.Runtime.InteropServices.NFloat Pressure; /// Whether the source supplied a real pressure measurement. public bool HasPressure; /// /// The mouse button that was released. /// public MouseButton Button; /// /// Optional text measure context for hit-testing text positions. /// May be null on platforms that do not provide one. /// public ITextMeasureContext? TextMeasure; } /// /// Represents a platform-level render event dispatched after a timing frame, /// indicating that views should perform layout and rendering operations within a given region. /// /// /// This event follows a and marks the phase during which /// views are expected to perform their Measure, Arrange, and Render passes. /// It is emitted by the Actual window and forwarded to the Abstract layer. /// public ref struct RenderEventRef { /// /// The region of the screen or surface that should be re-rendered. /// public Rect Rect; /// /// Timing information associated with this frame, typically used for animations. /// public FrameEventRef Frame; /// /// The frame-bound drawing context for this render pass. It must not be retained /// after the event returns to the render surface. /// public IContext Context; /// /// Initializes a new instance of the struct /// with the given invalidation region and frame timing data. /// /// The region to be rendered. /// The timing information for this frame. /// The drawing context for this render pass. public RenderEventRef(Rect rect, FrameEventRef frame, IContext context); } } namespace Xui.Core.Abstract.Events { using Xui.Core.Math2D; /// Lifecycle flags for direct scrolling or platform-generated scroll inertia. [Flags] public enum ScrollPhase { /// No phase information is available. None = 0, /// The sequence began. Began = 1, /// Contact continues without movement. Stationary = 2, /// The sequence moved. Changed = 4, /// The sequence ended normally. Ended = 8, /// The sequence was cancelled. Cancelled = 16, /// Contact may begin a scroll gesture. MayBegin = 32 } /// /// Represents a platform-level input event generated by a scroll wheel or trackpad gesture, /// indicating a change in scroll position. /// /// /// This event is dispatched by the Actual window and forwarded /// to the Abstract layer for routing through the view hierarchy. /// It may be used to scroll content, zoom views, or trigger kinetic effects, /// depending on platform and modifier keys. /// public ref struct ScrollWheelEventRef { /// /// The scroll delta, typically measured in logical units per axis. /// Positive Y values usually indicate upward scrolling. /// public Vector Delta; /// /// True for continuous, precise deltas in logical points (for example a macOS trackpad). /// False for ordinary wheel input or sources that do not report precision. /// public bool IsPrecise; /// Direct gesture phase, or when unavailable. public ScrollPhase Phase; /// /// Platform-generated inertia phase. Its deltas already include deceleration; /// a handler must not treat them as continued finger contact or add another fling. /// public ScrollPhase MomentumPhase; /// /// The position at which this gesture should be routed, when the input /// source provides one. Sources without a position use the most recently /// observed pointer location instead. /// public Point Position; /// Whether is populated. public bool HasPosition; /// /// Set to true by a handler to stop further propagation of this event. /// public bool Handled; } /// /// Represents a single touch point within a multi-touch input event. /// /// /// This structure contains identifying and positional data for a specific finger /// or contact point on a touch surface. Multiple instances may be /// reported in a single event when handling gestures or complex touch interactions. /// public struct Touch { /// /// A unique index identifying this touch point during its lifetime. /// Typically assigned by the platform and reused after release. /// public int Index; /// /// The current position of the touch in logical window coordinates. /// public Point Position; /// /// The estimated contact radius of the touch, in logical units. /// Used for gesture recognition or pressure emulation. /// public nfloat Radius; /// /// The current phase of the touch (e.g., began, moved, ended). /// public TouchPhase Phase; } /// /// Represents a platform-level hit test event that allows the application /// to define how a point within a custom window frame should be interpreted /// (e.g., as a draggable title bar, resize border, or transparent region). /// /// /// This event is dispatched when the user interacts with the non-client area /// of a custom-framed window (such as the emulator window or a styled installer). /// It is primarily used on platforms like Windows that support fine-grained /// window frame interaction via hit testing. /// /// On macOS and other platforms where native support is unavailable, /// this event may be ignored or implemented through custom code. /// public ref struct WindowHitTestEventRef { /// /// The location of the hit test, in logical window coordinates. /// public Point Point; /// /// The bounds of the entire window, in logical coordinates. /// This may be used to determine edge proximity for resizing logic. /// public Rect Window; /// /// The result of the hit test, set by the application to control /// how the system should interpret the hit location. /// public WindowArea Area; /// /// Initializes a new instance of the struct. /// /// The location of the pointer input. /// The bounds of the target window. public WindowHitTestEventRef(Point point, Rect window); /// /// Describes the purpose or function of a region within a window. /// public enum WindowArea : uint { /// /// The area is unspecified; the platform should handle it normally. /// Default = 0, /// /// The area is transparent to hit testing and should not trigger drag or resize. /// Transparent, /// /// The area represents the client region of the window (normal content). /// Client, /// /// The area represents a draggable title bar region. /// Title, /// Top-left resize corner. BorderTopLeft, /// Top edge resize border. BorderTop, /// Top-right resize corner. BorderTopRight, /// Right edge resize border. BorderRight, /// Bottom-right resize corner. BorderBottomRight, /// Bottom edge resize border. BorderBottom, /// Bottom-left resize corner. BorderBottomLeft, /// Left edge resize border. BorderLeft } } } namespace Xui.Core.Abstract.Events { using NFloat = System.Runtime.InteropServices.NFloat; using Xui.Core.Math2D; /// A platform magnification gesture, routed separately from scrolling and touch contacts. public ref struct ZoomEventRef { /// Incremental scale multiplier: 1 is unchanged, values above 1 zoom in. public NFloat ScaleFactor; /// The gesture anchor in window coordinates. public Point Position; /// Whether is available; otherwise routing uses the last mouse position. public bool HasPosition; /// The native gesture lifecycle, using the same flags as scrolling. public ScrollPhase Phase; /// Set to true to stop propagation to ancestor views. public bool Handled; } } namespace Xui.Core.Actual { /// /// Tactile presets. The platform chooses the closest available native effect; /// strength and texture are not guaranteed to be identical across devices. /// public enum HapticEffect { /// A small, crisp ruler or picker tick. /// /// On iOS, uses UISelectionFeedbackGenerator.selectionChanged(). /// On Android, uses View.performHapticFeedback(SEGMENT_TICK) on API 34+, /// falling back to CLOCK_TICK on earlier versions. /// Tick, /// A light physical impact. /// /// On iOS, uses UIImpactFeedbackGenerator.impactOccurred() with the light style. /// On Android, approximated with VibrationEffect.EFFECT_TICK on API 29+, /// falling back to View.performHapticFeedback(CLOCK_TICK) on earlier versions. /// LightImpact, /// A medium physical impact. /// /// On iOS, uses UIImpactFeedbackGenerator.impactOccurred() with the medium style. /// On Android, approximated with VibrationEffect.EFFECT_CLICK on API 29+, /// falling back to View.performHapticFeedback(LONG_PRESS) on earlier versions. /// MediumImpact, /// A heavy physical impact. /// /// On iOS, uses UIImpactFeedbackGenerator.impactOccurred() with the heavy style. /// On Android, approximated with VibrationEffect.EFFECT_HEAVY_CLICK on API 29+, /// falling back to View.performHapticFeedback(LONG_PRESS) on earlier versions. /// HeavyImpact, /// A soft, rounded impact. /// /// On iOS, uses UIImpactFeedbackGenerator.impactOccurred() with the soft style. /// On Android API 31+, approximated with a composed PRIMITIVE_THUD at scale 0.5 /// when the device supports it. Otherwise uses VibrationEffect.EFFECT_CLICK on API 29+, /// or View.performHapticFeedback(CLOCK_TICK) on earlier versions. /// SoftImpact, /// A firm, sharp impact. /// /// On iOS, uses UIImpactFeedbackGenerator.impactOccurred() with the rigid style. /// On Android API 31+, approximated with a composed PRIMITIVE_CLICK at scale 1.0 /// when the device supports it. Otherwise uses VibrationEffect.EFFECT_CLICK on API 29+, /// or View.performHapticFeedback(LONG_PRESS) on earlier versions. /// RigidImpact, /// Positive completion feedback. /// /// On iOS, uses UINotificationFeedbackGenerator.notificationOccurred(.success). /// On Android, uses View.performHapticFeedback(CONFIRM) on API 30+. /// Approximated with VibrationEffect.EFFECT_DOUBLE_CLICK on API 29, /// or View.performHapticFeedback(LONG_PRESS) on earlier versions. /// Success, /// A cautionary notification. /// /// On iOS, uses UINotificationFeedbackGenerator.notificationOccurred(.warning). /// Android has no dedicated warning preset. Approximated with /// VibrationEffect.EFFECT_DOUBLE_CLICK on API 29+, falling back to /// View.performHapticFeedback(LONG_PRESS) on earlier versions. /// Warning, /// Failure or rejection feedback. /// /// On iOS, uses UINotificationFeedbackGenerator.notificationOccurred(.error). /// On Android, uses View.performHapticFeedback(REJECT) on API 30+. /// Approximated with VibrationEffect.EFFECT_DOUBLE_CLICK on API 29, /// or View.performHapticFeedback(LONG_PRESS) on earlier versions. /// Error, } /// /// Represents a platform-specific dispatcher for marshaling callbacks onto the main UI thread. /// Used by the Xui runtime to ensure thread-safe execution of UI logic. /// /// Each platform must provide an implementation that posts callbacks to the appropriate runloop or UI thread. /// public interface IDispatcher { /// /// Posts the specified callback to be executed on the dispatcher's thread (typically the UI thread). /// Use this method when calling from a background thread and needing to safely transition /// to the main thread for UI updates or layout work. /// /// The action to execute on the dispatcher's thread. void Post(Action callback); } /// /// Optional, window-scoped tactile feedback. Resolve through the view's service /// provider and call on the UI thread. Desktop runtimes may leave this unregistered. /// Requests respect native settings and hardware capabilities; playback is not guaranteed. /// public interface IHapticFeedback { /// /// Prepares an effect without vibrating. This is an optional latency hint; /// must work without it. Platforms may ignore the hint. /// void Prepare(HapticEffect effect); /// /// Plays a preset using the platform's closest available effect. Native platforms /// may coalesce rapid requests; this does not queue delayed pulses. /// void Play(HapticEffect effect); } /// /// Represents a platform-specific run loop responsible for driving the application's lifecycle. /// Each platform must provide an implementation that enters the appropriate system event loop /// and continues running until the application exits. /// /// The Xui runtime uses this interface to abstract over platform differences in event dispatch and app execution. /// public interface IRunLoop { /// /// Starts the main run loop for the application. /// This method may block until the application terminates or exits naturally. /// On platforms with built-in UI event loops (e.g., iOS, Android), /// this method may return immediately after bootstrapping the application delegate. /// /// The application’s exit code. int Run(); /// /// Requests that the run loop exit gracefully. /// On platforms with a definite exit (Win32, macOS) this posts a quit message to the main thread. /// On platforms without a run loop (iOS, Browser) this is a no-op. /// void Quit(); } /// /// Provides a platform-specific implementation of the Xui runtime, /// responsible for creating and connecting abstract application components to their actual counterparts. /// /// This interface acts as a bridge between the platform-independent core and the underlying OS-specific APIs /// (e.g., Win32, Cocoa, UIKit), enabling rendering, windowing, and event dispatch. /// public interface IRuntime { /// /// Gets the main thread dispatcher for scheduling UI work. /// Used to marshal execution onto the main thread for layout, input, and rendering. /// IDispatcher MainDispatcher { get; } /// /// Creates a platform-specific window that is bound to the given abstract window definition. /// /// The abstract window definition provided by user code. /// The window/application service chain reached after platform services. /// A concrete window implementation for the current platform. Actual.IWindow CreateWindow(Abstract.IWindow windowAbstract, IServiceProvider applicationServices); /// /// Creates a platform-specific run loop associated with the given abstract application. /// The returned run loop is responsible for managing the application's execution lifecycle. /// /// The abstract application instance defined by user code. /// A platform-specific run loop instance. IRunLoop CreateRunloop(Abstract.Application applicationAbstract); } /// /// Optional window-scoped control of status-bar text and icons. Resolve through the /// window or view service provider and use on the UI thread. Desktop runtimes may /// leave this unregistered. This does not change the bar background or safe area. /// public interface IStatusBar { /// Gets or sets the requested foreground appearance. StatusBarAppearance Appearance { get; set; } } /// /// Optional, window-scoped vibration playback. Call on the UI thread. Each Play /// replaces this service's previous playback; stop when the owning interaction ends. /// Desktop runtimes need not register this service; emulators provide silent playback. /// public interface IVibration { /// Whether the device can produce vibration. bool IsSupported { get; } /// Whether normalized frequency/texture control is available. bool SupportsFrequency { get; } /// /// Starts or updates continuous vibration until Stop. Strength and frequency /// must be finite and in [0, 1]. Frequency describes texture, not physical Hz: /// iOS maps it to sharpness; Android uses envelope sharpness when supported. /// Android may replace the native effect when updating; otherwise frequency is ignored. /// Zero strength silences playback. Native settings and interruptions still apply. /// void Play(nfloat strength, nfloat frequency); /// /// Plays linearly interpolated control points, optionally repeating until Stop. /// At least two points are required, beginning at zero with strictly increasing /// times, up to 30 seconds. Implementations copy or consume the span before returning. /// Native devices may resample points or soften the pattern boundaries. /// void Play(scoped ReadOnlySpan points, bool repeat = false); /// Stops playback and cancels pending starts. Safe to call repeatedly. void Stop(); } /// Foreground appearance of the system status-bar text and icons. public enum StatusBarAppearance { /// Follow platform appearance policy (normally the system light/dark theme), not canvas pixel sampling. Auto = 0, /// Light text and icons, suitable for a dark background. Light = 1, /// Dark text and icons, suitable for a light background. Dark = 2, } /// Shared validation and interpolation for native vibration backends. public static class VibrationPattern { /// The portable pattern duration limit, matching one iOS continuous event. public static readonly TimeSpan MaximumDuration; /// Validates a normalized strength/frequency pair. public static void Validate(nfloat strength, nfloat frequency); /// Validates the point count, times, duration and normalized values. public static void Validate(scoped ReadOnlySpan points); /// Samples a validated pattern, clamping outside its time range. public static VibrationPoint Sample(scoped ReadOnlySpan points, TimeSpan time); } /// A vibration's normalized strength and frequency/texture at an absolute pattern time. /// Time from the beginning of the pattern. /// Strength in [0, 1]. /// Texture in [0, 1], from soft/low to crisp/high; not Hertz. public readonly record struct VibrationPoint(TimeSpan Time, nfloat Strength, nfloat Frequency); } namespace Xui.Core.Actual { using Xui.Core.Canvas; /// /// Platform image pipeline. Caches decoded GPU-resident images by URI and vends /// handles to views via the service-resolution chain. /// Implement this on each platform window to participate in image loading. /// public interface IImagePipeline { /// /// Creates a new handle backed by this pipeline's catalog. /// The handle is initially empty; populate it with /// or . /// IImage CreateImage(); } /// /// Represents a platform-specific window implementation used by the Xui runtime. /// Each platform (e.g., Windows, macOS, iOS) must provide an implementation of this interface /// to manage window lifecycle, rendering, and input. /// /// This interface is typically paired with an abstract window in the Xui framework, /// and is not used directly by application developers. /// public interface IWindow : IServiceProvider { /// /// Gets the abstract window immediately upstream of this actual window. /// Together with , this forms the /// bidirectional composed-window chain. /// Abstract.IWindow? Abstract { get; } /// /// The service provider reached after this actual window. Middleware uses this /// exclusively for its forward service chain; it must never use its abstract /// event receiver as a service fallback. /// IServiceProvider NextServiceProvider { get; } /// /// Gets or sets the window title, where supported by the platform (e.g., desktop). /// string Title { get; set; } /// /// Displays the window to the user. This may include making it visible, entering the main loop, /// or attaching it to the application's view hierarchy, depending on the platform. /// void Show(); /// /// Closes and destroys the platform window. Called when the abstract window is disposed /// programmatically rather than through a user-initiated close gesture. /// The default implementation is a no-op for platforms that do not support imperative close. /// void Close(); /// /// Requests a redraw of the window surface. /// The platform should trigger a paint or render callback as soon as possible. /// void Invalidate(); /// /// Gets or sets whether the window currently requires keyboard input focus. /// Platforms may use this to show or hide on-screen keyboards. /// bool RequireKeyboard { get; set; } /// /// Gets a lightweight text measure context for hit-testing text positions /// during pointer events. Returns null on platforms that do not support it. /// ITextMeasureContext? TextMeasureContext { get; } } } namespace Xui.Core.Actual { using Xui.Core.UI; /// Optional native range editing and selection service, resolved through the window. public interface ITextInputSession { /// Connects the focused editor, or ends the session on blur. The service owns NativeSelection while connected. void SetClient(ITextEditingClient? client); /// Cancels native selection gestures when an ancestor takes pointer capture. void CancelSelectionGesture(); } } namespace Xui.Core.Actual { using Xui.Core.Math2D; /// /// Optional, window-scoped native precision-selection UI. Resolve through the view's /// service provider; absence (or false) means no native loupe. /// This presents rendered content only; the focused view owns text and selection. /// public interface ITextMagnifier { /// Whether the running OS supports the native magnifier. bool IsSupported { get; } /// /// Begins or updates a precision-selection gesture. Both the touch position and /// caret bounds are in logical window coordinates, after all view transforms. /// Call on the UI thread, only from the focused selection owner. /// void Show(Point position, Rect caret); /// /// Ends the gesture and releases native state. Safe to call repeatedly. /// Call on release, cancellation, loss of capture/focus, or removal of the owner. /// void Hide(); } } namespace Xui.Core.Animation { /// /// Represents a 1D motion curve with constant deceleration (e.g., for scroll or fling). /// Starts at a given position and velocity, then decelerates linearly to a stop. /// /// /// This model is commonly used in UI frameworks to simulate natural-feeling scroll behavior. /// The acceleration is constant and opposite to the direction of motion, resulting in /// a predictable, smooth slowdown. /// public readonly struct ConstantDecelerationCurve { /// /// The time when the motion begins. /// public readonly TimeSpan StartTime; /// /// The time when the motion stops (velocity reaches zero). /// public readonly TimeSpan EndTime; /// /// The constant acceleration applied during motion, typically negative. /// public readonly nfloat A; /// /// The initial velocity at , in pixels per second. /// public readonly nfloat V0; /// /// The initial position at , in pixels. /// public readonly nfloat P0; /// /// Constructs a motion curve with constant deceleration. /// /// The time when motion begins. /// The initial position at . /// The initial velocity in pixels per second. /// The magnitude of deceleration (must be positive). /// Thrown if is not positive. public ConstantDecelerationCurve(TimeSpan startTime, nfloat position, nfloat velocity, nfloat accelerationMagnitude); /// /// The total duration of the motion in seconds. /// public nfloat DurationSeconds { get; } /// /// Evaluates the position at the specified time. /// /// The absolute time at which to evaluate the position. /// The position in pixels. public nfloat this[TimeSpan time] {[DebuggerStepThrough] get; } /// /// Evaluates the velocity at the specified time. /// /// The absolute time at which to evaluate the velocity. /// The velocity in pixels per second. public nfloat VelocityAt(TimeSpan time); } /// /// Represents a 1D cubic motion curve over time, interpolating both position and velocity. /// Time is expressed using , and calculations are performed in seconds. /// /// /// This curve is defined by a cubic polynomial: /// f(t) = A·t³ + B·t² + C·t + D, where t is time in seconds since the global epoch. /// It supports generation from boundary conditions (position and velocity at both ends), /// as well as curve continuation with seamless velocity transitions. /// public readonly struct CubicMotionCurve { /// /// The time at which the motion curve starts. /// public readonly TimeSpan StartTime; /// /// The time at which the motion curve ends. /// public readonly TimeSpan EndTime; /// /// The cubic coefficient (multiplied by t³). /// public readonly nfloat A; /// /// The quadratic coefficient (multiplied by t²). /// public readonly nfloat B; /// /// The linear coefficient (multiplied by t). /// public readonly nfloat C; /// /// The constant offset term. /// public readonly nfloat D; /// /// Initializes a new cubic motion curve with the given polynomial coefficients and time range. /// public CubicMotionCurve(TimeSpan startTime, TimeSpan endTime, nfloat a, nfloat b, nfloat c, nfloat d); /// /// The final position at . /// public nfloat FinalPosition { get; } /// /// The duration of the motion curve, in seconds. /// public nfloat DurationSeconds { get; } /// /// Continues the current curve by constructing a new cubic motion curve that /// begins where this one leaves off, matching position and velocity, and /// interpolating to a new position and velocity over the given time range. /// public CubicMotionCurve ContinueWithBoundaryConditions(TimeSpan startTime, TimeSpan endTime, nfloat endPosition, nfloat endVelocity); /// /// Constructs a cubic motion curve that interpolates position and velocity /// between two points in time using Hermite interpolation. /// /// The curve's start time. /// The position at . /// The velocity at . /// The curve's end time. /// The position at . /// The velocity at . /// A cubic motion curve satisfying the specified boundary conditions. public static CubicMotionCurve FromBoundaryConditions(TimeSpan startTime, nfloat startPosition, nfloat startVelocity, TimeSpan endTime, nfloat endPosition, nfloat endVelocity); /// /// Evaluates the position at the specified time. /// /// An absolute time value. /// The position at the given time. public nfloat this[TimeSpan time] {[DebuggerStepThrough] get; } /// /// Evaluates the velocity at the specified time. /// /// An absolute time value. /// The velocity at the given time. public nfloat VelocityAt(TimeSpan time); } /// /// Provides a collection of easing functions and smoothing utilities used in animations. /// All easing methods are normalized to take a parameter t in the range [0, 1]. /// public static partial class Easing { /// /// Represents a 3rd- or 4th-degree polynomial easing function for animation timing curves. /// /// /// This type can be used to approximate Bézier-based easing curves (like ) /// using polynomial coefficients, which are faster to evaluate and easier to store or serialize. /// public readonly struct PolynomialEasing { /// The coefficient for x⁴ (A = 0 for cubic curves). public readonly nfloat A; /// The coefficient for x³. public readonly nfloat B; /// The coefficient for x². public readonly nfloat C; /// The coefficient for x¹. public readonly nfloat D; /// The constant term. public readonly nfloat E; /// /// Constructs a 3rd-degree polynomial: y = B·x³ + C·x² + D·x + E /// public PolynomialEasing(nfloat b, nfloat c, nfloat d, nfloat e); /// /// Constructs a 4th-degree polynomial: y = A·x⁴ + B·x³ + C·x² + D·x + E /// public PolynomialEasing(nfloat a, nfloat b, nfloat c, nfloat d, nfloat e); /// /// Approximates a easing curve using a cubic polynomial. /// The result fits y = B·x³ + C·x² + D·x + E over the domain x ∈ [0, 1]. /// /// The Bézier curve to approximate. /// Number of sample points to use in least-squares fitting. Default is 16. public PolynomialEasing(CubicBezier bezier, int samples = 16); /// /// Evaluates the polynomial at a given value of x ∈ [0, 1]. /// /// The input value (typically time). /// The eased value at x. public nfloat this[nfloat x] {[DebuggerStepThrough] get; } } } /// /// Provides a collection of easing functions and smoothing utilities used in animations. /// All easing methods are normalized to take a parameter t in the range [0, 1]. /// public static partial class Easing { /// /// Normalizes a value between and into a [0,1] range. /// Returns 0 if ≤ . /// public static nfloat Normalize(nfloat value, nfloat min, nfloat max); /// /// Eases in and out with a sine curve. Smoothest at beginning and end. /// public static nfloat EaseInOutSine(nfloat t); /// /// Accelerates slowly from 0 to 1 with a quadratic curve. /// public static nfloat EaseInQuad(nfloat t); /// /// Decelerates smoothly from 1 to 0 with a quadratic curve. /// public static nfloat EaseOutQuad(nfloat t); /// /// Accelerates and decelerates using a quadratic curve. /// public static nfloat EaseInOutQuad(nfloat t); /// /// Accelerates slowly with a cubic curve. /// public static nfloat EaseInCubic(nfloat t); /// /// Decelerates slowly with a cubic curve. /// public static nfloat EaseOutCubic(nfloat t); /// /// Smoothly accelerates and decelerates with a cubic curve. /// public static nfloat EaseInOutCubic(nfloat t); /// /// Stronger acceleration from 0 using a quartic curve. /// public static nfloat EaseInQuart(nfloat t); /// /// Stronger deceleration to 1 using a quartic curve. /// public static nfloat EaseOutQuart(nfloat t); /// /// Strong acceleration and deceleration using a quartic curve. /// public static nfloat EaseInOutQuart(nfloat t); /// /// Creates an elastic "bounce-in" effect at the beginning of the transition. /// public static nfloat EaseInElastic(nfloat t); /// /// Creates an elastic "bounce-out" effect at the end of the transition. /// public static nfloat EaseOutElastic(nfloat t); /// /// Combines EaseInElastic and EaseOutElastic for a spring-like bounce effect at both ends. /// public static nfloat EaseInOutElastic(nfloat t); /// /// Eases in with a "backwards" overshoot effect before settling forward. /// public static nfloat EaseInBack(nfloat t); /// /// Eases out with a slight overshoot after reaching the target. /// public static nfloat EaseOutBack(nfloat t); /// /// Eases in and out with a "backwards" overshoot at both ends. /// public static nfloat EaseInOutBack(nfloat t); /// /// Creates a bounce effect as if hitting the ground and bouncing back. /// public static nfloat EaseOutBounce(nfloat t); /// /// Reverses EaseOutBounce to ease in with bounce. /// public static nfloat EaseInBounce(nfloat t); /// /// Eases in and out with a bounce at both ends. /// public static nfloat EaseInOutBounce(nfloat t); /// /// Applies a smoothstep-like easing function that produces smooth transitions with zero first and second derivatives at boundaries. /// public static nfloat SmootherStep(nfloat t); /// /// Smoothly interpolates between two values using a critically damped spring-like function. /// /// The starting value. /// The target value. /// Reference to current velocity (will be modified). /// Time it takes to reach the target value. /// Maximum speed during interpolation. /// Elapsed time since the last update. public static nfloat SmoothDamp(nfloat from, nfloat to, ref nfloat velocity, nfloat smoothTime, nfloat maxSpeed, nfloat deltaTime); } /// Bounded rubber-band displacement for dragging beyond a scrollable range. public static class ElasticMotion { /// Maps an unconstrained position to a progressively resisted position outside the bounds. public static nfloat Resist(nfloat position, nfloat min, nfloat max, nfloat viewport); /// Maps a position with a platform-specific resistance factor (smaller values feel firmer). public static nfloat Resist(nfloat position, nfloat min, nfloat max, nfloat viewport, nfloat resistance); /// Recovers the drag position so a new delta or a grabbed rebound does not jump. public static nfloat Unresist(nfloat position, nfloat min, nfloat max, nfloat viewport); /// Inverts resistance using the same factor as the drag that produced the position. public static nfloat Unresist(nfloat position, nfloat min, nfloat max, nfloat viewport, nfloat resistance); } /// /// Represents a motion curve where velocity decays exponentially over time. /// Commonly used to simulate fling or momentum-based motion with smooth slowdown. /// public readonly struct ExponentialDecayCurve { /// /// The time at which the motion begins. /// public readonly TimeSpan StartTime; /// /// The time at which the motion ends, determined by when velocity falls below a defined threshold. /// public readonly TimeSpan EndTime; /// /// The decay factor per second. Lower values result in faster deceleration. /// public readonly nfloat DecayPerSecond; /// /// The initial velocity at the start of the curve. /// public readonly nfloat InitialVelocity; /// /// The starting position of the motion. /// public readonly nfloat StartPosition; /// /// A typical decay factor (~0.998 per millisecond). Use for normal fling decay. /// public static readonly nfloat Normal; /// /// A faster decay factor (~0.99 per millisecond). Use for snappier motion. /// public static readonly nfloat Fast; /// /// Initializes an exponential decay motion curve. /// /// The time when motion begins. /// The initial position. /// The initial velocity (can be negative). /// /// The decay multiplier per second. A value less than 1, closer to 0 = faster decay. /// Recommended value is . /// /// /// The velocity below which motion is considered stopped (defaults to 0.5). /// [DebuggerStepThrough] public ExponentialDecayCurve(TimeSpan startTime, nfloat startPosition, nfloat initialVelocity, nfloat decayPerSecond, double velocityThreshold = 0.5); /// /// Gets the final position of the motion at . /// public nfloat FinalPosition { get; } /// /// Evaluates the position of the motion at a given time. /// /// The time to evaluate. /// The interpolated position at the specified time. public nfloat this[TimeSpan time] {[DebuggerStepThrough] get; } /// /// Evaluates the velocity of the motion at a given time. /// /// The time to evaluate. /// The current velocity at the specified time. public nfloat VelocityAt(TimeSpan time); } /// /// Represents a 1D motion curve under constant acceleration, defined as a quadratic function of time. /// /// This curve is useful for modeling motion that decelerates smoothly to a stop, /// such as fling or scroll-stop animations. /// public readonly struct QuadraticMotionCurve { /// /// The time at which the motion starts. /// public readonly TimeSpan StartTime; /// /// The time at which the motion ends (i.e., when velocity reaches zero). /// public readonly TimeSpan EndTime; /// /// The quadratic coefficient (0.5 * acceleration). /// public readonly nfloat A; /// /// The linear coefficient (initial velocity minus adjustment). /// public readonly nfloat B; /// /// The constant coefficient (initial position minus offset). /// public readonly nfloat C; /// /// Initializes the curve with explicit polynomial coefficients and time range. /// /// The time when motion starts. /// The time when motion ends. /// The quadratic coefficient. /// The linear coefficient. /// The constant offset. [DebuggerStepThrough] public QuadraticMotionCurve(TimeSpan startTime, TimeSpan endTime, nfloat a, nfloat b, nfloat c); /// /// Constructs a curve from initial position, velocity, and acceleration magnitude. /// The acceleration is applied in the opposite direction of velocity to decelerate to zero. /// /// The time when motion starts. /// Initial position. /// Initial velocity (positive or negative). /// Positive scalar magnitude of deceleration. public QuadraticMotionCurve(TimeSpan startTime, nfloat startPosition, nfloat startVelocity, nfloat accelerationMagnitude); /// /// Gets the final position of the motion at . /// public nfloat FinalPosition { get; } /// /// Evaluates the position of the motion at the specified . /// /// The time at which to evaluate the position. public nfloat this[TimeSpan time] {[DebuggerStepThrough] get; } /// /// Evaluates the instantaneous velocity at the specified . /// /// The time at which to evaluate the velocity. /// The velocity in units per second. public nfloat VelocityAt(TimeSpan time); } /// A critically damped spring evaluated analytically, independent of display refresh rate. public readonly struct SpringMotionCurve { /// The time at which the rebound starts. public TimeSpan StartTime { get; } /// The exact resting position. public nfloat Target { get; } /// Creates a spring preserving initial position and velocity. public SpringMotionCurve(TimeSpan startTime, nfloat position, nfloat velocity, nfloat target); /// Evaluates the position at an absolute frame time. public nfloat this[TimeSpan time] { get; } /// Evaluates the velocity in units per second. public nfloat VelocityAt(TimeSpan time); /// Whether the curve is close enough to finish at its exact target. public bool IsComplete(TimeSpan time); } } namespace Xui.Core.Animation { using Xui.Core.Math2D; /// /// Provides a collection of easing functions and smoothing utilities used in animations. /// All easing methods are normalized to take a parameter t in the range [0, 1]. /// public static partial class Easing { /// /// Represents a CSS-style cubic Bézier easing curve constrained between (0,0) and (1,1). /// /// /// These curves are used for timing animations and transitions. /// The curve always starts at (0,0) and ends at (1,1), and the control points and /// shape the acceleration and deceleration of the animation. /// public readonly struct CubicBezier { /// The first control point (typically near the origin). public readonly Point P1; /// The second control point (typically near the destination). public readonly Point P2; /// /// Initializes a new CSS-style cubic Bézier easing curve with the given control points. /// Assumes endpoints at (0,0) and (1,1). /// public CubicBezier(Point p1, Point p2); /// /// Returns the interpolated point on the Bézier curve at a given ∈ [0, 1]. /// public Point Lerp(nfloat t); /// /// Approximates the Y output value for a given input X ∈ [0,1] using a 16-step lookup table. /// public nfloat Evaluate(nfloat x); /// /// Approximates the Y output value for a given input X ∈ [0,1] using binary search to the given precision. /// public nfloat Evaluate(nfloat x, nfloat precision); /// /// Indexer alias for . /// public nfloat this[nfloat x] { get; } /// /// Finds the parameter t ∈ [0, 1] where the curve is closest to the given point. /// Uses 16-step approximation. /// public nfloat ClosestT(Point target); /// /// Returns a new cubic Bézier easing curve with a deformation applied near the closest point to , /// shifted by . /// public CubicBezier Drag(Point origin, Vector delta); /// /// Returns a new cubic Bézier easing curve with a deformation applied at the given parameter by . /// public CubicBezier DragAt(nfloat t, Vector delta); /// /// Converts a full into a CSS-style easing curve. /// The curve must begin at (0,0) and end at (1,1). /// public static implicit operator CubicBezier(Curves2D.CubicBezier bezier); /// Equivalent to CSS `ease`: cubic-bezier(0.25, 0.1, 0.25, 1.0) public static CubicBezier Ease { get; } /// Equivalent to CSS `ease-in`: cubic-bezier(0.42, 0, 1.0, 1.0) public static CubicBezier EaseIn { get; } /// Equivalent to CSS `ease-out`: cubic-bezier(0, 0, 0.58, 1.0) public static CubicBezier EaseOut { get; } /// Equivalent to CSS `ease-in-out`: cubic-bezier(0.42, 0, 0.58, 1.0) public static CubicBezier EaseInOut { get; } } } } namespace Xui.Core.Canvas { /// /// Parses the portable URI form used for application-packaged image assets. /// asset://icons/logo.png identifies the logical asset /// icons/logo.png; each runtime resolves it from its application package. /// public static class AssetUri { /// /// Gets an asset's logical relative path. Returns when /// is not a valid asset:// URI. /// public static bool TryGetRelativePath(string uri, out string relativePath); } /// /// Provides web standard named color constants in 32-bit RGBA format (0xRRGGBBAA). /// These match the named colors from the CSS color specification: /// https://developer.mozilla.org/en-US/docs/Web/CSS/named-color /// public static class Colors { public const uint Transparent = 0x00000000; public const uint Black = 0x000000FF; public const uint White = 0xFFFFFFFF; public const uint Red = 0xFF0000FF; public const uint Lime = 0x00FF00FF; public const uint Blue = 0x0000FFFF; public const uint Yellow = 0xFFFF00FF; public const uint Fuchsia = 0xFF00FFFF; public const uint Aqua = 0x00FFFFFF; public const uint Silver = 0xC0C0C0FF; public const uint Gray = 0x808080FF; public const uint Maroon = 0x800000FF; public const uint Purple = 0x800080FF; public const uint Green = 0x008000FF; public const uint Olive = 0x808000FF; public const uint Navy = 0x000080FF; public const uint Teal = 0x008080FF; public const uint AliceBlue = 0xf0f8ffFF; public const uint AntiqueWhite = 0xfaebd7FF; public const uint Aquamarine = 0x7fffd4FF; public const uint Azure = 0xf0ffffFF; public const uint Beige = 0xf5f5dcFF; public const uint Bisque = 0xffe4c4FF; public const uint BlanchedAlmond = 0xffebcdFF; public const uint BlueViolet = 0x8a2be2FF; public const uint Brown = 0xa52a2aFF; public const uint BurlyWood = 0xdeb887FF; public const uint CadetBlue = 0x5f9ea0FF; public const uint ChartReuse = 0x7fff00FF; public const uint Chocolate = 0xd2691eFF; public const uint Coral = 0xff7f50FF; public const uint CornflowerBlue = 0x6495edFF; public const uint CornSilk = 0xfff8dcFF; public const uint Crimson = 0xdc143cFF; public const uint Cyan = 0x00ffffFF; public const uint DarkBlue = 0x00008bFF; public const uint DarkCyan = 0x008b8bFF; public const uint DarkGoldenRod = 0xb8860bFF; public const uint DarkGray = 0xa9a9a9FF; public const uint DarkGreen = 0x006400FF; public const uint DarkGrey = 0xa9a9a9FF; public const uint DarkKhaki = 0xbdb76bFF; public const uint DarkMagenta = 0x8b008bFF; public const uint DarkOliveGreen = 0x556b2fFF; public const uint DarkOrange = 0xff8c00FF; public const uint DarkOrchid = 0x9932ccFF; public const uint DarkRed = 0x8b0000FF; public const uint DarkSalmon = 0xe9967aFF; public const uint DarkSeaGreen = 0x8fbc8fFF; public const uint DarkSlateBlue = 0x483d8bFF; public const uint DarkSlateGray = 0x2f4f4fFF; public const uint DarkSlateGrey = 0x2f4f4fFF; public const uint DarkTurquoise = 0x00ced1FF; public const uint DarkViolet = 0x9400d3FF; public const uint DeepPink = 0xff1493FF; public const uint DeepSkyBlue = 0x00bfffFF; public const uint DimGray = 0x696969FF; public const uint DimGrey = 0x696969FF; public const uint DodgerBlue = 0x1e90ffFF; public const uint FireBrick = 0xb22222FF; public const uint FloralWhite = 0xfffaf0FF; public const uint ForestGreen = 0x228b22FF; public const uint Gainsboro = 0xdcdcdcFF; public const uint GhostWhite = 0xf8f8ffFF; public const uint Gold = 0xffd700FF; public const uint GoldenRod = 0xdaa520FF; public const uint GreenYellow = 0xadff2fFF; public const uint Grey = 0x808080FF; public const uint Honeydew = 0xf0fff0FF; public const uint HotPink = 0xff69b4FF; public const uint IndianRed = 0xcd5c5cFF; public const uint Indigo = 0x4b0082FF; public const uint Ivory = 0xfffff0FF; public const uint Khaki = 0xf0e68cFF; public const uint Lavender = 0xe6e6faFF; public const uint LavenderBlush = 0xfff0f5FF; public const uint LawnGreen = 0x7cfc00FF; public const uint LemonChiffon = 0xfffacdFF; public const uint LightBlue = 0xadd8e6FF; public const uint LightCoral = 0xf08080FF; public const uint LightCyan = 0xe0ffffFF; public const uint LightGoldenRodYellow = 0xfafad2FF; public const uint LightGray = 0xd3d3d3FF; public const uint LightGreen = 0x90ee90FF; public const uint LightGrey = 0xd3d3d3FF; public const uint LightPink = 0xffb6c1FF; public const uint LightSalmon = 0xffa07aFF; public const uint LightSeaGreen = 0x20b2aaFF; public const uint LightSkyBlue = 0x87cefaFF; public const uint LightSlateGray = 0x778899FF; public const uint LightSlateGrey = 0x778899FF; public const uint LightSteelBlue = 0xb0c4deFF; public const uint LightYellow = 0xffffe0FF; public const uint LimeGreen = 0x32cd32FF; public const uint Linen = 0xfaf0e6FF; public const uint Magenta = 0xff00ffFF; public const uint MediumAquamarine = 0x66cdaaFF; public const uint MediumBlue = 0x0000cdFF; public const uint MediumOrchid = 0xba55d3FF; public const uint MediumPurple = 0x9370dbFF; public const uint MediumSeaGreen = 0x3cb371FF; public const uint MediumSlateBlue = 0x7b68eeFF; public const uint MediumSpringGreen = 0x00fa9aFF; public const uint MediumTurquoise = 0x48d1ccFF; public const uint MediumVioletRed = 0xc71585FF; public const uint MidnightBlue = 0x191970FF; public const uint MintCream = 0xf5fffaFF; public const uint MistyRose = 0xffe4e1FF; public const uint Moccasin = 0xffe4b5FF; public const uint NavajoWhite = 0xffdeadFF; public const uint OldLace = 0xfdf5e6FF; public const uint OliveDrab = 0x6b8e23FF; public const uint Orange = 0xffa500FF; public const uint OrangeRed = 0xff4500FF; public const uint Orchid = 0xda70d6FF; public const uint PaleGoldenRod = 0xeee8aaFF; public const uint PaleGreen = 0x98fb98FF; public const uint PaleTurquoise = 0xafeeeeFF; public const uint PaleVioletRed = 0xdb7093FF; public const uint PapayaWhip = 0xffefd5FF; public const uint PeachPuff = 0xffdab9FF; public const uint Peru = 0xcd853fFF; public const uint Pink = 0xffc0cbFF; public const uint Plum = 0xdda0ddFF; public const uint PowderBlue = 0xb0e0e6FF; public const uint RebeccaPurple = 0x663399FF; public const uint RosyBrown = 0xbc8f8fFF; public const uint RoyalBlue = 0x4169e1FF; public const uint SaddleBrown = 0x8b4513FF; public const uint Salmon = 0xfa8072FF; public const uint SandyBrown = 0xf4a460FF; public const uint SeaGreen = 0x2e8b57FF; public const uint Seashell = 0xfff5eeFF; public const uint Sienna = 0xa0522dFF; public const uint SkyBlue = 0x87ceebFF; public const uint SlateBlue = 0x6a5acdFF; public const uint SlateGray = 0x708090FF; public const uint SlateGrey = 0x708090FF; public const uint Snow = 0xfffafaFF; public const uint SpringGreen = 0x00ff7fFF; public const uint SteelBlue = 0x4682b4FF; public const uint Tan = 0xd2b48cFF; public const uint Thistle = 0xd8bfd8FF; public const uint Tomato = 0xff6347FF; public const uint Turquoise = 0x40e0d0FF; public const uint Violet = 0xee82eeFF; public const uint Wheat = 0xf5deb3FF; public const uint WhiteSmoke = 0xf5f5f5FF; public const uint YellowGreen = 0x9acd32FF; } /// /// Represents the radius of each corner of a rectangle, allowing for uniform or non-uniform rounding. /// public struct CornerRadius { /// /// A where all corners have a radius of zero. /// public static readonly CornerRadius Zero; /// /// Radius of the top-left corner. /// public nfloat TopLeft; /// /// Radius of the top-right corner. /// public nfloat TopRight; /// /// Radius of the bottom-right corner. /// public nfloat BottomRight; /// /// Radius of the bottom-left corner. /// public nfloat BottomLeft; /// /// Returns true if all corners have the same radius value. /// public bool IsUniform { get; } /// /// Returns true if all corner radii are zero. /// public readonly bool IsZero { get; } /// /// Initializes a with the same radius applied to all four corners. /// /// The uniform radius for all corners. [DebuggerStepThrough] public CornerRadius(nfloat radius); /// /// Initializes a with individual values for each corner. /// /// Radius of the top-left corner. /// Radius of the top-right corner. /// Radius of the bottom-right corner. /// Radius of the bottom-left corner. [DebuggerStepThrough] public CornerRadius(nfloat topLeft, nfloat topRight, nfloat bottomRight, nfloat bottomLeft); /// /// Implicitly converts a single radius value to a uniform . /// /// The uniform corner radius. public static implicit operator CornerRadius(nfloat radius); /// /// Implicitly converts a single integer radius value to a uniform . /// /// The uniform corner radius. public static implicit operator CornerRadius(int radius); /// /// Implicitly converts a 4-tuple of radius values to a . /// /// Tuple representing (TopLeft, TopRight, BottomRight, BottomLeft). public static implicit operator CornerRadius(Tuple radii); /// /// Adds two values component-wise. /// /// The first . /// The second . /// A new where each corner is the sum of the corresponding corners. [DebuggerStepThrough] public static CornerRadius operator +(CornerRadius lhs, CornerRadius rhs); /// /// Subtracts one from another component-wise. /// /// The first . /// The second to subtract. /// A new where each corner is the difference of the corresponding corners. [DebuggerStepThrough] public static CornerRadius operator -(CornerRadius lhs, CornerRadius rhs); /// /// Returns a where each corner is the minimum of the corresponding corners of the two inputs. /// /// First . /// Second . /// A new taking the minimum value at each corner. [DebuggerStepThrough] public static CornerRadius Min(CornerRadius a, CornerRadius b); /// /// Returns a where each corner is the maximum of the corresponding corners of the two inputs. /// /// First . /// Second . /// A new taking the maximum value at each corner. [DebuggerStepThrough] public static CornerRadius Max(CornerRadius a, CornerRadius b); /// /// Implicitly converts a tuple (horizontal, vertical) into a , /// where TopLeft and BottomRight use horizontal, and TopRight and BottomLeft use vertical radius. /// /// Tuple of two radii (horizontal, vertical). [DebuggerStepThrough] public static implicit operator CornerRadius((nfloat horizontal, nfloat vertical) radii); /// /// Implicitly converts a tuple (topLeft, topRight, bottomRight, bottomLeft) into a . /// /// Tuple of four radii representing each corner individually. [DebuggerStepThrough] public static implicit operator CornerRadius((nfloat topLeft, nfloat topRight, nfloat bottomRight, nfloat bottomLeft) radii); } /// /// Specifies the algorithm used to determine the "insideness" of a point in a path, /// controlling how filled shapes are rendered. /// public enum FillRule { /// /// Uses the non-zero winding rule. A point is inside the path if the sum of /// path segment windings around it is non-zero. This is the default rule. /// NonZero, /// /// Uses the even-odd rule. A point is inside the path if a ray drawn from it /// to infinity crosses the path segments an odd number of times. /// EvenOdd } /// /// Immutable description of one font face used for canvas text measurement and rendering. /// /// /// Xui currently selects one named family. Font fallback and per-run font selection are not /// supported by this value and must bypass font-metric caches when introduced in the future. /// public partial struct Font { public static readonly FontWeight Thin; public static readonly FontWeight ExtraLight; public static readonly FontWeight Light; public static readonly FontWeight Medium; public static readonly FontWeight SemiBold; public static readonly FontWeight Bold; public static readonly FontWeight ExtraBold; public static readonly FontWeight Black; public static readonly FontStretch UltraCondensed; public static readonly FontStretch ExtraCondensed; public static readonly FontStretch Condensed; public static readonly FontStretch SemiCondensed; public static readonly FontStretch SemiExpanded; public static readonly FontStretch Expanded; public static readonly FontStretch ExtraExpanded; public static readonly FontStretch UltraExpanded; public static readonly FontStyle Italic; public static readonly FontStyle Oblique; } /// /// Immutable description of one font face used for canvas text measurement and rendering. /// /// /// Xui currently selects one named family. Font fallback and per-run font selection are not /// supported by this value and must bypass font-metric caches when introduced in the future. /// public partial struct Font { /// /// Implicitly creates a from a font size. /// Uses normal weight, normal style, normal stretch, and line height = 1.2× size. /// /// The font size in user-space units (e.g., pixels). public static implicit operator Font(float size); /// /// Implicitly creates a from a font size and weight. /// Uses normal style, normal stretch, and line height = 1.2× size. /// /// The font size and font weight. public static implicit operator Font((float size, FontWeight weight) tuple); /// /// Implicitly creates a from a font size and style. /// Uses normal weight, normal stretch, and line height = 1.2× size. /// /// The font size and font style. public static implicit operator Font((float size, FontStyle style) tuple); /// /// Implicitly creates a from size, weight, and style. /// Uses normal stretch and line height = 1.2× size. /// /// The font size, weight, and style. public static implicit operator Font((float size, FontWeight weight, FontStyle style) tuple); /// /// Implicitly creates a from size, weight, and stretch. /// Uses normal style and line height = 1.2× size. /// /// The font size, weight, and stretch percentage. public static implicit operator Font((float size, FontWeight weight, FontStretch stretch) tuple); /// /// Implicitly creates a from size, style, and stretch. /// Uses normal weight and line height = 1.2× size. /// /// The font size, style, and stretch percentage. public static implicit operator Font((float size, FontStyle style, FontStretch stretch) tuple); /// /// Implicitly creates a from size, weight, style, and stretch. /// Uses line height = 1.2× size. /// /// The font size, weight, style, and stretch percentage. public static implicit operator Font((float size, FontWeight weight, FontStyle style, FontStretch stretch) tuple); /// /// Creates a from size and line height. /// public static implicit operator Font((float size, float lineHeight) tuple); /// /// Creates a from size, weight, and line height. /// public static implicit operator Font((float size, FontWeight weight, float lineHeight) tuple); /// /// Creates a from size, style, and line height. /// public static implicit operator Font((float size, FontStyle style, float lineHeight) tuple); /// /// Creates a from size, weight, style, and line height. /// public static implicit operator Font((float size, FontWeight weight, FontStyle style, float lineHeight) tuple); /// /// Creates a from size, weight, stretch, and line height. /// public static implicit operator Font((float size, FontWeight weight, FontStretch stretch, float lineHeight) tuple); /// /// Creates a from size, style, stretch, and line height. /// public static implicit operator Font((float size, FontStyle style, FontStretch stretch, float lineHeight) tuple); /// /// Creates a from size, weight, style, stretch, and line height. /// public static implicit operator Font((float size, FontWeight weight, FontStyle style, FontStretch stretch, float lineHeight) tuple); } /// /// Immutable description of one font face used for canvas text measurement and rendering. /// /// /// Xui currently selects one named family. Font fallback and per-run font selection are not /// supported by this value and must bypass font-metric caches when introduced in the future. /// public readonly partial struct Font : IEquatable { /// Initializes the default Inter text font. public Font(); /// Initializes a font face. public Font(nfloat fontSize, string fontFamily, FontWeight? fontWeight = null, FontStyle? fontStyle = null, FontStretch? fontStretch = null, nfloat? lineHeight = null); /// The one selected font family name. public string FontFamily { get; init; } /// The font size in user-space units. public nfloat FontSize { get; init; } /// The font style. public FontStyle FontStyle { get; init; } /// The numeric font weight. public FontWeight FontWeight { get; init; } /// The font stretch. public FontStretch FontStretch { get; init; } /// The requested line height. Layout will own line-spacing semantics. public nfloat LineHeight { get; init; } /// Indicates whether the current object is equal to another object of the same type. /// An object to compare with this object. /// /// if the current object is equal to the parameter; otherwise, . public bool Equals(Font other); /// Indicates whether this instance and a specified object are equal. /// The object to compare with the current instance. /// /// if and this instance are the same type and represent the same value; otherwise, . public override bool Equals(object? obj); /// Returns the hash code for this instance. /// A 32-bit signed integer that is the hash code for this instance. public override int GetHashCode(); /// Returns whether two font descriptions are equal. public static bool operator ==(Font left, Font right); /// Returns whether two font descriptions differ. public static bool operator !=(Font left, Font right); } /// /// Fixed-capacity, allocation-free-after-construction LRU cache keyed by . /// /// The cached value associated with a resolved font. public class FontCache { /// The standard number of font entries retained by a context cache. public const int DefaultCapacity = 64; /// Initializes a cache with the requested number of entries. public FontCache(int capacity = DefaultCapacity); /// Gets the number of retained font entries. public int EntryCapacity { get; } /// Gets the cached value for when available. public bool TryGet(in Font font, out T value); /// Adds or refreshes the value for . public void Set(in Font font, T value); /// Clears every retained entry. public void Clear(); /// Releases a value when its entry is replaced, evicted, or cleared. protected virtual void OnEvicted(T value); } /// /// Represents font-defined metrics used for vertical alignment and em box sizing. /// These values are constant for a given font and size. /// public readonly struct FontMetrics { /// /// Maximum ascent defined by the font (not necessarily used glyphs). /// public readonly nfloat FontBoundingBoxAscent; /// /// Maximum descent defined by the font. /// public readonly nfloat FontBoundingBoxDescent; /// /// Height from baseline to top of the em square. /// Recommended for app layout. /// public readonly nfloat EmHeightAscent; /// /// Height from baseline to bottom of the em square. /// Recommended for app layout. /// public readonly nfloat EmHeightDescent; /// /// Position of the alphabetic baseline (typically 0, used for alignment). /// public readonly nfloat AlphabeticBaseline; /// /// Vertical position of the hanging baseline (used in scripts like Devanagari), /// relative to the alphabetic baseline. Negative values are above it. /// public readonly nfloat HangingBaseline; /// /// Vertical position of the ideographic baseline (used in CJK layout), /// relative to the alphabetic baseline. Positive values are below it. /// public readonly nfloat IdeographicBaseline; /// /// Total height of the font bounding box. /// public nfloat Height { get; } /// /// Initializes a new instance. /// /// Maximum vertical extent above the baseline from the font’s bounding box. /// Maximum vertical extent below the baseline from the font’s bounding box. /// Ascent to the top of the em square. /// Descent to the bottom of the em square. /// Position of the alphabetic baseline (typically 0). /// Position of the hanging baseline for scripts that use it. /// Position of the ideographic baseline for CJK layout. public FontMetrics(nfloat fontAscent, nfloat fontDescent, nfloat emAscent, nfloat emDescent, nfloat alphabeticBaseline, nfloat hangingBaseline, nfloat ideographicBaseline); } /// /// Fixed-capacity, allocation-free-after-construction LRU cache of font-wide metrics. /// One instance belongs to a drawing or measurement context because native font resolution is /// surface-specific. /// public sealed class FontMetricsCache : FontCache { /// Maximum number of distinct font descriptions retained by this cache. public const int Capacity = DefaultCapacity; /// Initializes the standard 64-entry metrics cache. public FontMetricsCache(); } /// /// Represents the stretch or width percentage of a font, relative to its normal width (100%). /// /// /// Values less than 100 represent condensed fonts; values greater than 100 are expanded. /// Font stretch supports comparison operators for ordering and matching. /// public readonly struct FontStretch : IComparable, IEquatable { /// /// The numeric percentage value of the font stretch. /// public readonly nfloat Value; /// /// Initializes a new with the specified numeric value. /// /// The numeric width percentage (e.g., 100 = normal). public FontStretch(nfloat value); /// Implicitly converts a to . public static implicit operator nfloat(FontStretch stretch); /// Implicitly converts a to . public static implicit operator FontStretch(nfloat value); /// Implicitly converts a to . public static implicit operator FontStretch(float value); /// Implicitly converts an to . public static implicit operator FontStretch(int value); /// Returns true if two stretch values are equal. public static bool operator ==(FontStretch a, FontStretch b); /// Returns true if two stretch values are not equal. public static bool operator !=(FontStretch a, FontStretch b); /// Returns true if the left stretch is less than the right. public static bool operator <(FontStretch a, FontStretch b); /// Returns true if the left stretch is less than or equal to the right. public static bool operator <=(FontStretch a, FontStretch b); /// Returns true if the left stretch is greater than the right. public static bool operator>(FontStretch a, FontStretch b); /// Returns true if the left stretch is greater than or equal to the right. public static bool operator >=(FontStretch a, FontStretch b); /// Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object. /// An object to compare with this instance. /// A value that indicates the relative order of the objects being compared. The return value has these meanings: /// /// Value Meaning Less than zero This instance precedes in the sort order. Zero This instance occurs in the same position in the sort order as . Greater than zero This instance follows in the sort order. public int CompareTo(FontStretch other); /// Indicates whether the current object is equal to another object of the same type. /// An object to compare with this object. /// /// if the current object is equal to the parameter; otherwise, . public bool Equals(FontStretch other); /// Indicates whether this instance and a specified object are equal. /// The object to compare with the current instance. /// /// if and this instance are the same type and represent the same value; otherwise, . public override bool Equals(object? obj); /// Returns the hash code for this instance. /// A 32-bit signed integer that is the hash code for this instance. public override int GetHashCode(); /// Font stretch 50% – Ultra Condensed. Very narrow glyph width. public static readonly FontStretch UltraCondensed; /// Font stretch 62.5% – Extra Condensed. Narrower than Condensed. public static readonly FontStretch ExtraCondensed; /// Font stretch 75% – Condensed. Common for space-constrained text. public static readonly FontStretch Condensed; /// Font stretch 87.5% – Semi Condensed. Slightly narrower than normal. public static readonly FontStretch SemiCondensed; /// Font stretch 100% – Normal. Default glyph width. public static readonly FontStretch Normal; /// Font stretch 112.5% – Semi Expanded. Slightly wider than normal. public static readonly FontStretch SemiExpanded; /// Font stretch 125% – Expanded. Wider glyph appearance. public static readonly FontStretch Expanded; /// Font stretch 150% – Extra Expanded. Significantly wider. public static readonly FontStretch ExtraExpanded; /// Font stretch 200% – Ultra Expanded. Very wide glyphs. public static readonly FontStretch UltraExpanded; } /// /// Represents a web-like font style, supporting normal, italic, and oblique variations. /// Global CSS styles like inherit, unset, and initial are not supported. /// /// Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/font-style /// public struct FontStyle { /// /// Initializes a new with explicit flags for italic or oblique styling. /// /// Whether the font is italic. /// Whether the font is oblique (slanted). /// Angle for oblique style, in degrees. [DebuggerStepThrough] public FontStyle(bool italic, bool oblique, nfloat obliqueAngle); /// /// Gets a value indicating whether the font style is italic. /// public bool IsItalic { get; } /// /// Gets a value indicating whether the font style is oblique (slanted). /// public bool IsOblique { get; } /// /// Gets the oblique slant angle, in degrees. Only meaningful if is true. /// Range is typically from -90° to 90°. /// public nfloat ObliqueAngle { get; } /// /// Normal (upright) font style. /// public static FontStyle Normal { get; } /// /// Italic font style. /// public static FontStyle Italic { get; } /// /// Oblique font style using the default slant angle (14°). /// public static FontStyle Oblique { get; } /// /// Creates a custom oblique font style with a specific slant angle. /// /// The angle of the slant, in degrees. Should be between -90 and 90. /// A representing the custom oblique angle. [DebuggerStepThrough] public static FontStyle CustomOblique(nfloat obliqueAngle); } /// /// Represents the numeric weight of a font, corresponding to CSS font weights (100–900). /// /// /// Font weights are numeric and allow comparison using operators like <, >=, etc. /// public readonly struct FontWeight : IComparable, IEquatable { /// /// The numeric value of the font weight. /// public readonly nfloat Value; /// /// Creates a new with the specified numeric value. /// /// The numeric font weight value. public FontWeight(nfloat value); /// Implicitly converts a to . public static implicit operator nfloat(FontWeight weight); /// Implicitly converts a to . public static implicit operator uint (FontWeight weight); /// Implicitly converts a to . public static implicit operator FontWeight(nfloat value); /// Implicitly converts a to . public static implicit operator FontWeight(float value); /// Implicitly converts an to . public static implicit operator FontWeight(int value); /// Returns true if two font weights are equal. public static bool operator ==(FontWeight a, FontWeight b); /// Returns true if two font weights are not equal. public static bool operator !=(FontWeight a, FontWeight b); /// Returns true if the left font weight is less than the right. public static bool operator <(FontWeight a, FontWeight b); /// Returns true if the left font weight is less than or equal to the right. public static bool operator <=(FontWeight a, FontWeight b); /// Returns true if the left font weight is greater than the right. public static bool operator>(FontWeight a, FontWeight b); /// Returns true if the left font weight is greater than or equal to the right. public static bool operator >=(FontWeight a, FontWeight b); /// Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object. /// An object to compare with this instance. /// A value that indicates the relative order of the objects being compared. The return value has these meanings: /// /// Value Meaning Less than zero This instance precedes in the sort order. Zero This instance occurs in the same position in the sort order as . Greater than zero This instance follows in the sort order. public int CompareTo(FontWeight other); /// Indicates whether the current object is equal to another object of the same type. /// An object to compare with this object. /// /// if the current object is equal to the parameter; otherwise, . public bool Equals(FontWeight other); /// Indicates whether this instance and a specified object are equal. /// The object to compare with the current instance. /// /// if and this instance are the same type and represent the same value; otherwise, . public override bool Equals(object? obj); /// Returns the hash code for this instance. /// A 32-bit signed integer that is the hash code for this instance. public override int GetHashCode(); /// Font weight 100 – Thin. The lightest possible weight. public static readonly FontWeight Thin; /// Font weight 200 – Extra Light. Slightly heavier than Thin. public static readonly FontWeight ExtraLight; /// Font weight 300 – Light. Common for minimalist design. public static readonly FontWeight Light; /// Font weight 400 – Normal. Standard weight for body text. public static readonly FontWeight Normal; /// Font weight 500 – Medium. Slightly heavier than normal. public static readonly FontWeight Medium; /// Font weight 600 – Semi Bold. Between medium and bold. public static readonly FontWeight SemiBold; /// Font weight 700 – Bold. Common for emphasis and headings. public static readonly FontWeight Bold; /// Font weight 800 – Extra Bold. Heavier than Bold. public static readonly FontWeight ExtraBold; /// Font weight 900 – Black. The heaviest available weight. public static readonly FontWeight Black; } /// /// Represents a single color stop in a gradient, defined by an offset and a color. /// Used for both linear and radial gradients. /// public struct GradientStop { /// /// The position of the stop within the gradient, typically in the range [0, 1]. /// public nfloat Offset; /// /// The color at the specified offset. /// public Color Color; /// /// Initializes a new with a specified offset and color. /// /// Position of the color stop, usually from 0 to 1. /// Color at the given offset. public GradientStop(nfloat offset, Color color); /// /// Initializes a new with a specified offset and packed RGBA color. /// /// Position of the color stop, usually from 0 to 1. /// Color in packed 0xRRGGBBAA format. public GradientStop(nfloat offset, uint color); /// /// Implicitly converts a tuple of and to a . /// /// A tuple containing offset and color. public static implicit operator GradientStop((nfloat Offset, Color Color) pair); /// /// Implicitly converts a tuple of and uint (0xRRGGBBAA) to a . /// /// A tuple containing offset and packed RGBA color. public static implicit operator GradientStop((nfloat Offset, uint Color) pair); } /// /// Represents a 2D drawing context for the Xui Canvas, modeled after the HTML5 Canvas 2D context API. /// This interface aggregates all sub-contexts responsible for different aspects of 2D rendering, /// including state, drawing primitives, text, images, transformations, and resource management. /// public interface IContext : IMeasureContext, IStateContext, ISymbolContext, ICompositionContext, IFilterContext, IPenContext, IPathDrawingContext, IRectDrawingContext, ITextDrawingContext, IImageDrawingContext, ITransformContext, IDisposable { } /// /// Defines a measurement context that provides access to platform-specific text metrics, /// supports subpixel snapping for layout precision, and enables accurate text size calculations /// using the underlying rendering engine's font rasterization and shaping systems. /// public interface IMeasureContext : ITextMeasureContext { } /// /// Defines methods for clipping using a path, /// following the HTML5 Canvas path API model. /// /// Reference: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D#paths /// public interface IPathClipping { /// /// Sets the current clipping region to the current path. /// Subsequent drawing operations are clipped to this region. /// void Clip(); } /// /// Defines methods for drawing a constructed path, /// following the HTML5 Canvas path API model. /// /// Reference: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D#paths /// public interface IPathDrawing { /// /// Fills the current path using the specified fill rule. /// /// The fill rule to use (NonZero or EvenOdd). void Fill(FillRule rule = FillRule.NonZero); /// /// Strokes the current path using the current stroke style. /// void Stroke(); } /// /// Defines properties and methods for controlling stroke and fill styles in a 2D drawing context, /// including line caps, joins, width, dashes, and brush settings for fill and stroke. /// public interface IPenContext { /// /// Sets the global alpha value for all drawing operations. /// Range: 0.0 (fully transparent) to 1.0 (fully opaque). /// nfloat GlobalAlpha { set; } /// /// Sets the style of line caps used for strokes. /// LineCap LineCap { set; } /// /// Sets the style of line joins between segments. /// LineJoin LineJoin { set; } /// /// Sets the width of stroked lines, in user space units. /// nfloat LineWidth { set; } /// /// Sets the miter limit ratio for miter joins. /// If the ratio of miter length to line width exceeds this value, a bevel join is used instead. /// nfloat MiterLimit { set; } /// /// Sets the phase offset for the start of the dash pattern. /// nfloat LineDashOffset { set; } /// /// Sets the dash pattern used for stroking lines. /// Each element in the span represents a dash or gap length, alternating. /// /// A sequence of dash and gap lengths. void SetLineDash(ReadOnlySpan segments); /// /// Sets the stroke style to a solid color. /// /// The stroke color. void SetStroke(Color color); /// /// Sets the stroke style to a linear gradient. /// /// The gradient to use for stroking paths. void SetStroke(LinearGradient linearGradient); /// /// Sets the stroke style to a radial gradient. /// /// The gradient to use for stroking paths. void SetStroke(RadialGradient radialGradient); /// /// Sets the fill style to a solid color. /// /// The fill color. void SetFill(Color color); /// /// Sets the fill style to a linear gradient. /// /// The gradient to use for filling shapes. void SetFill(LinearGradient linearGradient); /// /// Sets the fill style to a radial gradient. /// /// The gradient to use for filling shapes. void SetFill(RadialGradient radialGradient); /// /// Sets the fill style to a tiled image pattern, equivalent to /// ctx.fillStyle = ctx.createPattern(image, repetition) in the browser. /// void SetFill(ImagePattern pattern); /// /// Sets the stroke style to a tiled image pattern. /// void SetStroke(ImagePattern pattern); } /// /// Provides methods to save and restore the current drawing state, /// including styles, transforms, and clipping paths. /// Mirrors the behavior of the HTML5 Canvas save() and restore() methods. /// public interface IStateContext { /// /// Pushes the current drawing state onto the state stack. /// This includes styles, transformations, clipping paths, etc. /// void Save(); /// /// Pops the top state off the state stack and restores it. /// Any modifications made since the last are discarded. /// void Restore(); } /// /// Describes an image-based fill or stroke pattern — the Canvas API equivalent of a /// CanvasPattern returned by createPattern(image, repetition). /// /// Pass to or /// to paint paths with a tiled image. /// public ref struct ImagePattern { /// The image to tile. public IImage Image; /// How the image repeats beyond its natural bounds. public PatternRepeat Repetition; /// The source image (must be loaded before drawing). /// Tiling mode; defaults to . public ImagePattern(IImage image, PatternRepeat repetition = PatternRepeat.Repeat); } /// /// Specifies the shape used at the ends of lines when stroking paths. /// Mirrors the lineCap property in the HTML5 Canvas API. /// public enum LineCap { /// /// The line ends exactly at the endpoint with no additional extension. This is the default. /// Butt = 0, /// /// The line ends with a semicircular extension, centered on the endpoint. /// Round = 1, /// /// The line ends with a square extension equal to half the line width, extending beyond the endpoint. /// Square = 2 } /// /// Specifies how two connected lines are joined when stroking a path. /// Mirrors the lineJoin property in the HTML5 Canvas API. /// public enum LineJoin { /// /// Lines are joined with a sharp corner or extended miter, depending on the miter limit. /// Miter = 0, /// /// Lines are joined with a circular arc, creating a rounded corner. /// Round = 1, /// /// Lines are joined with a beveled corner by connecting the outer corners of the strokes. /// Bevel = 2 } /// /// Represents text layout metrics that depend on the specific string being measured. /// Includes actual bounding box and visual advance width. /// public readonly struct LineMetrics { /// /// Advance width of the string, including kerning and shaping. /// This is how far the cursor should advance after drawing the text. /// public readonly nfloat Width; /// /// Distance from the text origin to the furthest left pixel of any glyph. /// May be negative for italic or overhanging glyphs. /// public readonly nfloat ActualBoundingBoxLeft; /// /// Distance from the text origin to the furthest right pixel of any glyph. /// public readonly nfloat ActualBoundingBoxRight; /// /// Distance from the baseline to the topmost pixel of any glyph. /// public readonly nfloat ActualBoundingBoxAscent; /// /// Distance from the baseline to the bottommost pixel of any glyph. /// public readonly nfloat ActualBoundingBoxDescent; /// /// Full height of the visual bounding box (ascent + descent). /// public nfloat ActualHeight { get; } /// /// Initializes a new instance. /// /// Advance width of the rendered text. /// Furthest left pixel offset relative to the origin. /// Furthest right pixel offset relative to the origin. /// Maximum pixel height above the baseline. /// Maximum pixel depth below the baseline. public LineMetrics(nfloat width, nfloat left, nfloat right, nfloat ascent, nfloat descent); } /// /// Specifies the type of brush or fill style used for painting shapes or strokes. /// Helps distinguish between solid colors and gradient fills. /// public enum PaintStyle { /// /// A single, uniform color. /// SolidColor = 0, /// /// A linear gradient that transitions colors along a straight line. /// LinearGradient = 1, /// /// A radial gradient that transitions colors outward in a circular or elliptical shape. /// RadialGradient = 2, /// /// A repeating bitmap pattern (equivalent to createPattern(image, "repeat")). /// BitmapBrush = 3 } /// /// Controls how an image pattern tiles, following the same values as the /// repetition argument to the browser's createPattern(image, repetition). /// public enum PatternRepeat { /// Tiles in both directions. Repeat, /// Tiles horizontally only; clamped vertically. RepeatX, /// Tiles vertically only; clamped horizontally. RepeatY, /// Drawn once — no tiling in either direction. NoRepeat, } /// /// Specifies the horizontal alignment of text relative to the drawing position. /// Mirrors the textAlign property in the HTML5 Canvas 2D API. /// public enum TextAlign { /// /// Aligns text to the start of the writing direction (left for LTR, right for RTL). /// Start, /// /// Aligns text to the end of the writing direction (right for LTR, left for RTL). /// End, /// /// Aligns text to the left, regardless of writing direction. /// Left, /// /// Aligns text to the right, regardless of writing direction. /// Right, /// /// Centers the text horizontally around the drawing position. /// Center } /// /// Specifies the vertical alignment of text relative to the drawing position. /// Mirrors the textBaseline property in the HTML5 Canvas 2D API. /// public enum TextBaseline { /// /// The top of the em box is aligned with the drawing position. /// Top, /// /// The hanging baseline is aligned with the drawing position (used in some scripts like Devanagari). /// Hanging, /// /// The middle of the text (roughly half the em height) is aligned with the drawing position. /// Middle, /// /// The alphabetic baseline (default for Latin scripts) is aligned with the drawing position. /// Alphabetic, /// /// The ideographic baseline is aligned with the drawing position (used in scripts like Chinese or Japanese). /// Ideographic, /// /// The bottom of the em box is aligned with the drawing position. /// Bottom } /// /// Bounded LRU of string measurements. Text keys use object identity, so stable /// labels never need character hashing or comparison. All storage is allocated /// once; misses and eviction do not allocate cache entries. Each measurement /// context owns its cache; clear it if native font resolution changes. /// public sealed class TextMetricsCache { /// The standard maximum number of retained string measurements. public const int DefaultCapacity = 128; /// Creates a context-owned cache with fixed storage. public TextMetricsCache(int capacity = DefaultCapacity); /// Looks up the same string instance and measurement settings, updating its recency. public bool TryGet(string text, in Font font, TextAlign align, TextBaseline baseline, out TextMetrics metrics); /// Stores metrics, replacing the least recently used entry when full. public void Set(string text, in Font font, TextAlign align, TextBaseline baseline, in TextMetrics metrics); /// Clears measurements and releases all retained string and font references. public void Clear(); } /// /// Specifies the direction in which arcs or elliptical curves are drawn, /// affecting fill and stroke behavior in path-based rendering. /// public enum Winding : int { /// /// The path is drawn in a clockwise direction. /// This is the default in most canvas and geometry operations. /// ClockWise = 1, /// /// The path is drawn in a counter-clockwise direction. /// CounterClockWise = 0 } } namespace Xui.Core.Canvas { using System.Runtime.InteropServices; /// /// Represents a color using red, green, blue, and alpha components, all normalized to the range [0, 1]. /// public struct Color : IEquatable { /// Indicates whether the current object is equal to another object of the same type. /// An object to compare with this object. /// /// if the current object is equal to the parameter; otherwise, . public readonly bool Equals(Color other); /// Indicates whether this instance and a specified object are equal. /// The object to compare with the current instance. /// /// if and this instance are the same type and represent the same value; otherwise, . public override readonly bool Equals(object? obj); /// Returns the hash code for this instance. /// A 32-bit signed integer that is the hash code for this instance. public override readonly int GetHashCode(); /// /// Red component of the color, in the range [0, 1]. /// public nfloat Red; /// /// Green component of the color, in the range [0, 1]. /// public nfloat Green; /// /// Blue component of the color, in the range [0, 1]. /// public nfloat Blue; /// /// Alpha (opacity) component of the color, in the range [0, 1]. /// public nfloat Alpha; /// /// Initializes a new with the specified red, green, blue, and alpha components. /// /// Red component, normalized [0, 1] /// Green component, normalized [0, 1] /// Blue component, normalized [0, 1] /// Alpha component, normalized [0, 1] public Color(nfloat red, nfloat green, nfloat blue, nfloat alpha); /// /// Initializes a new from byte components in the range [0, 255], /// which are normalized to [0, 1]. /// /// Red component [0, 255] /// Green component [0, 255] /// Blue component [0, 255] /// Alpha component [0, 255] public Color(byte red, byte green, byte blue, byte alpha); /// /// Initializes a new from a packed 32-bit RGBA value. /// The value format is 0xRRGGBBAA, where each component is 8 bits. /// /// Packed RGBA value in 0xRRGGBBAA format. public Color(uint rgba); /// /// Returns true if the color is fully transparent (Alpha = 0). /// public readonly bool IsTransparent { get; } /// /// Implicitly converts a 32-bit RGBA value (0xRRGGBBAA) to a . /// /// Packed RGBA hex value. public static implicit operator Color(uint rgbaHex); } } namespace Xui.Core.Canvas { using System.Reflection; /// Describes one concrete font face made available by an application. public readonly struct FontFaceDescriptor { /// The case-insensitive family name. public string Family { get; } /// The numeric weight. public FontWeight Weight { get; } /// The italic or oblique style. public FontStyle Style { get; } /// The width/stretch percentage. public FontStretch Stretch { get; } /// Initializes a concrete face descriptor. public FontFaceDescriptor(string family, FontWeight weight, FontStyle style, FontStretch stretch); /// Returns whether this exact face satisfies . public bool Matches(in Font font); } /// Identifies one font resource without loading its data. public readonly struct FontResource { /// The concrete face represented by this resource. public FontFaceDescriptor Face { get; } /// The source location understood by the supplying source. public Uri Uri { get; } /// Initializes a font resource. public FontResource(FontFaceDescriptor face, Uri uri); } /// URI-backed implementation of . public sealed class FontSource : IFontSource { /// Initializes a URI-backed source with its resource declarations and loader. public FontSource(IEnumerable resources, Func> loader); /// Gets all declared resources without loading their data. public IEnumerable Resources { get; } /// Finds the exact application-provided face for a request. public bool TryGet(in Font font, out FontResource resource); /// Loads a resource's bytes when a consumer needs them. public ReadOnlyMemory Load(in FontResource resource); /// Loads a resource addressed as embedded://Assembly/Path/File.ttf. public static ReadOnlyMemory LoadEmbedded(Uri uri); } /// /// Supplies declared application fonts and loads their bytes on demand. /// A platform must fall back to its installed font catalogue when no resource exactly matches a request. /// public interface IFontSource { /// Gets all declared resources without loading their data. IEnumerable Resources { get; } /// Finds the exact application-provided face for a request. bool TryGet(in Font font, out FontResource resource); /// Loads a resource's bytes when a consumer needs them. ReadOnlyMemory Load(in FontResource resource); } } namespace Xui.Core.Canvas { using Xui.Core.Canvas.Composition.GPU; using Xui.Core.Canvas.Composition.Graphics; /// Declares explicit groups in the drawing order of a canvas. public interface ICompositionContext { /// /// Opens a group and applies its presentation properties. Draw through the same context /// only when the returned scope's is true. /// Dispose the scope before drawing subsequent siblings. /// /// /// Keys identify siblings by reference, not value equality. Use a stable reference, not /// a boxed value or a newly allocated key each frame. HasUpdates=false permits reuse; /// it never guarantees it. Export and immediate contexts always request drawing. /// A retained backend must also redraw when it lacks valid content. Reusing a group /// reuses its entire subtree, so HasUpdates must include relevant descendant changes. /// Presentation changes are processed even when content can be reused. /// HasUpdates=true must request drawing; it is also used by capture middleware to /// force both the display and export branches to accept the same drawing commands. /// Groups inherit drawing state and restore it on disposal, with the same path and /// state semantics as Save/Restore. Bounds do not change the coordinate origin. /// In a view-backed group, issue direct drawing before declaring child surfaces. /// To draw above those children, declare a separate overlay group. Retained backends /// reject drawing that violates this ordering instead of silently changing its depth. /// An inherited arbitrary canvas clip may require flattening a surface into its parent; /// that fallback requests drawing on every frame. Prefer group bounds clipping when /// native composition and content reuse are needed. /// /// /// /// using var group = context.Group(new GroupOptions /// { /// Key = this, /// HasUpdates = HasRenderUpdates, /// Bounds = Frame /// }); /// if (group.NeedsRedraw) /// DrawContent(context); /// /// CompositionGroup Group(scoped in GroupOptions options); /// /// Declares a native GPU leaf in drawing order. Key must be a stable class implementing /// IGpuSurfaceContent; Bounds is required. Rendering is deferred until native placement, /// and requested when HasUpdates is true or the retained surface needs fresh content. /// Available from a Window render context as well as a View render context. /// /// True when native presentation is supported here; false requests an explicit /// application fallback (for example an offscreen image for SVG export). A false return /// does not change composition state. Arbitrary inherited canvas clips are unsupported; /// use group bounds clipping. Native GPU content does not inherit canvas paint/filter. /// /// A Window can declare the surface directly from its RenderEventRef.Context: /// /// context.GpuSurface(new GroupOptions /// { /// Key = cube, // cube implements IGpuSurfaceContent /// Bounds = displayArea, /// HasUpdates = cubeChanged /// }); /// /// Check the returned bool and render a portable fallback when false. /// bool GpuSurface(scoped in GroupOptions options); /// /// Attempts native GPU presentation and reports why it could not be accepted. /// Use to display an unavailable message; /// permits an explicit export /// or offscreen fallback. Invalid options and rendering/shader errors still throw. /// /// Older contexts preserve their existing portable-fallback behavior. bool GpuSurface(scoped in GroupOptions options, out GpuSurfaceFailure failure); /// Validates GPU identity and bounds before a backend changes state. static void ValidateGpuSurface(scoped in GroupOptions options); /// /// Closes the innermost group. Called by ; /// prefer disposing the returned scope over calling this directly. /// void EndGroup(); } } namespace Xui.Core.Canvas { using Xui.Core.Canvas.Filter; /// Controls source-color adjustment when selecting canvas paints. /// /// Set the filter before SetFill or SetStroke. It transforms solid colors and gradient stop /// colors as the paint is selected, including paints used for text. Existing paints and images /// are unchanged. The filter replaces the previous adjustment and participates in Save/Restore. /// public interface IFilterContext { /// Disables adjustment for subsequently selected paints. void SetFilter(); /// Sets the brightness of subsequently selected paints. void SetFilter(Brightness brightness); } } namespace Xui.Core.Canvas { using Xui.Core.Math2D; /// /// A lightweight interface for constructing TrueType glyph paths /// using move, line, curve, and close commands. /// /// /// Glyphs in TrueType fonts use quadratic Bézier curves with optional /// off-curve control points. This interface is intended for glyph outlines /// and font rendering engines. /// public interface IGlyphPathBuilder { /// /// Begins a new sub-path at the specified point. /// void MoveTo(Point to); /// /// Draws a straight line to the specified point. /// void LineTo(Point to); /// /// Draws a quadratic Bézier curve using a control point and end point. /// void CurveTo(Point control, Point to); /// /// Closes the current path contour. /// void ClosePath(); } /// /// Represents a decoded, GPU-resident image. Acts as a self-loading resource handle — /// analogous to HTMLImageElement in the browser. /// /// Acquire instances via GetService(typeof(IImage)) on any . /// Then set the source with (sync-if-cached) or /// for first-time remote or large assets. /// public interface IImage { /// /// Intrinsic size of the image in points. Returns until loaded. /// Size Size { get; } /// /// Loads the image from . /// Returns immediately if the image is already in the platform catalog. /// For local packaged assets this may block on first call; prefer /// for anything that could be slow. /// void Load(string uri); /// /// Loads the image from on a background thread. /// The returned task completes once the image is decoded and GPU-resident. /// Subsequent calls with the same URI return instantly from cache. /// Task LoadAsync(string uri); /// /// Uploads raw CPU pixel data into this image, replacing any previously loaded content. /// must contain width * height * 4 bytes in /// BGRA order (B at the lowest address), matching DXGI_FORMAT_B8G8R8A8_UNORM. /// Default implementation is a no-op on platforms that do not support pixel upload. /// void LoadPixels(int width, int height, ReadOnlySpan bgra32Data); } /// /// Defines methods for drawing images onto the canvas. /// Mirrors the drawImage API from the HTML5 Canvas 2D context. /// https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage /// public interface IImageDrawingContext { /// /// Draws the entire scaled to fit at full opacity. /// void DrawImage(IImage image, Rect dest); /// /// Draws the entire scaled to fit /// at the given . /// void DrawImage(IImage image, Rect dest, nfloat opacity); /// /// Draws the sub-region of /// scaled to fit at the given . /// Mirrors the 9-argument form of drawImage in the HTML5 Canvas API. /// void DrawImage(IImage image, Rect source, Rect dest, nfloat opacity); } /// /// Defines methods for constructing paths, /// following the HTML5 Canvas path API model. /// /// Reference: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D#paths /// public interface IPathBuilder : IGlyphPathBuilder { /// /// Begins a new path by resetting the current path list. /// void BeginPath(); /// /// Draws a cubic Bézier curve from the current point to the specified point, /// using two control points. /// /// First control point. /// Second control point. /// End point. void CurveTo(Point cp1, Point cp2, Point to); /// /// Adds an arc to the path centered at the specified point. /// /// Center of the arc. /// Radius of the arc. /// Start angle in radians. /// End angle in radians. /// Direction in which the arc is drawn. void Arc(Point center, nfloat radius, nfloat startAngle, nfloat endAngle, Winding winding = Winding.ClockWise); /// /// Adds an arc to the path, connecting two tangents defined by control points. /// /// First control point. /// Second control point. /// Arc radius. void ArcTo(Point cp1, Point cp2, nfloat radius); /// /// Adds an elliptical arc to the path. /// /// Center of the ellipse. /// Horizontal radius. /// Vertical radius. /// Rotation of the ellipse, in radians. /// Start angle in radians. /// End angle in radians. /// Direction in which the arc is drawn. void Ellipse(Point center, nfloat radiusX, nfloat radiusY, nfloat rotation, nfloat startAngle, nfloat endAngle, Winding winding = Winding.ClockWise); /// /// Adds a rectangle path to the current path. /// /// The rectangle to add. void Rect(Rect rect); /// /// Adds a rounded rectangle path with a uniform radius. /// /// The rectangle to round. /// Corner radius. void RoundRect(Rect rect, nfloat radius); /// /// Adds a rounded rectangle path with per-corner radii. /// /// The rectangle to round. /// Corner radius object defining each corner. void RoundRect(Rect rect, CornerRadius radius); } /// /// Defines methods for constructing and rendering 2D paths, /// following the HTML5 Canvas path API model. /// /// Reference: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D#paths /// public interface IPathDrawingContext : IPathBuilder, IPathDrawing, IPathClipping { } /// /// Provides convenience methods for drawing filled and stroked rectangles, /// similar to the fillRect() and strokeRect() functions in the HTML5 Canvas API. /// public interface IRectDrawingContext { /// /// Draws the outline of the specified rectangle using the current stroke style. /// /// The rectangle to stroke. void StrokeRect(Rect rect); /// /// Fills the specified rectangle using the current fill style. /// /// The rectangle to fill. void FillRect(Rect rect); } /// /// Provides functionality for measuring text and setting font properties. /// Mirrors the measurement behavior of the HTML5 Canvas 2D context, /// but returns a full structure for advanced layout. /// public interface ITextMeasureContext { /// /// Measures the layout and bounding box metrics of the specified text string /// using the current font. /// /// The text string to measure. /// /// A structure containing both string-specific /// and font-wide metrics. /// TextMetrics MeasureText(string text); /// /// Measures the layout and bounding box metrics of the specified text /// without allocating a string. /// /// The text characters to measure. /// /// A structure containing both string-specific /// and font-wide metrics. /// TextMetrics MeasureText(ReadOnlySpan text); /// /// Sets the font used for all subsequent text drawing and measurement operations. /// /// The font definition to apply. void SetFont(Font font); /// /// Returns the character index (caret position) in /// closest to the given coordinate, using the current font. /// The result ranges from 0 (before the first character) to text.Length /// (after the last character). The position snaps to whichever side of /// a character's midpoint falls on. /// /// The text to hit-test against. /// The horizontal offset to test, relative to the text origin. /// The nearest caret position (0 to text.Length). int HitTestTextPosition(string text, nfloat x); /// /// Returns the character index (caret position) in /// closest to the given coordinate, using the current font. /// The result ranges from 0 (before the first character) to text.Length /// (after the last character). The position snaps to whichever side of /// a character's midpoint falls on. /// /// The text to hit-test against. /// The horizontal offset to test, relative to the text origin. /// The nearest caret position (0 to text.Length). int HitTestTextPosition(ReadOnlySpan text, nfloat x); } /// /// Provides methods for manipulating the current transformation matrix of the drawing context. /// This includes translation, scaling, rotation, and applying affine transformations. /// Mirrors the transformation API of the HTML5 Canvas 2D context. /// public interface ITransformContext { /// /// Applies a translation by the specified vector. /// This offsets all subsequent drawing operations by the given amount. /// /// The translation vector (dx, dy). void Translate(Vector vector); /// /// Applies a clockwise rotation to the current transform. /// /// The rotation angle in radians. void Rotate(nfloat angle); /// /// Applies a scaling transformation using the specified scaling factors. /// /// The scaling vector (sx, sy). void Scale(Vector vector); /// /// Resets the current transformation matrix to the identity matrix, /// then replaces it with the specified transform. /// Equivalent to ctx.setTransform(...) in HTML5 Canvas. /// /// The new transformation matrix to apply. void SetTransform(AffineTransform transform); /// /// Multiplies the current transformation matrix by the specified matrix. /// This is equivalent to applying an additional transformation on top of the existing one. /// /// The matrix to multiply with the current transform. void Transform(AffineTransform matrix); } /// /// Represents a linear gradient brush that transitions between colors along a straight line, /// following the same behavior as the HTML5 Canvas createLinearGradient(). /// public ref struct LinearGradient { /// /// The starting point of the gradient, in user space coordinates. /// public Point StartPoint; /// /// The ending point of the gradient, in user space coordinates. /// public Point EndPoint; /// /// The sequence of gradient stops that define color transitions along the line. /// Offsets are typically in the range [0, 1]. /// public ReadOnlySpan GradientStops; /// /// Creates a new with the given start and end points and gradient stops. /// /// The start point of the gradient. /// The end point of the gradient. /// A span of gradient stops sorted by offset. public LinearGradient(Point start, Point end, ReadOnlySpan gradient); } /// /// Represents a radial gradient brush that transitions colors outward from one circle to another, /// similar to createRadialGradient() in the HTML5 Canvas API. /// public ref struct RadialGradient { /// /// The center point of the starting circle (inner circle). /// public Point StartCenter; /// /// The radius of the starting circle (inner circle), usually 0 for solid centers. /// public nfloat StartRadius; /// /// The center point of the ending circle (outer circle). /// public Point EndCenter; /// /// The radius of the ending circle (outer circle), defining the spread of the gradient. /// public nfloat EndRadius; /// /// A sequence of color stops defining how colors are interpolated from the inner to the outer circle. /// Offsets are typically in the range [0, 1]. /// public ReadOnlySpan GradientStops; /// /// Initializes a radial gradient that transitions between two circles. /// /// Center of the inner circle. /// Radius of the inner circle. /// Center of the outer circle. /// Radius of the outer circle. /// Span of color stops defining the gradient transition. public RadialGradient(Point startCenter, nfloat startRadius, Point endCenter, nfloat endRadius, ReadOnlySpan gradientStops); /// /// Initializes a radial gradient from a single point and radius, fading outward from a solid center. /// This is equivalent to setting the start radius to zero and both centers to the same point. /// /// Center point of the gradient. /// Radius of the gradient spread. /// Span of color stops defining the gradient transition. public RadialGradient(Point center, nfloat radius, ReadOnlySpan gradientStops); } /// /// Utility for clamping corner radii to fit within a rectangle, following the /// CSS Backgrounds and Borders Module Level 3, Section 5.5 "Overlapping Curves". /// When the sum of adjacent radii exceeds a side's length, all radii are scaled /// down proportionally so that curves never overlap. /// public static class RoundedRect { /// /// Returns a whose values are clamped so that adjacent /// corners do not overlap on any side of a rectangle of the given . /// /// Algorithm: compute f = min(1, L_i / S_i) over all four sides, where /// L_i is the side length and S_i is the sum of the two corner radii /// on that side. Then multiply every radius by f. /// /// The dimensions of the rectangle. /// The desired corner radii. /// Corner radii scaled to fit within the rectangle. public static CornerRadius Clamp(Size size, CornerRadius radius); /// /// Returns a uniform radius clamped to fit within the given . /// Equivalent to min(radius, width / 2, height / 2). /// /// The dimensions of the rectangle. /// The desired uniform corner radius. /// The clamped radius value. public static nfloat Clamp(Size size, nfloat radius); } /// /// Composite structure combining string-specific and font-specific text metrics. /// Used for precise layout, alignment, and rendering across all platforms. /// public readonly struct TextMetrics { /// /// Metrics specific to the given text string (shaping, kerning, bounding box). /// public readonly LineMetrics Line; /// /// Metrics derived from the current font and size, independent of input string. /// public readonly FontMetrics Font; /// /// Creates a new composite text metrics structure. /// public TextMetrics(LineMetrics line, FontMetrics font); /// /// Returns the visual bounding box of the text string, relative to the origin. /// X may be negative for glyphs that extend left of the starting point. /// public Rect BoundingBox { get; } /// The measured size of the text. public Size Size { get; } /// /// Implicitly converts the text metrics to a , using the /// advance width and total height of the string. The width corresponds to /// how far the cursor should advance, not the visual width. /// public static implicit operator Size(TextMetrics metrics); } } namespace Xui.Core.Canvas { using Xui.Core.Canvas.Symbols; /// Defines reusable vector drawings independently of their placements. /// /// /// using (var symbol = context.Symbol(new SymbolOptions { Key = chair, Bounds = (0, 0, 40, 40) })) /// { /// if (symbol.NeedsDrawing) /// { /// symbol.Context.SetFill(Colors.Gray); /// symbol.Context.FillRect((4, 4, 32, 32)); /// } /// } /// context.Save(); /// context.Translate((100, 50)); /// context.UseSymbol(chair); /// context.Restore(); /// /// /// /// Definitions start with default pen, alpha and text state. Placements inherit the current /// transform, clip and brightness, and restore enclosing paint/text state afterwards. /// Use relative transforms inside definitions. Native view groups, GPU surfaces, absolute /// SetTransform and nested symbols are not supported inside a symbol. On recording failure, /// call the scope's Cancel method before disposing it. Cache storage follows reference lifetime; /// ReleaseSymbol drops a key without invalidating already-recorded placements. /// public interface ISymbolContext { /// /// Opens a definition without drawing it. When NeedsDrawing is true, draw into the /// returned scope's Context, then dispose the scope before calling UseSymbol. /// Keys use reference identity. A new context may request the definition again. /// SymbolScope Symbol(scoped in SymbolOptions options); /// Draws a completed definition under the current transform and clip. void UseSymbol(object key); /// Forgets a definition. Previously recorded placements retain their immutable content. void ReleaseSymbol(object key); /// /// Backend playback entry point. Retained contexts record a reference; native contexts /// may compile it. The default implements vector command replay for any IContext. /// void DrawSymbol(SymbolContent content); } } namespace Xui.Core.Canvas { using Xui.Core.Math2D; using Xui.Core.Memory; /// /// Defines methods for drawing text onto the canvas, including alignment and baseline options. /// Mirrors the HTML5 Canvas 2D text API for fillText(). /// Also provides access to text measurement via . /// public interface ITextDrawingContext : ITextMeasureContext { /// /// Sets the horizontal alignment of the text relative to the given position. /// TextAlign TextAlign { set; } /// /// Sets the vertical alignment of the text relative to the given baseline. /// TextBaseline TextBaseline { set; } /// /// Draws filled text at the specified position using the current fill style and font settings. /// /// The text string to render. /// The position at which to start rendering the text. void FillText(string text, Point pos); /// /// Draws filled text at the specified position without allocating a string. /// Use with stackalloc and for zero-allocation rendering. /// /// The text characters to render. /// The position at which to start rendering the text. void FillText(ReadOnlySpan text, Point pos); /// /// Draws filled text from an interpolated string without heap-allocating the string. /// The compiler automatically prefers this overload for interpolated string arguments. /// /// The interpolated string handler that formats into a stack buffer. /// The position at which to start rendering the text. void FillText(FillTextInterpolatedStringHandler handler, Point pos); } } namespace Xui.Core.Canvas { using System.Runtime.CompilerServices; using Xui.Core.Math2D; /// /// A serialized path that stores drawing commands in a compact byte buffer and replays them /// into any . Use to replay recorded commands. /// public class Path2D : IPathBuilder { /// Initializes a new with the specified initial byte-buffer capacity. /// Initial buffer size in bytes. Grows automatically as needed. public Path2D(int initialCapacity = 256); /// Clears all recorded path commands, resetting the path to empty. public void BeginPath(); /// /// Begins a new sub-path at the specified point. /// public void MoveTo(Point to); /// /// Draws a straight line to the specified point. /// public void LineTo(Point to); /// /// Closes the current path contour. /// public void ClosePath(); /// /// Draws a quadratic Bézier curve using a control point and end point. /// public void CurveTo(Point cp1, Point to); /// /// Draws a cubic Bézier curve from the current point to the specified point, /// using two control points. /// /// First control point. /// Second control point. /// End point. public void CurveTo(Point cp1, Point cp2, Point to); /// /// Adds an arc to the path centered at the specified point. /// /// Center of the arc. /// Radius of the arc. /// Start angle in radians. /// End angle in radians. /// Direction in which the arc is drawn. public void Arc(Point center, nfloat radius, nfloat startAngle, nfloat endAngle, Winding winding = Winding.ClockWise); /// /// Adds an arc to the path, connecting two tangents defined by control points. /// /// First control point. /// Second control point. /// Arc radius. public void ArcTo(Point cp1, Point cp2, nfloat radius); /// /// Adds an elliptical arc to the path. /// /// Center of the ellipse. /// Horizontal radius. /// Vertical radius. /// Rotation of the ellipse, in radians. /// Start angle in radians. /// End angle in radians. /// Direction in which the arc is drawn. public void Ellipse(Point center, nfloat radiusX, nfloat radiusY, nfloat rotation, nfloat startAngle, nfloat endAngle, Winding winding = Winding.ClockWise); /// /// Adds a rectangle path to the current path. /// /// The rectangle to add. public void Rect(Rect rect); /// /// Adds a rounded rectangle path with a uniform radius. /// /// The rectangle to round. /// Corner radius. public void RoundRect(Rect rect, nfloat radius); /// /// Adds a rounded rectangle path with per-corner radii. /// /// The rectangle to round. /// Corner radius object defining each corner. public void RoundRect(Rect rect, CornerRadius radius); /// Replays all recorded path commands into the given . /// The path builder to receive the commands. public void Visit(T sink) where T : IPathBuilder; } } namespace Xui.Core.Canvas.Composition { /// A platform-independent retained composition element with identity, placement and children. /// /// /// Applications declare composition through ICompositionContext.Group and GpuSurface. A retained /// context reconciles those declarations by key into nodes. A platform presenter maps each node /// to suitable resources: native views or layers, compositor visuals, GPU surfaces, or drawing /// replayed into a parent. A node does not require a native view or an intermediate bitmap. /// Content can remain unchanged while its placement and presentation are updated. /// /// /// Immediate and export contexts can implement the same declarations without constructing this /// tree. SVG currently emits groups directly. iOS presents the retained tree using UIKit views, /// effect views and MTKView GPU surfaces. Android presents backed graphics groups through Java /// views and hardware display lists, with Vulkan presentation for GPU leaves. Windows currently draws groups immediately. Native visuals or offscreen GPU textures are possible /// backend strategies, not capabilities guaranteed by this base class. GPU surface support and /// the need for a portable fallback are reported by ICompositionContext.GpuSurface. /// /// /// This is a rendering/composition model, not the Xui UI view tree. It does not supply layout, /// input routing, focus or accessibility semantics merely because a backend uses native views. /// Derived nodes own their content, children and any platform resources, released by overriding /// DisposeCore. The base provides presentation properties and an idempotent disposal entry point. /// /// public abstract partial class Node { /// Stack-only enumerator over a node's visible children. public ref struct Enumerator { /// The current child. Valid only after MoveNext returns true. public readonly Node Current { get; } /// Advances to the next visible child in presentation order. public bool MoveNext(); } } /// A platform-independent retained composition element with identity, placement and children. /// /// /// Applications declare composition through ICompositionContext.Group and GpuSurface. A retained /// context reconciles those declarations by key into nodes. A platform presenter maps each node /// to suitable resources: native views or layers, compositor visuals, GPU surfaces, or drawing /// replayed into a parent. A node does not require a native view or an intermediate bitmap. /// Content can remain unchanged while its placement and presentation are updated. /// /// /// Immediate and export contexts can implement the same declarations without constructing this /// tree. SVG currently emits groups directly. iOS presents the retained tree using UIKit views, /// effect views and MTKView GPU surfaces. Android presents backed graphics groups through Java /// views and hardware display lists, with Vulkan presentation for GPU leaves. Windows currently draws groups immediately. Native visuals or offscreen GPU textures are possible /// backend strategies, not capabilities guaranteed by this base class. GPU surface support and /// the need for a portable fallback are reported by ICompositionContext.GpuSurface. /// /// /// This is a rendering/composition model, not the Xui UI view tree. It does not supply layout, /// input routing, focus or accessibility semantics merely because a backend uses native views. /// Derived nodes own their content, children and any platform resources, released by overriding /// DisposeCore. The base provides presentation properties and an idempotent disposal entry point. /// /// public abstract partial class Node { /// Number of visible children in back-to-front order. Leaf nodes return zero. public virtual int Count { get; } /// Returns the visible child at the given index. public virtual Node this[int index] { get; } /// Enumerates visible children without allocating or boxing an enumerator. /// Do not mutate the hierarchy during enumeration. public Enumerator GetEnumerator(); } } namespace Xui.Core.Canvas.Composition { using Xui.Core.Canvas.Composition.Graphics; using Xui.Core.Math2D; /// A platform-independent retained composition element with identity, placement and children. /// /// /// Applications declare composition through ICompositionContext.Group and GpuSurface. A retained /// context reconciles those declarations by key into nodes. A platform presenter maps each node /// to suitable resources: native views or layers, compositor visuals, GPU surfaces, or drawing /// replayed into a parent. A node does not require a native view or an intermediate bitmap. /// Content can remain unchanged while its placement and presentation are updated. /// /// /// Immediate and export contexts can implement the same declarations without constructing this /// tree. SVG currently emits groups directly. iOS presents the retained tree using UIKit views, /// effect views and MTKView GPU surfaces. Android presents backed graphics groups through Java /// views and hardware display lists, with Vulkan presentation for GPU leaves. Windows currently draws groups immediately. Native visuals or offscreen GPU textures are possible /// backend strategies, not capabilities guaranteed by this base class. GPU surface support and /// the need for a portable fallback are reported by ICompositionContext.GpuSurface. /// /// /// This is a rendering/composition model, not the Xui UI view tree. It does not supply layout, /// input routing, focus or accessibility semantics merely because a backend uses native views. /// Derived nodes own their content, children and any platform resources, released by overriding /// DisposeCore. The base provides presentation properties and an idempotent disposal entry point. /// /// public abstract partial class Node : IDisposable { /// Stable sibling identity, effects, clipping and content-update declarations. public GroupOptions Options { get; } /// Resolved content bounds used for drawing or native surface placement. public Rect RasterBounds { get; } /// Resolved transform relative to the parent presentation surface. public AffineTransform Placement { get; } /// Device scale used to present the content. public nfloat Scale { get; } /// Whether this frame requested fresh content for this node. public bool Updating { get; } /// Releases the node's owned resources once, including derived content and children. public void Dispose(); /// Overrides release their owned content, children and platform resources, then call base. protected virtual void DisposeCore(); } } namespace Xui.Core.Canvas.Composition.Commands { using System.Runtime.InteropServices; using Xui.Core.Canvas.Composition.Commands.Records; using Xui.Core.Canvas.Filter; using Xui.Core.Canvas.Symbols; /// Reusable pooled binary records and inline payloads, with a pooled managed resource table. /// Not thread-safe. Dispose the buffer to return its rented storage. Clear retains capacity /// for the next recording. Resource objects are retained by reference and are never disposed here. public sealed partial class CanvasCommandBuffer { /// Replays the owned stream into a canvas, reading each typed record without alignment assumptions. public void Replay(IContext target); } } namespace Xui.Core.Canvas.Composition.Commands { using System.Buffers; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Xui.Core.Canvas.Composition.Commands.Records; /// Reusable pooled binary records and inline payloads, with a pooled managed resource table. /// Not thread-safe. Dispose the buffer to return its rented storage. Clear retains capacity /// for the next recording. Resource objects are retained by reference and are never disposed here. public sealed partial class CanvasCommandBuffer : IDisposable { /// Creates a buffer backed by the shared byte and object array pools. public CanvasCommandBuffer(); /// Creates a buffer backed by the supplied pool; storage is rented on first use. public CanvasCommandBuffer(ArrayPool pool); /// Creates a buffer with supplied binary and resource pools, rented on first use. public CanvasCommandBuffer(ArrayPool pool, ArrayPool resourcePool); /// The number of complete commands in the stream. public int Count { get; } /// Packed headers followed immediately by their length-prefixed payload elements. /// The span is borrowed until the next mutation or disposal. Use MemoryMarshal.Read for /// unaligned headers. For text, dashes and gradients, Length specifies how many elements follow /// the header. Managed objects use ResourceRef IDs. These process-local bytes are not a portable /// serialization format. public ReadOnlySpan Data { get; } /// The number of retained object references in the shared resource list. public int ResourceCount { get; } /// Resolves an ID from this buffer to its retained object. /// The command determines the expected type, such as string or IImage. /// The list is not restricted to image resources; it can also retain future texture or /// other managed resource types. Null is allowed for a default font's family name. public object? GetResource(ResourceRef reference); /// Releases resource references while retaining rented storage for the next recording. public void Clear(); /// Clears all object references and returns both rented arrays. Safe to call more than once. public void Dispose(); /// Copies the binary stream and resource references into this buffer's owned storage. public void CopyFrom(CanvasCommandBuffer source); } } namespace Xui.Core.Canvas.Composition.Commands { /// Discriminator for a packed canvas command record. public enum CanvasOp { /// The Save operation. Save, /// The Restore operation. Restore, /// The BeginPath operation. BeginPath, /// The ClosePath operation. ClosePath, /// The Stroke operation. Stroke, /// The Clip operation. Clip, /// The GlobalAlpha operation. GlobalAlpha, /// The LineWidth operation. LineWidth, /// The MiterLimit operation. MiterLimit, /// The LineDashOffset operation. LineDashOffset, /// The LineCap operation. LineCap, /// The LineJoin operation. LineJoin, /// The TextAlign operation. TextAlign, /// The TextBaseline operation. TextBaseline, /// The Translate operation. Translate, /// The Scale operation. Scale, /// The Rotate operation. Rotate, /// The Transform operation. Transform, /// The SetTransform operation. SetTransform, /// The FillRect operation. FillRect, /// The StrokeRect operation. StrokeRect, /// The Rect operation. Rect, /// The MoveTo operation. MoveTo, /// The LineTo operation. LineTo, /// The Quadratic operation. Quadratic, /// The Cubic operation. Cubic, /// The ArcTo operation. ArcTo, /// The Arc operation. Arc, /// The Ellipse operation. Ellipse, /// The RoundRect operation. RoundRect, /// The Fill operation. Fill, /// The FilterNone operation. FilterNone, /// The Brightness operation. Brightness, /// The Font operation. Font, /// The FillColor operation. FillColor, /// The FillLinear operation. FillLinear, /// The FillRadial operation. FillRadial, /// The FillPattern operation. FillPattern, /// The StrokeColor operation. StrokeColor, /// The StrokeLinear operation. StrokeLinear, /// The StrokeRadial operation. StrokeRadial, /// The StrokePattern operation. StrokePattern, /// The Text operation. Text, /// The Dashes operation. Dashes, /// The Image operation. Image, /// The ImageCrop operation. ImageCrop, /// Text drawn from a retained string resource. TextResource, /// A placement of immutable reusable vector content. Symbol, } } namespace Xui.Core.Canvas.Composition.Commands { using System.Runtime.InteropServices; /// An ID for a managed object retained by a canvas command buffer. /// IDs belong to the buffer that recorded them. CopyFrom preserves their mapping; /// clearing or recording into that buffer invalidates previously borrowed IDs. /// The buffer retains references but does not dispose the resources. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct ResourceRef { /// Zero-based index in the owning buffer's shared resource list. public int Id; /// Creates a reference to an entry in the owning buffer. public ResourceRef(int id); } } namespace Xui.Core.Canvas.Composition.Commands { using Xui.Core.Canvas.Composition.Commands.Records; using Xui.Core.Canvas.Filter; using Xui.Core.Math2D; /// A keyed drawing tree. Each node draws its background first, then its child surfaces. public sealed partial class RetainedCanvasContext { public void DrawSymbol(Xui.Core.Canvas.Symbols.SymbolContent content); public void Save(); public void Restore(); public void BeginPath(); public void ClosePath(); public void Stroke(); public void Clip(); public nfloat GlobalAlpha { set; } public nfloat LineWidth { set; } public nfloat MiterLimit { set; } public nfloat LineDashOffset { set; } public LineCap LineCap { set; } public LineJoin LineJoin { set; } public TextAlign TextAlign { set; } public TextBaseline TextBaseline { set; } public void Translate(Vector value); public void Scale(Vector value); public void Rotate(nfloat angle); public void Transform(AffineTransform value); public void SetTransform(AffineTransform value); public void FillRect(Rect bounds); public void StrokeRect(Rect bounds); public void Rect(Rect bounds); public void MoveTo(Point position); public void LineTo(Point position); public void CurveTo(Point control, Point end); public void CurveTo(Point control1, Point control2, Point end); public void ArcTo(Point control, Point end, nfloat radius); public void Arc(Point center, nfloat radius, nfloat start, nfloat end, Winding winding = Winding.ClockWise); public void Ellipse(Point center, nfloat rx, nfloat ry, nfloat rotation, nfloat start, nfloat end, Winding winding = Winding.ClockWise); public void RoundRect(Rect bounds, CornerRadius corners); public void Fill(FillRule rule = FillRule.NonZero); public void SetFilter(); public void SetFilter(Brightness brightness); public void SetFont(Font font); public void SetFill(Color color); public void SetFill(LinearGradient gradient); public void SetFill(RadialGradient gradient); public void SetFill(ImagePattern pattern); public void SetStroke(Color color); public void SetStroke(LinearGradient gradient); public void SetStroke(RadialGradient gradient); public void SetStroke(ImagePattern pattern); public void FillText(ReadOnlySpan text, Point position); public void SetLineDash(ReadOnlySpan segments); public void DrawImage(IImage image, Rect destination, nfloat opacity); public void DrawImage(IImage image, Rect source, Rect destination, nfloat opacity); public void RoundRect(Rect rect, nfloat radius); public void FillText(string text, Point pos); public void DrawImage(IImage image, Rect dest); public TextMetrics MeasureText(string text); public TextMetrics MeasureText(ReadOnlySpan text); } } namespace Xui.Core.Canvas.Composition.Commands { using Xui.Core.Canvas.Composition.Commands.Records; using Xui.Core.Canvas.Composition.GPU; using Xui.Core.Canvas.Composition.Graphics; using Xui.Core.Math2D; /// A keyed drawing tree. Each node draws its background first, then its child surfaces. public sealed partial class RetainedCanvasContext : IContext { public GraphicsNode Root { get; } /// Creates a recorder, optionally using platform-specific nodes for the entire tree. /// Text service used while recording. /// Optional native GPU surface provider. /// Creates fresh graphics nodes for the root and keyed groups. /// Creates fresh GPU leaves. Cached nodes retain their instance and resources. public RetainedCanvasContext(ITextDrawingContext measure, IGpuSurfaceFactory? gpuSurfaces = null, Func? graphicsNodeFactory = null, Func? gpuNodeFactory = null); public void BeginFrame(Rect bounds, nfloat scale); public void EndFrame(); public void AcceptFrame(); public void AbortFrame(); public void Dispose(); public bool GpuSurface(scoped in GroupOptions options); public bool GpuSurface(scoped in GroupOptions options, out GpuSurfaceFailure failure); public CompositionGroup Group(scoped in GroupOptions options); public void EndGroup(); } } namespace Xui.Core.Canvas.Composition.Commands.Records { using System.Runtime.InteropServices; using Xui.Core.Math2D; /// Packed operands for the Arc canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct ArcCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The Center operand. public Point Center; /// The Radius operand. public nfloat Radius; /// The StartAngle operand. public nfloat StartAngle; /// The EndAngle operand. public nfloat EndAngle; /// The Winding operand. public Winding Winding; /// Initializes the discriminator and zeroes the operands. public ArcCommand(); } /// Packed operands for the ArcTo canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct ArcToCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The Control operand. public Point Control; /// The End operand. public Point End; /// The Radius operand. public nfloat Radius; /// Initializes the discriminator and zeroes the operands. public ArcToCommand(); } /// Packed operands for the Cubic canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct CubicCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The Control1 operand. public Point Control1; /// The Control2 operand. public Point Control2; /// The End operand. public Point End; /// Initializes the discriminator and zeroes the operands. public CubicCommand(); } /// Packed operands for the Ellipse canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct EllipseCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The Center operand. public Point Center; /// The RadiusX operand. public nfloat RadiusX; /// The RadiusY operand. public nfloat RadiusY; /// The Rotation operand. public nfloat Rotation; /// The StartAngle operand. public nfloat StartAngle; /// The EndAngle operand. public nfloat EndAngle; /// The Winding operand. public Winding Winding; /// Initializes the discriminator and zeroes the operands. public EllipseCommand(); } /// Packed operands for the FillLinear canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct FillLinearCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The StartPoint operand. public Point StartPoint; /// The EndPoint operand. public Point EndPoint; /// Number of GradientStop elements stored immediately after this record. public int Length; /// Initializes the discriminator and zeroes the operands. public FillLinearCommand(); } /// Packed operands for the FillRadial canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct FillRadialCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The StartCenter operand. public Point StartCenter; /// The StartRadius operand. public nfloat StartRadius; /// The EndCenter operand. public Point EndCenter; /// The EndRadius operand. public nfloat EndRadius; /// Number of GradientStop elements stored immediately after this record. public int Length; /// Initializes the discriminator and zeroes the operands. public FillRadialCommand(); } /// Packed operands for the FillRect canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct FillRectCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The Bounds operand. public Rect Bounds; /// Initializes the discriminator and zeroes the operands. public FillRectCommand(); } /// Packed operands for the Image canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct ImageCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The image object retained in the shared resource list. public ResourceRef Image; /// The Destination operand. public Rect Destination; /// The Opacity operand. public nfloat Opacity; /// Initializes the discriminator and zeroes the operands. public ImageCommand(); } /// Packed operands for the ImageCrop canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct ImageCropCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The image object retained in the shared resource list. public ResourceRef Image; /// The Source operand. public Rect Source; /// The Destination operand. public Rect Destination; /// The Opacity operand. public nfloat Opacity; /// Initializes the discriminator and zeroes the operands. public ImageCropCommand(); } /// Packed operands for the LineTo canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct LineToCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The Position operand. public Point Position; /// Initializes the discriminator and zeroes the operands. public LineToCommand(); } /// Packed operands for the MoveTo canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct MoveToCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The Position operand. public Point Position; /// Initializes the discriminator and zeroes the operands. public MoveToCommand(); } /// Packed operands for the Quadratic canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct QuadraticCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The Control operand. public Point Control; /// The End operand. public Point End; /// Initializes the discriminator and zeroes the operands. public QuadraticCommand(); } /// Packed operands for the Rect canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct RectCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The Bounds operand. public Rect Bounds; /// Initializes the discriminator and zeroes the operands. public RectCommand(); } /// Packed operands for the RoundRect canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct RoundRectCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The Bounds operand. public Rect Bounds; /// The Corners operand. public CornerRadius Corners; /// Initializes the discriminator and zeroes the operands. public RoundRectCommand(); } /// Packed operands for the Scale canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct ScaleCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The Value operand. public Vector Value; /// Initializes the discriminator and zeroes the operands. public ScaleCommand(); } /// Packed operands for the SetTransform canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct SetTransformCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The Value operand. public AffineTransform Value; /// Initializes the discriminator and zeroes the operands. public SetTransformCommand(); } /// Packed operands for the StrokeLinear canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct StrokeLinearCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The StartPoint operand. public Point StartPoint; /// The EndPoint operand. public Point EndPoint; /// Number of GradientStop elements stored immediately after this record. public int Length; /// Initializes the discriminator and zeroes the operands. public StrokeLinearCommand(); } /// Packed operands for the StrokeRadial canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct StrokeRadialCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The StartCenter operand. public Point StartCenter; /// The StartRadius operand. public nfloat StartRadius; /// The EndCenter operand. public Point EndCenter; /// The EndRadius operand. public nfloat EndRadius; /// Number of GradientStop elements stored immediately after this record. public int Length; /// Initializes the discriminator and zeroes the operands. public StrokeRadialCommand(); } /// Packed operands for the StrokeRect canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct StrokeRectCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The Bounds operand. public Rect Bounds; /// Initializes the discriminator and zeroes the operands. public StrokeRectCommand(); } /// Draws text copied from a span into the binary stream immediately after this record. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct TextCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The Position operand. public Point Position; /// Number of char elements stored immediately after this record. public int Length; /// Initializes the discriminator and zeroes the operands. public TextCommand(); } /// Draws a string retained by reference in the shared resource list. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct TextResourceCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The text drawing position. public Point Position; /// The retained string. Span-based text uses TextCommand instead. public ResourceRef Text; /// Initializes the discriminator and zeroes the operands. public TextResourceCommand(); } /// Packed operands for the Transform canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct TransformCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The Value operand. public AffineTransform Value; /// Initializes the discriminator and zeroes the operands. public TransformCommand(); } /// Packed operands for the Translate canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct TranslateCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The Value operand. public Vector Value; /// Initializes the discriminator and zeroes the operands. public TranslateCommand(); } } namespace Xui.Core.Canvas.Composition.Commands.Records { using System.Runtime.InteropServices; /// Packed operands for the BeginPath canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct BeginPathCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// Initializes the discriminator and zeroes the operands. public BeginPathCommand(); } /// Packed operands for the Brightness canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct BrightnessCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The Amount operand. public nfloat Amount; /// Initializes the discriminator and zeroes the operands. public BrightnessCommand(); } /// Packed operands for the Clip canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct ClipCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// Initializes the discriminator and zeroes the operands. public ClipCommand(); } /// Packed operands for the ClosePath canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct ClosePathCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// Initializes the discriminator and zeroes the operands. public ClosePathCommand(); } /// The common prefix of every packed canvas command. /// Read from a command boundary with MemoryMarshal.Read. Records contain no managed /// references and use process-local nfloat widths; this is not a portable file format. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct Command { /// Identifies the concrete header; variable-length headers also specify their payload length. public CanvasOp Op; } /// Packed operands for the Dashes canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct DashesCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// Number of nfloat elements stored immediately after this record. public int Length; /// Initializes the discriminator and zeroes the operands. public DashesCommand(); } /// Packed operands for the FillColor canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct FillColorCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The Color operand. public Color Color; /// Initializes the discriminator and zeroes the operands. public FillColorCommand(); } /// Packed operands for the Fill canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct FillCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The Rule operand. public FillRule Rule; /// Initializes the discriminator and zeroes the operands. public FillCommand(); } /// Packed operands for the FillPattern canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct FillPatternCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The image object retained in the shared resource list. public ResourceRef Image; /// The Repeat operand. public PatternRepeat Repeat; /// Initializes the discriminator and zeroes the operands. public FillPatternCommand(); } /// Packed operands for the FilterNone canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct FilterNoneCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// Initializes the discriminator and zeroes the operands. public FilterNoneCommand(); } /// Packed operands for the Font canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct FontCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The family-name string retained in the shared resource list. public ResourceRef Family; /// The font size. public nfloat Size; /// The font weight. public FontWeight Weight; /// The font style, stored inline without boxing. public FontStyle Style; /// The font stretch. public FontStretch Stretch; /// The line height. public nfloat LineHeight; /// Initializes the discriminator and zeroes the operands. public FontCommand(); } /// Packed operands for the GlobalAlpha canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct GlobalAlphaCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The Value operand. public nfloat Value; /// Initializes the discriminator and zeroes the operands. public GlobalAlphaCommand(); } /// Packed operands for the LineCap canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct LineCapCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The Value operand. public LineCap Value; /// Initializes the discriminator and zeroes the operands. public LineCapCommand(); } /// Packed operands for the LineDashOffset canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct LineDashOffsetCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The Value operand. public nfloat Value; /// Initializes the discriminator and zeroes the operands. public LineDashOffsetCommand(); } /// Packed operands for the LineJoin canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct LineJoinCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The Value operand. public LineJoin Value; /// Initializes the discriminator and zeroes the operands. public LineJoinCommand(); } /// Packed operands for the LineWidth canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct LineWidthCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The Value operand. public nfloat Value; /// Initializes the discriminator and zeroes the operands. public LineWidthCommand(); } /// Packed operands for the MiterLimit canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct MiterLimitCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The Value operand. public nfloat Value; /// Initializes the discriminator and zeroes the operands. public MiterLimitCommand(); } /// Packed operands for the Restore canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct RestoreCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// Initializes the discriminator and zeroes the operands. public RestoreCommand(); } /// Packed operands for the Rotate canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct RotateCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The Angle operand. public nfloat Angle; /// Initializes the discriminator and zeroes the operands. public RotateCommand(); } /// Packed operands for the Save canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct SaveCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// Initializes the discriminator and zeroes the operands. public SaveCommand(); } /// Packed operands for the StrokeColor canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct StrokeColorCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The Color operand. public Color Color; /// Initializes the discriminator and zeroes the operands. public StrokeColorCommand(); } /// Packed operands for the Stroke canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct StrokeCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// Initializes the discriminator and zeroes the operands. public StrokeCommand(); } /// Packed operands for the StrokePattern canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct StrokePatternCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The image object retained in the shared resource list. public ResourceRef Image; /// The Repeat operand. public PatternRepeat Repeat; /// Initializes the discriminator and zeroes the operands. public StrokePatternCommand(); } /// A retained reference to an immutable symbol definition. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct SymbolCommand { /// Operation discriminator. public CanvasOp Op; /// SymbolContent in the buffer's resource table. public ResourceRef Content; /// Initializes the operation. public SymbolCommand(); } /// Packed operands for the TextAlign canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct TextAlignCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The Value operand. public TextAlign Value; /// Initializes the discriminator and zeroes the operands. public TextAlignCommand(); } /// Packed operands for the TextBaseline canvas operation. [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct TextBaselineCommand { /// The command discriminator, at byte offset zero. public CanvasOp Op; /// The Value operand. public TextBaseline Value; /// Initializes the discriminator and zeroes the operands. public TextBaselineCommand(); } } namespace Xui.Core.Canvas.Composition.GPU { /// A retained GPU leaf, presented by its runtime-owned surface. /// GPU nodes have no canvas command buffers, inherited canvas paint, or children. /// A platform can derive from this type to own its native presentation container. public class GpuNode : Node { /// The runtime-owned GPU surface, created on first declaration. public ICompositionGpuSurface? Surface { get; } /// Overrides release their owned content, children and platform resources, then call base. protected override void DisposeCore(); } /// Why a context could not present a native GPU surface. public enum GpuSurfaceFailure { /// The native GPU surface was accepted. None, /// /// This drawing context requires portable output, for example an SVG capture or /// a native context under an unsupported clip. An offscreen fallback may still work. /// PortableFallbackRequired, /// The runtime could not create a GPU device or native GPU surface. NotSupported } /// Runtime-owned presentation resource for a retained GPU node. public interface ICompositionGpuSurface : IDisposable { /// Whether the surface already holds a successfully presented frame. bool HasContent { get; } /// Schedules drawing after native layout; the runtime owns frame acquisition and presentation. void RequestRender(IGpuSurfaceContent content); } /// Runtime factory for native GPU composition surfaces owned by a window. public interface IGpuSurfaceFactory { /// Whether native GPU presentation is available. bool IsSupported { get; } /// Creates a surface whose lifetime belongs to the retained composition tree. /// A native GPU surface cannot be created on this device. ICompositionGpuSurface CreateSurface(); } } namespace Xui.Core.Canvas.Composition.GPU { using Xui.GPU.Hardware; /// A stable reference used both as a GPU surface's key and as its renderer. /// Implement on a class, typically the View that owns the scene. The window calls /// Render on its UI thread after placing the native surface. Do not retain or dispose the /// borrowed target; encode and commit GPU commands during this call. Bounds are supplied /// by GroupOptions; target dimensions are physical pixels. Canvas paint is not inherited. public interface IGpuSurfaceContent { /// Draws and submits one frame into the borrowed presentation target. void Render(IGpuRenderTarget target); } } namespace Xui.Core.Canvas.Composition.Graphics { /// A backdrop material rather than a filter of the group's foreground drawing. public enum BackdropMaterial { /// No backdrop material. None, /// Native system material blur where available. Blur, /// Native Liquid Glass on supported iOS versions; system blur on older iOS. LiquidGlass } /// An allocation-free, stack-only lifetime for a canvas composition group. /// /// Use with a using declaration or statement. Scopes must close in reverse opening order; /// do not copy a live scope. Balance all Save/Restore calls inside the scope before closing it. /// public ref struct CompositionGroup { /// Whether the caller must emit this group's content into the context. public bool NeedsRedraw { get; } /// Creates a scope for an already-opened group. Intended for context implementations. public CompositionGroup(ICompositionContext owner, bool needsRedraw); /// Closes the group and restores its enclosing drawing state. public void Dispose(); } /// /// Explicit immediate-mode implementation for backends without retained composition. /// Groups isolate Save/Restore drawing state and apply presentation, but always redraw. /// Surface effects use portable approximations; this does not create native views or retain pixels. /// public sealed class ImmediateCompositionContext(IContext context) : ICompositionContext { /// /// Opens a group and applies its presentation properties. Draw through the same context /// only when the returned scope's is true. /// Dispose the scope before drawing subsequent siblings. /// /// /// Keys identify siblings by reference, not value equality. Use a stable reference, not /// a boxed value or a newly allocated key each frame. HasUpdates=false permits reuse; /// it never guarantees it. Export and immediate contexts always request drawing. /// A retained backend must also redraw when it lacks valid content. Reusing a group /// reuses its entire subtree, so HasUpdates must include relevant descendant changes. /// Presentation changes are processed even when content can be reused. /// HasUpdates=true must request drawing; it is also used by capture middleware to /// force both the display and export branches to accept the same drawing commands. /// Groups inherit drawing state and restore it on disposal, with the same path and /// state semantics as Save/Restore. Bounds do not change the coordinate origin. /// In a view-backed group, issue direct drawing before declaring child surfaces. /// To draw above those children, declare a separate overlay group. Retained backends /// reject drawing that violates this ordering instead of silently changing its depth. /// An inherited arbitrary canvas clip may require flattening a surface into its parent; /// that fallback requests drawing on every frame. Prefer group bounds clipping when /// native composition and content reuse are needed. /// /// /// /// using var group = context.Group(new GroupOptions /// { /// Key = this, /// HasUpdates = HasRenderUpdates, /// Bounds = Frame /// }); /// if (group.NeedsRedraw) /// DrawContent(context); /// /// public CompositionGroup Group(scoped in GroupOptions options); /// /// Closes the innermost group. Called by ; /// prefer disposing the returned scope over calling this directly. /// public void EndGroup(); } /// A solid border following the inside of a surface's rounded bounds. public readonly record struct OutlineBorder(Color Color, nfloat Width) { /// Checks a finite, nonnegative width. public void Validate(); } } namespace Xui.Core.Canvas.Composition.Graphics { using Xui.Core.Canvas.Composition.Commands; /// A retained 2D drawing surface with recorded canvas commands and ordered composition children. /// Command buffers and reconciliation caches belong here; shared presentation is provided by Node. Platforms may derive from this class to own their /// native resources and release them in DisposeCore. Native backends replay Commands when needed. public class GraphicsNode : Node { /// Inherited canvas state replayed before this surface's own commands. public readonly CanvasCommandBuffer Inherited; /// Recorded 2D drawing content owned by this surface. public readonly CanvasCommandBuffer Commands; /// Number of visible children in back-to-front order. Leaf nodes return zero. public override int Count { get; } /// Returns the visible child at the given index. public override Node this[int index] { get; } /// Cached, omitted children. Backends detach these surfaces until they are declared again. public readonly List HiddenChildren; /// Whether the command stream contains visible drawing operations. public bool HasDrawing { get; } /// Overrides release their owned content, children and platform resources, then call base. protected override void DisposeCore(); } } namespace Xui.Core.Canvas.Composition.Graphics { using Xui.Core.Math2D; /// Identity, content invalidation, and presentation of an explicit canvas group. public readonly struct GroupOptions { /// A stable reference identifying this group among its siblings. Never serialized as an SVG ID. public required object Key { get; init; } /// /// Whether the group's graphics or descendants have changed. Defaults to true. /// False permits a backend to reuse content, but callers must still check NeedsRedraw. /// public bool HasUpdates { get; init; } /// /// Optional content bounds in the group's coordinate system. Does not translate the /// origin or clip implicitly. Retained backends may use these bounds for backing storage. /// public Rect? Bounds { get; init; } /// Local transform concatenated with the parent transform. Defaults to identity. public AffineTransform Transform { get; init; } /// Clips drawing to Bounds, after applying Transform. Requires Bounds. public bool ClipToBounds { get; init; } /// Requests a retained native surface. Requires Bounds. Draw its content before declaring child groups. public bool ViewBacking { get; init; } /// Uniform radius of the surface outline and optional bounds clip. public nfloat CornerRadius { get; init; } /// Optional surface color, updated independently of recorded drawing content. public Color? Background { get; init; } /// Native backdrop material, approximated by a translucent surface in portable renderers. public BackdropMaterial Backdrop { get; init; } /// Optional shadow of the bounds outline, independent of the drawn content's alpha. public OutlineShadow? Shadow { get; init; } /// Optional border drawn inside the rounded bounds. public OutlineBorder? Border { get; init; } /// /// Keep this keyed surface in a bounded cache when omitted by culling. A parent /// retains at most eight hidden children; older entries release their native resources. /// public bool CacheWhenHidden { get; init; } /// Creates options that request drawing and preserve the parent transform. public GroupOptions(); /// Checks required identity and bounds before a backend changes drawing state. public void Validate(); } /// A drop shadow cast by the group's rounded bounds, not by its glyphs or transparent pixels. public readonly record struct OutlineShadow(Color Color, nfloat Radius, Vector Offset) { /// Checks finite, nonnegative blur and finite offsets. public void Validate(); } /// Portable surface approximation for contexts without native backdrop effects. public static class SurfaceEffects { /// Draws an outline shadow and translucent material without filtering foreground text. public static void Draw(IContext context, in GroupOptions options); } } namespace Xui.Core.Canvas.Filter { /// Multiplies paint RGB channels, preserving alpha. One is unchanged; zero is black. public readonly struct Brightness { /// The nonnegative, finite RGB multiplier. public nfloat Amount { get; } /// Creates a brightness adjustment. public Brightness(nfloat amount); } /// The paint color adjustment stored in a canvas state. public enum FilterKind { /// No color adjustment. None, /// Multiply RGB channels by the brightness amount. Brightness, } /// Owned, allocation-free filter state. The default value leaves colors unchanged. public readonly struct FilterState { /// The active adjustment. public FilterKind Kind { get; } /// The brightness multiplier, or one when no adjustment is active. public nfloat Amount { get; } /// Creates state for a brightness adjustment. public FilterState(Brightness brightness); /// Adjusts RGB, clamps each channel to [0,1], and preserves alpha. public Color Apply(Color color); } } namespace Xui.Core.Canvas.SVG { /// /// Specifies the size of the arc to be drawn when interpreting an SVG arc command. /// Used in conjunction with the sweep flag to determine the final arc segment. /// /// This corresponds to the "large-arc-flag" in the SVG path specification. /// public enum ArcFlag { /// /// Draw the smaller of the two possible arc sweeps (less than or equal to 180 degrees). /// Small = 0, /// /// Draw the larger of the two possible arc sweeps (greater than 180 degrees). /// Large = 1 } /// /// Provides SVG-related extension methods for the interface. /// public static class Extensions { /// /// Creates a for the given path drawing context. /// /// This enables fluent parsing or construction of SVG path commands targeting the current canvas context. /// /// The path drawing context (e.g., a canvas or drawing surface). /// A instance for building or parsing SVG paths. public static PathDataBuilder PathData(this IPathDrawingContext @this); } } namespace Xui.Core.Canvas.SVG { using Xui.Core.Math2D; /// /// A utility for converting parsed SVG path commands into drawing operations /// on an target. /// /// This builder supports both absolute (e.g., M, L, C) and relative (e.g., m, l, c) SVG commands, /// and tracks the current drawing point and control points for smooth curves. /// public ref struct PathDataBuilder { /// /// The target drawing context that receives path commands. /// public readonly IPathDrawingContext Sink; /// /// The starting point of the current subpath (used for Z command). /// public Point? StartPoint; /// /// The current position of the pen after the last command. /// public Point CurrentPoint; /// /// The reflected control point for the next cubic Bézier curve (used in S, s). /// public Point NextCubicControlPoint; /// /// The reflected control point for the next quadratic Bézier curve (used in T, t). /// public Point NextQuadraticControlPoint; /// /// Initializes a new targeting the specified drawing context. /// /// The drawing context that will receive the path instructions. public PathDataBuilder(IPathDrawingContext sink); /// /// Begins a new path on the drawing context. /// public PathDataBuilder Begin(); public PathDataBuilder M(Point point); public PathDataBuilder m(Vector vector); public PathDataBuilder L(Point point); public PathDataBuilder l(Vector vector); public PathDataBuilder H(nfloat h); public PathDataBuilder h(nfloat h); public PathDataBuilder V(nfloat v); public PathDataBuilder v(nfloat v); public PathDataBuilder C(Point cp1, Point cp2, Point to); public PathDataBuilder c(Vector cv1, Vector cv2, Vector to); public PathDataBuilder S(Point cp, Point to); public PathDataBuilder s(Vector cv, Vector to); public PathDataBuilder Q(Point cp, Point to); public PathDataBuilder q(Vector cv, Vector to); public PathDataBuilder T(Point to); public PathDataBuilder t(Vector to); public PathDataBuilder A(Vector sr, nfloat xAxisRotationDeg, ArcFlag largeArcFlag, Winding sweepDirection, Point p2); public PathDataBuilder a(Vector v2, nfloat xAxisRotationDeg, ArcFlag largeArcFlag, Winding sweepDirection, Vector sr); public PathDataBuilder Z(); public PathDataBuilder z(); } } namespace Xui.Core.Canvas.Symbols { using Xui.Core.Canvas.Composition.Commands; using Xui.Core.Math2D; /// /// Immutable, shareable drawing instructions. Recorded placements retain this exact definition, /// even when its key is subsequently updated. Storage is reclaimed when the last reference dies. /// public sealed class SymbolContent { /// The local clip and native recording bounds. public Rect Bounds { get; } /// Number of recorded instructions, useful for diagnostics. public int CommandCount { get; } /// /// Portable vector replay. Paint defaults belong to the definition; transform, clip, /// and brightness come from the placement. Save/Restore isolates changes to drawing state. /// The current path is consumed, as with other path drawing operations. /// public void Replay(IContext context); } } namespace Xui.Core.Canvas.Symbols { using Xui.Core.Math2D; /// Identity and local drawing bounds of a reusable symbol. public readonly struct SymbolOptions { /// A stable reference, never a boxed value or a serialized identifier. public required object Key { get; init; } /// Local drawing bounds, including strokes. Content is clipped to these bounds. public required Rect Bounds { get; init; } /// True replaces the definition; false (the default) reuses it when available. public bool HasUpdates { get; init; } } } namespace Xui.Core.Canvas.Symbols { /// A stack-only definition scope. Do not copy a live scope. Dispose before placing the symbol. public ref struct SymbolScope { /// Whether the caller must supply drawing instructions. public bool NeedsDrawing { get; } /// The definition canvas; drawing here never draws into the surrounding scene. public IContext Context { get; } /// Abandons a failed definition, preserving the previous completed content. public void Cancel(); /// Publishes balanced drawing instructions as immutable reusable content. public void Dispose(); } } namespace Xui.Core.Curves2D { using Xui.Core.Canvas; using Xui.Core.Math2D; /// /// Represents a circular or elliptical arc defined by a center point, radii, rotation, and sweep angles. /// /// /// Arcs are useful for describing elliptical curves in vector graphics, layout paths, and stroke outlines. /// They interpolate smoothly from to , optionally applying /// rotation and winding direction. /// public readonly struct Arc : ICurve { /// The center point of the arc's ellipse. public readonly Point Center; /// The horizontal radius of the arc. public readonly nfloat RadiusX; /// The vertical radius of the arc. public readonly nfloat RadiusY; /// The clockwise rotation (in radians) applied to the arc relative to the X axis. public readonly nfloat Rotation; /// The angle (in radians) at which the arc starts, before rotation is applied. public readonly nfloat StartAngle; /// The angle (in radians) at which the arc ends, before rotation is applied. public readonly nfloat EndAngle; /// Specifies whether the arc is drawn clockwise or counter-clockwise. public readonly Winding Winding; /// /// Initializes a new with the given center, radii, rotation, angles, and winding direction. /// /// The center point of the arc's ellipse. /// The horizontal radius. /// The vertical radius. /// The clockwise rotation in radians applied to the ellipse. /// The start angle of the arc in radians (before rotation). /// The end angle of the arc in radians (before rotation). /// Whether the arc is drawn clockwise or counter-clockwise. public Arc(Point center, nfloat rx, nfloat ry, nfloat rotation, nfloat startAngle, nfloat endAngle, Winding winding = Winding.ClockWise); /// /// Gets the interpolated point on the arc at the specified parameter . /// /// A normalized value from 0 to 1 representing the progression along the arc. public Point this[nfloat t] { get; } /// /// Computes the interpolated point on the arc at a given parameter . /// /// A normalized value in the range [0, 1]. public Point Lerp(nfloat t); /// /// Evaluates the arc at a normalized parameter , returning the corresponding point. /// /// A normalized value in the range [0, 1]. /// The corresponding point on the rotated ellipse arc. public Point Evaluate(nfloat t); /// /// Computes the tangent vector at parameter on the arc. /// /// A normalized value in the range [0, 1]. /// The normalized tangent vector at the evaluated point on the arc. public Vector Tangent(nfloat t); /// /// Approximates the arc length using uniform sampling with 16 segments. /// /// The approximate total arc length. public nfloat Length(); /// /// Approximates the arc length using recursive adaptive subdivision. /// /// The maximum allowed error per segment for arc approximation. /// The computed arc length within the specified flatness tolerance. public nfloat Length(nfloat flatness); /// /// Gets the signed sweep angle of the arc, in radians. /// Adjusts automatically for the specified . /// public nfloat SweepAngle { get; } /// /// Converts this arc to an endpoint-parameterized representation. /// /// /// This method generates a single arc segment between the start and end points of the original arc, /// preserving the sweep direction and determining whether the arc is the larger of the two possible segments. /// If the arc forms a complete circle (i.e., the start and end points match and the sweep covers 360°), /// the endpoint position is nudged slightly to avoid rendering ambiguities in formats that do not support full-circle arcs directly. /// /// /// An structure that approximates this arc using endpoint-based parametrization. /// public ArcEndpoint ToEndpointArc(); /// /// Converts this arc to one or two endpoint-parameterized arcs, depending on the arc's sweep angle. /// /// /// If the arc forms a complete or nearly complete circle (i.e., the sweep angle approaches ±360° and the start and end points match), /// the arc is split into two half-circle segments to avoid rendering issues in formats that do not support full-circle arcs directly. /// Otherwise, a single is returned with appropriate flags set for direction and size. /// /// /// A tuple of one or two instances that collectively represent the same elliptical arc: /// Item1 – The first arc segment (always non-null). /// Item2 – The second arc segment if the arc is split, or null if the arc fits in a single segment. /// public (ArcEndpoint, ArcEndpoint? ) ToEndpointArcs(); /// /// Evaluates the position on the ellipse at a given angle (in radians), /// relative to the unrotated ellipse center. /// /// /// The angle in radians, measured from the X axis of the unrotated ellipse. /// This is not a normalized parameter like t, but an absolute angle used in parametric arc equations. /// /// /// The corresponding on the arc's ellipse at the given angle, /// after applying the arc's rotation and translating from its center. /// /// /// The point is computed using the parametric equation of an axis-aligned ellipse: /// (x, y) = (rx * cos(θ), ry * sin(θ)), then rotated by and translated to . /// This method is useful when working directly with angle-based metrics like vertical extrema (e.g., θ = π/2 or 3π/2). /// public Point EvaluateAtAngle(nfloat θ); /// /// Splits this arc into a series of segments, /// each spanning ≤ 90° and aligned so that one edge is axis-aligned. /// /// /// A span to receive the output segments. Must have space for up to 4 entries. /// /// /// The number of segments written to . /// /// /// This method ensures consistent arc tessellation by aligning segment edges with /// X or Y axes and bounding each by ≤ 90°, suitable for round rects or shader-compatible curves. /// public void ToArc3Segments(Span buffer, out int count); } /// /// Represents a circular arc defined by three points: start, mid (on-curve), and end. /// /// /// The arc is guaranteed to pass through all three control points , , and . /// The arc lies on the unique circle that intersects these points and is useful for geometric primitives, /// shader-based SDF rendering, and polygonal arc approximation. /// public readonly struct Arc3Point : ICurve { /// The starting point of the arc. public readonly Point P0; /// A point on the arc between and . public readonly Point P1; /// The ending point of the arc. public readonly Point P2; /// /// Initializes a new defined by three on-curve points. /// public Arc3Point(Point p0, Point p1, Point p2); /// /// Converts this three-point arc into a center-based if the arc is valid. /// /// /// A valid if the input points define a circular segment; otherwise null. /// If the result is null, consider falling back to a straight from to . /// public Arc? ToCenterArc(); /// /// Converts this arc to an endpoint-based format, if valid. /// public ArcEndpoint? ToEndpointArc(); /// /// Evaluates the curve at the given normalized parameter t in [0, 1]. /// public Point Lerp(nfloat t); /// /// Computes the tangent vector at the specified t. /// public Vector Tangent(nfloat t); /// /// Provides indexer access as an alias for . /// public Point this[nfloat t] { get; } /// /// Computes an approximate arc length using 16 steps. /// public nfloat Length(); /// /// Computes a refined approximation of arc length with a specified precision. /// public nfloat Length(nfloat precision); /// /// Implicitly converts a tuple of 3 points to an . /// public static implicit operator Arc3Point((Point p0, Point p1, Point p2) value); /// /// Splits the arc into one or two Y-monotonic segments. /// /// /// This method finds the angle θ where the Y value of the arc reaches an extremum. /// If this point lies within the arc, the arc is split at that angle into two Y-monotonic sub-arcs. /// If no vertical extremum is found within the arc range, the arc is already monotonic. /// public MonotonicArc3Point SplitIntoYMonotonicCurves(); } /// /// Represents a circular or elliptical arc defined by radii, rotation, and endpoint parameters. /// /// /// This arc representation uses start and end points along with size and sweep flags. /// It is commonly used in vector graphics where the arc shape is inferred from geometry and direction flags. /// public readonly struct ArcEndpoint : ICurve { /// The start point of the arc. public readonly Point Start; /// The end point of the arc. public readonly Point End; /// The horizontal radius of the arc. public readonly nfloat RadiusX; /// The vertical radius of the arc. public readonly nfloat RadiusY; /// The clockwise rotation (in radians) applied to the arc's ellipse relative to the X axis. public readonly nfloat Rotation; /// If true, the arc is the longer (greater than 180°) of the two possible arcs between points. public readonly bool LargeArc; /// The direction in which the arc is drawn (clockwise or counter-clockwise). public readonly Winding Winding; /// /// Initializes a new with the given geometry and flags. /// /// The start point of the arc. /// The end point of the arc. /// The horizontal radius. /// The vertical radius. /// The clockwise rotation in radians applied to the ellipse. /// Whether the arc should be the larger of the two possible arcs. /// The sweep direction (clockwise or counter-clockwise). public ArcEndpoint(Point start, Point end, nfloat rx, nfloat ry, nfloat rotation, bool largeArc, Winding winding); /// /// Gets the interpolated point on the arc at the specified parameter . /// /// A normalized value from 0 to 1 representing the progression along the arc. public Point this[nfloat t] { get; } /// /// Computes the interpolated point on the arc at a given parameter . /// /// A normalized value in the range [0, 1]. public Point Lerp(nfloat t); /// /// Evaluates the arc at a normalized parameter , returning the corresponding point. /// /// A normalized value in the range [0, 1]. /// The corresponding point on the arc. public Point Evaluate(nfloat t); /// /// Computes the tangent vector at parameter on the arc. /// /// A normalized value in the range [0, 1]. /// The normalized tangent vector at the evaluated point on the arc. public Vector Tangent(nfloat t); /// /// Approximates the arc length using uniform sampling with 16 segments. /// /// The approximate total arc length. public nfloat Length(); /// /// Approximates the arc length using recursive adaptive subdivision. /// /// The maximum allowed error per segment for arc approximation. /// The computed arc length within the specified flatness tolerance. public nfloat Length(nfloat flatness); /// /// Converts this endpoint-parameterized arc to a center-based . /// /// A new representing the same shape. public Arc ToCenterArc(); /// /// Splits this arc into a series of segments, /// each spanning ≤ 90° and aligned so that one edge is axis-aligned. /// /// /// A span to receive the output segments. Must have space for up to 4 entries. /// /// /// The number of segments written to . /// /// /// This method converts the arc into a center-based representation, /// then delegates to its method. Each resulting /// segment spans ≤ 90° and is safe for monotonic tessellation. /// public void ToArc3Segments(Span buffer, out int count); } } namespace Xui.Core.Curves2D { using Xui.Core.Math2D; /// /// Static helper methods for constructing Bézier curves. /// public static class Bezier { /// /// Creates a linear Bézier curve from two points. /// public static LinearBezier Linear(Point p0, Point p1); /// /// Creates a quadratic Bézier curve from three control points. /// public static QuadraticBezier Quadratic(Point p0, Point p1, Point p2); /// /// Creates a cubic Bézier curve from four control points. /// public static CubicBezier Cubic(Point p0, Point p1, Point p2, Point p3); } /// /// Represents a cubic Bézier curve defined by four control points. /// /// /// A cubic Bézier curve provides smooth interpolation between and , /// influenced by the control points and . This is commonly used in vector graphics, /// animation timing, and layout paths. /// public readonly struct CubicBezier : ICurve { /// The starting point of the curve. public readonly Point P0; /// The first control point, influencing the curve near . public readonly Point P1; /// The second control point, influencing the curve near . public readonly Point P2; /// The ending point of the curve. public readonly Point P3; /// /// Initializes a new cubic Bézier curve with the specified control points. /// public CubicBezier(Point p0, Point p1, Point p2, Point p3); /// /// Computes the interpolated point on the curve at parameter using De Casteljau’s algorithm. /// /// A normalized parameter in the range [0, 1]. public Point Lerp(nfloat t); /// /// Returns a quadratic Bézier that approximates this cubic by averaging the endpoint tangents. /// Suitable as a fast approximation when subdivision is not required. /// public QuadraticBezier QuadraticApproximation { get; } /// /// Computes the tangent vector of the curve at parameter . /// /// A normalized parameter in the range [0, 1]. public Vector Tangent(nfloat t); /// /// Approximates the arc length of the curve using uniform sampling with 16 segments. /// public nfloat Length(); /// /// Approximates the arc length of the curve using recursive adaptive subdivision. /// /// /// The tolerance value used to determine when a segment is flat enough to stop subdividing. /// Smaller values result in more accurate results but require more computation. /// public nfloat Length(nfloat precision); /// /// Gets the interpolated point on the curve at the specified parameter. /// /// A normalized parameter in the range [0, 1]. public Point this[nfloat t] { get; } /// /// Implicitly converts a tuple of four points into a . /// /// A tuple representing the start point, two control points, and end point. public static implicit operator CubicBezier((Point p0, Point p1, Point p2, Point p3) value); /// /// Implicitly converts a to a /// using interpolation for smooth parameterization. /// /// /// This conversion evaluates the quadratic Bézier at fixed steps (1⁄3 and 2⁄3) to generate /// the internal control points of the cubic, resulting in a visually smooth upgrade path. /// public static implicit operator CubicBezier(QuadraticBezier quadratic); /// /// Implicitly converts this cubic Catmull–Rom spline to a . /// /// /// Uses the canonical Catmull–Rom to Bézier mapping, interpolating between P1 and P2. /// public static implicit operator CubicBezier(CubicSpline spline); /// /// Returns a new curve where the control points P1 and P2 /// are adjusted based on a drag gesture at a given parametric position . /// /// /// A normalized value (between 0 and 1) representing the position on the curve where the drag occurs. /// /// /// The drag vector representing how far the user dragged the point at . /// /// /// A new with P0 and P3 unchanged, /// and P1 and P2 adjusted proportionally to the drag direction and distance. /// /// /// The influence of the drag on P1 and P2 is weighted quadratically based on their /// distance from along the curve: /// P1 is influenced by (1 - t)² and P2 by t². /// This preserves the endpoints while allowing intuitive manipulation of the curve shape. /// public CubicBezier Drag(nfloat t, Vector delta); /// /// Returns a new cubic Bézier curve with adjusted control points so the point on the curve /// nearest to is moved by . /// public CubicBezier DragAt(Point origin, Vector delta); /// /// Returns a new cubic Bézier curve with adjusted control points so the point on the curve /// nearest to is moved by . /// Uses recursive refinement based on the specified . /// public CubicBezier DragAt(Point origin, Vector delta, nfloat precision); /// /// Returns the parameter t ∈ [0, 1] at which the curve is closest to the specified point. /// This version uses uniform sampling with 16 segments and is fast enough for interactive use. /// /// The point to compare against the curve. /// The approximate t value where the curve is closest to . public nfloat ClosestT(Point target); /// /// Returns the parameter t ∈ [0, 1] at which the curve is closest to the specified point, /// using recursive ternary subdivision until the difference in t range is less than . /// /// The point to compare against the curve. /// The minimum resolution for t convergence. Smaller values yield more accurate results. /// The t value where the curve is closest to within the specified . public nfloat ClosestT(Point target, nfloat precision); /// /// Splits this curve at the Y-derivative roots, returning up to three Y-monotonic segments /// packed into a . /// public MonotonicCubicBezier SplitIntoYMonotonicCurves(); /// /// Subdivides this cubic Bézier curve at parameter t, returning two curves. /// public (CubicBezier, CubicBezier) Subdivide(nfloat t); /// /// Converts this cubic Bézier curve into a sequence of Y-monotonic quadratic Bézier segments, /// each approximating a portion of the original curve within the specified flatness precision. /// /// /// A span to receive the quadratic segments. Must be large enough to hold the result. /// A typical size is between 4 and 32. Must be at least 3 to accommodate the initial monotonic split. /// /// /// The maximum allowed distance between the original cubic curve and its quadratic approximation. /// Lower values yield more accurate approximations but may require more output segments. /// /// /// The number of segments written to . /// /// /// This method uses an adaptive, flatness-aware subdivision strategy. It begins by splitting the /// cubic curve into up to 3 Y-monotonic segments. Each is then approximated with a quadratic Bézier, /// and the segments with the highest deviation are recursively subdivided until the total number of /// segments fits within and all segments meet the precision requirement. /// /// The output segments are returned in order, forming a continuous piecewise-curve that follows the /// original cubic. Suitable for SDF tessellation or scanline-based rasterization. /// /// /// Thrown if has fewer than 3 elements. /// public void ToQuadratics(Span buffer, nfloat precision, out int count); /// /// A node in the adaptive subdivision linked list used by . /// Each node holds a cubic segment, its quadratic approximation, and a flatness error measure. /// public struct SubcurveNode { /// The cubic Bézier segment represented by this node. public CubicBezier Segment; /// The quadratic Bézier approximation of . public QuadraticBezier QuadraticBezierApproximation; /// The maximum perpendicular deviation of the approximation from the original cubic. public nfloat Precision; /// Index of the next node in the linked chain; 0 indicates this is the last node. public ushort NextIndex; /// /// Initializes a new node representing a quadratic approximation of a cubic Bézier segment in a linked list. /// /// The original cubic Bézier segment. /// Index of the next node in the chain. Use 0 if this is the last node. public SubcurveNode(CubicBezier segment, ushort nextIndex = 0); } } /// /// Represents a 4-point spline segment using Catmull–Rom interpolation. /// The curve interpolates smoothly between and . /// /// /// Catmull–Rom splines are useful for generating smooth curves through a sequence of points /// with minimal configuration. This implementation produces a C¹-continuous cubic curve, /// influenced by neighboring control points and . /// The segment can also be converted into a for drawing or compatibility. /// public readonly struct CubicSpline : ICurve { /// The control point before the start of the curve. public readonly Point P0; /// The starting point of the interpolated segment. public readonly Point P1; /// The ending point of the interpolated segment. public readonly Point P2; /// The control point after the end of the curve. public readonly Point P3; /// /// Initializes a new Catmull–Rom spline segment from four control points. /// public CubicSpline(Point p0, Point p1, Point p2, Point p3); /// /// Evaluates the point on the spline at the given parameter using the Catmull–Rom formula. /// /// A normalized parameter in the range [0, 1]. public Point Lerp(nfloat t); /// /// Computes the tangent vector at parameter by differentiating the spline. /// /// A normalized parameter in the range [0, 1]. public Vector Tangent(nfloat t); /// /// Approximates the arc length of the curve using uniform sampling with 16 segments. /// public nfloat Length(); /// /// Approximates the arc length using recursive adaptive subdivision. /// /// The tolerance used to decide subdivision depth. public nfloat Length(nfloat precision); /// /// Indexer-style access to evaluate the curve at a given parameter. /// public Point this[nfloat t] { get; } /// /// Converts this Catmull–Rom spline segment to an equivalent . /// The resulting curve interpolates between and . /// public static implicit operator CubicBezier(CubicSpline s); } /// /// Represents a common interface for evaluable 2D curves. /// public interface ICurve { /// /// Evaluates the curve at the given normalized parameter t in [0, 1]. /// Point Lerp(nfloat t); /// /// Computes the tangent vector at the specified t. /// Vector Tangent(nfloat t); /// /// Provides indexer access as an alias for . /// Point this[nfloat t] { get; } /// /// Computes an approximate arc length using 16 steps. /// nfloat Length(); /// /// Computes a refined approximation of arc length with a specified precision. /// nfloat Length(nfloat precision); } /// /// Represents a linear Bézier curve, equivalent to a straight line between two points. /// /// /// This is the simplest form of Bézier curve, defined by two points and . /// It is often used for edges of polygonal paths or degenerate forms of higher-order Béziers. /// public readonly struct LinearBezier : ICurve { /// The start point of the curve. public readonly Point P0; /// The end point of the curve. public readonly Point P1; /// /// Initializes a new curve with the given start and end points. /// /// The starting point. /// The ending point. public LinearBezier(Point p0, Point p1); /// /// Computes the point on the line at parameter using linear interpolation. /// /// A normalized parameter in the range [0, 1]. public Point Lerp(nfloat t); /// /// Returns the constant tangent vector of the line segment. /// /// The curve parameter (ignored since the tangent is constant). public Vector Tangent(nfloat t); /// /// Returns the exact length of the line segment. /// public nfloat Length(); /// /// Returns the length of the line segment. This overload ignores the parameter. /// public nfloat Length(nfloat precision); /// /// Indexer-style access to the interpolated point at parameter . /// public Point this[nfloat t] { get; } /// /// Implicitly converts a tuple of two points into a . /// public static implicit operator LinearBezier((Point p0, Point p1) value); /// /// Implicitly converts this to a curve. /// The intermediate point is set to the midpoint for visual smoothness. /// public static implicit operator QuadraticBezier(LinearBezier linear); /// /// Implicitly converts this to a curve. /// Intermediate control points are interpolated at 1/3 and 2/3 for smooth spacing. /// public static implicit operator CubicBezier(LinearBezier linear); /// /// Implicitly converts a to a . /// public static implicit operator LinearBezier(LinearSpline spline); } /// /// Represents a linear spline segment between two points. /// /// /// A linear spline defines a straight-line interpolation between and . /// It is the simplest form of spline, useful for polyline paths, control handles, and degenerate Bézier cases. /// public readonly struct LinearSpline : ICurve { /// /// The starting point of the line segment. /// public readonly Point P0; /// /// The ending point of the line segment. /// public readonly Point P1; /// /// Initializes a new segment between two points. /// /// The starting point of the spline. /// The ending point of the spline. public LinearSpline(Point p0, Point p1); /// /// Interpolates a point on the segment at the specified parameter. /// /// A normalized parameter in the range [0, 1]. /// The interpolated point on the line. public Point Lerp(nfloat t); /// /// Gets the constant tangent vector of the line segment. /// /// A normalized parameter (unused, since the tangent is constant). public Vector Tangent(nfloat t); /// /// Evaluates the point on the spline at the specified parameter. /// public Point this[nfloat t] { get; } /// /// Returns the length of the segment. /// public nfloat Length(); /// /// Returns the length of the segment. Precision is ignored for linear splines. /// public nfloat Length(nfloat precision); /// /// Converts this linear spline to a . /// public static implicit operator LinearBezier(LinearSpline s); } /// /// Represents a quadratic Bézier curve defined by three control points. /// /// /// A quadratic Bézier curve smoothly interpolates between and . /// The curve is influenced by a single control point . /// Quadratic Béziers are widely used in vector graphics, font rendering, and easing functions. /// public readonly struct QuadraticBezier : ICurve { /// The starting point of the curve. public readonly Point P0; /// The control point that influences the curvature of the segment. public readonly Point P1; /// The ending point of the curve. public readonly Point P2; /// /// Initializes a new quadratic Bézier curve with the specified control points. /// public QuadraticBezier(Point p0, Point p1, Point p2); /// /// Evaluates the curve at parameter using De Casteljau’s algorithm. /// /// A normalized parameter in the range [0, 1]. /// The interpolated point on the curve. public Point Lerp(nfloat t); /// /// Computes the tangent vector at parameter . /// /// A normalized parameter in the range [0, 1]. /// The tangent vector at the specified point. public Vector Tangent(nfloat t); /// /// Approximates the arc length using uniform sampling over 16 segments. /// /// The approximate total length of the curve. public nfloat Length(); /// /// Approximates the arc length using recursive adaptive subdivision. /// /// The maximum allowed error for curve flatness. public nfloat Length(nfloat precision); /// /// Evaluates the point on the curve at the specified parameter. /// public Point this[nfloat t] { get; } /// /// Converts a tuple of 3 points to a . /// public static implicit operator QuadraticBezier((Point p0, Point p1, Point p2) value); /// /// Converts a to a . /// public static implicit operator QuadraticBezier(QuadraticSpline spline); /// /// Adjusts the control point to drag the curve at by the given delta. /// Keeps and fixed. /// public QuadraticBezier Drag(nfloat t, Vector delta); /// /// Adjusts the control point so that the curve is moved near by . /// Uses coarse sampling to find the closest point. /// public QuadraticBezier DragAt(Point origin, Vector delta); /// /// Adjusts the control point so that the curve is moved near by . /// Uses adaptive precision to locate the closest point. /// public QuadraticBezier DragAt(Point origin, Vector delta, nfloat precision); /// /// Finds the t value where the curve is closest to . /// Uses uniform sampling across 16 points. /// public nfloat ClosestT(Point target); /// /// Finds the t value where the curve is closest to . /// Uses recursive ternary subdivision with the specified . /// public nfloat ClosestT(Point target, nfloat precision); /// /// Splits the current quadratic Bézier curve into two segments if it is not monotonic in the Y direction. /// /// /// A instance containing one or two sub-curves, each guaranteed to be monotonic in Y. /// If the curve is already Y-monotonic (i.e., has no vertical extrema within (0,1)), a single-segment result is returned. /// /// /// This method analyzes the derivative of the Y component of the curve to determine if a vertical extremum occurs /// within the curve's parameter domain. If a critical point is found in (0,1), the curve is split at that point to ensure /// each resulting segment is Y-monotonic. This is useful for scanline rasterization, tessellation, or other geometry processing /// that requires monotonic segments. /// public MonotonicQuadraticBezier SplitIntoYMonotonicCurves(); /// /// Subdivides this quadratic Bézier curve at parameter t, returning two curves. /// public (QuadraticBezier, QuadraticBezier) Subdivide(nfloat t); } /// /// Represents a 3-point quadratic spline segment (parabolic arc) defined by a start point, control point, and end point. /// /// /// This spline uses the De Casteljau algorithm for interpolation and arc length approximation. /// The curve passes through and , with acting as the control point that defines curvature. /// public readonly struct QuadraticSpline : ICurve { /// The start point of the spline. public readonly Point P0; /// The control point that defines the curvature of the arc. public readonly Point P1; /// The end point of the spline. public readonly Point P2; /// /// Initializes a new with the given start, control, and end points. /// public QuadraticSpline(Point p0, Point p1, Point p2); /// /// Computes the point on the spline at parameter using De Casteljau interpolation. /// /// A normalized parameter between 0 and 1. public Point Lerp(nfloat t); /// /// Computes the tangent vector at parameter on the spline. /// /// A normalized parameter between 0 and 1. public Vector Tangent(nfloat t); /// /// Approximates the total arc length of the spline using a fixed 16-sample De Casteljau subdivision. /// public nfloat Length(); /// /// Approximates the arc length with adaptive subdivision using the specified precision tolerance. /// /// The maximum allowed error in the approximation. public nfloat Length(nfloat precision); /// /// Evaluates the point on the spline at parameter . /// public Point this[nfloat t] { get; } /// /// Converts this spline to a curve with the same control points. /// public static implicit operator QuadraticBezier(QuadraticSpline s); } /// /// Represents a straight line segment from to . /// Implements the interface for compatibility with other curve types. /// public readonly struct Segment : ICurve { /// The starting point of the line segment. public readonly Point P0; /// The ending point of the line segment. public readonly Point P1; /// Initializes a new line from to . public Segment(Point p0, Point p1); /// /// Evaluates the curve at the given normalized parameter t in [0, 1]. /// public Point Lerp(nfloat t); /// /// Computes the tangent vector at the specified t. /// public Vector Tangent(nfloat t); /// /// Provides indexer access as an alias for . /// public Point this[nfloat t] { get; } /// /// Computes an approximate arc length using 16 steps. /// public nfloat Length(); /// /// Computes a refined approximation of arc length with a specified precision. /// public nfloat Length(nfloat precision); /// /// Converts a tuple to a . /// public static implicit operator Segment((Point p0, Point p1) value); } /// /// Provides factory methods for creating spline segments of various degrees. /// public static class Spline { /// /// Creates a linear spline (degree 1) between two points. /// public static LinearSpline Linear(Point p0, Point p1); /// /// Creates a quadratic spline (degree 2) between three points. /// public static QuadraticSpline Quadratic(Point p0, Point p1, Point p2); /// /// Creates a cubic spline (degree 3) using Catmull–Rom interpolation through P1 and P2. /// /// /// This produces a smooth segment influenced by surrounding control points and . /// public static CubicSpline Cubic(Point p0, Point p1, Point p2, Point p3); } } namespace Xui.Core.Curves2D { /// /// Represents one or two segments that are each monotonic in the Y direction. /// public readonly struct MonotonicArc3Point { /// The first monotonic segment. public readonly Arc3Point First; /// The optional second segment, if the arc was split. public readonly Arc3Point? Second; /// Creates a single-segment monotonic arc. public MonotonicArc3Point(Arc3Point only); /// Creates a two-segment Y-monotonic arc. public MonotonicArc3Point(Arc3Point first, Arc3Point second); /// True if the arc was split into two segments. public bool IsSplit { get; } } /// /// Holds one, two, or three Y-monotonic cubic Bézier segments that together represent /// the result of splitting a single cubic at its Y-derivative roots. /// public readonly struct MonotonicCubicBezier { /// The first (and always present) Y-monotonic segment. public readonly CubicBezier First; /// The second Y-monotonic segment, or null if the original had at most one Y-extremum. public readonly CubicBezier? Second; /// The third Y-monotonic segment, or null if the original had fewer than two Y-extrema. public readonly CubicBezier? Third; /// Initializes the struct with one, two, or three Y-monotonic segments. /// The first monotonic segment. /// The second monotonic segment, if any. /// The third monotonic segment, if any. public MonotonicCubicBezier(CubicBezier first, CubicBezier? second = null, CubicBezier? third = null); } /// /// Holds one or two Y-monotonic quadratic Bézier segments that together represent /// a single quadratic curve split at its Y-extremum. /// public readonly struct MonotonicQuadraticBezier { /// The first (and always present) Y-monotonic segment. public readonly QuadraticBezier First; /// The second Y-monotonic segment, or null if no split was needed. public readonly QuadraticBezier? Second; /// Initializes the struct with one or two Y-monotonic segments. /// The first monotonic segment. /// The second monotonic segment, if any. public MonotonicQuadraticBezier(QuadraticBezier first, QuadraticBezier? second = null); } } namespace Xui.Core.Curves3D { using Xui.Core.Math3D; /// /// Provides factory methods for constructing 3D Bézier curves. /// public static class Bezier3 { /// /// Creates a linear (degree-1) Bézier curve — a straight line from /// to . /// public static LinearBezier3 Linear(Point3 p0, Point3 p1); /// /// Creates a quadratic (degree-2) Bézier curve with one control point. /// /// The start point. /// The control point. /// The end point. public static QuadraticBezier3 Quadratic(Point3 p0, Point3 p1, Point3 p2); /// /// Creates a cubic (degree-3) Bézier curve with two control points. /// /// The start point. /// The first control point. /// The second control point. /// The end point. public static CubicBezier3 Cubic(Point3 p0, Point3 p1, Point3 p2, Point3 p3); } /// /// Represents a cubic (degree-3) Bézier curve in 3D space, defined by a start point, /// two control points, and an end point. /// /// /// A cubic Bézier provides smooth interpolation from to , /// shaped by the two interior control points and . /// Points are computed using De Casteljau's algorithm for numerical stability. /// This is the standard curve type for 3D animation paths and splines. /// public readonly struct CubicBezier3 : ICurve3 { /// The starting point of the curve. public readonly Point3 P0; /// The first control point, influencing the curve near . public readonly Point3 P1; /// The second control point, influencing the curve near . public readonly Point3 P2; /// The ending point of the curve. public readonly Point3 P3; /// /// Initializes a new with the specified control points. /// public CubicBezier3(Point3 p0, Point3 p1, Point3 p2, Point3 p3); /// /// Evaluates the curve at parameter using De Casteljau's algorithm. /// /// A normalized parameter in the range [0, 1]. public Point3 Lerp(float t); /// /// Returns the tangent vector of the curve at parameter . /// /// A normalized parameter in the range [0, 1]. public Vector3 Tangent(float t); /// /// Evaluates the curve at the given parameter . /// Alias for . /// public Point3 this[float t] { get; } /// /// Approximates the arc length using 16 uniform samples. /// public float Length(); /// /// Approximates the arc length using adaptive subdivision until the error per /// segment is within . /// public float Length(float precision); /// /// Subdivides this curve at parameter using De Casteljau's algorithm, /// returning the left and right sub-curves. /// /// The split parameter in the range (0, 1). public (CubicBezier3 left, CubicBezier3 right) Subdivide(float t); /// /// Returns a quadratic Bézier that approximates this cubic by averaging the /// endpoint tangents. Suitable as a fast approximation when subdivision is not required. /// public QuadraticBezier3 QuadraticApproximation { get; } /// Returns the fully qualified type name of this instance. /// The fully qualified type name. public override string ToString(); } /// /// Defines a parametric curve in 3D space. /// /// /// The parameter t ranges from 0 to 1, where 0 is the start and 1 is the end of the curve. /// public interface ICurve3 { /// /// Evaluates the curve at the given parameter and returns the /// corresponding point in 3D space. /// /// A normalized parameter in the range [0, 1]. Point3 Lerp(float t); /// /// Returns the tangent (first derivative) vector of the curve at parameter . /// /// A normalized parameter in the range [0, 1]. Vector3 Tangent(float t); /// /// Evaluates the curve at the given parameter . /// Alias for . /// Point3 this[float t] { get; } /// /// Approximates the arc length of the curve using 16 uniform samples. /// float Length(); /// /// Approximates the arc length of the curve using adaptive subdivision /// until the error is within . /// /// The maximum allowed error per segment. float Length(float precision); } /// /// Represents a linear (degree-1) Bézier curve in 3D space — a straight line segment /// from to . /// public readonly struct LinearBezier3 : ICurve3 { /// The starting point of the segment. public readonly Point3 P0; /// The ending point of the segment. public readonly Point3 P1; /// /// Initializes a new with the specified endpoints. /// public LinearBezier3(Point3 p0, Point3 p1); /// /// Evaluates the segment at parameter . /// /// A normalized parameter in the range [0, 1]. public Point3 Lerp(float t); /// /// Returns the constant tangent (direction) of the segment. /// /// Ignored — the tangent is constant for a linear segment. public Vector3 Tangent(float t); /// /// Evaluates the curve at the given parameter . /// Alias for . /// public Point3 this[float t] { get; } /// /// Returns the length of the segment (the Euclidean distance from to ). /// public float Length(); /// /// Returns the length of the segment. /// The parameter is ignored for linear segments. /// public float Length(float precision); /// /// Converts this linear segment to a with a midpoint control. /// public QuadraticBezier3 ToQuadratic(); /// /// Converts this linear segment to a with collinear controls. /// public CubicBezier3 ToCubic(); /// Returns the fully qualified type name of this instance. /// The fully qualified type name. public override string ToString(); } /// /// Represents a quadratic (degree-2) Bézier curve in 3D space, defined by a start point, /// one control point, and an end point. /// /// /// A quadratic Bézier provides smooth interpolation from to , /// pulled toward the control point . Points are computed using /// De Casteljau's algorithm for numerical stability. /// public readonly struct QuadraticBezier3 : ICurve3 { /// The starting point of the curve. public readonly Point3 P0; /// The control point, which influences the curvature. public readonly Point3 P1; /// The ending point of the curve. public readonly Point3 P2; /// /// Initializes a new with the specified control points. /// public QuadraticBezier3(Point3 p0, Point3 p1, Point3 p2); /// /// Evaluates the curve at parameter using De Casteljau's algorithm. /// /// A normalized parameter in the range [0, 1]. public Point3 Lerp(float t); /// /// Returns the tangent vector of the curve at parameter . /// /// A normalized parameter in the range [0, 1]. public Vector3 Tangent(float t); /// /// Evaluates the curve at the given parameter . /// Alias for . /// public Point3 this[float t] { get; } /// /// Approximates the arc length using 16 uniform samples. /// public float Length(); /// /// Approximates the arc length using adaptive subdivision until the error per /// segment is within . /// public float Length(float precision); /// /// Subdivides this curve at parameter using De Casteljau's algorithm, /// returning the left and right sub-curves. /// /// The split parameter in the range (0, 1). public (QuadraticBezier3 left, QuadraticBezier3 right) Subdivide(float t); /// /// Elevates this quadratic curve to an equivalent . /// public CubicBezier3 ToCubic(); /// Returns the fully qualified type name of this instance. /// The fully qualified type name. public override string ToString(); } } namespace Xui.Core.DI { /// Whether the current effective appearance is light or dark. public enum ColorScheme { /// Light appearance — dark text on light backgrounds. Light, /// Dark appearance — light text on dark backgrounds. Dark, } /// The physical form factor of the device. public enum DeviceFormFactor { /// Desktop or laptop computer. Desktop, /// Handheld phone. Mobile, /// Tablet device. Tablet, } /// The operating system platform. public enum DevicePlatform { /// Microsoft Windows. Windows, /// Apple macOS. MacOS, /// Web browser (WASM). Browser, /// Apple iOS. iOS, /// Google Android. Android, } /// /// Provides information about the current device, platform, and user preferences. /// Resolved via this.GetService<IDeviceInfo>() from any . /// The emulator replaces this with a mock to simulate phone or tablet form factors. /// public interface IDeviceInfo { /// Raised on the UI thread when a device or system preference exposed by this service changes. event Action? Changed; /// Gets the operating system the app is running on. DevicePlatform Platform { get; } /// Gets the form factor of the current device. DeviceFormFactor FormFactor { get; } /// Gets the primary pointing device available to the user. PointerModel PointerModel { get; } /// Accessibility font scale multiplier (1.0 = default). nfloat AccessibilityFontScale { get; } /// True if the user has requested reduced motion. bool PrefersReducedMotion { get; } /// True if the user has requested high-contrast mode. bool PrefersHighContrast { get; } /// Light or dark appearance preference. ColorScheme ColorScheme { get; } } /// The primary pointing device available to the user. public enum PointerModel { /// Finger on a touch screen. Touch, /// Stylus or pen. Stylus, /// Mouse or trackpad. Mouse, /// D-pad or game controller. Controller, /// Eye-tracking or gaze-based input. Eye, } /// /// Generic convenience wrappers over , /// mirroring the shape of Microsoft.Extensions.DependencyInjection without /// pulling in that package. /// public static class ServiceProviderExtensions { /// /// Returns the service of type , or null /// if no such service is registered. /// public static T? GetService(this IServiceProvider provider); /// /// Returns the service of type . /// Throws if the service is not found. /// public static T GetRequiredService(this IServiceProvider provider); } } namespace Xui.Core.Debug { /// /// Factory interface for creating instrumentation sinks. /// Register in the DI container at startup. /// Implementations are swappable (console, file, network, E2E test). /// public interface IInstruments { /// Creates a new per-run-loop sink for receiving instrumentation events. IInstrumentsSink CreateSink(); } /// /// Per-surface instrumentation sink. A window or native popup owns one instance; /// its view tree receives it through . /// public interface IRenderSurfaceInstrumentsSink : IViewInstrumentsSink, IDisposable { /// Stable diagnostic name of the surface, such as its owning window type. string Name { get; } /// Begins one update frame for this render surface. void BeginFrame(); /// Completes one update frame for this render surface. void EndFrame(); } /// Factory for creating instrumentation sinks. public static partial class Instruments { } /// Factory for creating instrumentation sinks. public static partial class Instruments { /// Returns an instrumentation sink that writes to a file at the given path. /// The path of the log file to write to. public static IInstruments File(string path); } /// Factory for creating instrumentation sinks. public static partial class Instruments { /// Returns an instrumentation sink that writes to the console. public static readonly IInstruments Console; } /// Controls the verbosity threshold for instrumentation output. public enum LevelOfDetail : uint { /// No output. Silences all instrumentation. Quiet = 0, /// Only the most critical events (start, stop, fatal errors). Essential = 100, /// Standard operational events. Normal = 200, /// Additional informational context useful for understanding behavior. Info = 300, /// Fine-grained diagnostic detail for debugging. Diagnostic = 400, } /// Identifies the subsystem or category of an instrumentation event. [Flags] public enum Scope : uint { /// Application lifecycle events (startup, shutdown, window open/close). Application = 1 << 0, /// Input event processing (pointer, keyboard, touch). Input = 1 << 1, /// Top-level rendering pipeline events. Rendering = 1 << 2, /// View attach, detach, activate, and deactivate events. ViewLifecycle = 1 << 3, /// View animation frame callbacks. ViewAnimation = 1 << 4, /// View measure pass events. ViewMeasure = 1 << 5, /// View arrange pass events. ViewArrange = 1 << 6, /// View render pass events. ViewRendering = 1 << 7, /// View state changes (invalidation, focus, flags). ViewState = 1 << 8, } } namespace Xui.Core.Debug { using Xui.Core.UI; /// /// Per-run-loop instrumentation sink that receives fully-formatted messages. /// Thread-aligned — must not be shared across run loops or threads. /// public interface IInstrumentsSink : IViewInstrumentsSink, IDisposable { /// Creates a dedicated sink for one window, popup, or other render surface. IRenderSurfaceInstrumentsSink CreateRenderSurface(string name); /// Writes a surface event while retaining its source identity for aggregation. bool IsEnabled(IRenderSurfaceInstrumentsSink surface, Scope scope, LevelOfDetail lod); /// Reports structured traversal of a view in the specified scope. void TrackView(IRenderSurfaceInstrumentsSink surface, Scope scope, View view); /// Reports one text measurement and the elapsed underlying-context ticks. void TrackTextMeasure(IRenderSurfaceInstrumentsSink surface, long elapsedTicks); /// Writes a single log message to the sink. void Log(IRenderSurfaceInstrumentsSink surface, Scope scope, LevelOfDetail lod, ReadOnlySpan message); /// Begins a named trace scope. Must be paired with . void BeginTrace(IRenderSurfaceInstrumentsSink surface, Scope scope, LevelOfDetail lod, ReadOnlySpan message); /// Ends the most recently opened trace scope. void EndTrace(IRenderSurfaceInstrumentsSink surface); } /// /// Instrumentation API exposed to a visual tree. A view receives one instance for /// the render surface that owns its tree. /// public interface IViewInstrumentsSink { /// Returns true if this sink should receive events at the given scope and level of detail. bool IsEnabled(Scope scope, LevelOfDetail lod); /// Reports structured traversal of a view in the specified scope. void TrackView(Scope scope, View view); /// Reports one text measurement and the elapsed underlying-context ticks. void TrackTextMeasure(long elapsedTicks); /// Writes a single log message to the sink. void Log(Scope scope, LevelOfDetail lod, ReadOnlySpan message); /// Begins a named trace scope. Must be paired with . void BeginTrace(Scope scope, LevelOfDetail lod, ReadOnlySpan message); /// Ends the most recently opened trace scope. void EndTrace(); } /// Extension methods on for visual tree diagnostics. public static class InstrumentsAccessorExtensions { /// Logs the full visual tree rooted at at the given level of detail. /// The accessor to log through. /// The root view to dump. /// The level of detail threshold. public static void DumpVisualTree(this InstrumentsAccessor instruments, View root, LevelOfDetail lod = LevelOfDetail.Info); } } namespace Xui.Core.Debug { using System.Runtime.CompilerServices; using Xui.Core.UI; /// /// Lightweight zero-allocation facade over an for logging and tracing. /// All formatting is skipped when the sink is disabled for the given scope and level. /// public readonly struct InstrumentsAccessor { /// Initializes a new accessor backed by the given sink. /// The sink to write to, or null to produce a no-op accessor. [MethodImpl(MethodImplOptions.AggressiveInlining)] public InstrumentsAccessor(IViewInstrumentsSink? sink); /// Begins a render-surface update frame when supported by the current sink. [MethodImpl(MethodImplOptions.AggressiveInlining)] public void BeginFrame(); /// Completes a render-surface update frame when supported by the current sink. [MethodImpl(MethodImplOptions.AggressiveInlining)] public void EndFrame(); /// Reports structured traversal of without formatting a message. [MethodImpl(MethodImplOptions.AggressiveInlining)] public void TrackView(Scope scope, View view); /// Reports an underlying text measurement without formatting a message. [MethodImpl(MethodImplOptions.AggressiveInlining)] public void TrackTextMeasure(long elapsedTicks); /// Logs a formatted message at the given scope and level of detail. /// The instrumentation scope. /// The level of detail for filtering. /// The interpolated message string. Not evaluated when the sink is disabled. [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Log(Scope scope, LevelOfDetail lod, [InterpolatedStringHandlerArgument("", "scope", "lod")] ref InstrumentsInterpolatedStringHandler message); /// Begins a named trace scope and returns a that ends it when disposed. /// The instrumentation scope. /// The level of detail for filtering. /// The interpolated trace label. Not evaluated when the sink is disabled. /// A that calls on dispose. [MethodImpl(MethodImplOptions.AggressiveInlining)] public TraceScope Trace(Scope scope, LevelOfDetail lod, [InterpolatedStringHandlerArgument("", "scope", "lod")] ref InstrumentsInterpolatedStringHandler message); } } namespace Xui.Core.Debug { using System.Buffers; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; /// /// Low-allocation interpolated string handler used by and /// . The compiler selects this handler automatically /// when the sink is disabled, skipping all formatting entirely. /// [InterpolatedStringHandler] public ref struct InstrumentsInterpolatedStringHandler { /// /// Called by the compiler to initialize the handler and decide whether formatting is needed. /// /// Total character count of all literal string segments. /// Number of interpolated holes in the string. /// The accessor used to check whether the sink is enabled. /// The instrumentation scope. /// The level of detail. /// Set to true if formatting should proceed; false to skip. public InstrumentsInterpolatedStringHandler(int literalLength, int formattedCount, InstrumentsAccessor accessor, Scope scope, LevelOfDetail lod, out bool shouldAppend); /// Appends a literal string segment to the buffer. public void AppendLiteral(string s); /// Appends a span-formattable value using its default format. public void AppendFormatted(T value) where T : ISpanFormattable; /// Appends a span-formattable value using the specified format string. public void AppendFormatted(T value, ReadOnlySpan format) where T : ISpanFormattable; /// Appends a of characters directly. public void AppendFormatted(ReadOnlySpan value); /// Appends a string value. public void AppendFormatted(string? value); /// Appends any object by calling ToString(). public void AppendFormatted(object? value); /// Returns the currently accumulated characters as a read-only span. public readonly ReadOnlySpan AsSpan(); /// Returns any rented array buffer back to the pool. public void Dispose(); } } namespace Xui.Core.Debug { using System.Runtime.CompilerServices; /// /// A ref struct returned by that closes the active trace /// scope when disposed. Intended for use with using. /// public ref struct TraceScope : IDisposable { /// Initializes a new that will call on the given sink when disposed. /// The sink to notify on dispose, or null for a no-op scope. [MethodImpl(MethodImplOptions.AggressiveInlining)] public TraceScope(IViewInstrumentsSink? sink); /// Ends the active trace scope on the sink. [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Dispose(); } } namespace Xui.Core.Math1D { using Xui.Core.Set; /// /// Provides interval types ( and ) over a comparable element type, /// each modeled as a set with membership, containment, and intersection operations. /// public partial class Interval where T : IComparable, IEquatable { /// /// Represents a closed interval [, ] over a comparable type, /// modeled as a set with membership and containment operations. /// /// /// The closed convention [Start, End] means both bounds are inclusive. /// The interval is empty when Start > End. /// public struct Closed : INonEnumerableSet, IEquatable { /// The inclusive lower bound of the interval. public T Start; /// The inclusive upper bound of the interval. public T End; /// /// Creates a new closed interval [, ]. /// [DebuggerStepThrough] public Closed(T start, T end); /// /// Whether this interval represents the empty set (Start > End). /// public bool IsEmpty { get; } /// /// Membership test: ∈ [Start, End]. /// [DebuggerStepThrough] public bool Contains(T value); /// /// Subset test: ⊆ this. /// [DebuggerStepThrough] public bool Contains(Closed other); /// /// Whether two intervals share any elements (this ∩ other ≠ ∅). /// [DebuggerStepThrough] public bool Overlaps(Closed other); /// /// Set intersection: this ∩ . /// Returns ∅ if the intervals do not overlap. /// public Closed Intersect(Closed other); /// /// Implicit conversion from a 2-tuple to a closed interval. /// [DebuggerStepThrough] public static implicit operator Closed((T Start, T End) tuple); [DebuggerStepThrough] public static bool operator ==(Closed left, Closed right); [DebuggerStepThrough] public static bool operator !=(Closed left, Closed right); /// Indicates whether the current object is equal to another object of the same type. /// An object to compare with this object. /// /// if the current object is equal to the parameter; otherwise, . [DebuggerStepThrough] public bool Equals(Closed other); /// Indicates whether this instance and a specified object are equal. /// The object to compare with the current instance. /// /// if and this instance are the same type and represent the same value; otherwise, . public override bool Equals(object? obj); /// Returns the hash code for this instance. /// A 32-bit signed integer that is the hash code for this instance. public override int GetHashCode(); /// Returns the fully qualified type name of this instance. /// The fully qualified type name. [DebuggerStepThrough] public override string ToString(); } } /// /// Provides interval types ( and ) over a comparable element type, /// each modeled as a set with membership, containment, and intersection operations. /// public partial class Interval where T : IComparable, IEquatable { /// /// Represents a half-open interval [, ) over a comparable type, /// modeled as a set with membership and containment operations. /// /// /// The half-open convention [Start, End) means Start is inclusive and End is exclusive. /// The interval is empty when Start >= End, making [n, n) a natural /// representation for a cursor position with no selection. /// public struct ClosedOpen : INonEnumerableSet, IEquatable { /// The inclusive lower bound of the interval. public T Start; /// The exclusive upper bound of the interval. public T End; /// /// Creates a new half-open interval [, ). /// [DebuggerStepThrough] public ClosedOpen(T start, T end); /// /// Whether this interval represents the empty set (Start >= End). /// public bool IsEmpty { get; } /// /// Membership test: ∈ [Start, End). /// [DebuggerStepThrough] public bool Contains(T value); /// /// Subset test: ⊆ this. /// [DebuggerStepThrough] public bool Contains(ClosedOpen other); /// /// Whether two intervals share any elements (this ∩ other ≠ ∅). /// [DebuggerStepThrough] public bool Overlaps(ClosedOpen other); /// /// Set intersection: this ∩ . /// Returns ∅ if the intervals do not overlap. /// public ClosedOpen Intersect(ClosedOpen other); /// /// Implicit conversion from a 2-tuple to a half-open interval. /// [DebuggerStepThrough] public static implicit operator ClosedOpen((T Start, T End) tuple); [DebuggerStepThrough] public static bool operator ==(ClosedOpen left, ClosedOpen right); [DebuggerStepThrough] public static bool operator !=(ClosedOpen left, ClosedOpen right); /// Indicates whether the current object is equal to another object of the same type. /// An object to compare with this object. /// /// if the current object is equal to the parameter; otherwise, . [DebuggerStepThrough] public bool Equals(ClosedOpen other); /// Indicates whether this instance and a specified object are equal. /// The object to compare with the current instance. /// /// if and this instance are the same type and represent the same value; otherwise, . public override bool Equals(object? obj); /// Returns the hash code for this instance. /// A 32-bit signed integer that is the hash code for this instance. public override int GetHashCode(); /// Returns the fully qualified type name of this instance. /// The fully qualified type name. [DebuggerStepThrough] public override string ToString(); } } } namespace Xui.Core.Math2D { /// /// Represents a 2D affine transformation matrix in the form: /// /// | A C Tx | /// | B D Ty | /// | 0 0 1 | /// /// Used for rotating, scaling, translating, and skewing 2D vectors or points. /// /// /// Transformation is applied as: /// /// | x' | | A C Tx | | x | /// | y' | = | B D Ty | * | y | /// | 1 | | 0 0 1 | | 1 | /// public struct AffineTransform { /// The matrix component in the first row, first column (scale X / rotate). public nfloat A; /// The matrix component in the second row, first column (shear Y / rotate). public nfloat B; /// The matrix component in the first row, second column (shear X / rotate). public nfloat C; /// The matrix component in the second row, second column (scale Y / rotate). public nfloat D; /// The translation component along the X axis. public nfloat Tx; /// The translation component along the Y axis. public nfloat Ty; /// The identity transform (no scale, rotation, or translation). public static readonly AffineTransform Identity; /// Returns true if the current transform is the identity matrix. public bool IsIdentity { get; } /// /// Returns the inverse of this affine transform. /// /// /// This operation assumes the transform is invertible. Division by a zero determinant will cause a runtime exception. /// public AffineTransform Inverse {[DebuggerStepThrough] get; } /// /// Returns the determinant of the 2×2 linear portion of the matrix. /// /// /// This value determines if the matrix is invertible. A value of 0 means the matrix cannot be inverted. /// public nfloat Determinant {[DebuggerStepThrough] get; } /// /// Creates a rotation transform around the origin using the given angle in radians. /// [DebuggerStepThrough] public static AffineTransform Rotate(nfloat angle); /// /// Creates a translation transform using the specified offset vector. /// [DebuggerStepThrough] public static AffineTransform Translate(Vector v); /// /// Creates a scaling transform using the specified scale vector. /// [DebuggerStepThrough] public static AffineTransform Scale(Vector v); /// /// Creates a shear (skew) transformation along the X and Y axes. /// /// The shear factor in the X direction. /// The shear factor in the Y direction. [DebuggerStepThrough] public static AffineTransform Shear(nfloat shearX, nfloat shearY); /// /// Constructs an affine transform with the specified matrix coefficients. /// [DebuggerStepThrough] public AffineTransform(nfloat a, nfloat b, nfloat c, nfloat d, nfloat tx, nfloat ty); /// /// Applies only the linear portion (scale, rotation, shear) of this transform to a . /// /// /// Translation is not applied. Use this to transform directions, movement deltas, or normals. /// /// The affine transform. /// The vector to transform. /// A new with the linear transform applied. [DebuggerStepThrough] public static Vector operator *(AffineTransform t, Vector v); /// /// Applies this transform to a , including translation. /// /// /// This operation applies the full affine matrix, including scale, rotation, shear, and translation. /// Use this when transforming coordinates in space (e.g., an element's position). /// /// The affine transform. /// The point to transform. /// A new with the transform applied. [DebuggerStepThrough] public static Point operator *(AffineTransform t, Point p); /// /// Composes two affine transforms using matrix multiplication. /// /// A new transform representing the application of followed by . [DebuggerStepThrough] public static AffineTransform operator *(AffineTransform lhs, AffineTransform rhs); /// Returns the fully qualified type name of this instance. /// The fully qualified type name. [DebuggerStepThrough] public override string ToString(); } /// /// Common mathematical constants used throughout 2D geometry and curve computations. /// public static class Constants { /// π (pi): Ratio of a circle’s circumference to its diameter. public static readonly nfloat π; /// τ (tau): One full circle in radians (2π). public static readonly nfloat τ; /// ε (epsilon): A small value used for numerical stability checks. public static readonly nfloat ε; /// √2 (square root of 2): Diagonal of a unit square. public static readonly nfloat sqrt2; /// ϕ (phi): The golden ratio (≈ 1.618). public static readonly nfloat ϕ; } /// /// Represents thickness values for each edge of a rectangular element. /// /// /// A defines spacing from the left, top, right, and bottom edges. /// It is typically used for layout constructs such as Margin, Padding, or BorderWidth. /// Unlike , it does not represent position or size—only edge offsets. /// public struct Frame { /// The thickness of the top edge. public nfloat Top; /// The thickness of the right edge. public nfloat Right; /// The thickness of the bottom edge. public nfloat Bottom; /// The thickness of the left edge. public nfloat Left; /// /// Returns true if all four edges have equal thickness. /// public bool IsUniform { get; } /// /// Returns true if all sides (Left, Top, Right, Bottom) are zero. /// public readonly bool IsZero { get; } /// /// Gets the total horizontal edge thickness (left + right). /// public nfloat TotalWidth { get; } /// /// Gets the total vertical edge thickness (top + bottom). /// public nfloat TotalHeight { get; } /// /// A frame with all edge values set to zero. /// public static readonly Frame Zero; /// /// Initializes a new with all edges set to zero. /// [DebuggerStepThrough] public Frame(); /// /// Initializes a new with the specified edge thicknesses. /// /// Top edge thickness. /// Right edge thickness. /// Bottom edge thickness. /// Left edge thickness. [DebuggerStepThrough] public Frame(nfloat top, nfloat right, nfloat bottom, nfloat left); /// /// Converts a 4-tuple (top, right, bottom, left) to a . /// [DebuggerStepThrough] public static implicit operator Frame((nfloat top, nfloat right, nfloat bottom, nfloat left) value); /// /// Converts a 2-tuple (horizontal, vertical) to a . /// Horizontal is applied to left and right; vertical to top and bottom. /// [DebuggerStepThrough] public static implicit operator Frame((nfloat vertical, nfloat horizontal) value); /// /// Converts a scalar value into a uniform for all sides. /// [DebuggerStepThrough] public static implicit operator Frame(nfloat value); /// /// Implicitly converts an to a , /// applying the same value to all four sides (Left, Top, Right, Bottom). /// /// The integer value to apply uniformly to all sides. /// A with all sides set to . [DebuggerStepThrough] public static implicit operator Frame(int value); /// /// Implicitly converts a to a , /// applying the same value to all four sides (Left, Top, Right, Bottom). /// /// The double value to apply uniformly to all sides. /// A with all sides set to . [DebuggerStepThrough] public static implicit operator Frame(double value); /// /// Implicitly converts a to a , /// applying the same value to all four sides (Left, Top, Right, Bottom). /// /// The float value to apply uniformly to all sides. /// A with all sides set to . [DebuggerStepThrough] public static implicit operator Frame(float value); /// /// Scales all edges of the frame by the specified scalar. /// [DebuggerStepThrough] public static Frame operator *(Frame lhs, nfloat rhs); /// /// Adds the corresponding edge thicknesses of two frames. /// [DebuggerStepThrough] public static Frame operator +(Frame lhs, Frame rhs); /// /// Subtracts the corresponding edge thicknesses of two frames. /// [DebuggerStepThrough] public static Frame operator -(Frame lhs, Frame rhs); /// /// Returns a frame containing the maximum value for each edge from two frames. /// [DebuggerStepThrough] public static Frame Max(Frame lhs, Frame rhs); /// /// Returns a frame containing the minimum value for each edge from two frames. /// [DebuggerStepThrough] public static Frame Min(Frame lhs, Frame rhs); /// Returns the fully qualified type name of this instance. /// The fully qualified type name. [DebuggerStepThrough] public override string ToString(); /// /// Returns true if all edge values match exactly. /// public static bool operator ==(Frame left, Frame right); /// /// Returns true if any edge value differs. /// public static bool operator !=(Frame lhs, Frame rhs); /// Indicates whether this instance and a specified object are equal. /// The object to compare with the current instance. /// /// if and this instance are the same type and represent the same value; otherwise, . public override bool Equals(object? obj); /// Returns the hash code for this instance. /// A 32-bit signed integer that is the hash code for this instance. public override int GetHashCode(); } /// /// Represents a two-dimensional size with and components. /// /// /// A specifies how much space an element occupies, without defining its position. /// It is commonly used in layout systems to describe constraints or measured results. /// public struct Size { /// The width of the element. public nfloat Width; /// The height of the element. public nfloat Height; /// A size with zero width and height. public static readonly Size Empty; /// A size with infinite width and height. public static readonly Size Infinity; /// /// Initializes a new instance of the struct with zero dimensions. /// [DebuggerStepThrough] public Size(); /// /// Initializes a new instance of the struct with the given width and height. /// /// The width of the size. /// The height of the size. [DebuggerStepThrough] public Size(nfloat width, nfloat height); /// /// Implicitly converts a tuple to a . /// [DebuggerStepThrough] public static implicit operator Size(ValueTuple tuple); /// /// Returns the size of a square. /// public static implicit operator Size(int uniform); /// /// Explicitly converts a to a . /// [DebuggerStepThrough] public static explicit operator Size(Vector vector); /// /// Adds edge spacing from a to a , increasing its dimensions. /// [DebuggerStepThrough] public static Size operator +(Size size, Frame frame); /// /// Subtracts edge spacing from a , reducing its dimensions. /// [DebuggerStepThrough] public static Size operator -(Size size, Frame frame); /// /// Adds two sizes together component-wise. /// [DebuggerStepThrough] public static Size operator +(Size lhs, Size rhs); /// Returns the fully qualified type name of this instance. /// The fully qualified type name. [DebuggerStepThrough] public override string ToString(); /// /// Returns true if the two sizes have the same dimensions. /// [DebuggerStepThrough] public static bool operator ==(Size lhs, Size rhs); /// /// Returns true if the two sizes have different dimensions. /// [DebuggerStepThrough] public static bool operator !=(Size lhs, Size rhs); /// Indicates whether this instance and a specified object are equal. /// The object to compare with the current instance. /// /// if and this instance are the same type and represent the same value; otherwise, . [DebuggerStepThrough] public override bool Equals(object? obj); /// /// Returns true if this size is equal to the specified . /// public bool Equals(Size other); /// Returns the hash code for this instance. /// A 32-bit signed integer that is the hash code for this instance. [DebuggerStepThrough] public override int GetHashCode(); /// /// Returns the minimum of two sizes, using the smaller width and height from each. /// public static Size Min(Size lhs, Size rhs); /// /// Returns the maximum of two sizes, using the larger width and height from each. /// public static Size Max(Size lhs, Size rhs); } /// /// Represents a 2D vector with X and Y components, commonly used for geometric operations, /// layout math, and movement in 2D space. /// public struct Vector { /// The horizontal component of the vector. public nfloat X; /// The vertical component of the vector. public nfloat Y; /// /// Initializes a new instance of the struct /// with the specified X and Y components. /// /// The horizontal component of the vector. /// The vertical component of the vector. [DebuggerStepThrough] public Vector(nfloat x, nfloat y); /// A zero vector (0, 0). public static readonly Vector Zero; /// A unit vector (1, 1). public static readonly Vector One; /// A unit vector pointing left (-1, 0). public static readonly Vector Left; /// A unit vector pointing up (0, -1). public static readonly Vector Up; /// A unit vector pointing right (1, 0). public static readonly Vector Right; /// A unit vector pointing down (0, 1). public static readonly Vector Down; /// /// Returns a normalized (unit length) version of this vector. /// public Vector Normalized { get; } /// /// Returns the vector rotated 90° counter-clockwise (CCW). /// public Vector PerpendicularCCW { get; } /// /// Returns the vector rotated 90° clockwise (CW). /// public Vector PerpendicularCW { get; } /// /// Returns the magnitude (length) of the vector. /// public nfloat Magnitude { get; } /// /// Returns the magnitude (length) of the vector. /// public nfloat Length { get; } /// /// Returns the squared magnitude (length squared) of the vector. /// This avoids the square root computation used in . /// public nfloat MagnitudeSquared { get; } /// /// Gets the angle in radians between the vector and the positive X-axis, /// measured counter-clockwise in the range [-π, π]. /// /// /// This is equivalent to calling Atan2(Y, X) and is commonly used to compute /// polar angles from directional vectors, such as when determining the angular position /// of a point on a circle or ellipse. /// /// /// The angle in radians between this vector and the X-axis. /// public nfloat ArcAngle { get; } /// /// Rotates the vector counterclockwise by the given angle (in degrees). /// public Vector Rotate(nfloat degrees); /// /// Returns the dot product of two vectors. /// [DebuggerStepThrough] public static nfloat Dot(Vector lhs, Vector rhs); /// /// Projects onto . /// [DebuggerStepThrough] public static Vector Project(Vector lhs, Vector rhs); /// /// Returns the 2D cross product (scalar) of two vectors. /// [DebuggerStepThrough] public static nfloat Cross(Vector lhs, Vector rhs); /// /// Returns a new vector with its magnitude limited to the specified maximum. /// [DebuggerStepThrough] public Vector Clamp(nfloat max); /// /// Returns the clockwise angle (in radians) from the upward direction (0, 1) to the given vector. /// [DebuggerStepThrough] public static nfloat Angle(Vector v); /// /// Returns a unit vector rotated clockwise from the upward direction (0, 1) by the given angle (in radians). /// [DebuggerStepThrough] public static Vector Angle(nfloat radians); /// /// Returns the signed angle (in radians) from to , clockwise from upward. /// [DebuggerStepThrough] public static nfloat Angle(Vector lhs, Vector rhs); /// /// Linearly interpolates between two vectors by . /// [DebuggerStepThrough] public static Vector Lerp(Vector start, Vector end, nfloat step); /// /// Implicitly converts a to a . /// [DebuggerStepThrough] public static implicit operator Vector(Point point); /// /// Multiplies a vector by a scalar. /// [DebuggerStepThrough] public static Vector operator *(Vector v, nfloat f); /// /// Divides a vector by a scalar. /// [DebuggerStepThrough] public static Vector operator /(Vector v, nfloat f); /// /// Multiplies a scalar by a vector. /// [DebuggerStepThrough] public static Vector operator *(nfloat f, Vector v); /// /// Adds two vectors. /// [DebuggerStepThrough] public static Vector operator +(Vector lhs, Vector rhs); /// /// Subtracts one vector from another. /// [DebuggerStepThrough] public static Vector operator -(Vector lhs, Vector rhs); /// /// Implicitly converts a tuple to a . /// [DebuggerStepThrough] public static implicit operator Vector(ValueTuple tuple); /// /// Returns true if the two vectors have equal components. /// [DebuggerStepThrough] public static bool operator ==(Vector lhs, Vector rhs); /// /// Returns true if any component of the two vectors is different. /// [DebuggerStepThrough] public static bool operator !=(Vector lhs, Vector rhs); /// Indicates whether this instance and a specified object are equal. /// The object to compare with the current instance. /// /// if and this instance are the same type and represent the same value; otherwise, . public override bool Equals(object? obj); /// /// Returns true if this vector is equal to another vector. /// public bool Equals(Vector other); /// Returns the hash code for this instance. /// A 32-bit signed integer that is the hash code for this instance. public override int GetHashCode(); /// Returns the fully qualified type name of this instance. /// The fully qualified type name. public override string ToString(); } } namespace Xui.Core.Math2D { using System.Runtime.CompilerServices; /// /// Represents a point in 2D space, defined by its and coordinates. /// public struct Point { /// The X-coordinate of the point. public nfloat X; /// The Y-coordinate of the point. public nfloat Y; /// A point at the origin (0, 0). public static readonly Point Zero; /// /// A point at (1, 1), useful for normalized coordinates or vector math. /// public static readonly Point One; /// /// Initializes a new point with the specified coordinates. /// [DebuggerStepThrough] public Point(nfloat x, nfloat y); /// /// Linearly interpolates between two points by . /// /// The start point. /// The end point. /// A value from 0 to 1 indicating the interpolation position. [DebuggerStepThrough] public static Point Lerp(Point start, Point end, nfloat step); /// /// Returns the Euclidean distance between two points. /// [DebuggerStepThrough] public static nfloat Distance(Point a, Point b); /// /// Returns the squared Euclidean distance between two points (no square root). /// Useful for performance comparisons or ordering by proximity. /// [DebuggerStepThrough] public static nfloat SquaredDistance(Point a, Point b); /// /// Returns the Manhattan (taxicab) distance between two points. /// /// /// The sum of the absolute horizontal and vertical distances. /// Often used in grid-based or discrete movement systems. /// [DebuggerStepThrough] public static nfloat TaxicabDistance(Point a, Point b); /// /// Returns the vector difference from one point to another. /// [DebuggerStepThrough] public static Vector operator -(Point lhs, Point rhs); /// /// Offsets a point by a vector. /// [DebuggerStepThrough] public static Point operator +(Point lhs, Vector rhs); /// /// Subtracts a vector from a point, offsetting it in the opposite direction. /// [DebuggerStepThrough] public static Point operator -(Point lhs, Vector rhs); /// /// Converts a tuple to a point. /// [DebuggerStepThrough] public static implicit operator Point(ValueTuple tuple); /// /// Explicitly converts a vector to a point (drops directional semantics). /// [DebuggerStepThrough] public static explicit operator Point(Vector vector); /// /// Determines whether two points have equal coordinates. /// [DebuggerStepThrough] public static bool operator ==(Point lhs, Point rhs); /// /// Determines whether two points differ in any coordinate. /// [DebuggerStepThrough] public static bool operator !=(Point lhs, Point rhs); /// /// Apply an uniform scale to a point. /// [DebuggerStepThrough] public static Point operator *(Point v, nfloat f); /// Returns the fully qualified type name of this instance. /// The fully qualified type name. public override string ToString(); /// Indicates whether this instance and a specified object are equal. /// The object to compare with the current instance. /// /// if and this instance are the same type and represent the same value; otherwise, . public override bool Equals(object? obj); /// /// Returns true if this point has the same coordinates as another. /// public bool Equals(Point other); /// Returns the hash code for this instance. /// A 32-bit signed integer that is the hash code for this instance. public override int GetHashCode(); } } namespace Xui.Core.Math2D { using Xui.Core.Set; /// /// Represents a rectangle in 2D space, defined by its origin (, ) /// and its dimensions (, ). /// /// /// Unlike , which represents edge thicknesses around a box, /// defines a positioned, sized area used for layout and rendering. /// public struct Rect : INonEnumerableSet, IEquatable { /// The X-coordinate of the rectangle’s top-left corner. public nfloat X; /// The Y-coordinate of the rectangle’s top-left corner. public nfloat Y; /// The width of the rectangle. public nfloat Width; /// The height of the rectangle. public nfloat Height; /// /// Creates a new from position and size. /// [DebuggerStepThrough] public Rect(nfloat x, nfloat y, nfloat width, nfloat height); /// /// Creates a new from a top-left point and a size. /// [DebuggerStepThrough] public Rect(Point topLeft, Size size); /// /// Creates a new from a top-left vector and a size. /// [DebuggerStepThrough] public Rect(Vector topLeft, Size size); /// Returns the top-left point of the rectangle. [DebuggerBrowsable(DebuggerBrowsableState.Never)] public Point TopLeft { get; } /// Returns the top-center point of the rectangle. [DebuggerBrowsable(DebuggerBrowsableState.Never)] public Point TopCenter { get; } /// Returns the top-right point of the rectangle. [DebuggerBrowsable(DebuggerBrowsableState.Never)] public Point TopRight { get; } /// Returns the bottom-right point of the rectangle. [DebuggerBrowsable(DebuggerBrowsableState.Never)] public Point BottomRight { get; } /// Returns the bottom-left point of the rectangle. [DebuggerBrowsable(DebuggerBrowsableState.Never)] public Point BottomLeft { get; } /// Returns the X-coordinate of the left edge. [DebuggerBrowsable(DebuggerBrowsableState.Never)] public nfloat Left { get; } /// Returns the Y-coordinate of the top edge. [DebuggerBrowsable(DebuggerBrowsableState.Never)] public nfloat Top { get; } /// Returns the X-coordinate of the right edge. [DebuggerBrowsable(DebuggerBrowsableState.Never)] public nfloat Right { get; } /// Returns the Y-coordinate of the bottom edge. [DebuggerBrowsable(DebuggerBrowsableState.Never)] public nfloat Bottom { get; } /// /// Returns the center point of the rectangle. /// public Point Center { get; } /// /// Gets or sets the size of the rectangle. /// [DebuggerBrowsable(DebuggerBrowsableState.Never)] public Size Size { get; set; } /// /// Returns a new rectangle that is inset by the same amount on all four sides. /// [DebuggerStepThrough] public Rect Inset(nfloat inset); /// /// Returns true if the specified lies within this rectangle. /// [DebuggerStepThrough] public bool Contains(Point point); /// Returns whether this rectangle overlaps or touches . [DebuggerStepThrough] public bool Intersects(Rect other); /// /// Returns a rectangle expanded horizontally and vertically by the specified amounts. /// [DebuggerStepThrough] public Rect Expand(nfloat h, nfloat v); /// /// Returns a rectangle expanded uniformly in all directions. /// [DebuggerStepThrough] public Rect Expand(nfloat expand); /// /// Implicit conversion from a 4-tuple to a rectangle. /// [DebuggerStepThrough] public static implicit operator Rect(ValueTuple tuple); /// /// Returns a rectangle expanded outward by a . /// [DebuggerStepThrough] public static Rect operator +(Rect rect, Frame frame); /// /// Returns a rectangle inset inward by a . /// [DebuggerStepThrough] public static Rect operator -(Rect rect, Frame frame); /// /// Returns true if two rectangles are equal in position and size. /// [DebuggerStepThrough] public static bool operator ==(Rect lhs, Rect rhs); /// /// Returns true if any of the rectangle fields are different. /// [DebuggerStepThrough] public static bool operator !=(Rect lhs, Rect rhs); /// Indicates whether this instance and a specified object are equal. /// The object to compare with the current instance. /// /// if and this instance are the same type and represent the same value; otherwise, . public override bool Equals(object? obj); /// /// Returns true if this rectangle is equal to another rectangle in position and size. /// public bool Equals(Rect other); /// Returns the hash code for this instance. /// A 32-bit signed integer that is the hash code for this instance. public override int GetHashCode(); /// Returns the fully qualified type name of this instance. /// The fully qualified type name. [DebuggerStepThrough] public override string ToString(); } } namespace Xui.Core.Math3D { using System.Runtime.CompilerServices; /// /// Represents a 4×4 column-major transformation matrix for 3D geometry. /// /// /// /// Vectors and points are treated as column vectors and transformed by pre-multiplication: /// v' = M * v. Translation is stored in the last column (M14, M24, M34). /// /// /// The matrix is stored in row-major memory order (M_row_col) as 16 sequential floats /// (64 bytes), fitting exactly into four 128-bit SIMD registers. /// /// /// To interoperate with (which uses row-vector /// convention) use the explicit cast operators, which perform the necessary transpose. /// /// public struct Matrix4x4 { /// Row 1, Column 1 — X basis X component (scale X for pure-scale matrices). public float M11; /// Row 1, Column 2 — X basis Y shear. public float M12; /// Row 1, Column 3 — X basis Z shear. public float M13; /// Row 1, Column 4 — Translation along X. public float M14; /// Row 2, Column 1 — Y basis X shear. public float M21; /// Row 2, Column 2 — Y basis Y component (scale Y for pure-scale matrices). public float M22; /// Row 2, Column 3 — Y basis Z shear. public float M23; /// Row 2, Column 4 — Translation along Y. public float M24; /// Row 3, Column 1 — Z basis X shear. public float M31; /// Row 3, Column 2 — Z basis Y shear. public float M32; /// Row 3, Column 3 — Z basis Z component (scale Z for pure-scale matrices). public float M33; /// Row 3, Column 4 — Translation along Z. public float M34; /// Row 4, Column 1 — Perspective X component (0 for affine transforms). public float M41; /// Row 4, Column 2 — Perspective Y component (0 for affine transforms). public float M42; /// Row 4, Column 3 — Perspective Z component (0 for affine transforms). public float M43; /// Row 4, Column 4 — Homogeneous W scale (1 for affine transforms). public float M44; /// The identity matrix. public static readonly Matrix4x4 Identity; /// /// Initializes a new with the specified row-ordered coefficients. /// [DebuggerStepThrough] public Matrix4x4(float m11, float m12, float m13, float m14, float m21, float m22, float m23, float m24, float m31, float m32, float m33, float m34, float m41, float m42, float m43, float m44); /// Returns true when this matrix equals the identity matrix. public bool IsIdentity { get; } /// /// Returns the transpose of this matrix (swaps rows and columns). /// public Matrix4x4 Transposed { get; } /// /// Returns the determinant of the matrix. /// A determinant of zero means the matrix is not invertible. /// public float Determinant { get; } /// /// Returns the inverse of this matrix. /// /// /// For rotation-only or TRS (translation-rotation-scale) matrices, consider computing /// the inverse analytically for better performance. /// Throws a division-by-zero style error if the matrix is singular (determinant ≈ 0). /// public Matrix4x4 Inverse { get; } /// /// Creates a translation matrix that moves a point by the given vector. /// [DebuggerStepThrough] public static Matrix4x4 Translate(Vector3 v); /// /// Creates a uniform scale matrix. /// [DebuggerStepThrough] public static Matrix4x4 Scale(float s); /// /// Creates a non-uniform scale matrix. /// [DebuggerStepThrough] public static Matrix4x4 Scale(Vector3 v); /// /// Creates a rotation matrix around the X axis by the given angle in radians. /// [DebuggerStepThrough] public static Matrix4x4 RotateX(float angle); /// /// Creates a rotation matrix around the Y axis by the given angle in radians. /// [DebuggerStepThrough] public static Matrix4x4 RotateY(float angle); /// /// Creates a rotation matrix around the Z axis by the given angle in radians. /// [DebuggerStepThrough] public static Matrix4x4 RotateZ(float angle); /// /// Creates a rotation matrix from a unit quaternion. /// [DebuggerStepThrough] public static Matrix4x4 Rotate(Quaternion q); /// /// Creates a symmetric perspective projection matrix (right-handed, depth range [-1, 1]). /// /// Vertical field of view in radians. /// Aspect ratio (width / height). /// Distance to the near clipping plane (must be positive). /// Distance to the far clipping plane (must be greater than ). [DebuggerStepThrough] public static Matrix4x4 Perspective(float fovY, float aspect, float near, float far); /// /// Creates a look-at view matrix (right-handed coordinate system). /// /// The position of the camera. /// The position the camera is looking at. /// The world up direction (typically ). [DebuggerStepThrough] public static Matrix4x4 LookAt(Point3 eye, Point3 target, Vector3 up); /// /// Creates a symmetric orthographic projection matrix (right-handed, depth range [-1, 1]). /// /// The width of the view volume. /// The height of the view volume. /// Distance to the near clipping plane. /// Distance to the far clipping plane. [DebuggerStepThrough] public static Matrix4x4 Orthographic(float width, float height, float near, float far); /// /// Composes two transformation matrices. /// The result applies first, then . /// [DebuggerStepThrough] public static Matrix4x4 operator *(Matrix4x4 lhs, Matrix4x4 rhs); /// /// Transforms a by this matrix, ignoring the translation component. /// Use this for directions and normals. /// [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 operator *(Matrix4x4 m, Vector3 v); /// /// Transforms a by this matrix, including the translation component. /// Use this for positions. /// [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Point3 operator *(Matrix4x4 m, Point3 p); /// Returns true if two matrices have equal coefficients. [DebuggerStepThrough] public static bool operator ==(Matrix4x4 lhs, Matrix4x4 rhs); /// Returns true if any coefficient of two matrices differs. [DebuggerStepThrough] public static bool operator !=(Matrix4x4 lhs, Matrix4x4 rhs); /// /// Explicitly converts to a . /// /// /// uses row-vector convention, which is the /// transpose of the column-vector convention used by this type. /// The conversion transposes the matrix so that row-vector math on the result /// produces the same geometric transformation. /// [DebuggerStepThrough] public static explicit operator System.Numerics.Matrix4x4(Matrix4x4 m); /// /// Explicitly converts from a . /// /// /// uses row-vector convention. This conversion /// transposes the input matrix so that it works correctly with the column-vector /// convention used by this type. /// [DebuggerStepThrough] public static explicit operator Matrix4x4(System.Numerics.Matrix4x4 m); /// Indicates whether this instance and a specified object are equal. /// The object to compare with the current instance. /// /// if and this instance are the same type and represent the same value; otherwise, . public override bool Equals(object? obj); /// Returns true if this matrix equals another . public bool Equals(Matrix4x4 other); /// Returns the hash code for this instance. /// A 32-bit signed integer that is the hash code for this instance. public override int GetHashCode(); /// Returns the fully qualified type name of this instance. /// The fully qualified type name. public override string ToString(); } /// /// Represents a point in 3D space defined by its X, Y, and Z coordinates. /// /// /// A denotes a position. The difference of two points yields a /// . Adding a to a offsets it. /// public struct Point3 { /// The X coordinate of the point. public float X; /// The Y coordinate of the point. public float Y; /// The Z coordinate of the point. public float Z; /// A point at the origin (0, 0, 0). public static readonly Point3 Zero; /// A point at (1, 1, 1). public static readonly Point3 One; /// /// Initializes a new with the specified coordinates. /// /// The X coordinate. /// The Y coordinate. /// The Z coordinate. [DebuggerStepThrough] public Point3(float x, float y, float z); /// /// Linearly interpolates between two points by the factor . /// /// The start point at t = 0. /// The end point at t = 1. /// The interpolation factor, typically in the range [0, 1]. [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Point3 Lerp(Point3 start, Point3 end, float t); /// /// Returns the Euclidean distance between two points. /// [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Distance(Point3 a, Point3 b); /// /// Returns the squared Euclidean distance between two points (no square root). /// Useful for performance comparisons or ordering by proximity. /// [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float SquaredDistance(Point3 a, Point3 b); /// /// Returns the Manhattan (taxicab) distance between two points. /// This is the sum of the absolute differences of their coordinates. /// [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float TaxicabDistance(Point3 a, Point3 b); /// /// Returns the vector from to . /// [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 operator -(Point3 lhs, Point3 rhs); /// /// Offsets a point by a vector. /// [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Point3 operator +(Point3 p, Vector3 v); /// /// Offsets a point in the opposite direction of a vector. /// [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Point3 operator -(Point3 p, Vector3 v); /// /// Applies a uniform scale to a point relative to the origin. /// [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Point3 operator *(Point3 p, float f); /// Determines whether two points have equal coordinates. [DebuggerStepThrough] public static bool operator ==(Point3 lhs, Point3 rhs); /// Determines whether two points differ in any coordinate. [DebuggerStepThrough] public static bool operator !=(Point3 lhs, Point3 rhs); /// Implicitly converts a tuple to a . [DebuggerStepThrough] public static implicit operator Point3((float x, float y, float z) t); /// Explicitly converts a to a . [DebuggerStepThrough] public static explicit operator Point3(Vector3 v); /// Indicates whether this instance and a specified object are equal. /// The object to compare with the current instance. /// /// if and this instance are the same type and represent the same value; otherwise, . public override bool Equals(object? obj); /// Returns true if this point has the same coordinates as another. public bool Equals(Point3 other); /// Returns the hash code for this instance. /// A 32-bit signed integer that is the hash code for this instance. public override int GetHashCode(); /// Returns the fully qualified type name of this instance. /// The fully qualified type name. public override string ToString(); } /// /// Represents a unit quaternion used to encode a 3D rotation. /// /// /// /// A quaternion is stored as four floats (X, Y, Z, W) where (X, Y, Z) is the /// vector part and W is the scalar part. For a rotation of angle θ around a /// normalized axis n: X = n.X·sin(θ/2), Y = n.Y·sin(θ/2), /// Z = n.Z·sin(θ/2), W = cos(θ/2). /// /// /// The 16-byte memory layout (four sequential floats) makes /// compatible with SIMD registers and GPU constant buffers. /// /// public struct Quaternion { /// The X component of the vector part. public float X; /// The Y component of the vector part. public float Y; /// The Z component of the vector part. public float Z; /// The scalar (real) part of the quaternion. public float W; /// The identity quaternion representing no rotation. public static readonly Quaternion Identity; /// /// Initializes a new with the specified components. /// /// The X component of the vector part. /// The Y component of the vector part. /// The Z component of the vector part. /// The scalar (real) part. [DebuggerStepThrough] public Quaternion(float x, float y, float z, float w); /// /// Returns the magnitude (norm) of the quaternion. /// public float Magnitude {[MethodImpl(MethodImplOptions.AggressiveInlining)] get; } /// /// Returns the squared magnitude of the quaternion, avoiding a square root. /// public float MagnitudeSquared {[MethodImpl(MethodImplOptions.AggressiveInlining)] get; } /// /// Returns a normalized (unit) copy of this quaternion. /// Returns if the magnitude is zero. /// public Quaternion Normalized {[MethodImpl(MethodImplOptions.AggressiveInlining)] get; } /// /// Returns the conjugate of the quaternion (negates the vector part). /// For a unit quaternion, the conjugate equals the inverse. /// public Quaternion Conjugate {[MethodImpl(MethodImplOptions.AggressiveInlining)] get; } /// /// Returns the inverse of the quaternion. /// For a unit quaternion, prefer which is faster. /// public Quaternion Inverse { get; } /// /// Creates a quaternion representing a rotation of radians /// around the given . /// /// The axis of rotation (should be normalized). /// The rotation angle in radians. [DebuggerStepThrough] public static Quaternion FromAxisAngle(Vector3 axis, float angle); /// /// Creates a quaternion from Euler angles (in radians) applied in /// Z (roll) → X (pitch) → Y (yaw) order (intrinsic rotations). /// /// Rotation around the X axis in radians. /// Rotation around the Y axis in radians. /// Rotation around the Z axis in radians. [DebuggerStepThrough] public static Quaternion FromEuler(float pitch, float yaw, float roll); /// /// Returns the dot product of two quaternions. /// [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Dot(Quaternion a, Quaternion b); /// /// Linearly interpolates between two quaternions and normalizes the result. /// /// The start quaternion at t = 0. /// The end quaternion at t = 1. /// The interpolation factor, typically in the range [0, 1]. [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Quaternion Lerp(Quaternion a, Quaternion b, float t); /// /// Performs spherical linear interpolation (Slerp) between two unit quaternions. /// Produces a constant-speed rotation along the shortest arc on the unit 4-sphere. /// /// The start rotation at t = 0. /// The end rotation at t = 1. /// The interpolation factor, typically in the range [0, 1]. [DebuggerStepThrough] public static Quaternion Slerp(Quaternion a, Quaternion b, float t); /// /// Multiplies two quaternions, composing their rotations. /// The result applies first, then . /// [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Quaternion operator *(Quaternion lhs, Quaternion rhs); /// /// Rotates a by this quaternion using the sandwich product: /// v' = q * v * q⁻¹. /// [DebuggerStepThrough] public static Vector3 operator *(Quaternion q, Vector3 v); /// /// Rotates a by this quaternion. /// [DebuggerStepThrough] public static Point3 operator *(Quaternion q, Point3 p); /// /// Converts this quaternion to an equivalent 4×4 rotation matrix. /// [DebuggerStepThrough] public Matrix4x4 ToMatrix4x4(); /// /// Decomposes this quaternion into Euler angles (pitch, yaw, roll) in radians. /// /// /// The angles are in the range [-π, π] for pitch, yaw, and roll. /// Gimbal lock may occur near the poles of pitch (±90°). /// [DebuggerStepThrough] public (float pitch, float yaw, float roll) ToEuler(); /// Returns true if two quaternions have equal components. [DebuggerStepThrough] public static bool operator ==(Quaternion lhs, Quaternion rhs); /// Returns true if any component of two quaternions differs. [DebuggerStepThrough] public static bool operator !=(Quaternion lhs, Quaternion rhs); /// /// Implicitly converts this quaternion to a /// for use with SIMD-accelerated operations. /// [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator System.Numerics.Quaternion(Quaternion q); /// /// Implicitly converts a to a . /// [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator Quaternion(System.Numerics.Quaternion q); /// Indicates whether this instance and a specified object are equal. /// The object to compare with the current instance. /// /// if and this instance are the same type and represent the same value; otherwise, . public override bool Equals(object? obj); /// Returns true if this quaternion equals another. public bool Equals(Quaternion other); /// Returns the hash code for this instance. /// A 32-bit signed integer that is the hash code for this instance. public override int GetHashCode(); /// Returns the fully qualified type name of this instance. /// The fully qualified type name. public override string ToString(); } /// /// Represents a 3D vector with X, Y, and Z components. /// Commonly used for geometric operations, physics, lighting, and 3D movement. /// /// /// The struct is laid out sequentially as three 32-bit floats (12 bytes), making it /// directly compatible with SIMD operations and GPU shader inputs. /// Use for hardware-accelerated batch processing. /// public struct Vector3 { /// The X component of the vector. public float X; /// The Y component of the vector. public float Y; /// The Z component of the vector. public float Z; /// /// Initializes a new with the specified components. /// /// The X component. /// The Y component. /// The Z component. [DebuggerStepThrough] public Vector3(float x, float y, float z); /// A zero vector (0, 0, 0). public static readonly Vector3 Zero; /// A unit vector (1, 1, 1). public static readonly Vector3 One; /// A unit vector pointing right along the positive X axis (1, 0, 0). public static readonly Vector3 Right; /// A unit vector pointing left along the negative X axis (-1, 0, 0). public static readonly Vector3 Left; /// A unit vector pointing up along the positive Y axis (0, 1, 0). public static readonly Vector3 Up; /// A unit vector pointing down along the negative Y axis (0, -1, 0). public static readonly Vector3 Down; /// /// A unit vector pointing forward along the negative Z axis (0, 0, -1) in a right-handed coordinate system. /// public static readonly Vector3 Forward; /// A unit vector pointing backward along the positive Z axis (0, 0, 1). public static readonly Vector3 Back; /// /// Returns a normalized (unit length) copy of this vector. /// Returns if the vector has zero magnitude. /// public Vector3 Normalized {[MethodImpl(MethodImplOptions.AggressiveInlining)] get; } /// /// Returns the magnitude (length) of the vector. /// public float Magnitude {[MethodImpl(MethodImplOptions.AggressiveInlining)] get; } /// /// Returns the squared magnitude of the vector, avoiding a square root computation. /// Useful for distance comparisons where the exact length is not needed. /// public float MagnitudeSquared {[MethodImpl(MethodImplOptions.AggressiveInlining)] get; } /// /// Returns the dot product of two vectors. /// /// The left-hand vector. /// The right-hand vector. [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Dot(Vector3 lhs, Vector3 rhs); /// /// Returns the cross product of two vectors. /// The result is a vector perpendicular to both inputs, /// with direction determined by the right-hand rule. /// /// The left-hand vector. /// The right-hand vector. [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Cross(Vector3 lhs, Vector3 rhs); /// /// Projects onto . /// Returns if has zero magnitude. /// /// The vector to project. /// The target direction vector. [DebuggerStepThrough] public static Vector3 Project(Vector3 lhs, Vector3 rhs); /// /// Reflects the across the given surface . /// The normal is assumed to be unit length. /// /// The incident vector to reflect. /// The surface normal (should be normalized). [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Reflect(Vector3 vector, Vector3 normal); /// /// Returns the angle in radians between two vectors. /// Returns 0 if either vector has zero magnitude. /// /// The first vector. /// The second vector. [DebuggerStepThrough] public static float Angle(Vector3 lhs, Vector3 rhs); /// /// Linearly interpolates between two vectors by the factor . /// /// The start vector at t = 0. /// The end vector at t = 1. /// The interpolation factor, typically in the range [0, 1]. [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Lerp(Vector3 start, Vector3 end, float t); /// /// Returns the component-wise minimum of two vectors. /// [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Min(Vector3 lhs, Vector3 rhs); /// /// Returns the component-wise maximum of two vectors. /// [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Max(Vector3 lhs, Vector3 rhs); /// Adds two vectors. [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 operator +(Vector3 lhs, Vector3 rhs); /// Subtracts one vector from another. [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 operator -(Vector3 lhs, Vector3 rhs); /// Negates a vector. [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 operator -(Vector3 v); /// Multiplies a vector by a scalar. [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 operator *(Vector3 v, float f); /// Multiplies a scalar by a vector. [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 operator *(float f, Vector3 v); /// Divides a vector by a scalar. [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 operator /(Vector3 v, float f); /// Multiplies two vectors component-wise. [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 operator *(Vector3 lhs, Vector3 rhs); /// Returns true if two vectors have equal components. [DebuggerStepThrough] public static bool operator ==(Vector3 lhs, Vector3 rhs); /// Returns true if any component of two vectors differs. [DebuggerStepThrough] public static bool operator !=(Vector3 lhs, Vector3 rhs); /// Implicitly converts a tuple to a . [DebuggerStepThrough] public static implicit operator Vector3((float x, float y, float z) t); /// Implicitly converts a to a . [DebuggerStepThrough] public static implicit operator Vector3(Point3 p); /// /// Implicitly converts this vector to a /// for use with SIMD-accelerated operations. /// [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator System.Numerics.Vector3(Vector3 v); /// /// Implicitly converts a to a . /// [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator Vector3(System.Numerics.Vector3 v); /// Indicates whether this instance and a specified object are equal. /// The object to compare with the current instance. /// /// if and this instance are the same type and represent the same value; otherwise, . public override bool Equals(object? obj); /// Returns true if this vector equals another . public bool Equals(Vector3 other); /// Returns the hash code for this instance. /// A 32-bit signed integer that is the hash code for this instance. public override int GetHashCode(); /// Returns the fully qualified type name of this instance. /// The fully qualified type name. public override string ToString(); } } namespace Xui.Core.Memory { using System.Buffers; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; /// /// Low-allocation interpolated string handler for building text in a stack-first inline buffer, /// spilling to a rented array only when the text exceeds 256 characters. /// [InterpolatedStringHandler] public ref struct FillTextInterpolatedStringHandler { /// Initializes the handler and allocates or rents a buffer of the appropriate size. /// Total character count of all literal string segments. /// Number of interpolated holes in the string. public FillTextInterpolatedStringHandler(int literalLength, int formattedCount); /// Appends a literal string segment to the buffer. public void AppendLiteral(string s); /// Appends a span-formattable value using its default format. public void AppendFormatted(T value) where T : ISpanFormattable; /// Appends a span-formattable value using the specified format string. public void AppendFormatted(T value, ReadOnlySpan format) where T : ISpanFormattable; /// Appends a span-formattable value with the specified alignment width. public void AppendFormatted(T value, int alignment) where T : ISpanFormattable; /// Appends a span-formattable value with the specified format and alignment width. public void AppendFormatted(T value, int alignment, ReadOnlySpan format) where T : ISpanFormattable; /// Appends a of characters directly. public void AppendFormatted(ReadOnlySpan value); /// Appends a string value. public void AppendFormatted(string? value); /// Appends any object by calling ToString(). public void AppendFormatted(object? value); /// Returns the currently accumulated characters as a read-only span. public readonly ReadOnlySpan AsSpan(); /// Returns any rented array buffer back to the pool. public void Dispose(); } } namespace Xui.Core.Middleware { /// /// Represents a middleware-level window that bridges both the abstract UI model and the platform-specific window implementation. /// /// /// This interface unifies and , enabling a single component to mediate input, rendering, /// and lifecycle events between the platform and the UI framework. It is commonly used in emulators, testing layers, or composition hosts /// that need to intercept and control both sides of the window stack. /// public interface IWindow : Actual.IWindow, Abstract.IWindow { } /// /// Provides traversal helpers for the abstract side of a composed window chain. /// public static class WindowCompositionExtensions { /// /// Returns the first desktop style found from a native window's paired abstract /// side towards the application window. Middleware can override the application /// style by implementing itself. /// public static Abstract.IWindow.IDesktopStyle? GetDesktopStyle(this Abstract.IWindow window); /// /// Returns the first macOS window style found from a native window's paired /// abstract side towards the application window. Middleware can override the /// application style by implementing itself. /// public static Abstract.IMacOSWindowStyle? GetMacOSWindowStyle(this Abstract.IWindow window); } } namespace Xui.Core.Set { /// /// Represents an empty set — a set that contains no elements. /// /// The type of elements the set could (but does not) contain. /// /// This type always returns false from . It is a useful identity for /// set composition and for scenarios like default hit test areas or disabled regions. /// public sealed class EmptySet : INonEnumerableSet { /// /// A shared singleton instance of the empty set. /// public static readonly EmptySet Instance; /// /// Always returns false, since no element belongs to the empty set. /// /// The object to test. /// /// false for all inputs. public bool Contains(T obj); } /// /// Represents a mathematical set as defined by its membership test: /// whether an element belongs to the set. /// /// The type of elements being tested for membership. /// /// This interface does not imply enumeration, mutation, or collection semantics. /// It aligns with the pure set-theoretic notion where a set is characterized solely /// by the ability to determine if a value is a member of the set (i.e., x ∈ S). /// public interface INonEnumerableSet { /// /// Determines whether the specified element is a member of this set. /// /// The element to test for membership. /// /// true if the element belongs to the set; otherwise, false. public bool Contains(T obj); } } namespace Xui.Core.UI { using Xui.Core.Math2D; /// Immutable input to an arrangement operation. public readonly struct ArrangeConstraints { /// Initializes arrangement constraints. public ArrangeConstraints(Size availableSize, Size desiredSize, Point anchor, LayoutSizeMode xSize = LayoutSizeMode.Exact, LayoutSizeMode ySize = LayoutSizeMode.Exact, LayoutAlign xAlign = LayoutAlign.Start, LayoutAlign yAlign = LayoutAlign.Start); /// Available margin-box size. public Size AvailableSize { get; } /// Desired margin-box size from measurement. public Size DesiredSize { get; } /// Reference point for alignment. public Point Anchor { get; } /// Horizontal sizing mode. public LayoutSizeMode XSize { get; } /// Vertical sizing mode. public LayoutSizeMode YSize { get; } /// Horizontal anchor alignment. public LayoutAlign XAlign { get; } /// Vertical anchor alignment. public LayoutAlign YAlign { get; } } /// /// A transient in-window overlay acquired via GetService<IOverlay>(). /// Rendered by on top of all other content — no native window is created. /// Works on every platform (Windows, macOS, iOS, Android, Browser) with no platform-specific code. /// /// /// Use this for cross-platform scenarios: mobile, simulators, web/SPA, or /// in-app surfaces like top-of-screen search fields that must stay within the window. /// For native OS-level popups that can extend outside the app window, /// use instead. /// /// Usage pattern: /// /// var overlay = this.GetService<IOverlay>(); /// overlay.Show(content, anchorRect, PopupPlacement.Below); /// /// The overlay auto-dismisses when the user clicks outside. /// Disposing the overlay closes it if still visible. /// public interface IOverlay : IDisposable { /// /// Shows the overlay with the given content, positioned relative to /// (in the owning window's coordinate space). /// /// The view to display inside the overlay. /// /// The rect of the triggering element in window coordinates. /// Used to position the overlay (for example, below a button). /// /// Preferred placement direction. /// /// Desired overlay size. If null, a default size is used. /// /// Visual backdrop effect (reserved for future use). void Show(View content, Rect anchorRect, PopupPlacement placement = PopupPlacement.Below, Size? size = null, PopupEffect effect = PopupEffect.None); /// Closes the overlay if visible. void Close(); /// Whether the overlay is currently visible. bool IsVisible { get; } /// Raised when the overlay is dismissed (click-outside, explicit close, or parent window close). event Action? Closed; } /// /// A transient native popup surface acquired via GetService<IPopup>(). /// Each call returns a new instance backed by a platform-specific child window, /// which can extend beyond the parent window bounds. /// /// /// Available on platforms that support native popups (Windows, macOS). /// For cross-platform in-window overlays that work on all platforms including /// mobile, web, and simulators, use instead. /// /// Usage pattern (similar to ): /// /// var popup = this.GetService<IPopup>(); /// popup.Show(content, anchorRect, PopupPlacement.Below); /// /// The popup auto-dismisses when the user clicks outside. /// Disposing the popup closes it if still visible. /// public interface IPopup : IDisposable { /// /// Shows the popup with the given content, positioned relative to /// (in the owning window's coordinate space). /// /// The view to display inside the popup. /// /// The rect of the triggering element in window coordinates. /// The platform uses this to position the popup so that (for example) /// a selected item aligns with the anchor text. /// /// Preferred placement direction. /// /// Desired popup size. If null, the platform falls back to a default size. /// /// Visual backdrop effect to apply to the popup window. void Show(View content, Rect anchorRect, PopupPlacement placement = PopupPlacement.Below, Size? size = null, PopupEffect effect = PopupEffect.None); /// Closes the popup if visible. void Close(); /// Whether the popup is currently visible. bool IsVisible { get; } /// Raised when the popup is dismissed (click-outside, explicit close, or parent window close). event Action? Closed; } /// /// Per-view results written by an update. The caller owns this value and passes it by reference, /// so sibling updates cannot share or overwrite one another's results. /// public struct LayoutMeasurements { /// Desired margin-box size produced by measurement. public Size DesiredSize; /// Final border-edge rectangle produced by arrangement. public Rect ArrangedRect; } /// Immutable input to a measurement operation. public readonly struct MeasureConstraints { /// Initializes measurement constraints. public MeasureConstraints(Size availableSize, LayoutSizeMode xSize = LayoutSizeMode.AtMost, LayoutSizeMode ySize = LayoutSizeMode.AtMost); /// Available margin-box size. public Size AvailableSize { get; } /// Horizontal sizing mode. public LayoutSizeMode XSize { get; } /// Vertical sizing mode. public LayoutSizeMode YSize { get; } } /// /// Base class for all UI elements in the Xui layout engine. /// A view participates in layout, rendering, and input hit testing, and may contain child views. /// /// /// Base class for all UI elements in the Xui layout engine. /// A view participates in layout, rendering, and input hit testing, and may contain child views. /// public partial class View { /// /// Gets this view's conservative bounds in its parent coordinate space for render culling. /// /// /// A container may override this when its rendered geometry differs from its layout frame. /// Computing the union of descendant culling frames is deliberately deferred: it can be /// more expensive than rendering for small subtrees. /// public virtual Rect CullingFrame { get; } /// /// Maps a point from this view's parent coordinate space into this view's local coordinate space. /// /// /// Layout still supplies frames using the existing coordinate model. The default identity /// mapping deliberately preserves that behaviour until a container opts into a local /// coordinate transform. Containers such as can override this /// to map input into their content space. /// public virtual Point TransformPoint(Point point); /// /// Maps a point from this view's local coordinate space into its parent coordinate space. /// /// /// This must be the inverse of for points that can be hit /// tested. It is separate so a view can support coordinate mappings that are not yet /// represented by the canvas transform API. /// public virtual Point InverseTransformPoint(Point point); /// /// Conservatively maps an axis-aligned rectangle from this view's parent coordinate space /// into this view's coordinate space. /// /// /// For non-translation transforms, an override must return the smallest parent-axis-aligned /// rectangle that encloses every transformed corner. /// public virtual Rect TransformRect(Rect rect); /// /// Conservatively maps an axis-aligned rectangle from this view's coordinate space into its /// parent coordinate space. /// /// /// For non-translation transforms, an override must return the smallest parent-axis-aligned /// rectangle that encloses every transformed corner. /// public virtual Rect InverseTransformRect(Rect rect); /// /// Maps a point in this view's local coordinate space into root/window coordinate space. /// public Point LocalToGlobal(Point point); /// /// Maps a point in root/window coordinate space into this view's local coordinate space. /// public Point GlobalToLocal(Point point); } /// /// Base class for all UI elements in the Xui layout engine. /// A view participates in layout, rendering, and input hit testing, and may contain child views. /// /// /// Base class for all UI elements in the Xui layout engine. /// A view participates in layout, rendering, and input hit testing, and may contain child views. /// public partial class View { /// /// An optional unique identifier for this view, used for lookup via /// . /// public string? Id { get; set; } /// /// The set of class names assigned to this view, used for lookup via /// . /// public ClassNameCollection ClassName; /// /// The parent view in the visual hierarchy. This is set automatically when the view is added to a container. /// public View? Parent { get; } /// /// The border edge of this view in global coordinates relative to the top-left of the window. /// public Rect Frame { get; protected set; } /// Gets or sets the external spacing around the view. public Frame Margin { get; set; } /// Gets or sets the horizontal alignment within the layout anchor region. public HorizontalAlignment HorizontalAlignment { get; set; } /// Gets or sets the vertical alignment within the layout anchor region. public VerticalAlignment VerticalAlignment { get; set; } /// Gets or sets the writing direction. public Direction Direction { get; set; } /// Gets or sets the writing mode. public WritingMode WritingMode { get; set; } /// Gets or sets the child flow behavior. public Flow Flow { get; set; } /// Gets or sets the minimum border-edge width. public nfloat MinimumWidth { get; set; } /// Gets or sets the minimum border-edge height. public nfloat MinimumHeight { get; set; } /// Gets or sets the maximum border-edge width. public nfloat MaximumWidth { get; set; } /// Gets or sets the maximum border-edge height. public nfloat MaximumHeight { get; set; } /// /// Determines whether the given point (in this view's local coordinates) hits this view's visual bounds. /// Used for input dispatch and hit testing. /// /// The point to test, relative to this view's coordinate space. /// /// true if the point is inside the view's frame; otherwise false. public virtual bool HitTest(Point point); } } namespace Xui.Core.UI { using Xui.Core.Debug; /// /// Passed to when a view is added to the visual tree. /// Carries tree-wide shared resources (e.g. instrumentation) down the DFS walk so /// every view in the subtree receives them without per-view service lookups. /// public ref struct AttachEventRef { /// /// Instrumentation sink for the visual tree. Views receive this during attach /// and store it so invalidation methods (e.g. , /// ) can log consistently with the /// render-surface instrumentation carried by . /// public InstrumentsAccessor Instruments; /// Initializes a new . public AttachEventRef(); } /// /// Base class for all UI elements in the Xui layout engine. /// A view participates in layout, rendering, and input hit testing, and may contain child views. /// /// /// Base class for all UI elements in the Xui layout engine. /// A view participates in layout, rendering, and input hit testing, and may contain child views. /// public partial class View { /// /// Flags used internally by a to track invalidation state across /// measure, arrangement, rendering, and hit testing phases. /// These flags allow the framework to selectively recompute only dirty subtrees /// during recursive passes. /// [Flags] public enum ViewFlags { /// /// This view is animated. /// It has properties that are calculated based on the current UI time. /// It requires an animation notification on the next frame. /// Animated = 1 << 0, /// /// This view has animated children. /// While this view directly does not depend on the next frame time, /// it must propagate an animation notification to its animated children. /// DescendantAnimated = 1 << 1, /// /// The has changed since its last measure. /// It will likely return a different desired size if measured again /// with the same constraints. /// MeasureChanged = 1 << 2, /// /// The has changed in a way that may cause it to arrange /// its children differently, even if the available rectangle and measure /// context are the same. /// ArrangeChanged = 1 << 3, /// /// One or more descendants of this have had their /// flag set since the last validation. /// This flag does not indicate that this view itself needs re-arranging, /// but rather that some descendant may need to be re-arranged with its /// existing rectangle (e.g., a visual state change that affects only /// internal layout). /// DescendantArrangeChanged = 1 << 4, /// /// The has changed visually since its last render pass, /// and produce different output even if rendered within the same frame and context. /// RenderChanged = 1 << 5, /// /// One or more descendants of this have had their /// flag set since the last validation. /// This is a hint that rendering work exists below, even if this view itself /// does not need re-rendering. /// DescendantRenderChanged = 1 << 6, /// /// This view's changed. /// It will probably return a new results for the same . /// HitTestChanged = 1 << 7, /// /// One or more descendants of this have their hit testing changed. /// They will probably return a new result for the same . /// DescendantHitTestChanged = 1 << 8, /// /// This view is active — it is part of a live visual tree and will receive /// events, render, and animate. Set by and /// cleared by . /// Active = 1 << 9, /// /// This view is attached — it has been added to a visual tree that is itself /// attached to the platform (e.g. a window). Set by /// and cleared by . /// Attached = 1 << 10, } /// /// Gets the current change flags for this view. These flags indicate which /// aspects (measure, arrange, render, hit test) have changed since the last /// time the parent acknowledged them via the corresponding Validate* method. /// public ViewFlags Flags { get; } /// Whether graphics changed, or this view last rendered into a different context. /// Use when declaring a retained child surface before calling the child's Render method. public bool RequiresRender(Xui.Core.Canvas.IContext context); /// /// Whether this view or its descendants have graphics updates for the current render. /// Unlike Flags, this remains available inside RenderCore after the render shell clears /// the incoming invalidation flags. Suitable for GroupOptions.HasUpdates; the context /// still decides whether content must be drawn, including on first use or SVG export. /// protected bool HasRenderUpdates { get; } /// /// Invalidates every phase affected by a change to the view's layout contract. /// Used by the base layout properties so cached measurements cannot survive a /// change to constraints, alignment, or spacing. /// protected void Invalidate(); /// /// Assigns a layout-affecting property when its value changes, then invalidates /// the view's measure, arrange, and render state. /// /// /// true when changed. protected bool SetViewProperty(ref T field, T value); /// Assigns a render-only property when its value changes. /// /// true when changed. protected bool SetViewRenderProperty(ref T field, T value); /// /// Requests another animation frame for this view on the next UI tick. /// Sets and notifies ancestors (via /// ) so they carry /// . /// public void RequestAnimationFrame(); /// /// Called when a direct or indirect child has requested another animation frame /// for the next UI tick. The default implementation marks /// and forwards the notification up /// the visual tree. /// /// The child view that requested the animation frame. protected virtual void OnChildRequestedAnimationFrame(View child); /// /// Marks this view as having changed in a way that may affect its measured size. /// Causes to be invoked on the parent. /// public void InvalidateMeasure(); /// /// Marks this view as having changed in a way that may cause it to arrange its /// children differently, even with the same rectangle and context. /// Causes to be invoked on the parent. /// protected void InvalidateArrange(); /// /// Marks this view as having changed visually in a way that requires re-rendering. /// Causes to be invoked on the parent. /// public void InvalidateRender(); /// /// Marks this view as having changed in a way that may cause hit testing to yield /// different results, even for the same input coordinates. /// Causes to be invoked on the parent. /// protected void InvalidateHitTest(); /// /// Clears the flag on this view, indicating that /// a parent or container has acknowledged the child’s measure change and handled it /// (e.g., decided to keep the same column width in a grid regardless of the child’s new desired size). /// Use this when the parent has considered the change and no re-measure is required for this child. /// public void ValidateMeasure(); /// /// Clears the flag on this view, indicating that /// a parent or container has acknowledged the child’s arrange change. /// public void ValidateArrange(); /// /// Clears the flag on this view, indicating that /// the parent (or the rendering pipeline) has acknowledged the visual change and /// re-rendering for this view has been completed. /// public void ValidateRender(); /// /// Clears the flag on this view, indicating that /// hit-test caches (if any) have been updated or the parent has otherwise accounted for /// the changed hit-test behavior. /// public void ValidateHitTest(); /// /// Called when a direct or indirect child view has changed in a way that may /// affect its measured size. The default implementation forwards the notification /// up the visual tree to the parent. /// /// The child view whose measure state has changed. protected virtual void OnChildMeasureChanged(View child); /// /// Called when a direct or indirect child view has changed in a way that may /// affect its arrangement of children. The default implementation forwards the /// notification up the visual tree to the parent. /// /// The child view whose arrange state has changed. protected virtual void OnChildArrangeChanged(View child); /// /// Called when a direct or indirect child view has changed visually and requires /// re-rendering. The default implementation forwards the notification up the visual tree. /// /// The child view whose render state has changed. protected virtual void OnChildRenderChanged(View child); /// /// Called when a direct or indirect child view has changed in a way that may cause /// hit testing results to change. The default implementation forwards the notification /// up the visual tree to the parent. /// /// The child view whose hit testing state has changed. protected virtual void OnChildHitTestChanged(View child); /// /// Captures the pointer with the specified identifier so that it continues to /// receive pointer events even if the pointer moves outside its bounds. /// /// The platform-assigned pointer identifier. /// /// Optional marker describing what kind of gesture this view is tracking /// (e.g. for a button, /// for a slider). Ancestor /// containers (e.g. ScrollView) inspect this via /// EventRouter.GetCapturedGesture to decide whether they may steal capture. /// public void CapturePointer(int pointerId, Xui.Core.UI.Input.IPointerGesture? gesture = null); /// /// Releases a previously captured pointer so that pointer events are routed /// according to normal hit testing rules. /// /// The platform-assigned pointer identifier. public void ReleasePointer(int pointerId); /// /// Returns the gesture marker for the view currently capturing /// , or null if the pointer is not captured /// or was captured without a gesture marker. /// public Xui.Core.UI.Input.IPointerGesture? GetCapturedGesture(int pointerId); } } namespace Xui.Core.UI { using Xui.Core.Canvas; using Xui.Core.Math2D; using Xui.Core.UI.Layer; /// /// A view that draws a background, border, and padding around a single child content view. /// All rendering is owned by composed with /// . The child view lives in Layer.Child.Child and is /// managed via the standard lifecycle. /// public class Border : LayerView> { /// Gets or sets the content view displayed inside the border. public View? Content { get; set; } /// Gets or sets the per-side border thickness. public Frame BorderThickness { get; set; } /// Gets or sets the corner radius. public CornerRadius CornerRadius { get; set; } /// Gets or sets the background fill color. public Color BackgroundColor { get; set; } /// Gets or sets the border stroke color. public Color BorderColor { get; set; } /// Gets or sets the padding between the border edge and the content. public Frame Padding { get; set; } /// /// Returns the number of child views. Used by layout containers and traversal logic. /// Leaf views should return 0. /// public override int Count { get; } /// /// Indexer to access child views by index. /// Layout containers should implement this to expose their children. /// public override View this[int index] { get; } } } namespace Xui.Core.UI { using System.Collections; /// /// A compact collection of CSS-like class name strings for a view. /// Stores up to 3 class names inline without allocation. If more are added, /// spills over into a . /// public struct ClassNameCollection : IEnumerable { /// /// Returns the number of class names in the collection. /// public readonly int Count { get; } /// /// Returns true if the collection contains the specified class name. /// public readonly bool Contains(string className); /// /// Adds a class name to the collection. Returns true if it was added (not already present). /// public bool Add(string className); /// /// Removes a class name from the collection. Returns true if it was found and removed. /// public bool Remove(string className); /// Adds a class name to the collection and returns the updated collection. public static ClassNameCollection operator +(ClassNameCollection collection, string className); /// Removes a class name from the collection and returns the updated collection. public static ClassNameCollection operator -(ClassNameCollection collection, string className); /// Returns an enumerator that iterates over all class names in the collection. public readonly IEnumerator GetEnumerator(); } } namespace Xui.Core.UI { /// /// Passed to when a view is removed from the visual tree. /// public ref struct DetachEventRef { /// Initializes a new . public DetachEventRef(); } /// /// Indicates the semantic inline direction of content, such as left-to-right or right-to-left. /// Used to resolve text alignment, layout flow, and mirroring behavior. /// public enum Direction : byte { /// /// Inherit direction from the parent view. /// Inherit = 0, /// /// Left-to-right flow (default for Western languages). /// LeftToRight = 1, /// /// Right-to-left flow (used in Arabic, Hebrew, etc). /// RightToLeft = 2 } /// /// Controls whether layout and rendering should respect directionality and writing mode. /// Used to suppress mirroring and bidi-aware behavior for diagrams, graphs, and non-linguistic views. /// public enum Flow : byte { /// /// Inherit flow behavior from the parent view. /// Inherit = 0, /// /// Enable direction-aware and writing-mode-aware behavior. /// Aware = 1, /// /// Disable all direction-aware layout and rendering. Used for charts, maps, etc. /// Unaware = 2 } /// /// Represents the resolved physical direction of layout flow along an axis. /// This is derived from and , /// and is used to control stacking, alignment, and layout flow along block or inline axes. /// public enum FlowDirection : byte { /// /// Content flows from left to right. /// LeftToRight = 0, /// /// Content flows from right to left. /// RightToLeft = 1, /// /// Content flows from top to bottom. /// TopToBottom = 2, /// /// Content flows from bottom to top. /// BottomToTop = 3 } /// /// Specifies how a view should be aligned horizontally within its layout bounds. /// Used by parent containers during layout to position the view along the inline axis. /// public enum HorizontalAlignment : byte { /// /// Stretch to fill the full available horizontal space. /// Stretch = 0, /// /// Align to the left edge (or start edge in LTR layouts). /// Left = 1, /// /// Center horizontally within the available space. /// Center = 2, /// /// Align to the right edge (or start edge in RTL layouts). /// Right = 3 } /// /// Service interface for programmatic focus navigation. /// Resolved via this.GetService<IFocus>() from any . /// provides the default implementation. /// public interface IFocus { /// Moves focus to the next focusable element (same order as Tab). void Next(); /// Moves focus to the previous focusable element (same order as Shift+Tab). void Previous(); /// Returns the next focusable view without moving focus. Does not wrap by default. View? GetNext(bool wrap = false); /// Returns the preceding focusable view without moving focus. Does not wrap by default. View? GetPrevious(bool wrap = false); /// /// Gets or sets the view that currently holds keyboard focus. /// Setting to null clears focus. Setting fires / /// on the affected views. /// View? FocusedView { get; set; } } /// Declares whether root content supplies an opaque background for the entire window. /// /// This is a coverage promise, not a layout hint. Return true only when every draw /// covers the whole display area with opaque pixels. Hosts may skip their clear. /// Wrappers must forward the promise explicitly, and changes must invalidate the view. /// public interface IFullScreenView { /// Whether the current state paints the whole display area opaquely. bool DrawsOpaqueFullScreen { get; } } /// Defines an anchor alignment on one layout axis. public enum LayoutAlign : byte { /// Align to the start edge. Start, /// Align to the center. Center, /// Align to the end edge. End, } /// Passes that may be requested during a render-surface update. [Flags] public enum LayoutPass : byte { /// Advance time-based state. Animate = 1 << 0, /// Measure desired size. Measure = 1 << 1, /// Arrange final frame. Arrange = 1 << 2, /// Render the view. Render = 1 << 3, } /// Defines how an axis participates in a layout pass. public enum LayoutSizeMode : byte { /// The view must exactly match the available size. Exact, /// The view may size to content without exceeding the available size. AtMost, } /// Pass selection and per-pass immutable constraints for one view update. public readonly struct LayoutUpdate { /// Initializes a layout update. public LayoutUpdate(LayoutPass pass, MeasureConstraints measure, ArrangeConstraints arrange); /// Requested passes. public LayoutPass Pass { get; } /// Measurement constraints. public MeasureConstraints Measure { get; } /// Arrangement constraints. public ArrangeConstraints Arrange { get; } /// Whether animation is requested. public bool IsAnimate { get; } /// Whether measurement is requested. public bool IsMeasure { get; } /// Whether arrangement is requested. public bool IsArrange { get; } /// Whether rendering is requested. public bool IsRender { get; } } /// /// Controls the visual backdrop material of a popup surface. /// Mirrors /// for popup-specific use. /// public enum PopupEffect { /// /// Standard opaque popup with no translucency. /// None = 0, /// /// Translucent popup using the system's standard popup/popover material. /// On macOS this uses NSVisualEffectView with the Popover material, /// which on macOS 26+ automatically gains the liquid-glass treatment. /// Translucent = 1, } /// /// Specifies the preferred placement of a popup relative to its anchor rect. /// The platform may adjust placement to keep the popup on screen. /// public enum PopupPlacement { /// Show below the anchor (default for dropdowns/comboboxes). Below, /// Show above the anchor. Above, /// Show to the right of the anchor (e.g. nested/submenu). Right, /// Show to the left of the anchor. Left, } /// /// Specifies how a view should be aligned vertically within its layout bounds. /// Used by parent containers to control vertical positioning along the block axis. /// public enum VerticalAlignment : byte { /// /// Stretch to fill the full available vertical space. /// Stretch = 0, /// /// Align to the top edge (or start edge in top-down layouts). /// Top = 1, /// /// Center vertically within the available space. /// Middle = 2, /// /// Align to the bottom edge (or start edge in bottom-up layouts). /// Bottom = 3 } /// /// Base class for all UI elements in the Xui layout engine. /// A view participates in layout, rendering, and input hit testing, and may contain child views. /// /// /// Base class for all UI elements in the Xui layout engine. /// A view participates in layout, rendering, and input hit testing, and may contain child views. /// public partial class View : IServiceProvider, Layer.ILayerHost { /// /// Resolves a service of the given type by walking up the parent chain. /// Returns null if no ancestor provides the service. /// public virtual object? GetService(Type serviceType); } /// /// Base class for all UI elements in the Xui layout engine. /// A view participates in layout, rendering, and input hit testing, and may contain child views. /// /// /// Base class for all UI elements in the Xui layout engine. /// A view participates in layout, rendering, and input hit testing, and may contain child views. /// public partial class View { /// Gets or sets an extra on this view. public nint this[Extra key] { get; set; } /// Gets or sets an extra on this view. public nfloat this[Extra key] { get; set; } /// Gets or sets a extra on this view. public string? this[Extra key] { get; set; } /// Gets or sets a extra on this view. public bool this[Extra key] { get; set; } /// /// Fallback indexer for extras whose value type is not covered by a typed overload (e.g. enums). /// Values are boxed. Prefer the typed overloads for , , /// , and where possible. /// public object? this[Extra key] { get; set; } /// /// Non-generic base for . Used as a dictionary key when storage is implemented. /// public abstract class Extra { } /// /// A typed key for attaching extra layout or styling data to any . /// Declare one static instance per logical property (e.g. Grid.Row, FlexBox.Grow) /// and use it with the view indexer: view[Grid.Row] = 2. /// /// The type of the value stored under this key. public sealed class Extra : Extra { /// The value returned when no data has been stored for this key on a given view. public T DefaultValue { get; } /// Returned by the indexer getter until a value is explicitly set. public Extra(T defaultValue = default !); /// /// Returns the value stored for this key on , /// or if nothing has been set. /// public T Get(View view); } } /// /// Base class for all UI elements in the Xui layout engine. /// A view participates in layout, rendering, and input hit testing, and may contain child views. /// /// /// Base class for all UI elements in the Xui layout engine. /// A view participates in layout, rendering, and input hit testing, and may contain child views. /// public partial class View { /// /// Returns the number of child views. Used by layout containers and traversal logic. /// Leaf views should return 0. /// public virtual int Count { get; } /// /// Indexer to access child views by index. /// Layout containers should implement this to expose their children. /// public virtual View this[int index] { get; } /// /// Attaches a child view to this parent, setting Parent and performing basic validation. /// Intended for internal use by container views and single-child hosts. /// protected void AddProtectedChild(View child); /// /// Detaches a child view from this parent, clearing Parent. /// Intended for internal use by container views and single-child hosts. /// protected void RemoveProtectedChild(View child); /// /// Sets a single protected child field, automatically detaching the old child (if any) /// and attaching the new child (if any). Use this for single-child containers. /// protected void SetProtectedChild(ref T? field, T? value) where T : View; } /// /// Base class for all UI elements in the Xui layout engine. /// A view participates in layout, rendering, and input hit testing, and may contain child views. /// /// /// Base class for all UI elements in the Xui layout engine. /// A view participates in layout, rendering, and input hit testing, and may contain child views. /// public partial class View { /// /// Called when this view is added to the visual tree and platform contexts become available. /// Override to acquire resources that depend on text measurement or bitmap factories. /// protected virtual void OnAttach(ref AttachEventRef e); /// /// Called when this view is removed from the visual tree. /// Override to release any resources acquired in . /// protected virtual void OnDetach(ref DetachEventRef e); /// /// Called when this view becomes active — it will receive events, render, and animate. /// Override this to start animations, subscribe to data sources, or acquire resources. /// protected virtual void OnActivate(); /// /// Called when this view becomes dormant — it should stop animations, timers, and event subscriptions. /// The view may remain in the tree (e.g., in a virtualizing panel's recycle pool). /// protected virtual void OnDeactivate(); } /// /// Specifies the orientation and flow direction of text and block layout. /// Affects which axis is considered "block" and "inline". /// public enum WritingMode : byte { /// /// Inherit direction from the parent view. /// Inherit, /// /// Horizontal writing mode. Text flows left-to-right, lines stack top-to-bottom. /// HorizontalTB, /// /// Vertical writing mode. Lines stack right-to-left, text flows top-to-bottom. /// VerticalRL, /// /// Vertical writing mode. Lines stack left-to-right, text flows top-to-bottom. /// VerticalLR, /// /// Sideways vertical mode. Lines stack right-to-left, but glyphs are rotated to remain horizontal. /// SidewaysRL, /// /// Sideways vertical mode. Lines stack left-to-right, with horizontal glyph orientation. /// SidewaysLR } } namespace Xui.Core.UI { using Xui.Core.Canvas; using Xui.Core.Math2D; /// /// A layout container that arranges its children horizontally from left to right. /// /// Each child is measured with unconstrained width and a constrained height. /// The container expands to fit the combined width of all children. /// public class HorizontalStack : ViewCollection { /// Override to compute the desired border-edge size. protected override Size MeasureCore(Size availableBorderEdgeSize, IMeasureContext context); /// Override to arrange children within this view's final frame. protected override void ArrangeCore(Rect rect, IMeasureContext context); } /// /// A layout container that arranges its children in a horizontal stack, /// assigning each child the same width. /// /// /// /// If the parent provides a constrained width, the container divides /// the available width equally among all children. /// /// /// If the width is unconstrained (infinite), the container measures each child /// to determine the maximum width, and assigns that uniform width to all columns. /// /// /// The height of the container is based on the tallest child. /// /// public class HorizontalUniformStack : ViewCollection { /// /// Measures the desired size of this layout container and its children, /// based on the available space provided by the parent. /// /// /// The space available for layout, excluding padding and borders. /// /// The measure context used for child measurement. /// /// The desired size of this container based on its layout strategy. /// protected override Size MeasureCore(Size availableBorderEdgeSize, IMeasureContext context); /// Override to arrange children within this view's final frame. protected override void ArrangeCore(Rect rect, IMeasureContext context); } /// /// A view that displays a single line of styled text. /// public class Label : View { /// /// Gets or sets the text content displayed by the label. /// public string Text { get; set; } /// /// Gets or sets the color used to fill the text. /// public Color TextColor { get; set; } /// Gets or sets the complete font used for text measurement and rendering. public Font Font { get; set; } /// Gets or sets the font family used for rendering the text. public string FontFamily { get; set; } /// /// Gets or sets the font size in points. /// public nfloat FontSize { get; set; } /// /// Gets or sets the font style (e.g., normal, italic, oblique). /// public FontStyle FontStyle { get; set; } /// /// Gets or sets the font weight (e.g., normal, bold, numeric weight). /// public FontWeight FontWeight { get; set; } /// /// Gets or sets the font stretch (e.g., condensed, semi-expanded etc.). /// public FontStretch FontStretch { get; set; } /// /// Gets or sets the line height of the text, in user units. /// /// /// If set to a numeric value, this value overrides the default line height computation from the font metrics. /// If set to , the line height will be automatically computed based on the font's ascender, /// descender, and line gap, or fallback to a platform-specific multiplier of the (typically 1.2×). /// public nfloat LineHeight { get; set; } /// Override to compute the desired border-edge size. protected override Size MeasureCore(Size availableBorderEdgeSize, IMeasureContext context); /// Override to render this view and its children. protected override void RenderCore(IContext context); } /// /// A layout container that arranges its children vertically from top to bottom. /// /// Each child is measured with an unconstrained height and is allowed to take up as much vertical space as needed. /// The container expands to fit the combined height of all children. /// public class VerticalStack : ViewCollection { /// Override to compute the desired border-edge size. protected override Size MeasureCore(Size availableBorderEdgeSize, IMeasureContext context); /// Override to arrange children within this view's final frame. protected override void ArrangeCore(Rect rect, IMeasureContext context); } /// /// A layout container that arranges its children in a vertical stack, /// giving each child the same height. /// /// /// /// If the parent provides a constrained height, the container divides /// the available height equally among all children. /// /// /// If the height is unconstrained (infinite), the container measures each child /// to determine the maximum height, and uses that height for all rows. /// /// public class VerticalUniformStack : ViewCollection { /// Override to compute the desired border-edge size. protected override Size MeasureCore(Size availableBorderEdgeSize, IMeasureContext context); /// Override to arrange children within this view's final frame. protected override void ArrangeCore(Rect rect, IMeasureContext context); } /// /// A base class for container views that hold and manage a list of child views. /// Provides methods for adding, removing, rendering, and hit testing children. /// public class ViewCollection : View { /// /// The internal list of child views contained within this view. /// protected readonly List children; /// /// Gets the number of child views in this collection. /// public override int Count { get; } /// /// Gets the child view at the specified index. /// public override View this[int index] { get; } /// /// Adds the provided views to this container during object initialization. /// This property is intended for use with C# object initializers and will not clear existing children. /// public ReadOnlySpan Content { init; } /// /// Adds a view to this container. /// /// Thrown if the view already has a parent. public virtual void Add(View child); /// /// Removes a view from this container. /// public virtual void Remove(View child); /// /// Removes all child views from this container. /// public virtual void Clear(); } } namespace Xui.Core.UI { using Xui.Core.Canvas; using Xui.Core.Math2D; using Xui.Core.UI.Input; /// A canvas text editor that a native text-input service can manipulate. public interface ITextEditingClient : ITextInputClient { /// The document and selection shared with the native input system. TextEditingState Editor { get; } /// Whether a native interaction owns caret, selection handles, and touch selection. bool NativeSelection { get; set; } /// The input's hit-test bounds, in logical window coordinates. Rect InputBounds { get; } /// Returns the caret rectangle for a UTF-16 offset, in logical window coordinates. Rect GetCaretRect(int offset, ITextMeasureContext measure); /// Hit-tests a logical window point, returning a UTF-16 grapheme boundary. int GetTextPosition(Point point, ITextMeasureContext measure); } } namespace Xui.Core.UI { using Xui.Core.UI.Input; /// /// Basic text-entry capabilities of a focusable view. Focus requests the software /// keyboard; the responder can query these traits without copying the text buffer. /// This does not imply support for marked text, IME composition, or native range editing. /// public interface ITextInputClient { /// Whether the input contains any text. bool HasText { get; } /// Whether the input is a masked password field. bool IsPassword { get; } /// Keyboard layout, content semantics and return-key action. TextInputOptions InputOptions { get; } /// Whether a keyboard action is currently available. bool CanPerformInputAction(TextInputAction action); /// Handles a keyboard action, including focus navigation or finishing editing. void PerformInputAction(TextInputAction action); } } namespace Xui.Core.UI { using Xui.Core.Canvas; using Xui.Core.DI; using Xui.Core.Math2D; /// /// A view that displays an image. Works like HTMLImageElement: it holds an /// handle (acquired from the service chain) and sets its source /// via . The platform catalog handles caching and device-lost /// rehydration transparently. /// public class ImageView : View { /// /// Gets or sets the URI of the image to display. /// Setting this property triggers a load if the view is already active. /// public string? Source { get; set; } /// /// Called when this view becomes active — it will receive events, render, and animate. /// Override this to start animations, subscribe to data sources, or acquire resources. /// protected override void OnActivate(); /// /// Called when this view becomes dormant — it should stop animations, timers, and event subscriptions. /// The view may remain in the tree (e.g., in a virtualizing panel's recycle pool). /// protected override void OnDeactivate(); /// Override to compute the desired border-edge size. protected override Size MeasureCore(Size availableBorderEdgeSize, IMeasureContext context); /// Override to render this view and its children. protected override void RenderCore(IContext context); } } namespace Xui.Core.UI { using Xui.Core.Canvas; using Xui.Core.Debug; /// /// Immutable services and timing shared by every view visited during one render-surface update. /// public readonly struct LayoutFrameContext { /// Initializes a frame context. public LayoutFrameContext(TimeSpan previousTime, TimeSpan currentTime, IMeasureContext? measureContext, IContext? renderContext, InstrumentsAccessor instruments); /// Time of the preceding frame. public TimeSpan PreviousTime { get; } /// Time of this frame. public TimeSpan CurrentTime { get; } /// Measurement services for this render surface. public IMeasureContext? MeasureContext { get; } /// Rendering context for this render surface. public IContext? RenderContext { get; } /// Instrumentation associated with this render surface. public InstrumentsAccessor Instruments { get; } } } namespace Xui.Core.UI { using Xui.Core.Abstract.Events; using Xui.Core.Abstract; using Xui.Core.Canvas.Composition.Graphics; using Xui.Core.Canvas; using Xui.Core.Debug; using Xui.Core.Math2D; using Xui.Core.UI.Input; /// /// The root container view that bridges a with its UI content hierarchy. /// public class RootView : View, IContent, IFocus { /// The render-surface instruments that own this visual tree, if instrumentation is enabled. public IRenderSurfaceInstrumentsSink? RenderSurfaceInstruments { get; } /// The input event router for this view tree. public EventRouter EventRouter { get; } /// The window that owns this root view. public Window Window { get; } /// The currently focused view within this tree, or null if none. public View? FocusedView { get; set; } /// Gets or sets the single content view hosted by this root view. public View? Content { get; set; } /// The content followed by visible in-window overlays, in render and hit-test order. public override int Count { get; } /// Gets the child view at the given index. public override View this[int index] { get; } /// Override to compute the desired border-edge size. protected override Size MeasureCore(Size available, IMeasureContext context); /// Override to arrange children within this view's final frame. protected override void ArrangeCore(Rect rect, IMeasureContext context); /// Override to render this view and its children. protected override void RenderCore(IContext context); /// Initializes a new RootView for the given window. /// The window that owns this root view. public RootView(Window window); /// /// Resolves a service of the given type by walking up the parent chain. /// Returns null if no ancestor provides the service. /// public override object? GetService(Type serviceType); /// Called when a child view signals that its rendered state has changed. protected override void OnChildRenderChanged(View child); } } namespace Xui.Core.UI { using Xui.Core.Abstract.Events; using Xui.Core.Abstract; using Xui.Core.Animation; using Xui.Core.Canvas.Composition.Graphics; using Xui.Core.Canvas; using Xui.Core.DI; using Xui.Core.Math2D; using Xui.Core.UI.Input; /// /// Controls which axis (or axes) a scrolls along. /// public enum ScrollDirection { /// Scrolls vertically only (default). Vertical, /// Scrolls horizontally only. Horizontal, /// Scrolls both axes simultaneously (map-panning style). Both } /// /// A container that clips its content and allows scrolling via pointer drag/fling /// and scroll wheel input. Supports vertical, horizontal, or both axes. /// Displays thin overlay scrollbar indicators on the relevant edges. /// public partial class ScrollView : View { /// Current scroll displacement, including elastic overscroll. public Vector ScrollOffset { get; } /// Raised after the content's scroll transform changes, including during inertia and rebound. public event Action? ScrollChanged; /// A viewport-sized foreground view that stays outside the content's scroll transform. /// Its input still participates in this scroll view's gesture negotiation. public View? Overlay { get; set; } /// Width of the scrollbar track in points. public nfloat ScrollbarWidth { get; set; } /// Inset at each end of the scrollbar. When unset, adapts to the screen corners. public nfloat ScrollbarEndInset { get; set; } /// /// Gets or sets whether content is clipped and culled to the viewport. /// Disable this for a root scroller that is laid out inside a safe area but /// is allowed to paint underneath the system areas while it scrolls. /// public bool ClipToViewport { get; set; } /// Retains this viewport as a native composition surface where supported. public bool UseCompositionGroup { get; set; } /// /// Gets or sets which axis (or axes) this scroll view responds to. /// public new ScrollDirection Direction { get; set; } /// /// Gets or sets the single child view to scroll. /// public View? Content { get; set; } /// Number of child views. public override int Count { get; } /// Gets the child view at the given index. public override View this[int index] { get; } /// /// Called when this view becomes active — it will receive events, render, and animate. /// Override this to start animations, subscribe to data sources, or acquire resources. /// protected override void OnActivate(); /// Override to compute the desired border-edge size. protected override Size MeasureCore(Size available, IMeasureContext context); /// Override to arrange children within this view's final frame. protected override void ArrangeCore(Rect rect, IMeasureContext context); /// /// Maps a point from this view's parent coordinate space into this view's local coordinate space. /// /// /// Layout still supplies frames using the existing coordinate model. The default identity /// mapping deliberately preserves that behaviour until a container opts into a local /// coordinate transform. Containers such as can override this /// to map input into their content space. /// public override Point TransformPoint(Point point); /// /// Maps a point from this view's local coordinate space into its parent coordinate space. /// /// /// This must be the inverse of for points that can be hit /// tested. It is separate so a view can support coordinate mappings that are not yet /// represented by the canvas transform API. /// public override Point InverseTransformPoint(Point point); /// /// Conservatively maps an axis-aligned rectangle from this view's parent coordinate space /// into this view's coordinate space. /// /// /// For non-translation transforms, an override must return the smallest parent-axis-aligned /// rectangle that encloses every transformed corner. /// public override Rect TransformRect(Rect rect); /// /// Conservatively maps an axis-aligned rectangle from this view's coordinate space into its /// parent coordinate space. /// /// /// For non-translation transforms, an override must return the smallest parent-axis-aligned /// rectangle that encloses every transformed corner. /// public override Rect InverseTransformRect(Rect rect); /// /// Determines whether the given point (in this view's local coordinates) hits this view's visual bounds. /// Used for input dispatch and hit testing. /// /// The point to test, relative to this view's coordinate space. /// /// true if the point is inside the view's frame; otherwise false. public override bool HitTest(Point point); /// Override to render this view and its children. protected override void RenderCore(IContext context); /// /// Called during event dispatch to handle a pointer event in a specific event phase. /// public override void OnPointerEvent(ref PointerEventRef e, EventPhase phase); /// Override to animate this view and its children. protected override void AnimateCore(TimeSpan previous, TimeSpan current); /// /// Called when this view becomes dormant — it should stop animations, timers, and event subscriptions. /// The view may remain in the tree (e.g., in a virtualizing panel's recycle pool). /// protected override void OnDeactivate(); } } namespace Xui.Core.UI { using Xui.Core.Animation; /// /// A container that clips its content and allows scrolling via pointer drag/fling /// and scroll wheel input. Supports vertical, horizontal, or both axes. /// Displays thin overlay scrollbar indicators on the relevant edges. /// public partial class ScrollView { } } namespace Xui.Core.UI { using Xui.Core.Abstract.Events; using Xui.Core.DI; /// /// A container that clips its content and allows scrolling via pointer drag/fling /// and scroll wheel input. Supports vertical, horizontal, or both axes. /// Displays thin overlay scrollbar indicators on the relevant edges. /// public partial class ScrollView { /// /// Called when a scroll wheel or trackpad scroll event is dispatched to this view. /// Override to handle scroll input. Set to stop propagation. /// public override void OnScrollWheel(ref ScrollWheelEventRef e); } } namespace Xui.Core.UI { using Xui.Core.Canvas; using Xui.Core.Math1D; using Xui.Core.Math2D; using Xui.Core.UI.Input; using Xui.Core.UI.Layer; /// /// A single-line text input view implemented as /// LayerView<View, FocusBorderLayer<View, TextInputLayer>>. /// All text editing state, selection, caret blinking, and hit-testing live in /// ; focus-aware border drawing lives in /// . /// public class TextBox : LayerView>, ITextEditingClient { /// Gets whether this view can receive keyboard focus. Always true for . public override bool Focusable { get; } /// Keyboard hints, applied when this field receives focus. public TextInputOptions InputOptions { get; set; } /// Whether a keyboard action is currently available. public bool CanPerformInputAction(TextInputAction action); /// Handles a keyboard action, including focus navigation or finishing editing. public void PerformInputAction(TextInputAction action); /// The document and selection shared with the native input system. public Xui.Core.UI.Input.TextEditingState Editor { get; } /// Whether a native interaction owns caret, selection handles, and touch selection. public bool NativeSelection { get; set; } /// The input's hit-test bounds, in logical window coordinates. public Rect InputBounds { get; } /// Returns the caret rectangle for a UTF-16 offset, in logical window coordinates. public Rect GetCaretRect(int offset, ITextMeasureContext measure); /// Hit-tests a logical window point, returning a UTF-16 grapheme boundary. public int GetTextPosition(Point point, ITextMeasureContext measure); /// Whether the input contains any text. public bool HasText { get; } /// /// Called when this view becomes dormant — it should stop animations, timers, and event subscriptions. /// The view may remain in the tree (e.g., in a virtualizing panel's recycle pool). /// protected override void OnDeactivate(); /// Initializes a new with default styling. public TextBox(); /// Gets or sets the text content of this input. public string Text { get; set; } /// Gets or sets the current text selection range. public Interval.ClosedOpen Selection { get; set; } /// Gets or sets whether input is masked as a password. public bool IsPassword { get; set; } /// Gets or sets whether all text is selected when the view receives focus. public bool SelectAllOnFocus { get; set; } /// Gets or sets the character filter predicate for input validation. public Func? InputFilter { get; set; } /// Gets or sets the text color. public Color Color { get; set; } /// Gets or sets the color of selected text. public Color SelectedColor { get; set; } /// Gets or sets the background color of the selection. public Color SelectionBackgroundColor { get; set; } /// Gets or sets the complete text font. public Font Font { get; set; } /// Gets or sets the font family name. public string FontFamily { get; set; } /// Gets or sets the font size. public nfloat FontSize { get; set; } /// Gets or sets the font style. public FontStyle FontStyle { get; set; } /// Gets or sets the font weight. public FontWeight FontWeight { get; set; } /// Gets or sets the font stretch. public FontStretch FontStretch { get; set; } } } namespace Xui.Core.UI { using Xui.Core.Canvas.Composition.Graphics; using Xui.Core.Canvas; using Xui.Core.Math2D; /// /// Hosts one child and presents it through an affine transform without changing /// its layout rectangle. Input and render culling are mapped through the inverse /// transform so a translated or scaled child remains interactive and cullable. /// public class TransformView : View { /// Retain the complete child drawing while only its native surface transform changes. public bool UseCompositionGroup { get; set; } /// Gets or sets the single child presented by this host. public View? Content { get; set; } /// /// Gets or sets the transform from this view's layout coordinates into its /// parent presentation coordinates. /// public AffineTransform Transform { get; set; } /// /// Returns the number of child views. Used by layout containers and traversal logic. /// Leaf views should return 0. /// public override int Count { get; } /// /// Indexer to access child views by index. /// Layout containers should implement this to expose their children. /// public override View this[int index] { get; } /// /// Gets this view's conservative bounds in its parent coordinate space for render culling. /// /// /// A container may override this when its rendered geometry differs from its layout frame. /// Computing the union of descendant culling frames is deliberately deferred: it can be /// more expensive than rendering for small subtrees. /// public override Rect CullingFrame { get; } /// /// Maps a point from this view's parent coordinate space into this view's local coordinate space. /// /// /// Layout still supplies frames using the existing coordinate model. The default identity /// mapping deliberately preserves that behaviour until a container opts into a local /// coordinate transform. Containers such as can override this /// to map input into their content space. /// public override Point TransformPoint(Point point); /// /// Maps a point from this view's local coordinate space into its parent coordinate space. /// /// /// This must be the inverse of for points that can be hit /// tested. It is separate so a view can support coordinate mappings that are not yet /// represented by the canvas transform API. /// public override Point InverseTransformPoint(Point point); /// /// Conservatively maps an axis-aligned rectangle from this view's parent coordinate space /// into this view's coordinate space. /// /// /// For non-translation transforms, an override must return the smallest parent-axis-aligned /// rectangle that encloses every transformed corner. /// public override Rect TransformRect(Rect rect); /// /// Conservatively maps an axis-aligned rectangle from this view's coordinate space into its /// parent coordinate space. /// /// /// For non-translation transforms, an override must return the smallest parent-axis-aligned /// rectangle that encloses every transformed corner. /// public override Rect InverseTransformRect(Rect rect); /// /// Determines whether the given point (in this view's local coordinates) hits this view's visual bounds. /// Used for input dispatch and hit testing. /// /// The point to test, relative to this view's coordinate space. /// /// true if the point is inside the view's frame; otherwise false. public override bool HitTest(Point point); /// Override to render this view and its children. protected override void RenderCore(IContext context); /// Renders content after has been applied. protected virtual void RenderTransformedContent(IContext context); } } namespace Xui.Core.UI { using Xui.Core.DI; /// /// Base class for all UI elements in the Xui layout engine. /// A view participates in layout, rendering, and input hit testing, and may contain child views. /// /// /// Base class for all UI elements in the Xui layout engine. /// A view participates in layout, rendering, and input hit testing, and may contain child views. /// public partial class View { /// /// Called when this view receives keyboard focus. /// protected internal virtual void OnFocus(); /// /// Called when this view loses keyboard focus. /// protected internal virtual void OnBlur(); /// /// Gets whether this view can receive keyboard focus via Tab navigation. /// public virtual bool Focusable { get; } /// Whether focusing this view requests the platform's software keyboard. public virtual bool RequiresKeyboard { get; } /// /// Gets whether this view currently has keyboard focus. /// public bool IsFocused { get; } /// /// Requests keyboard focus for this view. /// public bool Focus(); /// /// Releases keyboard focus from this view. /// public void Blur(); } } namespace Xui.Core.UI { using Xui.Core.Abstract.Events; using Xui.Core.UI.Input; /// /// Base class for all UI elements in the Xui layout engine. /// A view participates in layout, rendering, and input hit testing, and may contain child views. /// /// /// Base class for all UI elements in the Xui layout engine. /// A view participates in layout, rendering, and input hit testing, and may contain child views. /// public partial class View { /// /// Called during event dispatch to handle a pointer event in a specific event phase. /// public virtual void OnPointerEvent(ref PointerEventRef e, EventPhase phase); /// /// Called when a scroll wheel or trackpad scroll event is dispatched to this view. /// Override to handle scroll input. Set to stop propagation. /// public virtual void OnScrollWheel(ref ScrollWheelEventRef e); /// Handles a platform magnification gesture. Set Handled to stop bubbling. public virtual void OnZoom(ref ZoomEventRef e); /// /// Called when a key is pressed while this view has focus. /// public virtual void OnKeyDown(ref KeyEventRef e); /// /// Called when a character is input while this view has focus. /// public virtual void OnChar(ref KeyEventRef e); } } namespace Xui.Core.UI { using Xui.Core.Canvas; using Xui.Core.Debug; using Xui.Core.Math2D; /// /// Base class for all UI elements in the Xui layout engine. /// A view participates in layout, rendering, and input hit testing, and may contain child views. /// /// /// Base class for all UI elements in the Xui layout engine. /// A view participates in layout, rendering, and input hit testing, and may contain child views. /// public partial class View { /// The active render culling rectangle in this view's coordinate space, if any. protected Rect? RenderCullingFrame { get; } /// Drives the requested passes using shared frame state and per-view constraints. public virtual void Update(in LayoutFrameContext frame, in LayoutUpdate update, ref LayoutMeasurements measurements); /// Advances animation state for this view and all descendants. public void Animate(TimeSpan previousTime, TimeSpan currentTime); /// Measures the view and returns the desired margin-box size. public Size Measure(Size availableSize, IMeasureContext context); /// Arranges the view within , finalising its position and size. public Rect Arrange(Rect rect, IMeasureContext context, Size? desiredSize = null); /// Renders the view. Must be called after layout is complete. public void Render(IContext context); /// Performs bookkeeping and animation for this view. protected void AnimateShell(in LayoutFrameContext frame); /// Measures this view using the supplied immutable constraints. protected void MeasureShell(in LayoutFrameContext frame, in MeasureConstraints constraints, ref LayoutMeasurements measurements); /// Arranges this view using the supplied immutable constraints. protected void ArrangeShell(in LayoutFrameContext frame, in ArrangeConstraints constraints, ref LayoutMeasurements measurements); /// Performs bookkeeping and renders this view. protected void RenderShell(in LayoutFrameContext frame, Rect? parentCullingFrame = null); /// Override to animate this view and its children. protected virtual void AnimateCore(TimeSpan previousTime, TimeSpan currentTime); /// Override to compute the desired border-edge size. protected virtual Size MeasureCore(Size availableBorderEdgeSize, IMeasureContext context); /// Override to arrange children within this view's final frame. protected virtual void ArrangeCore(Rect rect, IMeasureContext context); /// Override to render this view and its children. protected virtual void RenderCore(IContext context); /// /// Applies the drawing defaults used at the start of every view render. /// The active transform and clip are intentionally inherited from the parent. /// protected virtual void SetDefaultRenderState(IContext context); /// Renders a child while preserving this view's active culling rectangle. protected internal void RenderChild(IContext context, View child); /// Renders a child using an explicit culling rectangle in this view's coordinate space. protected internal void RenderChild(IContext context, View child, Rect cullingFrame); } } namespace Xui.Core.UI { using System.Diagnostics.CodeAnalysis; /// /// Provides extension methods for navigating the Xui view tree. /// public static class ViewExtensions { /// /// Returns an allocation-free enumerable that walks up the parent chain of a view. /// /// The view whose parent chain should be traversed. /// An enumerable of the view's parents, from immediate to root. public static ParentsEnumerable Parents(this View view); /// /// Attempts to find the first parent of a specific type in the view tree. /// Zero allocations. Returns true if a matching parent was found. /// /// The type of view to search for. /// The view whose parent chain will be searched. /// The found parent of type , or null if not found. /// True if a matching parent was found; otherwise, false. public static bool TryFindParent(this View view, [NotNullWhen(true)] out T? result) where T : View; /// /// Performs a depth-first search of the view subtree (including itself) /// and returns the first view whose matches . /// /// The matching view, or null if not found. public static View? FindViewById(this View root, string id); /// /// Performs a depth-first search of the view subtree (including itself) /// and collects all views whose contains . /// public static void FindViewsByClass(this View root, string className, List results); /// /// Allocation-free enumerable for walking up the parent chain of a view. /// public readonly ref struct ParentsEnumerable { /// /// Creates a new starting from the given view. /// /// The starting view. public ParentsEnumerable(View? start); /// /// Returns an enumerator that iterates over the view's parents. /// public Enumerator GetEnumerator(); /// /// Enumerator for , walking up the view hierarchy. /// public ref struct Enumerator { /// /// Initializes a new instance of the struct. /// /// The starting view for traversal. public Enumerator(View? start); /// /// Gets the current parent view in the traversal. /// public View Current { get; } /// /// Moves to the next parent view. /// /// True if there is a next parent; otherwise, false. public bool MoveNext(); } } } } namespace Xui.Core.UI.Input { /// /// Defines the phase of event delivery through the view hierarchy. /// public enum EventPhase { /// /// Event is tunneling from the root down toward the target view. /// Tunnel, /// /// Event is bubbling from the target view up toward the root. /// Bubble } /// /// A capturing view declares when it is consuming pointer /// motion as ongoing input (e.g. a color wheel, a slider thumb, a drawing /// canvas). Ancestor scroll views and similar containers must not steal /// capture while an gesture is active. /// public interface IDrag : IPointerGesture { } /// /// A horizontal-axis drag that is willing to yield capture to a vertical-axis /// ancestor whose drag intent appears stronger. Used by horizontal scroll views /// nested inside vertical ones: the inner scrolls horizontally from the first /// pointer move, but if the user's motion is dominantly vertical when crossing /// the recognition threshold, the outer scroll view steals capture. /// /// /// The capturing view is expected to "promote" itself by re-capturing with a /// plain (e.g. ) once /// horizontal motion has clearly committed to its axis (typical threshold: /// 20pt of horizontal travel). After promotion, vertical ancestors can no /// longer steal capture for this pointer. /// public interface IDragHorizontalTentative : IDrag { } /// /// A vertical drag willing to yield to a horizontal ancestor until its direction /// commits. Promote to once vertical intent is clear. /// public interface IDragVerticalTentative : IDrag { } /// /// Marker interface attached to a captured pointer to describe what kind of /// gesture the capturing view is performing. Ancestor views can inspect this /// (via ) to negotiate handover — /// for example a ScrollView will steal an after a /// drag threshold but stand down for an . /// public interface IPointerGesture { } /// /// A capturing view declares when it is tracking a press /// that may or may not become a tap (e.g. Button, Checkbox). /// An ancestor that wants the pointer for a drag may steal capture after its /// own threshold is exceeded. /// public interface ITap : IPointerGesture { } /// /// Defines the mouse or pointer button associated with a pointer event, based on the W3C Pointer Events specification. /// public enum PointerButton : short { /// /// No button or touch/pen contact change occurred (-1). /// None = -1, /// /// Left mouse button, touch contact, or pen contact (0). /// Left = 0, /// /// Middle mouse button (usually the scroll wheel button) (1). /// Middle = 1, /// /// Right mouse button or pen barrel button (2). /// Right = 2, /// /// X1 (back) mouse button (3). /// X1 = 3, /// /// X2 (forward) mouse button (4). /// X2 = 4, /// /// Pen eraser button (5). /// Eraser = 5, } /// /// Defines the set of mouse or pointer buttons currently pressed, based on the W3C Pointer Events specification. /// [Flags] public enum PointerButtons : short { /// /// No buttons are currently pressed. /// None = 0, /// /// Left mouse button, touch contact, or pen contact. /// Left = 1 << 0, /// /// Right mouse button or pen barrel button. /// Right = 1 << 1, /// /// Middle mouse button. /// Middle = 1 << 2, /// /// X1 (back) mouse button. /// X1 = 1 << 3, /// /// X2 (forward) mouse button. /// X2 = 1 << 4, /// /// Pen eraser button. /// Eraser = 1 << 5, } /// /// Defines the type of action associated with a pointer event, based on the W3C Pointer Events specification. /// public enum PointerEventType { /// /// The pointer has moved onto the element's hit region. /// Corresponds to the "pointerover" event. /// Over, /// /// The pointer has entered the element or one of its descendants. /// Corresponds to the "pointerenter" event. /// Enter, /// /// A pointer button has been pressed. /// Corresponds to the "pointerdown" event. /// Down, /// /// The pointer has moved while being active. /// Corresponds to the "pointermove" event. /// Move, /// /// A pointer button has been released. /// Corresponds to the "pointerup" event. /// Up, /// /// The pointer input was canceled by the system. /// Corresponds to the "pointercancel" event. /// Cancel, /// /// The pointer has moved off of the element's hit region. /// Corresponds to the "pointerout" event. /// Out, /// /// The pointer has left the element and all its descendants. /// Corresponds to the "pointerleave" event. /// Leave, /// /// The pointer has been captured by the element. /// Corresponds to the "gotpointercapture" event. /// GotCapture, /// /// The pointer capture has been released from the element. /// Corresponds to the "lostpointercapture" event. /// LostCapture, } /// /// Singleton gesture markers used by simple widgets when capturing a pointer. /// Reusing these avoids per-event heap allocation. Widgets that need to carry /// extra state can implement on their own type /// and pass an instance to CapturePointer instead. /// public static class PointerGestures { /// Generic tap (e.g. Button, Checkbox) — may be stolen by an ancestor drag. public static ITap Tap { get; } /// Generic drag (e.g. color wheel, slider thumb) — ancestors must not steal. public static IDrag Drag { get; } /// /// A horizontal-axis drag that is tentatively willing to yield to a vertical-axis /// ancestor (see ). Replace with /// once horizontal motion has firmly committed. /// public static IDragHorizontalTentative DragHorizontalTentative { get; } /// A vertical drag that can yield to a horizontal ancestor before committing. public static IDragVerticalTentative DragVerticalTentative { get; } } /// /// Defines the type of input device associated with a pointer event. /// public enum PointerType { /// /// A mouse device generated the pointer event. /// Mouse, /// /// A touch contact (e.g., finger or capacitive touch) generated the pointer event. /// Touch, /// /// A pen, stylus, or similar fine-point device generated the pointer event. /// Pen, /// /// The pointer device type could not be determined. /// Unknown, } /// An editing action from a software keyboard or its navigation controls. public enum TextInputAction { /// Use the field's configured action; otherwise finish editing. Default, /// Focus the preceding text input, without wrapping. Previous, /// Focus the next control, or finish editing at the end. Next, /// Finish editing and release keyboard focus. Done, } /// Semantic hints for platform suggestions and autofill. public enum TextInputContentType { /// No specific semantic hint. None, /// A person's name. Name, /// An existing password. Masking is controlled separately by IsPassword. Password, } /// Keyboard layout hint. Character validation remains the editor's responsibility. public enum TextInputKeyboard { /// Ordinary text in the user's language. Text, /// ASCII letters, numbers and punctuation, for values such as hex colors. Ascii, /// Digits. Number, /// Digits and a decimal separator. Decimal, } /// /// Platform-independent keyboard hints, read when a field receives focus. /// These do not restrict pasted, dictated, or hardware-keyboard input; use InputFilter for validation. /// public readonly record struct TextInputOptions(TextInputKeyboard Keyboard = TextInputKeyboard.Text, TextInputContentType ContentType = TextInputContentType.None, TextInputAction ReturnAction = TextInputAction.Default); } namespace Xui.Core.UI.Input { using Xui.Core.Abstract.Events; using Xui.Core.Math2D; /// /// Routes pointer, mouse, scroll, and touch events through the view tree, /// performing hit testing, pointer capture, and enter/leave tracking. /// public class EventRouter { /// Initializes a new rooted at the given view. /// The root of the view tree to route events through. public EventRouter(View rootView); /// Dispatches a touch event, translating each touch point into a pointer event. public void Dispatch(ref TouchEventRef touchEvent); /// Dispatches a mouse button down event as a pointer down event. public void Dispatch(ref MouseDownEventRef e); /// Dispatches a mouse button up event as a pointer up event. public void Dispatch(ref MouseUpEventRef e); /// Dispatches a mouse move event as a pointer move event. public void Dispatch(ref MouseMoveEventRef e); /// Captures all subsequent pointer events for the given pointer ID to . /// The view that will exclusively receive events for this pointer. /// The pointer identifier to capture. /// /// Optional marker describing what kind of gesture the view is tracking /// (, , …). Ancestor views can read this /// via to decide whether to steal capture. /// public void CapturePointer(View view, int pointerId, IPointerGesture? gesture = null); /// Releases pointer capture previously set by . /// The view that currently holds the capture. /// The pointer identifier to release. public void ReleasePointer(View view, int pointerId); /// /// Returns the gesture marker associated with the current capture for /// , or null if the pointer is not /// captured or was captured without a gesture marker. /// public IPointerGesture? GetCapturedGesture(int pointerId); /// /// Returns the view currently holding pointer capture for /// , or null if the pointer is not captured. /// public View? GetCapturedView(int pointerId); /// /// Dispatches a scroll wheel event to the deepest view under /// that handles it, bubbling up until is set. /// public void Dispatch(ref ScrollWheelEventRef e, Point position); /// Routes magnification to the innermost view under the anchor, then its ancestors. public void Dispatch(ref ZoomEventRef e, Point position); } } namespace Xui.Core.UI.Input { using Xui.Core.Canvas; /// /// Represents a reference to a pointer event routed to a view, containing identification and pointer state information. /// public ref struct PointerEventRef { /// /// Up to eight handlers pushed earlier during this event's down tunnel, /// oldest first. Storage is shared by the routed event copies and exists /// only for this dispatch; do not retain this span across events. /// public readonly ReadOnlySpan PotentialGestures { get; } /// /// Advertises a possible gesture without capturing the pointer. Call during /// Down/Tunnel so descendants can adapt feedback while recognition is pending. /// When full, drops the oldest handler and retains the newest eight. /// This does not change capture or the handler's recognition rules. /// public readonly void PushPotentialGesture(View handler, IPointerGesture gesture); /// /// Gets the type of pointer event (e.g., Down, Move, Up, Enter, Leave). /// public readonly PointerEventType Type; /// /// Gets the unique ID of the pointer. Used to distinguish different active pointers (e.g., different fingers or pen tips). /// public readonly int PointerId; /// /// Gets the persistent device ID, if known. Identifies the underlying hardware across multiple pointer sessions. /// public readonly long PersistentDeviceId; /// /// Gets a value indicating whether this pointer is the primary pointer in a multi-pointer interaction (e.g., first touch). /// public readonly bool IsPrimary; /// /// Gets the current physical state of the pointer (position, pressure, tilt, etc.). /// public readonly PointerState State; /// /// Gets high-frequency coalesced samples recorded between the last and current events. /// public readonly ReadOnlySpan CoalescedStates; /// /// Gets future-predicted samples estimated from the current pointer movement. /// public readonly ReadOnlySpan PredictedStates; /// /// Optional text measure context for hit-testing text positions. /// May be null on platforms that do not provide one. /// public readonly ITextMeasureContext? TextMeasure; /// /// Initializes a new instance of the struct. /// public PointerEventRef(PointerEventType type, int pointerId, long persistentDeviceId, bool isPrimary, PointerState state, ReadOnlySpan coalescedStates, ReadOnlySpan predictedStates, ITextMeasureContext? textMeasure = null); } } namespace Xui.Core.UI.Input { using System.Runtime.CompilerServices; /// A handler advertising a possible gesture during pointer-down tunneling. /// The view which may later claim capture. /// The gesture it may recognize. public readonly record struct PointerGestureCandidate(View Handler, IPointerGesture Gesture); } namespace Xui.Core.UI.Input { using Xui.Core.Math2D; /// /// Describes the physical state of a pointer at a specific moment in time, including position, pressure, tilt, and button information. /// public readonly struct PointerState { /// /// Gets the position of the pointer in global (window) coordinates. /// public readonly Point Position; /// /// Gets the size of the pointer's contact geometry, such as the area covered by a finger or stylus tip. /// public readonly Size ContactSize; /// /// Gets the normalized pressure applied by the pointer (range: 0.0 to 1.0). /// public readonly nfloat Pressure; /// Whether Pressure is a device measurement rather than a synthesized button value. public readonly bool HasPressure; /// /// Gets the normalized tangential (barrel) pressure applied by the pointer (range: -1.0 to 1.0). /// public readonly nfloat TangentialPressure; /// /// Gets the tilt of the pointer relative to the X and Y axes (in degrees). /// public readonly Vector Tilt; /// /// Gets the clockwise twist (rotation) of the pointer around its major axis, in degrees (0.0 to 359.9). /// public readonly nfloat Twist; /// /// Gets the altitude angle of the pointer relative to the surface (0 = horizontal, π/2 = vertical), in radians. /// public readonly nfloat AltitudeAngle; /// /// Gets the azimuth angle (compass direction) of the pointer around the vertical axis, in radians. /// public readonly nfloat AzimuthAngle; /// /// Gets the type of device generating the pointer input (mouse, touch, pen, etc.). /// public readonly PointerType PointerType; /// /// Gets which button was responsible for triggering this pointer state change (left, right, middle, eraser, etc.). /// public readonly PointerButton Button; /// /// Gets the set of all currently pressed buttons on the device. /// public readonly PointerButtons Buttons; /// /// Initializes a new instance of the struct. /// /// The global position of the pointer. /// The size of the contact area. /// The normalized pressure applied. /// The normalized tangential (barrel) pressure applied. /// The tilt vector of the pointer. /// The clockwise twist rotation of the pointer. /// The altitude angle relative to the surface. /// The azimuth angle (compass direction). /// The type of input device. /// The button that triggered the event. /// The set of currently pressed buttons. /// Whether the source supplies real pressure measurements. public PointerState(Point position, Size contactSize, nfloat pressure, nfloat tangentialPressure, Vector tilt, nfloat twist, nfloat altitudeAngle, nfloat azimuthAngle, PointerType pointerType, PointerButton button, PointerButtons buttons, bool hasPressure = false); /// Returns this state with a coordinate-space-specific position. public PointerState WithPosition(Point position); } } namespace Xui.Core.UI.Input { using System.Globalization; /// Changes reported before and after a text editing transaction. [Flags] public enum TextEditingChange { /// The document or marked text changed. Text = 1, /// The insertion point or selected range changed. Selection = 2, } /// /// Single-line editing state shared by canvas text views and native input adapters. /// Offsets use UTF-16; selection and deletion respect Unicode grapheme boundaries. /// public sealed class TextEditingState { /// Raised before an editing transaction, while old state is still readable. public event Action? Changing; /// Raised after an editing transaction. public event Action? Changed; /// Optional validation for committed input; composition is validated when committed. public Func? InputFilter { get; set; } /// The document. Assignment ends composition and places the caret at the end. public string Text { get; set; } /// The normalized selection. Assignments are clamped to the document and grapheme boundaries. public TextRange Selection { get; set; } /// The provisional IME composition range, or null. public TextRange? MarkedRange { get; } /// Finds the grapheme boundary at or before an offset. public int Boundary(int offset); /// Finds the previous grapheme boundary. public int Previous(int offset); /// Finds the next grapheme boundary. public int Next(int offset); /// Normalizes a range, expanding a nonempty range to whole graphemes. public TextRange Normalize(TextRange range); /// Replaces the selection (or composition) atomically with committed input. public bool Insert(string value); /// Replaces a range with validated single-line input. public bool Replace(TextRange range, string value); /// Deletes the selection or the grapheme before the caret. public void DeleteBackward(); /// Deletes the selection or the grapheme after the caret. public void DeleteForward(); /// Updates provisional IME text; the selection is relative to the marked text. public void SetMarkedText(string value, TextRange relativeSelection); /// Commits composition, or restores the pre-composition document if validation fails. public void UnmarkText(); } /// A UTF-16 range in a text document, with an exclusive end. public readonly record struct TextRange(int Start, int End) { /// The number of UTF-16 code units in the range. public int Length { get; } } } namespace Xui.Core.UI.Input { using Xui.Core.DI; /// Shared focus behavior for single-line editors and native keyboard actions. public static class TextInputNavigation { /// Whether an action is available for the currently focused editor. public static bool CanPerform(View view, TextInputAction action); /// Moves through focus order without wrapping, or dismisses the keyboard. public static void Perform(View view, TextInputAction action); } } namespace Xui.Core.UI.Layer { using Xui.Core.Abstract.Events; using Xui.Core.Canvas; using Xui.Core.Math2D; using Xui.Core.UI.Input; /// /// A layer that draws a background fill, a border stroke, and optional padding around /// a child layer. Rendering logic is identical to but /// expressed as a composable struct with no heap allocation. /// /// The host type. Must implement . /// The inner layer that receives the inset rectangle. public struct BorderLayer : ILayer where TView : ILayerHost where TChild : struct, ILayer { /// The inner layer rendered inside the border and padding. public TChild Child; /// Per-side border thickness. public Frame BorderThickness; /// Corner radius for the background fill and border stroke. public CornerRadius CornerRadius; /// Background fill color. public Color BackgroundColor; /// Border stroke color. public Color BorderColor; /// Padding between the border edge and the child layer. public Frame Padding; /// Returns the desired border-edge size given the available space. public Size Measure(TView view, Size availableSize, IMeasureContext context); /// Finalises position and size within . public void Arrange(TView view, Rect rect, IMeasureContext context); /// Draws content. Called after Arrange. public void Render(TView view, IContext context); /// Advances time-based state (animations, blinking cursors, etc.). public void Animate(TView view, TimeSpan previousTime, TimeSpan currentTime); /// Handles a pointer event in the given dispatch phase. public void OnPointerEvent(TView view, ref PointerEventRef e, EventPhase phase); /// Handles a key-down event while the host view has focus. public void OnKeyDown(TView view, ref KeyEventRef e); /// Handles a character input event while the host view has focus. public void OnChar(TView view, ref KeyEventRef e); /// Called when the host view gains keyboard focus. public void OnFocus(TView view); /// Called when the host view loses keyboard focus. public void OnBlur(TView view); } /// /// A terminal layer that delegates layout and rendering to a child , /// bridging the layer tree back into the standard view hierarchy. /// Input routing is left to the which hit-tests the child /// view directly, so all input methods here are intentional no-ops. /// public struct ContentLayer : ILayer { /// The child view to measure, arrange, and render. public View? Child; /// Returns the desired border-edge size given the available space. public Size Measure(View view, Size availableSize, IMeasureContext context); /// Finalises position and size within . public void Arrange(View view, Rect rect, IMeasureContext context); /// Draws content. Called after Arrange. public void Render(View view, IContext context); /// Advances time-based state (animations, blinking cursors, etc.). public void Animate(View view, TimeSpan previousTime, TimeSpan currentTime); /// Handles a pointer event in the given dispatch phase. public void OnPointerEvent(View view, ref PointerEventRef e, EventPhase phase); /// Handles a key-down event while the host view has focus. public void OnKeyDown(View view, ref KeyEventRef e); /// Handles a character input event while the host view has focus. public void OnChar(View view, ref KeyEventRef e); /// Called when the host view gains keyboard focus. public void OnFocus(View view); /// Called when the host view loses keyboard focus. public void OnBlur(View view); } /// /// Container for dock layout types. /// Usage: DockLayer.Dock3<View, StepButton, NumberInputLayer, StepButton> public static class DockLayer { /// Determines how docked children are aligned on the cross axis. public enum Align { /// Align to the left edge. Left, /// Stretch to fill the available cross-axis space. Stretch, /// Align to the right edge. Right } /// Wraps a dockable child with its alignment setting. public struct Docked where T : struct { /// The cross-axis alignment for the docked child. public Align Align; /// The docked child layer. public T Child; } /// Two-slot dock layout. public struct Dock2 : ILayer where TView : ILayerHost where T1 : struct, ILayer where T2 : struct, ILayer { /// The first docked child. public Docked Child1; /// The second docked child. public Docked Child2; /// Returns the desired border-edge size given the available space. public Size Measure(TView view, Size available, IMeasureContext ctx); /// Finalises position and size within . public void Arrange(TView view, Rect rect, IMeasureContext ctx); /// Draws content. Called after Arrange. public void Render(TView view, IContext ctx); /// Advances time-based state (animations, blinking cursors, etc.). public void Animate(TView view, TimeSpan p, TimeSpan c); /// Handles a pointer event in the given dispatch phase. public void OnPointerEvent(TView view, ref PointerEventRef e, EventPhase phase); /// Handles a key-down event while the host view has focus. public void OnKeyDown(TView view, ref KeyEventRef e); /// Handles a character input event while the host view has focus. public void OnChar(TView view, ref KeyEventRef e); /// Called when the host view gains keyboard focus. public void OnFocus(TView view); /// Called when the host view loses keyboard focus. public void OnBlur(TView view); } /// Three-slot dock layout. Typical usage: Left button | Stretch content | Right button. public struct Dock3 : ILayer where TView : ILayerHost where T1 : struct, ILayer where T2 : struct, ILayer where T3 : struct, ILayer { /// The first docked child. public Docked Child1; /// The second docked child. public Docked Child2; /// The third docked child. public Docked Child3; /// Returns the desired border-edge size given the available space. public Size Measure(TView view, Size available, IMeasureContext ctx); /// Finalises position and size within . public void Arrange(TView view, Rect rect, IMeasureContext ctx); /// Draws content. Called after Arrange. public void Render(TView view, IContext ctx); /// Advances time-based state (animations, blinking cursors, etc.). public void Animate(TView view, TimeSpan p, TimeSpan c); /// Handles a pointer event in the given dispatch phase. public void OnPointerEvent(TView view, ref PointerEventRef e, EventPhase phase); /// Handles a key-down event while the host view has focus. public void OnKeyDown(TView view, ref KeyEventRef e); /// Handles a character input event while the host view has focus. public void OnChar(TView view, ref KeyEventRef e); /// Called when the host view gains keyboard focus. public void OnFocus(TView view); /// Called when the host view loses keyboard focus. public void OnBlur(TView view); } /// Four-slot dock layout. public struct Dock4 : ILayer where TView : ILayerHost where T1 : struct, ILayer where T2 : struct, ILayer where T3 : struct, ILayer where T4 : struct, ILayer { /// The first docked child. public Docked Child1; /// The second docked child. public Docked Child2; /// The third docked child. public Docked Child3; /// The fourth docked child. public Docked Child4; /// Returns the desired border-edge size given the available space. public Size Measure(TView view, Size available, IMeasureContext ctx); /// Finalises position and size within . public void Arrange(TView view, Rect rect, IMeasureContext ctx); /// Draws content. Called after Arrange. public void Render(TView view, IContext ctx); /// Advances time-based state (animations, blinking cursors, etc.). public void Animate(TView view, TimeSpan p, TimeSpan c); /// Handles a pointer event in the given dispatch phase. public void OnPointerEvent(TView view, ref PointerEventRef e, EventPhase phase); /// Handles a key-down event while the host view has focus. public void OnKeyDown(TView view, ref KeyEventRef e); /// Handles a character input event while the host view has focus. public void OnChar(TView view, ref KeyEventRef e); /// Called when the host view gains keyboard focus. public void OnFocus(TView view); /// Called when the host view loses keyboard focus. public void OnBlur(TView view); } } /// /// A variant that switches border color when the host /// view has keyboard focus. All layout and rendering is delegated to an inner /// ; only swaps the color, and /// / request a repaint. /// public struct FocusBorderLayer : ILayer where TView : ILayerHost where TChild : struct, ILayer { /// The inner border layer that owns all geometry and rendering. public BorderLayer Border; /// Border color used when the host view has keyboard focus. public Color FocusedBorderColor; /// Per-side border thickness. public Frame BorderThickness { get; set; } /// Corner radius for the background fill and border stroke. public CornerRadius CornerRadius { get; set; } /// Background fill color. public Color BackgroundColor { get; set; } /// Border stroke color. public Color BorderColor { get; set; } /// Padding between the border edge and the child layer. public Frame Padding { get; set; } /// Returns the desired border-edge size given the available space. public Size Measure(TView view, Size availableSize, IMeasureContext context); /// Finalises position and size within . public void Arrange(TView view, Rect rect, IMeasureContext context); /// Draws content. Called after Arrange. public void Render(TView view, IContext context); /// Advances time-based state (animations, blinking cursors, etc.). public void Animate(TView view, TimeSpan previousTime, TimeSpan currentTime); /// Handles a pointer event in the given dispatch phase. public void OnPointerEvent(TView view, ref PointerEventRef e, EventPhase phase); /// Handles a key-down event while the host view has focus. public void OnKeyDown(TView view, ref KeyEventRef e); /// Handles a character input event while the host view has focus. public void OnChar(TView view, ref KeyEventRef e); /// Called when the host view gains keyboard focus. public void OnFocus(TView view); /// Called when the host view loses keyboard focus. public void OnBlur(TView view); } /// /// A composable struct that handles a portion of a view's layout, rendering, and input. /// Layers are value types composed at compile time — no virtual dispatch, no allocations. /// The host provides resources and invalidation callbacks; /// the layer carries its own state and logic. /// /// /// The host type for this layer. Must implement . /// Almost always ; use a more derived type only when the layer /// needs access to host-specific APIs beyond the contract. /// public interface ILayer where TView : ILayerHost { /// Advances time-based state (animations, blinking cursors, etc.). void Animate(TView view, TimeSpan previousTime, TimeSpan currentTime); /// Returns the desired border-edge size given the available space. Size Measure(TView view, Size availableSize, IMeasureContext context); /// Finalises position and size within . void Arrange(TView view, Rect rect, IMeasureContext context); /// Draws content. Called after Arrange. void Render(TView view, IContext context); /// Handles a pointer event in the given dispatch phase. void OnPointerEvent(TView view, ref PointerEventRef e, EventPhase phase); /// Handles a key-down event while the host view has focus. void OnKeyDown(TView view, ref KeyEventRef e); /// Handles a character input event while the host view has focus. void OnChar(TView view, ref KeyEventRef e); /// Called when the host view gains keyboard focus. void OnFocus(TView view); /// Called when the host view loses keyboard focus. void OnBlur(TView view); } /// /// A that owns a single struct and delegates /// every layout, rendering, and input override to it, passing itself as the fully-typed /// host to every layer method. /// /// Because the compiler resolves statically, all delegation is /// devirtualised and inlined by the JIT — zero overhead compared to writing the overrides by hand. /// Child views: This class is a leaf by default (Count = 0). /// Subclasses that host child instances should override /// and , and manage attachment via . /// Use to bridge those views back into the layer tree. /// /// The concrete view subclass. Must be the class that inherits this. /// Pass when no specific host type is needed. /// The layer struct type. public class LayerView : View where TView : View where TLayer : struct, ILayer { /// The layer struct that owns all layout and rendering logic for this view. protected TLayer Layer; /// Override to animate this view and its children. protected override void AnimateCore(TimeSpan previousTime, TimeSpan currentTime); /// Override to compute the desired border-edge size. protected override Size MeasureCore(Size availableSize, IMeasureContext context); /// Override to arrange children within this view's final frame. protected override void ArrangeCore(Rect rect, IMeasureContext context); /// Override to render this view and its children. protected override void RenderCore(IContext context); /// /// Called during event dispatch to handle a pointer event in a specific event phase. /// public override void OnPointerEvent(ref PointerEventRef e, EventPhase phase); /// /// Called when a key is pressed while this view has focus. /// public override void OnKeyDown(ref KeyEventRef e); /// /// Called when a character is input while this view has focus. /// public override void OnChar(ref KeyEventRef e); /// /// Called when this view receives keyboard focus. /// protected internal override void OnFocus(); /// /// Called when this view loses keyboard focus. /// protected internal override void OnBlur(); } } namespace Xui.Core.UI.Layer { /// /// Zero-allocation click handler for button layers. /// Implement as a private nested struct inside the owning view so /// receives the fully-typed host and can call any method on it without closures. /// public interface IButtonAction where THost : ILayerHost { /// Executes the button action on the given host view. /// The host view that owns the button. void Execute(THost host); } } namespace Xui.Core.UI.Layer { using Xui.Core.Math2D; using Xui.Core.UI.Input; /// /// The contract a host view must satisfy to be used with . /// Provides the invalidation, focus, pointer-capture, and service-resolution APIs /// that layers call on their host during layout, rendering, and input handling. /// public interface ILayerHost : IServiceProvider { /// The arranged frame of the host view, in parent-local coordinates. Rect Frame { get; } /// Whether the host view currently holds keyboard focus. bool IsFocused { get; } /// Requests keyboard focus for the host view. Returns true if focus was granted. bool Focus(); /// Marks the view as needing re-render. void InvalidateRender(); /// Marks the view as needing re-measure (and re-layout). void InvalidateMeasure(); /// Schedules an animation frame callback via AnimateCore. void RequestAnimationFrame(); /// Routes all subsequent pointer events for to this view. /// The platform-assigned pointer identifier. /// Optional gesture marker (see ) so ancestor containers can negotiate handover. void CapturePointer(int pointerId, IPointerGesture? gesture = null); /// Releases a previously captured pointer. void ReleasePointer(int pointerId); } } namespace Xui.Core.UI.Layer { using System.Buffers; using Xui.Core.Abstract.Events; using Xui.Core.Actual; using Xui.Core.Canvas; using Xui.Core.DI; using Xui.Core.Math1D; using Xui.Core.Math2D; using Xui.Core.UI.Input; /// /// A leaf layer that implements single-line text input: typing, selection, caret blinking, /// password masking, and mouse-driven selection. Shares document state with native text input adapters. /// /// The layer stores the arranged during /// so that and pointer hit-testing both know the exact text area, /// independent of any border or padding applied by a wrapping layer. /// public struct TextInputLayer : ILayer { /// The editing state shared with native adapters. public TextEditingState Editor { get; } /// Whether the platform draws and manipulates the selection. public bool NativeSelection { get; set; } /// Whether the input contains text, without allocating a string. public bool HasText { get; } /// Gets or sets the text content. public string Text { get; set; } /// /// Gets or sets the selection as a half-open interval [Start, End). /// Start == End represents the caret position. /// public Interval.ClosedOpen Selection { get; set; } /// When true, displays bullet characters instead of the actual text. public bool IsPassword { get; set; } /// When true (default), selects all text when the view gains focus. public bool SelectAllOnFocus { get; set; } /// Optional character filter. Return true to accept, false to reject. public Func? InputFilter { get; set; } /// Normal text color. public Color Color { get; set; } /// Color of text inside the selection highlight. public Color SelectedColor { get; set; } /// Background color drawn behind selected text. public Color SelectionBackgroundColor { get; set; } /// Corner radius of the selection highlight rectangle. Zero by default. public CornerRadius SelectionCornerRadius { get; set; } /// Inset applied to the arranged rect before text layout and hit-testing. public Frame Padding { get; set; } /// Font used for input measurement, hit testing, and rendering. public Font Font { get; set; } /// Returns the desired border-edge size given the available space. public Size Measure(View view, Size availableSize, IMeasureContext context); /// Finalises position and size within . public void Arrange(View view, Rect rect, IMeasureContext context); /// Draws content. Called after Arrange. public void Render(View view, IContext context); /// Advances time-based state (animations, blinking cursors, etc.). public void Animate(View view, TimeSpan previousTime, TimeSpan currentTime); /// Handles a pointer event in the given dispatch phase. public void OnPointerEvent(View view, ref PointerEventRef e, EventPhase phase); /// Handles a key-down event while the host view has focus. public void OnKeyDown(View view, ref KeyEventRef e); /// Handles a character input event while the host view has focus. public void OnChar(View view, ref KeyEventRef e); /// Called when the host view gains keyboard focus. public void OnFocus(View view); /// Called when the host view loses keyboard focus. public void OnBlur(View view); /// Returns caret geometry in window coordinates. public Rect GetCaretRect(View view, int offset, ITextMeasureContext measure); /// Hit-tests text using a point in window coordinates. public int GetTextPosition(View view, Point point, ITextMeasureContext measure); } } namespace Xui.Core.UI.Layout { /// /// A container view that arranges children along a main axis with flexible sizing and wrapping. /// Container-level properties mirror the CSS Flex Box spec. /// /// /// Supports row/column layout, wrapping, order, gaps, flexible sizing, and space distribution. /// Item baseline alignment currently falls back to cross-axis start; line baseline alignment /// falls back to start. Views do not yet expose a common layout-baseline contract. /// public partial class FlexBox { /// /// Aligns flex lines along the cross axis when there is extra space (only applies when wrapping). /// Corresponds to the CSS align-content property on a flex container. /// public enum AlignContent : byte { /// Browser default. Acts like . Normal = 0, /// Lines are packed toward the flex-start edge of the cross axis. FlexStart = 1, /// Lines are packed toward the flex-end edge of the cross axis. FlexEnd = 2, /// Lines are centered on the cross axis. Center = 3, /// Lines are evenly distributed; first line at start, last at end. SpaceBetween = 4, /// Lines are evenly distributed with equal space around each line. SpaceAround = 5, /// Lines are evenly distributed with equal space between all lines including edges. SpaceEvenly = 6, /// Lines are stretched to fill the container. Stretch = 7, /// Lines are aligned along their first baseline. FirstBaseline = 8, /// Lines are aligned along their last baseline. LastBaseline = 9, } } /// /// A container view that arranges children along a main axis with flexible sizing and wrapping. /// Container-level properties mirror the CSS Flex Box spec. /// /// /// Supports row/column layout, wrapping, order, gaps, flexible sizing, and space distribution. /// Item baseline alignment currently falls back to cross-axis start; line baseline alignment /// falls back to start. Views do not yet expose a common layout-baseline contract. /// public partial class FlexBox { /// /// Sets the default cross-axis alignment for all flex items on a line. /// Corresponds to the CSS align-items property on a flex container. /// public enum AlignItems : byte { /// Browser default. Acts like . Normal = 0, /// Items are stretched to fill the cross axis. Stretch = 1, /// Items are packed toward the flex-start edge of the cross axis. FlexStart = 2, /// Items are packed toward the flex-end edge of the cross axis. FlexEnd = 3, /// Items are centered on the cross axis. Center = 4, /// Items are aligned along their first baseline. Baseline = 5, /// Items are aligned along their first baseline (same as ). FirstBaseline = 6, /// Items are aligned along their last baseline. LastBaseline = 7, } } /// /// A container view that arranges children along a main axis with flexible sizing and wrapping. /// Container-level properties mirror the CSS Flex Box spec. /// /// /// Supports row/column layout, wrapping, order, gaps, flexible sizing, and space distribution. /// Item baseline alignment currently falls back to cross-axis start; line baseline alignment /// falls back to start. Views do not yet expose a common layout-baseline contract. /// public partial class FlexBox { /// /// Specifies the direction of the main axis along which flex items are placed. /// Corresponds to the CSS flex-direction property. /// public new enum Direction : byte { /// Items are placed left to right (inline-start to inline-end). Row = 0, /// Items are placed right to left (inline-end to inline-start). RowReverse = 1, /// Items are placed top to bottom (block-start to block-end). Column = 2, /// Items are placed bottom to top (block-end to block-start). ColumnReverse = 3, } } /// /// A container view that arranges children along a main axis with flexible sizing and wrapping. /// Container-level properties mirror the CSS Flex Box spec. /// /// /// Supports row/column layout, wrapping, order, gaps, flexible sizing, and space distribution. /// Item baseline alignment currently falls back to cross-axis start; line baseline alignment /// falls back to start. Views do not yet expose a common layout-baseline contract. /// public partial class FlexBox { /// /// Controls the order in which the item appears within the flex container, overriding source order. /// Corresponds to CSS order. /// public static readonly View.Extra Order; /// /// How much the item will grow relative to other flex items when free space is available. /// Corresponds to CSS flex-grow. Default is 0 (does not grow). /// public static readonly View.Extra Grow; /// /// How much the item will shrink relative to other flex items when space is insufficient. /// Corresponds to CSS flex-shrink. Default is 1 (shrinks evenly). /// public static readonly View.Extra Shrink; /// /// The initial size of the item along the main axis before free space is distributed. /// nfloat.NaN means auto (use the item's width or height). /// Corresponds to CSS flex-basis. /// public static readonly View.Extra Basis; } /// /// A container view that arranges children along a main axis with flexible sizing and wrapping. /// Container-level properties mirror the CSS Flex Box spec. /// /// /// Supports row/column layout, wrapping, order, gaps, flexible sizing, and space distribution. /// Item baseline alignment currently falls back to cross-axis start; line baseline alignment /// falls back to start. Views do not yet expose a common layout-baseline contract. /// public partial class FlexBox { /// /// Aligns flex items along the main axis when there is free space. /// Corresponds to the CSS justify-content property on a flex container. /// public enum JustifyContent : byte { /// Browser default. Acts like . Normal = 0, /// Items are packed toward the flex-start edge of the main axis. FlexStart = 1, /// Items are packed toward the flex-end edge of the main axis. FlexEnd = 2, /// Items are centered along the main axis. Center = 3, /// Items are evenly distributed; first item at start, last at end. SpaceBetween = 4, /// Items are evenly distributed with equal space around each item. SpaceAround = 5, /// Items are evenly distributed with equal space between all items including edges. SpaceEvenly = 6, /// Items are packed toward the start of the main axis. Start = 7, /// Items are packed toward the end of the main axis. End = 8, } } /// /// A container view that arranges children along a main axis with flexible sizing and wrapping. /// Container-level properties mirror the CSS Flex Box spec. /// /// /// Supports row/column layout, wrapping, order, gaps, flexible sizing, and space distribution. /// Item baseline alignment currently falls back to cross-axis start; line baseline alignment /// falls back to start. Views do not yet expose a common layout-baseline contract. /// public partial class FlexBox { /// /// Controls whether flex items are forced onto a single line or can wrap onto multiple lines. /// Corresponds to the CSS flex-wrap property. /// public enum Wrap : byte { /// All flex items are on a single line. NoWrap = 0, /// Flex items wrap onto additional lines in the block-start direction. Wrap = 1, /// Flex items wrap onto additional lines in the block-end direction. WrapReverse = 2, } } /// /// A container view that arranges children along a main axis with flexible sizing and wrapping. /// Container-level properties mirror the CSS Flex Box spec. /// /// /// Supports row/column layout, wrapping, order, gaps, flexible sizing, and space distribution. /// Item baseline alignment currently falls back to cross-axis start; line baseline alignment /// falls back to start. Views do not yet expose a common layout-baseline contract. /// public partial class FlexBox : ViewCollection { /// /// Sets the main axis direction along which flex items are placed. /// Corresponds to flex-direction. Default is . /// public Direction FlexDirection { get; set; } /// /// Controls whether flex items wrap onto multiple lines. /// Corresponds to flex-wrap. Default is . /// public Wrap FlexWrap { get; set; } /// /// Aligns flex items along the main axis when there is free space. /// Corresponds to justify-content. Default is . /// public JustifyContent FlexJustifyContent { get; set; } /// /// Sets the default cross-axis alignment for all flex items on a line. /// Corresponds to align-items. Default is . /// public AlignItems FlexAlignItems { get; set; } /// /// Aligns flex lines along the cross axis when there is extra space (only applies when wrapping). /// Corresponds to align-content. Default is . /// public AlignContent FlexAlignContent { get; set; } /// /// Space between rows of flex items. /// Corresponds to row-gap. Default is 0. /// public nfloat RowGap { get; set; } /// /// Space between columns of flex items. /// Corresponds to column-gap. Default is 0. /// public nfloat ColumnGap { get; set; } } /// /// A container view that arranges children in a grid of rows and columns. /// Container-level properties mirror the CSS Grid spec. /// /// /// CSS Grid Layout implementation for the Grid container. /// Provides MeasureCore and ArrangeCore implementations following the CSS Grid Layout Module Level 1 specification. /// /// /// Implementation notes: /// /// Track sizing supports: Length, Auto, MinContent, MaxContent, Fr (fractional units), MinMax, and FitContent /// Auto-placement follows grid-auto-flow (row or column direction) /// Named grid areas are parsed from TemplateAreas /// Gaps are applied between tracks /// Alignment is supported via justify-items, align-items, justify-content, align-content /// Child positioning via grid-row-start/end, grid-column-start/end, and grid-area /// /// Algorithm approach: /// /// Build grid structure: parse areas, determine placement for each child /// Measure tracks: resolve fixed sizes, content-based sizes, then distribute fr units /// Arrange children: position each child in its grid area with alignment /// /// public partial class Grid { /// /// Aligns the grid along the block axis within the container when the grid is smaller than the container. /// Corresponds to the CSS align-content property on a grid container. /// public enum AlignContent : byte { /// Browser default. Acts like . Normal = 0, /// Rows are packed toward the start of the block axis. Start = 1, /// Rows are packed toward the end of the block axis. End = 2, /// Rows are centered on the block axis. Center = 3, /// Rows are evenly distributed; first row at start, last at end. SpaceBetween = 4, /// Rows are evenly distributed with equal space around each row. SpaceAround = 5, /// Rows are evenly distributed with equal space between all rows including edges. SpaceEvenly = 6, /// Rows are stretched to fill the container block size. Stretch = 7, /// Rows are aligned along their first baseline. FirstBaseline = 8, /// Rows are aligned along their last baseline. LastBaseline = 9, } } /// /// A container view that arranges children in a grid of rows and columns. /// Container-level properties mirror the CSS Grid spec. /// /// /// CSS Grid Layout implementation for the Grid container. /// Provides MeasureCore and ArrangeCore implementations following the CSS Grid Layout Module Level 1 specification. /// /// /// Implementation notes: /// /// Track sizing supports: Length, Auto, MinContent, MaxContent, Fr (fractional units), MinMax, and FitContent /// Auto-placement follows grid-auto-flow (row or column direction) /// Named grid areas are parsed from TemplateAreas /// Gaps are applied between tracks /// Alignment is supported via justify-items, align-items, justify-content, align-content /// Child positioning via grid-row-start/end, grid-column-start/end, and grid-area /// /// Algorithm approach: /// /// Build grid structure: parse areas, determine placement for each child /// Measure tracks: resolve fixed sizes, content-based sizes, then distribute fr units /// Arrange children: position each child in its grid area with alignment /// /// public partial class Grid { /// /// Sets the default block-axis alignment for all grid items within their grid areas. /// Corresponds to the CSS align-items property on a grid container. /// public enum AlignItems : byte { /// Browser default. Acts like . Normal = 0, /// Items are stretched to fill the grid area block size. Stretch = 1, /// Items are packed toward the start of the block axis. Start = 2, /// Items are packed toward the end of the block axis. End = 3, /// Items are centered on the block axis. Center = 4, /// Items are aligned along their first baseline. Baseline = 5, /// Items are aligned along their first baseline (same as ). FirstBaseline = 6, /// Items are aligned along their last baseline. LastBaseline = 7, } } /// /// A container view that arranges children in a grid of rows and columns. /// Container-level properties mirror the CSS Grid spec. /// /// /// CSS Grid Layout implementation for the Grid container. /// Provides MeasureCore and ArrangeCore implementations following the CSS Grid Layout Module Level 1 specification. /// /// /// Implementation notes: /// /// Track sizing supports: Length, Auto, MinContent, MaxContent, Fr (fractional units), MinMax, and FitContent /// Auto-placement follows grid-auto-flow (row or column direction) /// Named grid areas are parsed from TemplateAreas /// Gaps are applied between tracks /// Alignment is supported via justify-items, align-items, justify-content, align-content /// Child positioning via grid-row-start/end, grid-column-start/end, and grid-area /// /// Algorithm approach: /// /// Build grid structure: parse areas, determine placement for each child /// Measure tracks: resolve fixed sizes, content-based sizes, then distribute fr units /// Arrange children: position each child in its grid area with alignment /// /// public partial class Grid { /// /// Controls how auto-placed items are inserted into the grid. /// Corresponds to the CSS grid-auto-flow property. /// public enum AutoFlow : byte { /// Auto-placed items fill each row in turn, adding new rows as needed. Row = 0, /// Auto-placed items fill each column in turn, adding new columns as needed. Column = 1, /// /// Auto-placed items fill each row, using a dense packing algorithm that attempts /// to fill in holes earlier in the grid. /// RowDense = 2, /// /// Auto-placed items fill each column, using a dense packing algorithm that attempts /// to fill in holes earlier in the grid. /// ColumnDense = 3, } } /// /// A container view that arranges children in a grid of rows and columns. /// Container-level properties mirror the CSS Grid spec. /// /// /// CSS Grid Layout implementation for the Grid container. /// Provides MeasureCore and ArrangeCore implementations following the CSS Grid Layout Module Level 1 specification. /// /// /// Implementation notes: /// /// Track sizing supports: Length, Auto, MinContent, MaxContent, Fr (fractional units), MinMax, and FitContent /// Auto-placement follows grid-auto-flow (row or column direction) /// Named grid areas are parsed from TemplateAreas /// Gaps are applied between tracks /// Alignment is supported via justify-items, align-items, justify-content, align-content /// Child positioning via grid-row-start/end, grid-column-start/end, and grid-area /// /// Algorithm approach: /// /// Build grid structure: parse areas, determine placement for each child /// Measure tracks: resolve fixed sizes, content-based sizes, then distribute fr units /// Arrange children: position each child in its grid area with alignment /// /// public partial class Grid { /// /// The grid line where the item's row starts (1-indexed). 0 means auto. /// Corresponds to CSS grid-row-start. /// public static readonly View.Extra RowStart; /// /// The grid line where the item's row ends (1-indexed, exclusive). 0 means auto. /// Corresponds to CSS grid-row-end. /// public static readonly View.Extra RowEnd; /// /// The grid line where the item's column starts (1-indexed). 0 means auto. /// Corresponds to CSS grid-column-start. /// public static readonly View.Extra ColumnStart; /// /// The grid line where the item's column ends (1-indexed, exclusive). 0 means auto. /// Corresponds to CSS grid-column-end. /// public static readonly View.Extra ColumnEnd; /// /// Places the item into a named grid area defined by . /// Corresponds to CSS grid-area. /// public static readonly View.Extra Area; /// /// Controls the order in which the item appears within the grid, overriding source order. /// Corresponds to CSS order. /// public static readonly View.Extra Order; /// /// The number of rows the item spans. Shorthand for setting = + RowSpan. /// public static readonly View.Extra RowSpan; /// /// The number of columns the item spans. Shorthand for setting = + ColumnSpan. /// public static readonly View.Extra ColumnSpan; } /// /// A container view that arranges children in a grid of rows and columns. /// Container-level properties mirror the CSS Grid spec. /// /// /// CSS Grid Layout implementation for the Grid container. /// Provides MeasureCore and ArrangeCore implementations following the CSS Grid Layout Module Level 1 specification. /// /// /// Implementation notes: /// /// Track sizing supports: Length, Auto, MinContent, MaxContent, Fr (fractional units), MinMax, and FitContent /// Auto-placement follows grid-auto-flow (row or column direction) /// Named grid areas are parsed from TemplateAreas /// Gaps are applied between tracks /// Alignment is supported via justify-items, align-items, justify-content, align-content /// Child positioning via grid-row-start/end, grid-column-start/end, and grid-area /// /// Algorithm approach: /// /// Build grid structure: parse areas, determine placement for each child /// Measure tracks: resolve fixed sizes, content-based sizes, then distribute fr units /// Arrange children: position each child in its grid area with alignment /// /// public partial class Grid { /// /// Aligns the grid along the inline axis within the container when the grid is smaller than the container. /// Corresponds to the CSS justify-content property on a grid container. /// public enum JustifyContent : byte { /// Browser default. Acts like . Normal = 0, /// Grid is packed toward the start of the inline axis. Start = 1, /// Grid is packed toward the end of the inline axis. End = 2, /// Grid is centered along the inline axis. Center = 3, /// Grid is packed toward the left end of the inline axis. Left = 4, /// Grid is packed toward the right end of the inline axis. Right = 5, /// Columns are evenly distributed; first column at start, last at end. SpaceBetween = 6, /// Columns are evenly distributed with equal space around each column. SpaceAround = 7, /// Columns are evenly distributed with equal space between all columns including edges. SpaceEvenly = 8, /// Columns are stretched to fill the container inline size. Stretch = 9, } } /// /// A container view that arranges children in a grid of rows and columns. /// Container-level properties mirror the CSS Grid spec. /// /// /// CSS Grid Layout implementation for the Grid container. /// Provides MeasureCore and ArrangeCore implementations following the CSS Grid Layout Module Level 1 specification. /// /// /// Implementation notes: /// /// Track sizing supports: Length, Auto, MinContent, MaxContent, Fr (fractional units), MinMax, and FitContent /// Auto-placement follows grid-auto-flow (row or column direction) /// Named grid areas are parsed from TemplateAreas /// Gaps are applied between tracks /// Alignment is supported via justify-items, align-items, justify-content, align-content /// Child positioning via grid-row-start/end, grid-column-start/end, and grid-area /// /// Algorithm approach: /// /// Build grid structure: parse areas, determine placement for each child /// Measure tracks: resolve fixed sizes, content-based sizes, then distribute fr units /// Arrange children: position each child in its grid area with alignment /// /// public partial class Grid { /// /// Sets the default justify-self for all items, aligning them along the inline axis within their grid area. /// Corresponds to the CSS justify-items property. /// public enum JustifyItems : byte { /// Browser default. Acts like . Normal = 0, /// Items are stretched to fill the grid area inline size. Stretch = 1, /// Items are packed toward the start of the inline axis. Start = 2, /// Items are packed toward the end of the inline axis. End = 3, /// Items are centered along the inline axis. Center = 4, /// Items are packed toward the left end of the inline axis. Left = 5, /// Items are packed toward the right end of the inline axis. Right = 6, /// Items are aligned along their first baseline. Baseline = 7, /// Items are aligned along their first baseline (same as ). FirstBaseline = 8, /// Items are aligned along their last baseline. LastBaseline = 9, } } /// /// A container view that arranges children in a grid of rows and columns. /// Container-level properties mirror the CSS Grid spec. /// /// /// CSS Grid Layout implementation for the Grid container. /// Provides MeasureCore and ArrangeCore implementations following the CSS Grid Layout Module Level 1 specification. /// /// /// Implementation notes: /// /// Track sizing supports: Length, Auto, MinContent, MaxContent, Fr (fractional units), MinMax, and FitContent /// Auto-placement follows grid-auto-flow (row or column direction) /// Named grid areas are parsed from TemplateAreas /// Gaps are applied between tracks /// Alignment is supported via justify-items, align-items, justify-content, align-content /// Child positioning via grid-row-start/end, grid-column-start/end, and grid-area /// /// Algorithm approach: /// /// Build grid structure: parse areas, determine placement for each child /// Measure tracks: resolve fixed sizes, content-based sizes, then distribute fr units /// Arrange children: position each child in its grid area with alignment /// /// public partial class Grid { /// /// Represents a single CSS grid track sizing value such as a length, fr unit, /// auto, min-content, max-content, minmax(), or fit-content(). /// public readonly struct TrackSize { /// The kind of track sizing function. public TrackSizeKind Kind { get; } /// Pixel length for the track. public nfloat Value { get; } /// Minimum value for tracks. public nfloat MinValue { get; } /// Maximum value for and tracks. public nfloat MaxValue { get; } /// The track sizes to content automatically. Equivalent to CSS auto. public static readonly TrackSize Auto; /// The track is sized to the smallest size that fits its content without overflow. Equivalent to CSS min-content. public static readonly TrackSize MinContent; /// The track is sized to the largest max-content contribution of its items. Equivalent to CSS max-content. public static readonly TrackSize MaxContent; /// Creates a track of an exact pixel length. public static TrackSize Px(nfloat px); /// Creates a fractional track. Fr(1) = CSS 1fr. public static TrackSize Fr(nfloat fr); /// Creates a minmax(min, max) track with pixel min and max values. public static TrackSize MinMax(nfloat min, nfloat max); /// Creates a fit-content(max) track clamped to the given pixel maximum. public static TrackSize FitContent(nfloat max); /// Implicitly converts a pixel value to a track. public static implicit operator TrackSize(nfloat px); /// Implicitly converts a pixel value to a track. public static implicit operator TrackSize(float px); /// Implicitly converts a pixel value to a track. public static implicit operator TrackSize(double px); /// Implicitly converts a pixel value to a track. public static implicit operator TrackSize(int px); /// Returns the fully qualified type name of this instance. /// The fully qualified type name. public override string ToString(); } /// Identifies the kind of sizing function a represents. public enum TrackSizeKind : byte { /// Sized to available space (auto). Auto = 0, /// Sized to smallest content contribution (min-content). MinContent = 1, /// Sized to largest content contribution (max-content). MaxContent = 2, /// Fixed pixel length. Length = 3, /// Flexible fractional unit (fr). Fr = 4, /// Clamped between a min and a max (minmax()). MinMax = 5, /// Like but clamped to a maximum (fit-content()). FitContent = 6, } } /// /// A container view that arranges children in a grid of rows and columns. /// Container-level properties mirror the CSS Grid spec. /// /// /// CSS Grid Layout implementation for the Grid container. /// Provides MeasureCore and ArrangeCore implementations following the CSS Grid Layout Module Level 1 specification. /// /// /// Implementation notes: /// /// Track sizing supports: Length, Auto, MinContent, MaxContent, Fr (fractional units), MinMax, and FitContent /// Auto-placement follows grid-auto-flow (row or column direction) /// Named grid areas are parsed from TemplateAreas /// Gaps are applied between tracks /// Alignment is supported via justify-items, align-items, justify-content, align-content /// Child positioning via grid-row-start/end, grid-column-start/end, and grid-area /// /// Algorithm approach: /// /// Build grid structure: parse areas, determine placement for each child /// Measure tracks: resolve fixed sizes, content-based sizes, then distribute fr units /// Arrange children: position each child in its grid area with alignment /// /// public partial class Grid : ViewCollection { /// /// Defines the track sizes for explicitly defined columns. /// Corresponds to grid-template-columns. Default is an empty array (no explicit columns). /// public TrackSize[] TemplateColumns { get; set; } /// /// Defines the track sizes for explicitly defined rows. /// Corresponds to grid-template-rows. Default is an empty array (no explicit rows). /// public TrackSize[] TemplateRows { get; set; } /// /// Defines named grid areas. Each string in the array defines one row; space-separated cell names /// define columns within that row. A dot (.) denotes an unnamed cell. /// Corresponds to grid-template-areas. Default is an empty array. /// public string[] TemplateAreas { get; set; } /// /// Sizing for implicitly created columns (those outside ). /// Corresponds to grid-auto-columns. Default is . /// public TrackSize AutoColumns { get; set; } /// /// Sizing for implicitly created rows (those outside ). /// Corresponds to grid-auto-rows. Default is . /// public TrackSize AutoRows { get; set; } /// /// Controls how auto-placed items flow into the grid. /// Corresponds to grid-auto-flow. Default is . /// public AutoFlow GridAutoFlow { get; set; } /// /// Sets the default inline-axis alignment for all grid items within their grid areas. /// Corresponds to justify-items. Default is . /// public JustifyItems GridJustifyItems { get; set; } /// /// Sets the default block-axis alignment for all grid items within their grid areas. /// Corresponds to align-items. Default is . /// public AlignItems GridAlignItems { get; set; } /// /// Aligns the grid along the inline axis within the container when the grid is smaller than the container. /// Corresponds to justify-content. Default is . /// public JustifyContent GridJustifyContent { get; set; } /// /// Aligns the grid along the block axis within the container when the grid is smaller than the container. /// Corresponds to align-content. Default is . /// public AlignContent GridAlignContent { get; set; } /// /// Space between grid rows. /// Corresponds to row-gap. Default is 0. /// public nfloat RowGap { get; set; } /// /// Space between grid columns. /// Corresponds to column-gap. Default is 0. /// public nfloat ColumnGap { get; set; } } } namespace Xui.Core.UI.Layout { using Xui.Core.Canvas; using Xui.Core.Math2D; /// /// A container view that arranges children along a main axis with flexible sizing and wrapping. /// Container-level properties mirror the CSS Flex Box spec. /// /// /// Supports row/column layout, wrapping, order, gaps, flexible sizing, and space distribution. /// Item baseline alignment currently falls back to cross-axis start; line baseline alignment /// falls back to start. Views do not yet expose a common layout-baseline contract. /// public partial class FlexBox { /// Override to compute the desired border-edge size. protected override Size MeasureCore(Size available, IMeasureContext context); /// Override to arrange children within this view's final frame. protected override void ArrangeCore(Rect rect, IMeasureContext context); } /// /// A container view that arranges children in a grid of rows and columns. /// Container-level properties mirror the CSS Grid spec. /// /// /// CSS Grid Layout implementation for the Grid container. /// Provides MeasureCore and ArrangeCore implementations following the CSS Grid Layout Module Level 1 specification. /// /// /// Implementation notes: /// /// Track sizing supports: Length, Auto, MinContent, MaxContent, Fr (fractional units), MinMax, and FitContent /// Auto-placement follows grid-auto-flow (row or column direction) /// Named grid areas are parsed from TemplateAreas /// Gaps are applied between tracks /// Alignment is supported via justify-items, align-items, justify-content, align-content /// Child positioning via grid-row-start/end, grid-column-start/end, and grid-area /// /// Algorithm approach: /// /// Build grid structure: parse areas, determine placement for each child /// Measure tracks: resolve fixed sizes, content-based sizes, then distribute fr units /// Arrange children: position each child in its grid area with alignment /// /// public partial class Grid { /// Override to compute the desired border-edge size. protected override Size MeasureCore(Size availableBorderEdgeSize, IMeasureContext context); /// Override to arrange children within this view's final frame. protected override void ArrangeCore(Rect rect, IMeasureContext context); } } namespace Xui.GPU.Backends { /// /// Base interface for shader backend code generators. /// public interface IShaderBackend { /// /// Gets the name of this backend (e.g., "HLSL", "MSL", "GLSL"). /// string Name { get; } /// /// Generates shader code from the IR module. /// /// The IR module to generate code from. /// The generated shader code as a string. string GenerateCode(IR.IrShaderModule module); } } namespace Xui.GPU.Backends.Glsl { using System.Globalization; using System.Text; using Xui.GPU.IR; /// Emits GLSL ES 3.00 for WebGL 2 from the shared shader IR. /// /// Define XUI_VERTEX or XUI_FRAGMENT immediately after the version line when compiling /// a stage. Both stages use main. Bind XuiBindings as a std140 uniform block; matrices /// are row-major in that buffer, matching Xui's CPU matrices. Vertex clip depth is /// converted from Xui's [0,w] convention to OpenGL's [-w,w]. Texture/sampler pairs /// become combined sampler uniforms named x_texture_TextureField_SamplerField. /// Unsupported IR fails explicitly; this backend does not provide a GPU device. /// public sealed class GlslCodeGenerator : IShaderBackend { /// Gets the source-generator backend selector. public string Name { get; } /// Generates a source bundle containing both compile-time-selected stages. public string GenerateCode(IrShaderModule module); } } namespace Xui.GPU.Backends.Hlsl { using System.Text; using Xui.GPU.IR; /// /// HLSL code generator for DirectX shaders. /// Translates IR to HLSL shader code. /// public class HlslCodeGenerator : IShaderBackend { /// Gets the name of this backend ("HLSL"). public string Name { get; } /// /// Generates HLSL shader code from an IR module. /// public string GenerateCode(IrShaderModule module); } } namespace Xui.GPU.Backends.Metal { using System.Text; using Xui.GPU.IR; /// /// Metal Shading Language (MSL) code generator for Apple platforms (macOS, iOS). /// Translates IR to MSL shader code compatible with the Metal framework. /// /// /// MSL maps closely to C++14 with Metal-specific extensions. /// Key differences from HLSL: /// - Vertex/fragment functions use [[attribute(n)]] instead of semantics /// - Built-ins use [[position]], [[color(n)]], etc. /// - Resource bindings use [[buffer(n)]], [[texture(n)]], [[sampler(n)]] /// - Entry points are marked with [[vertex]] and [[fragment]] attributes /// - Structs use attribute annotations directly on fields /// public class MslCodeGenerator : IShaderBackend { /// /// Gets the name of this backend (e.g., "HLSL", "MSL", "GLSL"). /// public string Name { get; } /// /// Generates MSL shader code from an IR module. /// public string GenerateCode(IrShaderModule module); } } namespace Xui.GPU.Hardware { /// /// Specifies which triangle faces to cull during rasterization. /// public enum GpuCullMode { /// No culling — all triangles are rendered. None = 0, /// Back-facing triangles are culled (default). Back = 1, /// Front-facing triangles are culled. Front = 2, } /// /// Describes a hardware GPU render pipeline, binding shaders and state together. /// public sealed class GpuPipelineDesc { /// Enables premultiplied source-over blending. Requires the resource-device capability. public bool PremultipliedAlpha { get; set; } /// Vertex attribute component counts in location order; null selects Float3 + Float4. public int[]? VertexComponents { get; set; } /// Gets or sets the compiled vertex shader. public IGpuVertexShader? VertexShader { get; set; } /// Gets or sets the compiled fragment (pixel) shader. public IGpuFragmentShader? FragmentShader { get; set; } /// Gets or sets whether depth testing is enabled. public bool DepthTestEnabled { get; set; } /// Gets or sets whether depth writing is enabled. public bool DepthWriteEnabled { get; set; } /// Gets or sets the triangle cull mode. public GpuCullMode CullMode { get; set; } } /// Shared validation for tightly packed RGBA8 mip chains. public static class GpuTextureValidation { /// Checks dimensions and each mip's byte length before any native allocation. public static void Validate(int width, int height, IReadOnlyList levels); } /// /// Describes the vertex buffer layout for a GPU draw call. /// public sealed class GpuVertexBufferDesc { /// Gets or sets the stride (bytes per vertex). public int Stride { get; set; } /// Gets or sets the vertex count. public int VertexCount { get; set; } } /// /// Represents a GPU command list / draw context for recording rendering commands. /// public interface IGpuCommandList : IDisposable { /// /// Begins a render pass targeting the given render target. /// void BeginRenderPass(IGpuRenderTarget renderTarget, Xui.GPU.Shaders.Types.Color4 clearColor); /// /// Ends the current render pass. /// void EndRenderPass(); /// /// Sets the pipeline state for subsequent draw calls. /// void SetPipeline(GpuPipelineDesc pipeline); /// /// Sets the vertex buffer for subsequent draw calls. /// /// Pointer to vertex data. /// Vertex buffer description. unsafe void SetVertexBuffer(void* data, GpuVertexBufferDesc desc); /// Uploads tightly packed unmanaged vertices; the input is borrowed only for this call. /// Native backends use the pointer overload by default. Managed backends may override this /// overload to copy non-contiguous managed storage into their upload representation. unsafe void SetVertexBuffer(ReadOnlySpan vertices) where T : unmanaged; /// Uploads one unmanaged constant-buffer value, borrowed only for this call. unsafe void SetConstantBuffer(in T value) where T : unmanaged; /// /// Sets the uniform/constant buffer data. /// /// Pointer to constant data. /// Size of the constant data in bytes. unsafe void SetConstantBuffer(void* data, int sizeInBytes); /// /// Draws primitives using the current pipeline and vertex buffer. /// /// Number of vertices to draw. void Draw(int vertexCount); /// /// Submits all recorded commands. Native presentation targets schedule presentation /// asynchronously; submission does not mean that the frame has finished displaying. /// Offscreen readback uses the backend's completion/synchronization mechanism. /// void Commit(); } /// /// Abstract interface for a GPU hardware device. /// Implementations exist for Direct3D 11 (Windows) and Metal (macOS/iOS). /// public interface IGpuDevice : IDisposable { /// Gets the name of this GPU backend (e.g., "D3D11", "Metal"). string BackendName { get; } /// Gets whether this device has been disposed. bool IsDisposed { get; } /// /// Compiles a vertex shader from native shader source code. /// /// The shader source (HLSL for D3D11, MSL for Metal). /// The name of the entry point function. /// A compiled vertex shader. IGpuVertexShader CompileVertexShader(string source, string entryPoint); /// /// Compiles a fragment (pixel) shader from native shader source code. /// /// The shader source (HLSL for D3D11, MSL for Metal). /// The name of the entry point function. /// A compiled fragment shader. IGpuFragmentShader CompileFragmentShader(string source, string entryPoint); /// /// Creates a render target texture. /// /// Width in pixels. /// Height in pixels. /// A render target that can be used with a command list. IGpuRenderTarget CreateRenderTarget(int width, int height); /// /// Creates a command list for recording rendering commands. /// IGpuCommandList CreateCommandList(); } /// /// Represents a compiled fragment (pixel) shader. /// public interface IGpuFragmentShader : IGpuShader { } /// /// Represents a GPU render target backed by a texture. /// Offscreen targets support readback; borrowed native presentation targets may forbid it. /// public interface IGpuRenderTarget : IDisposable { /// Gets the underlying texture. Framebuffer-only presentation targets may throw NotSupportedException. IGpuTexture Texture { get; } /// Gets the width of the render target in pixels. int Width { get; } /// Gets the height of the render target in pixels. int Height { get; } /// /// Reads back the rendered pixels to a CPU byte array. /// Native presentation targets may throw NotSupportedException. /// The pixel format is BGRA (Blue, Green, Red, Alpha), 4 bytes per pixel. /// /// /// A byte array of size Width * Height * 4 to receive the pixels. /// void ReadbackPixelsBgra(byte[] destination); } /// /// Represents a compiled GPU shader ready for use in a hardware pipeline. /// public interface IGpuShader : IDisposable { /// Gets the name of this shader. string Name { get; } } /// /// Represents a GPU texture that can be used as a render target. /// public interface IGpuTexture : IDisposable { /// Gets the width of the texture in pixels. int Width { get; } /// Gets the height of the texture in pixels. int Height { get; } } /// /// Represents a compiled vertex shader. /// public interface IGpuVertexShader : IGpuShader { } } namespace Xui.GPU.Hardware { using Xui.GPU.Shaders.Types; /// Resource bindings supported by devices implementing . public interface IGpuResourceCommandList : IGpuCommandList { /// Binds an immutable vertex buffer without uploading it again. void SetVertexBuffer(IGpuVertexBuffer buffer); /// Binds a sampled texture to a fragment texture and sampler slot; mip filtering is linear. void SetTexture(int slot, IGpuTexture texture, Sampler sampler); } /// Optional device capability for sampled RGBA textures and immutable vertex buffers. public interface IGpuResourceDevice : IGpuDevice { /// Uploads premultiplied RGBA8 mip levels, largest first, with tightly packed rows. IGpuTexture CreateSampledTexture(int width, int height, IReadOnlyList mipLevels); /// Uploads immutable vertices once. The caller owns the returned buffer. IGpuVertexBuffer CreateVertexBuffer(ReadOnlySpan vertices, int stride); } /// An owned immutable vertex buffer. public interface IGpuVertexBuffer : IDisposable { /// Number of vertices in the buffer. int VertexCount { get; } } } namespace Xui.GPU.IR { /// /// Binary operator kind. /// public enum BinaryOperator { /// Addition operator (+). Add, /// Subtraction operator (-). Subtract, /// Multiplication operator (*). Multiply, /// Division operator (/). Divide, /// Modulo operator (%). Modulo, /// Equality comparison (==). Equal, /// Inequality comparison (!=). NotEqual, /// Less-than comparison (<). LessThan, /// Less-than-or-equal comparison (<=). LessThanOrEqual, /// Greater-than comparison (>). GreaterThan, /// Greater-than-or-equal comparison (>=). GreaterThanOrEqual, /// Logical AND. LogicalAnd, /// Logical OR. LogicalOr, /// Bitwise AND (&). BitwiseAnd, /// Bitwise OR (|). BitwiseOr, /// Bitwise XOR (^). BitwiseXor, /// Left bit shift (<<). ShiftLeft, /// Right bit shift (>>). ShiftRight } /// /// Built-in semantic kinds. /// public enum BuiltInSemantic { /// Vertex position output semantic. Position, /// Fragment depth output semantic. FragDepth, /// Instance identifier semantic. InstanceId, /// Vertex identifier semantic. VertexId } /// /// Interpolation mode for varyings. /// public enum InterpolationMode { /// Linear interpolation without perspective correction. Linear, /// No interpolation; value is constant across the primitive. Flat, /// Perspective-correct interpolation (default). Perspective } /// /// Represents an assignment statement. /// public class IrAssignment : IrStatement { /// Gets the IR node kind for this statement. public override IrNodeKind Kind { get; } /// Gets the assignment target expression. public IrExpression Target { get; } /// Gets the value expression to assign. public IrExpression Value { get; } /// /// Initializes a new instance of with the specified target and value. /// public IrAssignment(IrExpression target, IrExpression value); } /// /// Represents a binary operation. /// public class IrBinaryOp : IrExpression { /// Gets the node kind for this binary operation. public override IrNodeKind Kind { get; } /// Gets the result type of the binary operation. public override IrType Type { get; } /// Gets the binary operator. public BinaryOperator Operator { get; } /// Gets the left-hand operand. public IrExpression Left { get; } /// Gets the right-hand operand. public IrExpression Right { get; } /// Initializes a new instance of the class. public IrBinaryOp(BinaryOperator op, IrExpression left, IrExpression right, IrType type); } /// /// Represents a binding decoration for resources. /// public class IrBindingDecoration : IrDecoration { /// Gets the IR node kind for this decoration. public override IrNodeKind Kind { get; } /// Gets the binding group index. public int Group { get; } /// Gets the binding slot index within the group. public int Binding { get; } /// /// Initializes a new instance of with the specified group and binding. /// public IrBindingDecoration(int group, int binding); } /// /// Represents a block of statements. /// public class IrBlock : IrStatement { /// Gets the IR node kind for this block. public override IrNodeKind Kind { get; } /// Gets the list of statements in this block. public List Statements { get; } /// /// Initializes a new empty block. /// public IrBlock(); /// /// Initializes a new block with the specified statements. /// public IrBlock(IEnumerable statements); } /// /// Represents a built-in semantic decoration. /// public class IrBuiltInDecoration : IrDecoration { /// Gets the IR node kind for this decoration. public override IrNodeKind Kind { get; } /// Gets the built-in semantic. public BuiltInSemantic Semantic { get; } /// /// Initializes a new instance of with the specified semantic. /// public IrBuiltInDecoration(BuiltInSemantic semantic); } /// /// Represents a constant value. /// public class IrConstant : IrExpression { /// Gets the node kind for this constant. public override IrNodeKind Kind { get; } /// Gets the type of the constant. public override IrType Type { get; } /// Gets the constant value. public object Value { get; } /// Initializes a new instance of the class. public IrConstant(IrType type, object value); } /// /// Represents a constructor call. /// public class IrConstructor : IrExpression { /// Gets the node kind for this constructor call. public override IrNodeKind Kind { get; } /// Gets the type being constructed. public override IrType Type { get; } /// Gets the list of arguments passed to the constructor. public List Arguments { get; } /// Initializes a new instance of the class. public IrConstructor(IrType type, List arguments); } /// /// Base class for decoration nodes (attributes). /// public abstract class IrDecoration : IrNode { } /// /// Base class for all expression nodes in the IR. /// public abstract class IrExpression : IrNode { /// /// Gets the type of this expression. /// public abstract IrType Type { get; } } /// /// Represents a field access. /// public class IrFieldAccess : IrExpression { /// Gets the node kind for this field access. public override IrNodeKind Kind { get; } /// Gets the result type of the field access. public override IrType Type { get; } /// Gets the expression representing the object being accessed. public IrExpression Object { get; } /// Gets the name of the field being accessed. public string FieldName { get; } /// Initializes a new instance of the class. public IrFieldAccess(IrExpression obj, string fieldName, IrType type); } /// /// Represents a fragment shader stage. /// public class IrFragmentStage : IrNode { /// Gets the IR node kind for this stage. public override IrNodeKind Kind { get; } /// Gets or sets the stage name. public string Name { get; set; } /// Gets or sets the input struct type. public IrStructType InputType { get; set; } /// Gets or sets the output struct type. public IrStructType OutputType { get; set; } /// Gets or sets the optional bindings struct type. public IrStructType? BindingsType { get; set; } /// Gets or sets the body block of this stage. public IrBlock Body { get; set; } } /// /// Represents a function declaration. /// public class IrFunctionDecl : IrNode { /// Gets the IR node kind for this declaration. public override IrNodeKind Kind { get; } /// Gets or sets the function name. public string Name { get; set; } /// Gets or sets the return type. public IrType ReturnType { get; set; } /// Gets the list of function parameters. public List Parameters { get; } /// Gets or sets the function body block. public IrBlock Body { get; set; } } /// /// Represents an if statement. /// public class IrIf : IrStatement { /// Gets the IR node kind for this statement. public override IrNodeKind Kind { get; } /// Gets the condition expression. public IrExpression Condition { get; } /// Gets the block executed when the condition is true. public IrBlock ThenBlock { get; } /// Gets the optional block executed when the condition is false. public IrBlock? ElseBlock { get; } /// /// Initializes a new instance of with the specified condition and blocks. /// public IrIf(IrExpression condition, IrBlock thenBlock, IrBlock? elseBlock = null); } /// /// Represents an interpolation mode decoration. /// public class IrInterpolationDecoration : IrDecoration { /// Gets the IR node kind for this decoration. public override IrNodeKind Kind { get; } /// Gets the interpolation mode. public InterpolationMode Mode { get; } /// /// Initializes a new instance of with the specified mode. /// public IrInterpolationDecoration(InterpolationMode mode); } /// /// Represents a location decoration for vertex inputs/outputs. /// public class IrLocationDecoration : IrDecoration { /// Gets the IR node kind for this decoration. public override IrNodeKind Kind { get; } /// Gets the location index. public int Location { get; } /// /// Initializes a new instance of with the specified location. /// public IrLocationDecoration(int location); } /// /// Represents a matrix type (Float4x4, etc.). /// public class IrMatrixType : IrType { /// Gets the IR node kind for this type. public override IrNodeKind Kind { get; } /// Gets the display name of this matrix type. public override string Name { get; } /// Gets the scalar element type of the matrix. public IrScalarType ElementType { get; } /// Gets the number of rows. public int Rows { get; } /// Gets the number of columns. public int Columns { get; } /// /// Initializes a new instance of with the specified element type and dimensions. /// public IrMatrixType(IrScalarType elementType, int rows, int columns); } /// /// Represents a method call (shader intrinsic or user function). /// public class IrMethodCall : IrExpression { /// Gets the node kind for this method call. public override IrNodeKind Kind { get; } /// Gets the return type of the method call. public override IrType Type { get; } /// Gets the name of the method being called. public string MethodName { get; } /// Gets the list of arguments passed to the method. public List Arguments { get; } /// Gets the optional target expression for instance method calls. public IrExpression? Target { get; } /// Initializes a new instance of the class. public IrMethodCall(string methodName, List arguments, IrType type, IrExpression? target = null); } /// /// Base class for all IR nodes in the intermediate representation. /// public abstract class IrNode { /// /// Gets the node kind for pattern matching and visitors. /// public abstract IrNodeKind Kind { get; } /// /// Gets or sets the source location where this node originates from. /// Used to generate accurate error messages mapping back to C# source. /// public SourceLocation? SourceLocation { get; set; } } /// /// Enumeration of all IR node kinds. /// public enum IrNodeKind { /// Scalar type node. ScalarType, /// Vector type node. VectorType, /// Matrix type node. MatrixType, /// Struct type node. StructType, /// Texture type node. TextureType, /// Sampler type node. SamplerType, /// Constant expression. Constant, /// Parameter reference expression. Parameter, /// Field access expression. Field, /// Binary operation expression. BinaryOp, /// Unary operation expression. UnaryOp, /// Method call expression. MethodCall, /// Constructor call expression. Constructor, /// Variable declaration statement. VarDecl, /// Assignment statement. Assignment, /// Return statement. Return, /// Conditional statement. If, /// Block of statements. Block, /// Location decoration. Location, /// Built-in semantic decoration. BuiltIn, /// Resource binding decoration. Binding, /// Interpolation mode decoration. Interpolation, /// Shader module node. ShaderModule, /// Vertex shader stage. VertexStage, /// Fragment shader stage. FragmentStage, /// Struct declaration. StructDecl, /// Function declaration. FunctionDecl, } /// /// Represents a parameter reference. /// public class IrParameter : IrExpression { /// Gets the node kind for this parameter reference. public override IrNodeKind Kind { get; } /// Gets the type of the parameter. public override IrType Type { get; } /// Gets the name of the parameter. public string Name { get; } /// Initializes a new instance of the class. public IrParameter(string name, IrType type); } /// /// Represents a return statement. /// public class IrReturn : IrStatement { /// Gets the IR node kind for this statement. public override IrNodeKind Kind { get; } /// Gets the optional return value expression. public IrExpression? Value { get; } /// /// Initializes a new instance of with an optional return value. /// public IrReturn(IrExpression? value = null); } /// /// Represents a sampler type. /// public class IrSamplerType : IrType { /// Gets the IR node kind for this type. public override IrNodeKind Kind { get; } /// Gets the display name of this sampler type. public override string Name { get; } /// Shared singleton instance of the sampler type. public static readonly IrSamplerType Instance; } /// /// Represents a scalar type (F32, I32, U32, Bool). /// public class IrScalarType : IrType { /// Gets the IR node kind for this type. public override IrNodeKind Kind { get; } /// Gets the display name of this scalar type. public override string Name { get; } /// Gets the scalar kind. public ScalarKind ScalarKind { get; } /// /// Initializes a new instance of with the specified scalar kind. /// public IrScalarType(ScalarKind kind); } /// /// Represents a complete shader module with all stages and declarations. /// public class IrShaderModule : IrNode { /// Gets the IR node kind for this module. public override IrNodeKind Kind { get; } /// Gets or sets the module name. public string Name { get; set; } /// Gets the list of struct declarations. public List Structs { get; } /// Gets the list of function declarations. public List Functions { get; } /// Gets or sets the optional vertex shader stage. public IrVertexStage? VertexStage { get; set; } /// Gets or sets the optional fragment shader stage. public IrFragmentStage? FragmentStage { get; set; } } /// /// Base class for all statement nodes in the IR. /// public abstract class IrStatement : IrNode { } /// /// Represents a struct declaration. /// public class IrStructDecl : IrNode { /// Gets the IR node kind for this declaration. public override IrNodeKind Kind { get; } /// Gets the struct type being declared. public IrStructType Type { get; } /// /// Initializes a new instance of with the specified struct type. /// public IrStructDecl(IrStructType type); } /// /// Represents a field in a struct. /// public class IrStructField { /// Gets or sets the field name. public string Name { get; set; } /// Gets or sets the field type. public IrType Type { get; set; } /// Gets the list of decorations applied to this field. public List Decorations { get; } } /// /// Represents a struct type. /// public class IrStructType : IrType { /// Gets the IR node kind for this type. public override IrNodeKind Kind { get; } /// Gets the name of this struct type. public override string Name { get; } /// Gets the list of fields in this struct. public List Fields { get; } /// /// Initializes a new instance of with the specified name. /// public IrStructType(string name); } /// /// Represents a texture type. /// public class IrTextureType : IrType { /// Gets the IR node kind for this type. public override IrNodeKind Kind { get; } /// Gets the display name of this texture type. public override string Name { get; } /// Gets the pixel element type of the texture. public IrType PixelType { get; } /// /// Initializes a new instance of with the specified pixel type. /// public IrTextureType(IrType pixelType); } /// /// Base class for all type nodes in the IR. /// public abstract class IrType : IrNode { /// /// Gets the name of this type. /// public abstract string Name { get; } } /// /// Represents a unary operation. /// public class IrUnaryOp : IrExpression { /// Gets the node kind for this unary operation. public override IrNodeKind Kind { get; } /// Gets the result type of the unary operation. public override IrType Type { get; } /// Gets the unary operator. public UnaryOperator Operator { get; } /// Gets the operand of the unary operation. public IrExpression Operand { get; } /// Initializes a new instance of the class. public IrUnaryOp(UnaryOperator op, IrExpression operand, IrType type); } /// /// Represents a variable declaration. /// public class IrVarDecl : IrStatement { /// Gets the IR node kind for this statement. public override IrNodeKind Kind { get; } /// Gets the variable name. public string Name { get; } /// Gets the variable type. public IrType Type { get; } /// Gets the optional initializer expression. public IrExpression? Initializer { get; } /// /// Initializes a new instance of with the specified name, type, and optional initializer. /// public IrVarDecl(string name, IrType type, IrExpression? initializer = null); } /// /// Represents a vector type (Float2, Float3, Float4, Int2, etc.). /// public class IrVectorType : IrType { /// Gets the IR node kind for this type. public override IrNodeKind Kind { get; } /// Gets the display name of this vector type. public override string Name { get; } /// Gets the scalar element type of the vector. public IrScalarType ElementType { get; } /// Gets the number of components (2-4). public int Dimension { get; } /// /// Initializes a new instance of with the specified element type and dimension. /// public IrVectorType(IrScalarType elementType, int dimension); } /// /// Represents a vertex shader stage. /// public class IrVertexStage : IrNode { /// Gets the IR node kind for this stage. public override IrNodeKind Kind { get; } /// Gets or sets the stage name. public string Name { get; set; } /// Gets or sets the input struct type. public IrStructType InputType { get; set; } /// Gets or sets the output struct type. public IrStructType OutputType { get; set; } /// Gets or sets the optional bindings struct type. public IrStructType? BindingsType { get; set; } /// Gets or sets the body block of this stage. public IrBlock Body { get; set; } } /// /// Kind of scalar type. /// public enum ScalarKind { /// 32-bit floating point. F32, /// 32-bit signed integer. I32, /// 32-bit unsigned integer. U32, /// Boolean value. Bool } /// /// Represents a location in source code. /// Used to map IR nodes back to original C# source for error reporting. /// public class SourceLocation { /// /// Gets the source file path. /// public string FilePath { get; set; } /// /// Gets the line number (1-based). /// public int Line { get; set; } /// /// Gets the column number (1-based). /// public int Column { get; set; } /// /// Gets a formatted string representation of this location. /// public string ToDisplayString(); } /// /// Unary operator kind. /// public enum UnaryOperator { /// Arithmetic negation (-). Negate, /// Logical NOT (!). LogicalNot, /// Bitwise NOT (~). BitwiseNot } } namespace Xui.GPU.Resources { /// /// Represents a uniform buffer resource containing constant shader data. /// /// The uniform data structure type. public readonly struct Uniform where T : unmanaged { /// /// Gets the uniform data value. /// public T Value { get; init; } /// /// Initializes a new instance of the struct. /// /// The uniform data. public Uniform(T value); } } namespace Xui.GPU.Shaders { using Xui.GPU.Shaders.Types; /// /// Standard fragment shader output structure. /// public struct FragmentOutput { /// /// The output color value. /// public Color4 Color; } } namespace Xui.GPU.Shaders { /// /// Fragment shader interface that computes pixel colors. /// /// The fragment input/varyings structure type. /// The fragment output structure type. /// The shader resource bindings type. public interface IFragmentShader : IShaderStage where TInput : unmanaged where TOutput : unmanaged where TBindings : struct { /// /// Executes the fragment shader for a single fragment. /// /// The interpolated fragment input data. /// The shader resource bindings. /// The computed fragment output. TOutput Execute(TInput input, in TBindings bindings); } /// /// Base interface for all shader stages. /// Shader stages are the execution points in the rendering pipeline. /// public interface IShaderStage { } /// /// Vertex shader interface that transforms vertex input data. /// /// The vertex input structure type. /// The vertex output/varyings structure type. /// The shader resource bindings type. public interface IVertexShader : IShaderStage where TInput : unmanaged where TOutput : unmanaged where TBindings : struct { /// /// Executes the vertex shader for a single vertex. /// /// The vertex input data. /// The shader resource bindings. /// The transformed vertex output. TOutput Execute(TInput input, in TBindings bindings); } } namespace Xui.GPU.Shaders.Attributes { /// /// Built-in shader semantics. /// public enum BuiltIn { /// /// Vertex position in clip space. /// Position, /// /// Fragment depth value. /// FragDepth, /// /// Vertex instance ID. /// InstanceId, /// /// Vertex ID. /// VertexId, } /// /// Specifies that a field represents a built-in shader semantic. /// [AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = false)] public sealed class BuiltInAttribute : Attribute { /// /// Gets the built-in semantic. /// public BuiltIn Semantic { get; } /// /// Initializes a new instance of the class. /// /// The built-in semantic. public BuiltInAttribute(BuiltIn semantic); } /// /// Marks a type as a fragment shader stage. /// [AttributeUsage(AttributeTargets.Struct, AllowMultiple = false, Inherited = false)] public sealed class FragmentShaderAttribute : Attribute { } /// /// Attribute to control how a varying (vertex shader output / fragment shader input) is interpolated. /// /// /// This attribute maps to HLSL interpolation modifiers (linear, noperspective, nointerpolation), /// Metal's [[flat]], [[center_perspective]], etc., and Vulkan's interpolation decorations. /// [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = false)] public sealed class InterpolationAttribute : Attribute { /// /// Gets the interpolation mode. /// public InterpolationMode Mode { get; } /// /// Initializes a new instance of the class. /// /// The interpolation mode to use for this varying. public InterpolationAttribute(InterpolationMode mode); } /// /// Specifies the interpolation mode for a shader varying (vertex output / fragment input). /// public enum InterpolationMode { /// /// Default perspective-correct interpolation. /// Values are interpolated with perspective correction across the triangle. /// Perspective, /// /// Linear interpolation without perspective correction. /// Values are interpolated linearly in screen space. /// Linear, /// /// No interpolation - flat shading. /// The value from the provoking vertex is used for the entire primitive. /// Flat } /// /// Specifies the location index for a vertex input or fragment output field. /// [AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = false)] public sealed class LocationAttribute : Attribute { /// /// Gets the location index. /// public int Index { get; } /// /// Initializes a new instance of the class. /// /// The location index. public LocationAttribute(int index); } /// /// Marks a type as a shader program definition. /// Used by source generators to discover and process shader programs. /// [AttributeUsage(AttributeTargets.Struct, AllowMultiple = false, Inherited = false)] public sealed class ShaderProgramAttribute : Attribute { } /// /// Marks a type as a vertex shader stage. /// [AttributeUsage(AttributeTargets.Struct, AllowMultiple = false, Inherited = false)] public sealed class VertexShaderAttribute : Attribute { } } namespace Xui.GPU.Shaders.Intrinsics { using Xui.GPU.Shaders.Types; /// /// Provides shader intrinsic functions for mathematical operations. /// These functions mirror GPU shader intrinsics and will be translated /// to appropriate backend-specific implementations. /// public static class Shader { /// /// Clamps a value between a minimum and maximum value. /// public static F32 Clamp(F32 value, F32 min, F32 max); /// /// Saturates a value to the range [0, 1]. /// public static F32 Saturate(F32 value); /// /// Linearly interpolates between two values. /// /// The start value. /// The end value. /// The interpolation factor (typically 0-1). public static F32 Lerp(F32 a, F32 b, F32 t); /// /// Returns the minimum of two values. /// public static F32 Min(F32 a, F32 b); /// /// Returns the maximum of two values. /// public static F32 Max(F32 a, F32 b); /// /// Returns the absolute value. /// public static F32 Abs(F32 value); /// /// Returns the sine of the specified angle in radians. /// public static F32 Sin(F32 angle); /// /// Returns the cosine of the specified angle in radians. /// public static F32 Cos(F32 angle); /// /// Returns the tangent of the specified angle in radians. /// public static F32 Tan(F32 angle); /// /// Returns the arc sine (inverse sine) in radians. /// public static F32 Asin(F32 value); /// /// Returns the arc cosine (inverse cosine) in radians. /// public static F32 Acos(F32 value); /// /// Returns the arc tangent (inverse tangent) in radians. /// public static F32 Atan(F32 value); /// /// Returns the arc tangent of y/x in radians. /// public static F32 Atan2(F32 y, F32 x); /// /// Returns the value raised to the specified power. /// public static F32 Pow(F32 value, F32 exponent); /// /// Returns the exponential (e^x). /// public static F32 Exp(F32 value); /// /// Returns the natural logarithm. /// public static F32 Log(F32 value); /// /// Returns the base-2 logarithm. /// public static F32 Log2(F32 value); /// /// Returns the square root. /// public static F32 Sqrt(F32 value); /// /// Returns the reciprocal square root (1 / sqrt(x)). /// public static F32 Rsqrt(F32 value); /// /// Returns the largest integer less than or equal to the value. /// public static F32 Floor(F32 value); /// /// Returns the smallest integer greater than or equal to the value. /// public static F32 Ceil(F32 value); /// /// Returns the fractional part of the value. /// public static F32 Fract(F32 value); /// /// Returns the value rounded to the nearest integer. /// public static F32 Round(F32 value); /// /// Returns the dot product of two 2D vectors. /// public static F32 Dot(Float2 a, Float2 b); /// /// Returns the dot product of two 3D vectors. /// public static F32 Dot(Float3 a, Float3 b); /// /// Returns the dot product of two 4D vectors. /// public static F32 Dot(Float4 a, Float4 b); /// /// Returns the length (magnitude) of a 2D vector. /// public static F32 Length(Float2 v); /// /// Returns the length (magnitude) of a 3D vector. /// public static F32 Length(Float3 v); /// /// Returns the length (magnitude) of a 4D vector. /// public static F32 Length(Float4 v); /// /// Returns the distance between two 2D points. /// public static F32 Distance(Float2 a, Float2 b); /// /// Returns the distance between two 3D points. /// public static F32 Distance(Float3 a, Float3 b); /// /// Returns the distance between two 4D points. /// public static F32 Distance(Float4 a, Float4 b); /// /// Returns the normalized 2D vector (length = 1). /// public static Float2 Normalize(Float2 v); /// /// Returns the normalized 3D vector (length = 1). /// public static Float3 Normalize(Float3 v); /// /// Returns the normalized 4D vector (length = 1). /// public static Float4 Normalize(Float4 v); /// /// Returns the cross product of two 3D vectors. /// public static Float3 Cross(Float3 a, Float3 b); /// /// Linearly interpolates between two 2D vectors. /// public static Float2 Lerp(Float2 a, Float2 b, F32 t); /// /// Linearly interpolates between two 3D vectors. /// public static Float3 Lerp(Float3 a, Float3 b, F32 t); /// /// Linearly interpolates between two 4D vectors. /// public static Float4 Lerp(Float4 a, Float4 b, F32 t); /// /// Component-wise minimum of two 2D vectors. /// public static Float2 Min(Float2 a, Float2 b); /// /// Component-wise minimum of two 3D vectors. /// public static Float3 Min(Float3 a, Float3 b); /// /// Component-wise minimum of two 4D vectors. /// public static Float4 Min(Float4 a, Float4 b); /// /// Component-wise maximum of two 2D vectors. /// public static Float2 Max(Float2 a, Float2 b); /// /// Component-wise maximum of two 3D vectors. /// public static Float3 Max(Float3 a, Float3 b); /// /// Component-wise maximum of two 4D vectors. /// public static Float4 Max(Float4 a, Float4 b); /// /// Component-wise clamp of a 2D vector. /// public static Float2 Clamp(Float2 value, Float2 min, Float2 max); /// /// Component-wise clamp of a 3D vector. /// public static Float3 Clamp(Float3 value, Float3 min, Float3 max); /// /// Component-wise clamp of a 4D vector. /// public static Float4 Clamp(Float4 value, Float4 min, Float4 max); /// /// Saturates a 2D vector to the range [0, 1] component-wise. /// public static Float2 Saturate(Float2 value); /// /// Saturates a 3D vector to the range [0, 1] component-wise. /// public static Float3 Saturate(Float3 value); /// /// Saturates a 4D vector to the range [0, 1] component-wise. /// public static Float4 Saturate(Float4 value); /// /// Returns the partial derivative of the value with respect to screen-space X. /// Only available in fragment shaders. /// /// /// This intrinsic requires fragment execution in 2x2 quads to compute derivatives. /// In the software renderer, this will be implemented by comparing adjacent fragment values. /// public static F32 Ddx(F32 value); /// /// Returns the partial derivative of the value with respect to screen-space Y. /// Only available in fragment shaders. /// /// /// This intrinsic requires fragment execution in 2x2 quads to compute derivatives. /// In the software renderer, this will be implemented by comparing adjacent fragment values. /// public static F32 Ddy(F32 value); /// /// Returns the sum of absolute values of ddx and ddy. /// Only available in fragment shaders. /// public static F32 Fwidth(F32 value); /// /// Samples a 2D texture at the specified UV coordinates using a sampler. /// /// The texture to sample from. /// The sampler defining filtering and addressing modes. /// The UV texture coordinates. /// The sampled color value. /// /// This is a placeholder implementation. Actual texture sampling will be /// implemented by the software renderer or hardware backend. /// public static Color4 Sample(Texture2D texture, Sampler sampler, Float2 uv); /// Samples a texture at an explicit mip level, interpolating adjacent levels. public static Color4 SampleLevel(Texture2D texture, Sampler sampler, Float2 uv, F32 level); /// /// Loads a texel from a 2D texture at the specified integer coordinates. /// /// The texture to load from. /// The integer texel coordinates. /// The texel color value. /// /// Unlike Sample(), Load() does not perform filtering and uses integer coordinates. /// This is a placeholder implementation that will be implemented by the renderer backend. /// public static Color4 Load(Texture2D texture, Int2 location); } } namespace Xui.GPU.Shaders.Types { /// /// Represents texture sampling addressing modes. /// public enum AddressMode { /// /// Texture coordinates wrap at the boundaries (repeat). /// Repeat, /// /// Texture coordinates are clamped to the edge. /// ClampToEdge, /// /// Texture coordinates mirror at the boundaries. /// MirroredRepeat, /// /// Texture coordinates outside [0, 1] return a border color. /// ClampToBorder, } /// /// Shader boolean type. /// public readonly struct Bool { /// /// Initializes a new instance of the struct. /// /// The bool value. public Bool(bool value); /// /// Gets the false constant. /// public static Bool False { get; } /// /// Gets the true constant. /// public static Bool True { get; } /// /// Converts from bool to Bool. /// public static implicit operator Bool(bool value); /// /// Converts from Bool to bool. /// public static implicit operator bool (Bool value); /// /// Tests equality of two Bool values. /// public static Bool operator ==(Bool left, Bool right); /// /// Tests inequality of two Bool values. /// public static Bool operator !=(Bool left, Bool right); /// /// Performs logical AND of two Bool values. /// public static Bool operator &(Bool left, Bool right); /// /// Performs logical OR of two Bool values. /// public static Bool operator |(Bool left, Bool right); /// /// Performs logical NOT of a Bool value. /// public static Bool operator !(Bool value); /// Indicates whether this instance and a specified object are equal. /// The object to compare with the current instance. /// /// if and this instance are the same type and represent the same value; otherwise, . public override bool Equals(object? obj); /// Returns the hash code for this instance. /// A 32-bit signed integer that is the hash code for this instance. public override int GetHashCode(); /// Returns the fully qualified type name of this instance. /// The fully qualified type name. public override string ToString(); } /// /// A 4-component RGBA color value. /// public struct Color4 { /// /// The red component. /// public F32 R; /// /// The green component. /// public F32 G; /// /// The blue component. /// public F32 B; /// /// The alpha component. /// public F32 A; /// /// Initializes a new instance of the struct. /// public Color4(F32 r, F32 g, F32 b, F32 a); /// /// Initializes a new instance from RGB values with alpha set to 1. /// public Color4(F32 r, F32 g, F32 b); /// /// Gets a white color (1, 1, 1, 1). /// public static Color4 White { get; } /// /// Gets a black color (0, 0, 0, 1). /// public static Color4 Black { get; } /// /// Gets a transparent color (0, 0, 0, 0). /// public static Color4 Transparent { get; } /// Adds color components without clamping. public static Color4 operator +(Color4 a, Color4 b); /// /// Multiplies two colors component-wise. /// public static Color4 operator *(Color4 left, Color4 right); /// /// Multiplies a color by a scalar. /// public static Color4 operator *(Color4 left, F32 right); /// /// Implicitly converts from to . /// public static implicit operator Color4(Xui.Core.Canvas.Color color); /// /// Implicitly converts a packed 32-bit RGBA value (0xRRGGBBAA) to a . /// Compatible with Xui.Core.Canvas.Colors web color constants. /// public static implicit operator Color4(uint rgba); /// Returns the fully qualified type name of this instance. /// The fully qualified type name. public override string ToString(); } /// /// Shader 32-bit floating-point scalar type. /// This is the fundamental scalar type for shader math operations. /// /// /// In CPU execution, this may be represented as a single float (in vertex stage) /// or as a quad of floats (in fragment stage for derivative support). /// public readonly struct F32 { /// /// Initializes a new instance of the struct. /// /// The float value. public F32(float value); /// /// Gets the zero constant. /// public static F32 Zero { get; } /// /// Gets the one constant. /// public static F32 One { get; } /// /// Converts from float to F32. /// public static implicit operator F32(float value); /// /// Converts from double to F32 (narrowing). /// public static implicit operator F32(double value); /// /// Converts from nfloat to F32. /// public static implicit operator F32(nfloat value); /// /// Converts from F32 to float. /// public static implicit operator float (F32 value); /// /// Converts from F32 to double. /// public static implicit operator double (F32 value); /// /// Converts from F32 to nfloat. /// public static implicit operator nfloat(F32 value); /// /// Adds two F32 values. /// public static F32 operator +(F32 left, F32 right); /// /// Subtracts two F32 values. /// public static F32 operator -(F32 left, F32 right); /// /// Multiplies two F32 values. /// public static F32 operator *(F32 left, F32 right); /// /// Divides two F32 values. /// public static F32 operator /(F32 left, F32 right); /// /// Negates an F32 value. /// public static F32 operator -(F32 value); /// /// Tests equality of two F32 values. /// public static Bool operator ==(F32 left, F32 right); /// /// Tests inequality of two F32 values. /// public static Bool operator !=(F32 left, F32 right); /// /// Tests if left is less than right. /// public static Bool operator <(F32 left, F32 right); /// /// Tests if left is greater than right. /// public static Bool operator>(F32 left, F32 right); /// /// Tests if left is less than or equal to right. /// public static Bool operator <=(F32 left, F32 right); /// /// Tests if left is greater than or equal to right. /// public static Bool operator >=(F32 left, F32 right); /// Indicates whether this instance and a specified object are equal. /// The object to compare with the current instance. /// /// if and this instance are the same type and represent the same value; otherwise, . public override bool Equals(object? obj); /// Returns the hash code for this instance. /// A 32-bit signed integer that is the hash code for this instance. public override int GetHashCode(); /// Returns the fully qualified type name of this instance. /// The fully qualified type name. public override string ToString(); } /// /// Represents texture sampling filter modes. /// public enum FilterMode { /// /// Point (nearest neighbor) sampling. /// Point, /// /// Linear (bilinear) sampling. /// Linear, } /// /// A 2-component vector of 32-bit floats. /// public struct Float2 { /// /// The X component. /// public F32 X; /// /// The Y component. /// public F32 Y; /// /// Initializes a new instance of the struct. /// public Float2(F32 x, F32 y); /// /// Initializes a new instance with both components set to the same value. /// public Float2(F32 value); /// /// Gets the zero vector. /// public static Float2 Zero { get; } /// /// Gets the one vector. /// public static Float2 One { get; } /// /// Adds two vectors. /// public static Float2 operator +(Float2 left, Float2 right); /// /// Subtracts two vectors. /// public static Float2 operator -(Float2 left, Float2 right); /// /// Multiplies two vectors component-wise. /// public static Float2 operator *(Float2 left, Float2 right); /// /// Multiplies a vector by a scalar. /// public static Float2 operator *(Float2 left, F32 right); /// /// Multiplies a scalar by a vector. /// public static Float2 operator *(F32 left, Float2 right); /// /// Divides two vectors component-wise. /// public static Float2 operator /(Float2 left, Float2 right); /// /// Divides a vector by a scalar. /// public static Float2 operator /(Float2 left, F32 right); /// /// Negates a vector. /// public static Float2 operator -(Float2 value); /// /// Gets the XX swizzle (X, X). /// public readonly Float2 XX { get; } /// /// Gets the XY swizzle (X, Y). /// public readonly Float2 XY { get; } /// /// Gets the YX swizzle (Y, X). /// public readonly Float2 YX { get; } /// /// Gets the YY swizzle (Y, Y). /// public readonly Float2 YY { get; } /// /// Implicitly converts from to . /// public static implicit operator Float2(Xui.Core.Math2D.Point point); /// /// Implicitly converts from to . /// public static implicit operator Float2(Xui.Core.Math2D.Vector vector); /// /// Implicitly converts from to . /// public static implicit operator Float2(Xui.Core.Math2D.Size size); /// Returns the fully qualified type name of this instance. /// The fully qualified type name. public override string ToString(); } /// /// A 3-component vector of 32-bit floats. /// public struct Float3 { /// /// The X component. /// public F32 X; /// /// The Y component. /// public F32 Y; /// /// The Z component. /// public F32 Z; /// /// Initializes a new instance of the struct. /// public Float3(F32 x, F32 y, F32 z); /// /// Initializes a new instance with all components set to the same value. /// public Float3(F32 value); /// /// Gets the zero vector. /// public static Float3 Zero { get; } /// /// Gets the one vector. /// public static Float3 One { get; } /// /// Adds two vectors. /// public static Float3 operator +(Float3 left, Float3 right); /// /// Subtracts two vectors. /// public static Float3 operator -(Float3 left, Float3 right); /// /// Multiplies two vectors component-wise. /// public static Float3 operator *(Float3 left, Float3 right); /// /// Multiplies a vector by a scalar. /// public static Float3 operator *(Float3 left, F32 right); /// /// Multiplies a scalar by a vector. /// public static Float3 operator *(F32 left, Float3 right); /// /// Divides two vectors component-wise. /// public static Float3 operator /(Float3 left, Float3 right); /// /// Divides a vector by a scalar. /// public static Float3 operator /(Float3 left, F32 right); /// /// Negates a vector. /// public static Float3 operator -(Float3 value); /// /// Computes the cross product of two vectors. /// public static Float3 Cross(Float3 a, Float3 b); /// /// Normalizes the vector to unit length. /// public static Float3 Normalize(Float3 v); /// /// Gets the XY swizzle (X, Y). /// public readonly Float2 XY { get; } /// /// Gets the XZ swizzle (X, Z). /// public readonly Float2 XZ { get; } /// /// Gets the YX swizzle (Y, X). /// public readonly Float2 YX { get; } /// /// Gets the YZ swizzle (Y, Z). /// public readonly Float2 YZ { get; } /// /// Gets the ZX swizzle (Z, X). /// public readonly Float2 ZX { get; } /// /// Gets the ZY swizzle (Z, Y). /// public readonly Float2 ZY { get; } /// /// Gets the XYZ swizzle (X, Y, Z). /// public readonly Float3 XYZ { get; } /// /// Gets the XZY swizzle (X, Z, Y). /// public readonly Float3 XZY { get; } /// /// Gets the YXZ swizzle (Y, X, Z). /// public readonly Float3 YXZ { get; } /// /// Gets the YZX swizzle (Y, Z, X). /// public readonly Float3 YZX { get; } /// /// Gets the ZXY swizzle (Z, X, Y). /// public readonly Float3 ZXY { get; } /// /// Gets the ZYX swizzle (Z, Y, X). /// public readonly Float3 ZYX { get; } /// Returns the fully qualified type name of this instance. /// The fully qualified type name. public override string ToString(); } /// /// A 4-component vector of 32-bit floats. /// public struct Float4 { /// /// The X component. /// public F32 X; /// /// The Y component. /// public F32 Y; /// /// The Z component. /// public F32 Z; /// /// The W component. /// public F32 W; /// /// Initializes a new instance of the struct. /// public Float4(F32 x, F32 y, F32 z, F32 w); /// /// Initializes a new instance from a Float2 and z, w components. /// public Float4(Float2 xy, F32 z, F32 w); /// /// Initializes a new instance from a Float3 and w component. /// public Float4(Float3 xyz, F32 w); /// /// Initializes a new instance with all components set to the same value. /// public Float4(F32 value); /// /// Gets the zero vector. /// public static Float4 Zero { get; } /// /// Gets the one vector. /// public static Float4 One { get; } /// /// Adds two vectors. /// public static Float4 operator +(Float4 left, Float4 right); /// /// Subtracts two vectors. /// public static Float4 operator -(Float4 left, Float4 right); /// /// Multiplies two vectors component-wise. /// public static Float4 operator *(Float4 left, Float4 right); /// /// Multiplies a vector by a scalar. /// public static Float4 operator *(Float4 left, F32 right); /// /// Multiplies a scalar by a vector. /// public static Float4 operator *(F32 left, Float4 right); /// /// Divides two vectors component-wise. /// public static Float4 operator /(Float4 left, Float4 right); /// /// Divides a vector by a scalar. /// public static Float4 operator /(Float4 left, F32 right); /// /// Negates a vector. /// public static Float4 operator -(Float4 value); /// /// Gets the XY swizzle (X, Y). /// public readonly Float2 XY { get; } /// /// Gets the XZ swizzle (X, Z). /// public readonly Float2 XZ { get; } /// /// Gets the XW swizzle (X, W). /// public readonly Float2 XW { get; } /// /// Gets the YZ swizzle (Y, Z). /// public readonly Float2 YZ { get; } /// /// Gets the YW swizzle (Y, W). /// public readonly Float2 YW { get; } /// /// Gets the ZW swizzle (Z, W). /// public readonly Float2 ZW { get; } /// /// Gets the XYZ swizzle (X, Y, Z). /// public readonly Float3 XYZ { get; } /// /// Gets the XYW swizzle (X, Y, W). /// public readonly Float3 XYW { get; } /// /// Gets the XZW swizzle (X, Z, W). /// public readonly Float3 XZW { get; } /// /// Gets the YZW swizzle (Y, Z, W). /// public readonly Float3 YZW { get; } /// /// Gets the RGB swizzle (X, Y, Z) - color alias for XYZ. /// public readonly Float3 RGB { get; } /// /// Gets the XYZW swizzle (X, Y, Z, W). /// public readonly Float4 XYZW { get; } /// /// Gets the RGBA swizzle (X, Y, Z, W) - color alias for XYZW. /// public readonly Float4 RGBA { get; } /// Returns the fully qualified type name of this instance. /// The fully qualified type name. public override string ToString(); } /// /// A 4x4 matrix of 32-bit floats. /// Used for transformations in shader code. /// public struct Float4x4 { /// /// First row of the matrix. /// public Float4 Row0; /// /// Second row of the matrix. /// public Float4 Row1; /// /// Third row of the matrix. /// public Float4 Row2; /// /// Fourth row of the matrix. /// public Float4 Row3; /// /// Initializes a new instance of the struct. /// public Float4x4(Float4 row0, Float4 row1, Float4 row2, Float4 row3); /// /// Gets the identity matrix. /// public static Float4x4 Identity { get; } /// /// Multiplies a matrix by a vector. /// public static Float4 operator *(Float4x4 matrix, Float4 vector); /// /// Multiplies two matrices. /// public static Float4x4 operator *(Float4x4 left, Float4x4 right); /// /// Creates a translation matrix. /// public static Float4x4 CreateTranslation(F32 x, F32 y, F32 z); /// /// Creates a rotation matrix around the X axis. /// public static Float4x4 CreateRotationX(F32 angle); /// /// Creates a rotation matrix around the Y axis. /// public static Float4x4 CreateRotationY(F32 angle); /// /// Creates a rotation matrix around the Z axis. /// public static Float4x4 CreateRotationZ(F32 angle); /// /// Creates a perspective projection matrix. /// /// Field of view in the Y direction (in radians). /// Aspect ratio (width / height). /// Near clipping plane distance. /// Far clipping plane distance. /// /// This uses a [0, 1] depth range (DirectX/Vulkan style) instead of OpenGL's [-1, 1]. /// The matrix maps the near plane to NDC Z = 0 and far plane to NDC Z = 1. /// public static Float4x4 CreatePerspective(F32 fovY, F32 aspectRatio, F32 nearPlane, F32 farPlane); /// /// Creates a view matrix (look-at matrix). /// public static Float4x4 CreateLookAt(Float3 eye, Float3 target, Float3 up); /// Returns the fully qualified type name of this instance. /// The fully qualified type name. public override string ToString(); } /// /// Shader 32-bit signed integer scalar type. /// public readonly struct I32 { /// /// Initializes a new instance of the struct. /// /// The int value. public I32(int value); /// /// Gets the zero constant. /// public static I32 Zero { get; } /// /// Gets the one constant. /// public static I32 One { get; } /// /// Converts from int to I32. /// public static implicit operator I32(int value); /// /// Converts from I32 to int. /// public static implicit operator int (I32 value); /// /// Adds two I32 values. /// public static I32 operator +(I32 left, I32 right); /// /// Subtracts two I32 values. /// public static I32 operator -(I32 left, I32 right); /// /// Multiplies two I32 values. /// public static I32 operator *(I32 left, I32 right); /// /// Divides two I32 values. /// public static I32 operator /(I32 left, I32 right); /// /// Negates an I32 value. /// public static I32 operator -(I32 value); /// /// Tests equality of two I32 values. /// public static Bool operator ==(I32 left, I32 right); /// /// Tests inequality of two I32 values. /// public static Bool operator !=(I32 left, I32 right); /// /// Tests if left is less than right. /// public static Bool operator <(I32 left, I32 right); /// /// Tests if left is greater than right. /// public static Bool operator>(I32 left, I32 right); /// /// Tests if left is less than or equal to right. /// public static Bool operator <=(I32 left, I32 right); /// /// Tests if left is greater than or equal to right. /// public static Bool operator >=(I32 left, I32 right); /// /// Performs bitwise AND of two I32 values. /// public static I32 operator &(I32 left, I32 right); /// /// Performs bitwise OR of two I32 values. /// public static I32 operator |(I32 left, I32 right); /// /// Performs bitwise XOR of two I32 values. /// public static I32 operator ^(I32 left, I32 right); /// /// Performs bitwise NOT of an I32 value. /// public static I32 operator ~(I32 value); /// /// Left shifts an I32 value. /// public static I32 operator <<(I32 left, int right); /// /// Right shifts an I32 value. /// public static I32 operator >>(I32 left, int right); /// Indicates whether this instance and a specified object are equal. /// The object to compare with the current instance. /// /// if and this instance are the same type and represent the same value; otherwise, . public override bool Equals(object? obj); /// Returns the hash code for this instance. /// A 32-bit signed integer that is the hash code for this instance. public override int GetHashCode(); /// Returns the fully qualified type name of this instance. /// The fully qualified type name. public override string ToString(); } /// CPU implementation of a shader texture resource; pixel storage belongs to the renderer. /// Pixel result type. public interface ISampledTexture where TPixel : unmanaged { /// Samples normalized coordinates at an explicit mip level. TPixel Sample(Sampler sampler, Float2 uv, F32 level); } /// /// A 2-component vector of 32-bit signed integers. /// public struct Int2 { /// /// The X component. /// public I32 X; /// /// The Y component. /// public I32 Y; /// /// Initializes a new instance of the struct. /// public Int2(I32 x, I32 y); /// /// Initializes a new instance with both components set to the same value. /// public Int2(I32 value); /// /// Gets the zero vector. /// public static Int2 Zero { get; } /// /// Gets the one vector. /// public static Int2 One { get; } /// /// Adds two vectors. /// public static Int2 operator +(Int2 left, Int2 right); /// /// Subtracts two vectors. /// public static Int2 operator -(Int2 left, Int2 right); /// /// Multiplies two vectors component-wise. /// public static Int2 operator *(Int2 left, Int2 right); /// /// Multiplies a vector by a scalar. /// public static Int2 operator *(Int2 left, I32 right); /// /// Multiplies a scalar by a vector. /// public static Int2 operator *(I32 left, Int2 right); /// /// Divides two vectors component-wise. /// public static Int2 operator /(Int2 left, Int2 right); /// /// Divides a vector by a scalar. /// public static Int2 operator /(Int2 left, I32 right); /// /// Negates a vector. /// public static Int2 operator -(Int2 value); /// Returns the fully qualified type name of this instance. /// The fully qualified type name. public override string ToString(); } /// /// Represents a texture sampler that controls how textures are sampled. /// /// /// Samplers define the filtering and addressing behavior when reading from textures. /// public readonly struct Sampler { /// /// Gets the minification filter mode. /// public FilterMode MinFilter { get; init; } /// /// Gets the magnification filter mode. /// public FilterMode MagFilter { get; init; } /// /// Gets the addressing mode for the U coordinate. /// public AddressMode AddressU { get; init; } /// /// Gets the addressing mode for the V coordinate. /// public AddressMode AddressV { get; init; } /// /// Initializes a new instance of the struct. /// public Sampler(FilterMode minFilter = FilterMode.Linear, FilterMode magFilter = FilterMode.Linear, AddressMode addressU = AddressMode.Repeat, AddressMode addressV = AddressMode.Repeat); /// /// Gets a default linear sampler with repeat addressing. /// public static Sampler LinearRepeat { get; } /// /// Gets a default linear sampler with clamp-to-edge addressing. /// public static Sampler LinearClamp { get; } /// /// Gets a default point sampler with repeat addressing. /// public static Sampler PointRepeat { get; } /// /// Gets a default point sampler with clamp-to-edge addressing. /// public static Sampler PointClamp { get; } } /// /// Represents a 2D texture resource in shader code. /// /// The pixel format type (typically Color4). /// /// In CPU execution, this wraps actual texture data. /// In GPU execution, this will be translated to the appropriate backend texture type. /// public readonly struct Texture2D where TPixel : unmanaged { /// /// Initializes a new instance of the struct. /// /// The underlying texture data (implementation-specific). public Texture2D(object? data); } /// /// Shader 32-bit unsigned integer scalar type. /// public readonly struct U32 { /// /// Initializes a new instance of the struct. /// /// The uint value. public U32(uint value); /// /// Gets the zero constant. /// public static U32 Zero { get; } /// /// Gets the one constant. /// public static U32 One { get; } /// /// Converts from uint to U32. /// public static implicit operator U32(uint value); /// /// Converts from U32 to uint. /// public static implicit operator uint (U32 value); /// /// Adds two U32 values. /// public static U32 operator +(U32 left, U32 right); /// /// Subtracts two U32 values. /// public static U32 operator -(U32 left, U32 right); /// /// Multiplies two U32 values. /// public static U32 operator *(U32 left, U32 right); /// /// Divides two U32 values. /// public static U32 operator /(U32 left, U32 right); /// /// Tests equality of two U32 values. /// public static Bool operator ==(U32 left, U32 right); /// /// Tests inequality of two U32 values. /// public static Bool operator !=(U32 left, U32 right); /// /// Tests if left is less than right. /// public static Bool operator <(U32 left, U32 right); /// /// Tests if left is greater than right. /// public static Bool operator>(U32 left, U32 right); /// /// Tests if left is less than or equal to right. /// public static Bool operator <=(U32 left, U32 right); /// /// Tests if left is greater than or equal to right. /// public static Bool operator >=(U32 left, U32 right); /// /// Performs bitwise AND of two U32 values. /// public static U32 operator &(U32 left, U32 right); /// /// Performs bitwise OR of two U32 values. /// public static U32 operator |(U32 left, U32 right); /// /// Performs bitwise XOR of two U32 values. /// public static U32 operator ^(U32 left, U32 right); /// /// Performs bitwise NOT of a U32 value. /// public static U32 operator ~(U32 value); /// /// Left shifts a U32 value. /// public static U32 operator <<(U32 left, int right); /// /// Right shifts a U32 value. /// public static U32 operator >>(U32 left, int right); /// Indicates whether this instance and a specified object are equal. /// The object to compare with the current instance. /// /// if and this instance are the same type and represent the same value; otherwise, . public override bool Equals(object? obj); /// Returns the hash code for this instance. /// A 32-bit signed integer that is the hash code for this instance. public override int GetHashCode(); /// Returns the fully qualified type name of this instance. /// The fully qualified type name. public override string ToString(); } }