Framework/Scripting/Api/LuaUi.cs

Lua binding layer for a roleplay framework's client UI. Exposes a `ui` library to Lua scripts that creates engine Panels (panel, label, button, textentry, image) under a shared screen root, plus class, style, text, event handler, image and avatar methods on the returned Panel userdata. Images are limited by path/package/https validation, panels and CSS are capped, and a separate path handles world-space panels.

Http Calls
using System;
using System.Collections.Generic;
using System.Linq;
using RoleplayFramework.Lua;
using Sandbox.UI;

namespace RoleplayFramework.Scripting;

internal sealed class PanelHandle
{
	public Panel Panel;
}

/// <summary>
/// Client-side UI for Lua, built on the engine's panel system and styled with CSS.
///
///   local p = ui.Create("panel" | "label" | "button" | "textentry" [, parent] [, classes])
///   p:AddClass(c)  p:RemoveClass(c)  p:SetClass(c, on)  p:HasClass(c)  p:SetStyle("width: 200px; color: red;")
///   p:SetText(t)  p:GetText()  p:SetPlaceholder(t)  p:SetMaxLength(n)  p:Focus()  p:HasFocus()
///   p:OnClick(fn)  p:OnSubmit(fn(text))  p:OnChange(fn(text))
///   p:SetImage(src)  p:SetAvatar(ply|steamid64)   src: image path, https URL, package ident, "thumb:<model>"   (ui.Create("image") or any panel's background)
///   p:SetVisible(b)  p:IsVisible()  p:Clear()  p:Remove()  p:IsValid()  p:ScrollToBottom()  p:ScrollToTop()
///   ui.AddStyle(css)   ui.SetCursor(visible)   ui.IsTyping()   ui.ScreenSize()
///
/// Panels live under one Lua root that covers the screen (pointer-events: none, so give interactive panels
/// "pointer-events: all"). Everything is removed when the client realm stops. Limits: 4000 panels, 128 KB of CSS.
/// </summary>
public static partial class LuaUi
{
	public const int MaxPanels = 4000;
	public const int MaxCssChars = 128 * 1024;

	const string BaseCss = """
		.lua-root { position: absolute; left: 0; top: 0; right: 0; bottom: 0; pointer-events: none; font-family: Inter; color: #e8ebf0; }
		.lua-root .rp-hidden { display: none; }
		""";

	static Panel _root;
	static readonly List<Panel> _panels = new();
	static int _cssChars;
	static readonly List<string> _css = new();   // replayed into world panels, which have their own root
	static LuaTable _meta;

	/// <summary>True while a Lua text entry has keyboard focus (game hotkeys are not forwarded to Lua then).</summary>
	internal static Panel ScreenRoot => Root;

	internal static LuaValue Wrap( Panel p ) => LuaValue.FromUserData( new LuaUserData( new PanelHandle { Panel = p }, _meta ) );

	public static bool IsTyping => _panels.Any( p => p is TextEntry te && te.IsValid() && te.HasFocus );

	static Panel Root
	{
		get
		{
			if ( _root is not null && _root.IsValid() ) return _root;
			var screen = Game.ActiveScene?.GetAllComponents<ScreenPanel>().FirstOrDefault();
			if ( screen is null ) throw new LuaRuntimeException( "this world has no ScreenPanel for Lua UI" );
			_root = new Panel( screen.GetPanel(), "lua-root" );
			_root.StyleSheet.Parse( BaseCss, false );
			_cssChars = 0;
			return _root;
		}
	}

	/// <summary>Removes every Lua panel (client realm shutdown).</summary>
	public static void Reset()
	{
		if ( _root is not null && _root.IsValid() ) _root.Delete( true );
		_root = null;
		_panels.Clear();
		_cssChars = 0;
		_css.Clear();
		ResetWorld();
		Mouse.Visibility = MouseVisibility.Auto;
	}

	static readonly string[] ImageExtensions = { ".png", ".jpg", ".jpeg", ".vtex", ".svg" };

