// 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