// 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.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;
}
}