	/// <summary>
	/// A texture reference from Lua: an https URL, "avatar:&lt;steamid64&gt;", an engine path (.png/.jpg/.vtex/.svg),
	/// or a mounted package ident (its main asset).
	/// </summary>
	public static string TextureSource( string raw )
	{
		var src = (raw ?? "").Trim();
		if ( src.Length is 0 or > 1024 ) throw new LuaRuntimeException( "SetImage: empty or too long image source" );
		if ( src.StartsWith( "https://", StringComparison.OrdinalIgnoreCase ) ) return src;
		if ( src.StartsWith( "http://", StringComparison.OrdinalIgnoreCase ) ) throw new LuaRuntimeException( "SetImage: only https:// URLs are allowed" );
		// Model thumbnails: "thumb:models/x.vmdl" (or a mounted model package's main model).
		if ( src.StartsWith( "thumb:" ) )
		{
			var m = src.Substring( 6 ).Replace( "\\", "/" ).ToLowerInvariant();
			if ( !m.Contains( '/' ) && Core.ContentPackages.PrimaryAssetOf( Core.ContentPackages.Normalize( m ) ) is { } asset ) m = asset;
			if ( m.Contains( ".." ) || m.StartsWith( "/" ) || m.Contains( ':' ) || !m.EndsWith( ".vmdl" ) ) throw new LuaRuntimeException( $"SetImage: '{raw}' - thumb: needs a .vmdl path or a mounted model package" );
			return "thumb:" + m;
		}
		if ( src.StartsWith( "avatar:" ) )
		{
			if ( !(long.TryParse( src.Substring( 7 ), out var sid ) && sid > 0) ) throw new LuaRuntimeException( "SetImage: avatar:<steamid64> expected" );
			return src;
		}

		var lower = src.Replace( "\\", "/" ).ToLowerInvariant();
		if ( lower.EndsWith( "_c" ) ) lower = lower.Substring( 0, lower.Length - 2 );
		if ( !lower.Contains( '/' ) && !ImageExtensions.Any( lower.EndsWith ) && Core.ContentPackages.IsValidIdent( Core.ContentPackages.Normalize( lower ) ) )
		{
			var id = Core.ContentPackages.Normalize( lower );
			return Core.ContentPackages.PrimaryAssetOf( id ) ?? throw new LuaRuntimeException( $"SetImage: package '{id}' is not mounted" );
		}
		if ( lower.Contains( ".." ) || lower.StartsWith( "/" ) || lower.Contains( ':' ) ) throw new LuaRuntimeException( $"SetImage: '{raw}' is not a valid path" );
		if ( !ImageExtensions.Any( lower.EndsWith ) ) throw new LuaRuntimeException( $"SetImage: '{raw}' must be an image (.png, .jpg, .vtex, .svg), an https URL or a package ident" );
		return lower;
	}

	public static void Register( LuaRealm realm )
	{
		if ( realm.Kind != LuaRealmKind.Client ) return;

		var methods = new LuaTable();
		var meta = new LuaTable();
		meta.Set( "__index", methods );
		meta.Set( "__metatable", "Panel" );
		LuaState.Register( meta, "__tostring", ( s, a ) => new LuaValue[] { Resolve( a, 0 ) is { } p ? $"Panel [{p.GetType().Name} .{p.Classes}]" : "Panel [NULL]" } );

		realm.MethodTables["Panel"] = methods;
		_meta = meta;
		var ui = realm.State.GetOrCreateLibrary( "ui" );

		LuaState.Register( ui, "Create", ( s, a ) =>
		{
			var kind = LuaState.CheckString( a, 0, "ui.Create" );
			var parentArg = LuaState.Arg( a, 1 );
			var parent = parentArg.IsNil ? Root : Resolve( a, 1 ) ?? throw LuaState.ArgError( 1, "ui.Create", "parent panel expected" );
			var classes = LuaState.OptString( a, 2, "ui.Create", "" );

			_panels.RemoveAll( p => !p.IsValid() );
			if ( _panels.Count >= MaxPanels ) throw new LuaRuntimeException( $"too many UI panels (limit {MaxPanels})" );

			Panel panel = kind switch
			{
				"panel" => new Panel( parent ),
				"label" => new Label { Parent = parent },
				"button" => new Button { Parent = parent },
				"textentry" => new TextEntry { Parent = parent },
				"image" => new Image { Parent = parent },
				_ => throw LuaState.ArgError( 0, "ui.Create", "kind must be panel, label, button, textentry or image" ),
			};
			if ( !string.IsNullOrWhiteSpace( classes ) ) panel.AddClass( classes );
			_panels.Add( panel );
			return new LuaValue[] { Wrap( panel ) };
		} );

		LuaState.Register( ui, "AddStyle", ( s, a ) =>
		{
			var css = LuaState.CheckString( a, 0, "ui.AddStyle" );
			if ( _cssChars + css.Length > MaxCssChars ) throw new LuaRuntimeException( $"too much UI CSS (limit {MaxCssChars} characters)" );
			try { Root.StyleSheet.Parse( css, false ); }
			catch ( Exception e ) { throw new LuaRuntimeException( $"invalid CSS: {e.Message}" ); }
			_cssChars += css.Length;
			_css.Add( css );
			foreach ( var w in _worldRoots.Keys ) if ( w.IsValid() ) w.StyleSheet.Parse( css, false );
			return null;
		} );

		LuaState.Register( ui, "SetCursor", ( s, a ) =>
		{
			Mouse.Visibility = LuaState.Arg( a, 0 ).IsTruthy ? MouseVisibility.Visible : MouseVisibility.Auto;
			return null;
		} );

		LuaState.Register( ui, "IsTyping", ( s, a ) => new LuaValue[] { IsTyping } );
		LuaState.Register( ui, "ScreenSize", ( s, a ) => new LuaValue[] { Screen.Width, Screen.Height } );

		// ---------------------------------------------------------------- methods

		void M( string name, LuaNativeFunction f ) => LuaState.Register( methods, name, f );

		M( "IsValid", ( s, a ) => new LuaValue[] { Resolve( a, 0 ) is not null } );
		M( "AddClass", ( s, a ) => { Check( a, "AddClass" ).AddClass( LuaState.CheckString( a, 1, "AddClass" ) ); return null; } );
		M( "RemoveClass", ( s, a ) => { Check( a, "RemoveClass" ).RemoveClass( LuaState.CheckString( a, 1, "RemoveClass" ) ); return null; } );
		M( "SetClass", ( s, a ) => { Check( a, "SetClass" ).SetClass( LuaState.CheckString( a, 1, "SetClass" ), LuaState.Arg( a, 2 ).IsTruthy ); return null; } );
		M( "HasClass", ( s, a ) => new LuaValue[] { Check( a, "HasClass" ).HasClass( LuaState.CheckString( a, 1, "HasClass" ) ) } );
		M( "SetStyle", ( s, a ) =>
		{
			var css = LuaState.CheckString( a, 1, "SetStyle" );
			if ( css.Length > 4096 ) throw LuaState.ArgError( 1, "SetStyle", "inline style longer than 4096 characters" );
			Check( a, "SetStyle" ).SetProperty( "style", css );
			return null;
		} );
		// Textures: an image panel shows it, any other panel uses it as its background (size it with CSS).
		M( "SetImage", ( s, a ) =>
		{
			var p = Check( a, "SetImage" );
			var src = TextureSource( LuaState.CheckString( a, 1, "SetImage" ) );
			if ( p is Image img ) img.SetTexture( src );
			else p.Style.BackgroundImage = src.StartsWith( "avatar:" ) ? Texture.LoadAvatar( long.Parse( src.Substring( 7 ) ), 128 ) : Texture.Load( src );
			return null;
		} );
		M( "SetKeyGlyph", ( s, a ) =>
		{
			// The engine's glyph for an input action ("Use") or a raw key ("m"), as this panel's background.
			var p = Check( a, "SetKeyGlyph" );
			var name = LuaState.CheckString( a, 1, "SetKeyGlyph" );
			Texture tex = null;
			try
			{
				tex = Input.GetActions().Any( x => x.Name == name )
					? Input.GetGlyph( name, InputGlyphSize.Medium, true )
					: Input.Keyboard.GetGlyph( name.ToLowerInvariant(), InputGlyphSize.Medium, true );
			}
			catch ( Exception ) { }
			if ( tex is null ) throw LuaState.ArgError( 1, "SetKeyGlyph", $"no glyph for '{name}'" );
			p.Style.BackgroundImage = tex;
			p.Style.Set( "background-size: contain; background-repeat: no-repeat; background-position: center;" );
			return null;
		} );
		M( "SetAvatar", ( s, a ) =>
		{
			// A player or a SteamID64 → their Steam avatar.
			var p = Check( a, "SetAvatar" );
			var arg = LuaState.Arg( a, 1 );
			string steamId = arg.IsString ? arg.AsString
				: LuaPlayers.HandleOf( arg ) is { } pid ? LuaPlayers.Find( pid )?.SteamId : null;
			if ( string.IsNullOrEmpty( steamId ) || !long.TryParse( steamId, out _ ) ) throw LuaState.ArgError( 1, "SetAvatar", "player or SteamID64 expected" );
			if ( p is Image img ) img.SetTexture( $"avatar:{steamId}" );
			else p.Style.BackgroundImage = Texture.LoadAvatar( long.Parse( steamId ), 128 );
			return null;
		} );

		M( "SetVisible", ( s, a ) => { Check( a, "SetVisible" ).SetClass( "rp-hidden", !LuaState.Arg( a, 1 ).IsTruthy ); return null; } );
		M( "IsVisible", ( s, a ) => new LuaValue[] { !Check( a, "IsVisible" ).HasClass( "rp-hidden" ) } );

		M( "SetText", ( s, a ) =>
		{
			var p = Check( a, "SetText" );
			var text = Net.FrameworkRpc.Bound( s.ToStringMeta( LuaState.Arg( a, 1 ) ), 4096 );
			switch ( p )
			{
				case Label l: l.Text = text; break;
				case Button b: b.Text = text; break;
				case TextEntry t: t.Text = text; break;
				default: throw new LuaRuntimeException( "SetText needs a label, button or textentry" );
			}
			return null;
		} );
		M( "GetText", ( s, a ) => new LuaValue[] { Check( a, "GetText" ) switch
		{
			Label l => l.Text ?? "",
			Button b => b.Text ?? "",
			TextEntry t => t.Text ?? "",
			_ => "",
		} } );
		M( "SetPlaceholder", ( s, a ) => { AsEntry( a, "SetPlaceholder" ).Placeholder = LuaState.CheckString( a, 1, "SetPlaceholder" ); return null; } );
		M( "SetMaxLength", ( s, a ) => { AsEntry( a, "SetMaxLength" ).MaxLength = Math.Clamp( LuaState.CheckInt( a, 1, "SetMaxLength" ), 1, 4096 ); return null; } );
		M( "Focus", ( s, a ) => { Check( a, "Focus" ).Focus(); return null; } );
		M( "HasFocus", ( s, a ) => new LuaValue[] { Check( a, "HasFocus" ).HasFocus } );

		M( "OnClick", ( s, a ) =>
		{
			var p = Check( a, "OnClick" );
			var fn = LuaValue.FromFunction( LuaState.CheckFunction( a, 1, "OnClick" ) );
			p.AddEventListener( "onclick", () => realm.Call( fn ) );
			return null;
		} );
		M( "OnSubmit", ( s, a ) =>
		{
			var te = AsEntry( a, "OnSubmit" );
			var fn = LuaValue.FromFunction( LuaState.CheckFunction( a, 1, "OnSubmit" ) );
			te.AddEventListener( "onsubmit", () => realm.Call( fn, te.Text ?? "" ) );
			return null;
		} );
		M( "OnChange", ( s, a ) =>
		{
			var te = AsEntry( a, "OnChange" );
			var fn = LuaValue.FromFunction( LuaState.CheckFunction( a, 1, "OnChange" ) );
			te.OnTextEdited = text => realm.Call( fn, text ?? "" );
			return null;
		} );

		// Mouse: OnMouseDown/OnMouseUp(fn(x, y, button)) with x, y as 0-1 fractions of the panel's size (resolution
		// independent; button "left" | "right" | "middle"), OnMouseEnter/OnMouseLeave(fn), OnRightClick(fn).
		// p:GetMousePos() -> x, y (fractions, can be outside 0-1), p:GetSize() -> w, h (screen pixels),
		// ui.IsMouseDown([button]) -> true while the button is held (for dragging), p:IsHovered().
		void MouseEvent( string name, string ev, bool withPos )
		{
			M( name, ( s, a ) =>
			{
				var p = Check( a, name );
				var fn = LuaValue.FromFunction( LuaState.CheckFunction( a, 1, name ) );
				p.AddEventListener( ev, ( PanelEvent e ) =>
				{
					if ( !withPos ) { realm.Call( fn ); return; }
					var (x, y) = Fraction( p );
					var button = e is MousePanelEvent me ? me.MouseButton switch { MouseButtons.Right => "right", MouseButtons.Middle => "middle", _ => "left" } : "left";
					realm.Call( fn, x, y, button );
				} );
				return null;
			} );
		}
		MouseEvent( "OnMouseDown", "onmousedown", true );
		MouseEvent( "OnMouseUp", "onmouseup", true );
		MouseEvent( "OnMouseEnter", "onmouseover", false );
		MouseEvent( "OnMouseLeave", "onmouseout", false );
		M( "OnRightClick", ( s, a ) =>
		{
			var p = Check( a, "OnRightClick" );
			var fn = LuaValue.FromFunction( LuaState.CheckFunction( a, 1, "OnRightClick" ) );
			p.AddEventListener( "onrightclick", () => realm.Call( fn ) );
			return null;
		} );
		M( "GetMousePos", ( s, a ) => { var (x, y) = Fraction( Check( a, "GetMousePos" ) ); return new LuaValue[] { x, y }; } );
		M( "GetSize", ( s, a ) => { var r = Check( a, "GetSize" ).Box.Rect; return new LuaValue[] { r.Width, r.Height }; } );
		M( "IsHovered", ( s, a ) => new LuaValue[] { Check( a, "IsHovered" ).HasHovered } );
		// p:SetParent(newParent) moves the panel (keeps its handlers); p:SetTooltip(text | nil)
		M( "SetParent", ( s, a ) =>
		{
			var p = Check( a, "SetParent" );
			var parent = LuaState.Arg( a, 1 ).IsNil ? Root : Resolve( a, 1 ) ?? throw LuaState.ArgError( 1, "SetParent", "panel expected" );
			for ( var x = parent; x is not null; x = x.Parent ) if ( x == p ) throw LuaState.ArgError( 1, "SetParent", "can't move a panel into itself" );
			p.Parent = parent;
			return null;
		} );
		M( "SetTooltip", ( s, a ) =>
		{
			var v = LuaState.Arg( a, 1 );
			Check( a, "SetTooltip" ).Tooltip = v.IsNil ? null : Net.FrameworkRpc.Bound( s.ToStringMeta( v ), 512 );
			return null;
		} );
		M( "GetChildCount", ( s, a ) => new LuaValue[] { Check( a, "GetChildCount" ).ChildrenCount } );
		LuaState.Register( ui, "IsMouseDown", ( s, a ) =>
		{
			var b = LuaState.OptString( a, 0, "ui.IsMouseDown", "left" );
			var key = b switch { "right" => "mouse2", "middle" => "mouse3", _ => "mouse1" };
			try { return new LuaValue[] { Input.Keyboard.Down( key ) }; }
			catch ( Exception ) { return new LuaValue[] { false }; }
		} );

		M( "Clear", ( s, a ) => { Check( a, "Clear" ).DeleteChildren( true ); return null; } );
		M( "Remove", ( s, a ) =>
		{
			var p = Resolve( a, 0 );
			if ( p is not null && _worldRoots.Remove( p, out var go ) ) go.Destroy();
			else p?.Delete( true );
			return null;
		} );
		RegisterWorld( realm, ui, M );
		M( "ScrollToTop", ( s, a ) => { ScrollSafely( Check( a, "ScrollToTop" ), top: true ); return null; } );
		M( "ScrollToBottom", ( s, a ) => { ScrollSafely( Check( a, "ScrollToBottom" ), top: false ); return null; } );
	}

	/// <summary>
	/// Jumps to the top or bottom. <c>Panel.ScrollTo</c> also stops scroll inertia (which would otherwise carry the panel
	/// back), but it throws on a panel that hasn't been laid out yet (e.g. right after it was created): then the
	/// offset is set directly, and the gamemode's delayed second call does the rest.
	/// </summary>
	static void ScrollSafely( Panel p, bool top )
	{
		var target = new Vector2( p.ScrollOffset.x, top ? 0 : Math.Max( 0, p.ScrollSize.y ) );
		try { p.ScrollTo( target ); }
		catch ( Exception ) { p.ScrollOffset = target; }
	}

	/// <summary>The mouse over a panel as 0-1 fractions of its size (outside the panel: below 0 or above 1).</summary>
	static (double, double) Fraction( Panel p )
	{
		var r = p.Box.Rect;
		var m = p.MousePosition;
		return (r.Width > 0 ? m.x / r.Width : 0, r.Height > 0 ? m.y / r.Height : 0);
	}

	static Panel Resolve( LuaValue[] a, int i )
	{
		var v = LuaState.Arg( a, i );
		return v.Type == LuaType.UserData && v.AsUserData.Value is PanelHandle h && h.Panel.IsValid() ? h.Panel : null;
	}

	static Panel Check( LuaValue[] a, string method ) =>
		Resolve( a, 0 ) ?? throw new LuaRuntimeException( $"calling '{method}' on a removed or non-panel value" );

	static TextEntry AsEntry( LuaValue[] a, string method ) =>
		Check( a, method ) as TextEntry ?? throw new LuaRuntimeException( $"{method} needs a textentry" );
}