From 8aeb0314922e4c5ab0aab8e39c1ab26d41433332 Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Wed, 14 Oct 2026 13:05:38 -0700 Subject: [PATCH 01/38] Comment out Awesomium load, add LoadHTML stub --- Source.Engine/GarrysMod/Get.cs | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/Source.Engine/GarrysMod/Get.cs b/Source.Engine/GarrysMod/Get.cs index 905877e70..5a2d39af9 100644 --- a/Source.Engine/GarrysMod/Get.cs +++ b/Source.Engine/GarrysMod/Get.cs @@ -146,17 +146,20 @@ public void Initialize(IFileSystem fileSystem) { Msg("Attempting to load Chromium...\n"); // todo: LoadHTML("html_chromium.dll"); } + LoadHTML("html_chromium"); - if (html == null && !commandLine.CheckParm("-noawesomium")) { - Msg("Attempting to load Awesomium...\n"); + // if (html == null && !commandLine.CheckParm("-noawesomium")) { + // Msg("Attempting to load Awesomium...\n"); // todo: LoadHTML("html_awesomium.dll"); - } + // } } if (html == null) { Msg("Attempting to load Stub...\n"); + LoadHTML("html_stub"); // todo: LoadHTML("html_stub.dll"); - // todo: if (html == null) Error("Couldn't find an HTML system."); + if (html == null) + Error("Couldn't find an HTML system."); } } @@ -167,6 +170,10 @@ public void Initialize(IFileSystem fileSystem) { StripLastDir(gameDirParent); } + private void LoadHTML(string name) { + + } + static void FixSlashes(Span str, char separator) { for (int i = 0; i < str.Length && str[i] != '\0'; i++) { if (str[i] == '/' || str[i] == '\\') From d533a0010e12c4b7b909fa0033136d82fcf17f49 Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Wed, 14 Oct 2026 14:17:24 -0700 Subject: [PATCH 02/38] Fix interface naming, add new structs and interfaces --- Source.Common/GarrysMod/IGMHTML.cs | 6 -- Source.Common/GarrysMod/IGet.cs | 2 +- Source.Common/GarrysMod/IHtmlClient.cs | 82 +++++++++++++++++++ .../GarrysMod/IHtmlClientListener.cs | 34 ++++++++ .../GarrysMod/IHtmlResourceHandler.cs | 14 ++++ Source.Common/GarrysMod/IHtmlSystem.cs | 29 +++++++ Source.Common/GarrysMod/JSValue.cs | 78 ++++++++++++++++++ 7 files changed, 238 insertions(+), 7 deletions(-) delete mode 100644 Source.Common/GarrysMod/IGMHTML.cs create mode 100644 Source.Common/GarrysMod/IHtmlClient.cs create mode 100644 Source.Common/GarrysMod/IHtmlClientListener.cs create mode 100644 Source.Common/GarrysMod/IHtmlResourceHandler.cs create mode 100644 Source.Common/GarrysMod/IHtmlSystem.cs create mode 100644 Source.Common/GarrysMod/JSValue.cs diff --git a/Source.Common/GarrysMod/IGMHTML.cs b/Source.Common/GarrysMod/IGMHTML.cs deleted file mode 100644 index 96375144e..000000000 --- a/Source.Common/GarrysMod/IGMHTML.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace Source.Common.GarrysMod; - -public interface IGMHTML -{ - // TODO: This looks like Awesomium related code, so won't implement if that's the case -} diff --git a/Source.Common/GarrysMod/IGet.cs b/Source.Common/GarrysMod/IGet.cs index a2326b7a3..2e5b8be11 100644 --- a/Source.Common/GarrysMod/IGet.cs +++ b/Source.Common/GarrysMod/IGet.cs @@ -23,7 +23,7 @@ public interface IGet IIntroScreen? IntroScreen(); IMaterialSystem? Materials(); IServerAddons? ServerAddons(); - IGMHTML? HTML(); + IHtmlSystem? HTML(); ISteamHTTP? SteamHTTP(); ISteamUtils? SteamUtils(); ISteamUGC? SteamUGC(); diff --git a/Source.Common/GarrysMod/IHtmlClient.cs b/Source.Common/GarrysMod/IHtmlClient.cs new file mode 100644 index 000000000..e2f3f967a --- /dev/null +++ b/Source.Common/GarrysMod/IHtmlClient.cs @@ -0,0 +1,82 @@ +using System.Runtime.InteropServices; + +namespace Source.Common.GarrysMod; + +public interface IHtmlClient +{ + [Flags] + public enum EventModifiers + { + None = 0, + Shift = 1 << 0, + Control = 1 << 1, + Alt = 1 << 2, + LeftMouse = 1 << 3, + MiddleMouse = 1 << 4, + RightMouse = 1 << 5, + OSX_Cmd = 1 << 6, + ShiftR = 1 << 7, + ControlR = 1 << 8, + AltGr = 1 << 9, + Numpad = 1 << 10 + } + + [StructLayout(LayoutKind.Explicit)] + public struct KeyEvent + { + public enum Type + { + KeyDown, + KeyUp, + KeyChar, + } + + [FieldOffset(0)] public Type EventType; + [FieldOffset(4)] public ushort KeyChar; + [FieldOffset(4)] public int WindowsKeyCode; + [FieldOffset(8)] public int NativeKeyCode; + [FieldOffset(12)] public EventModifiers Modifiers; + } + + public enum MouseButton + { + Left, + Middle, + Right, + } + + public struct MouseEvent + { + public int X; + public int Y; + public EventModifiers Modifiers; + } + + void Close(); + + void SetSize(int wide, int tall); + void SetFocused(bool hasFocus); + + void SendKeyEvent(KeyEvent keyEvent); + + void SendMouseMoveEvent(MouseEvent mouseEvent, bool mouseLeave); + void SendMouseWheelEvent(MouseEvent mouseEvent, int deltaX, int deltaY); + void SendMouseClickEvent(MouseEvent mouseEvent, MouseButton mouseButton, bool mouseUp, int clickCount); + + void LoadUrl(ReadOnlySpan url); + void SetHtml(ReadOnlySpan html); + void Refresh(); + void Stop(); + void GoBack(); + void GoForward(); + + void RunJavaScript(ReadOnlySpan code); + + void RegisterJavaScriptFunction(ReadOnlySpan objName, ReadOnlySpan funcName); + + void SetOpenLinksExternally(bool openLinksExternally); + + bool LockImageData(); + void UnlockImageData(); + ReadOnlySpan GetImageData(out int imageWide, out int imageTall); +} diff --git a/Source.Common/GarrysMod/IHtmlClientListener.cs b/Source.Common/GarrysMod/IHtmlClientListener.cs new file mode 100644 index 000000000..dc4f938c9 --- /dev/null +++ b/Source.Common/GarrysMod/IHtmlClientListener.cs @@ -0,0 +1,34 @@ +namespace Source.Common.GarrysMod; + +public interface IHtmlClientListener +{ + public enum CursorType + { + Default, + Crosshair, + Hand, + IBeam, + Hourglass, + SizeEW, + SizeNS, + SizeNWSE, + SizeNESW, + SizeAll, + No, + None, + } + + void OnAddressChange(ReadOnlySpan address); + void OnConsoleMessage(ReadOnlySpan message, ReadOnlySpan source, int lineNumber, int severity); + void OnTitleChange(ReadOnlySpan title); + void OnTargetUrlChange(ReadOnlySpan url); + void OnCursorChange(CursorType cursorType); + + void OnLoadStart(ReadOnlySpan address); + void OnLoadEnd(ReadOnlySpan address); + void OnDocumentReady(ReadOnlySpan address); + + void OnCreateChildView(ReadOnlySpan sourceUrl, ReadOnlySpan targetUrl, bool isPopup); + + JSValue OnJavaScriptCall(ReadOnlySpan objName, ReadOnlySpan funcName, in JSValue parameters); +} diff --git a/Source.Common/GarrysMod/IHtmlResourceHandler.cs b/Source.Common/GarrysMod/IHtmlResourceHandler.cs new file mode 100644 index 000000000..c96655a44 --- /dev/null +++ b/Source.Common/GarrysMod/IHtmlResourceHandler.cs @@ -0,0 +1,14 @@ +namespace Source.Common.GarrysMod; + +public abstract class HtmlResource; + +public interface IHtmlResourceHandler +{ + HtmlResource? OpenResource(ReadOnlySpan host, ReadOnlySpan path); + void CloseResource(HtmlResource resource); + + long GetLength(HtmlResource resource); + void ReadData(HtmlResource resource, Span destination); + + void Message(ReadOnlySpan data); +} diff --git a/Source.Common/GarrysMod/IHtmlSystem.cs b/Source.Common/GarrysMod/IHtmlSystem.cs new file mode 100644 index 000000000..d7a3abff4 --- /dev/null +++ b/Source.Common/GarrysMod/IHtmlSystem.cs @@ -0,0 +1,29 @@ +using System.Reflection; + +namespace Source.Common.GarrysMod; + +public interface IHtmlSystem +{ + bool Init(ReadOnlySpan baseDir, IHtmlResourceHandler resourceHandler); + void Shutdown(); + + IHtmlClient CreateClient(IHtmlClientListener listener); + + void Update(); + + JSValue CreateArray(ReadOnlySpan values); + JSValue CreateString(ReadOnlySpan value); + JSValue CreateHashMap(ReadOnlySpan keys, ReadOnlySpan values); +} + +[AttributeUsage(AttributeTargets.Assembly)] +public sealed class HtmlSystemExportAttribute(Type type) : Attribute +{ + public Type Type => type; + + public static IHtmlSystem? Find(Assembly assembly) { + HtmlSystemExportAttribute? export = assembly.GetCustomAttribute(); + FieldInfo? field = export?.Type.GetField("g_pHtmlSystem", BindingFlags.Public | BindingFlags.Static); + return field?.GetValue(null) as IHtmlSystem; + } +} diff --git a/Source.Common/GarrysMod/JSValue.cs b/Source.Common/GarrysMod/JSValue.cs new file mode 100644 index 000000000..fc5a9a859 --- /dev/null +++ b/Source.Common/GarrysMod/JSValue.cs @@ -0,0 +1,78 @@ +namespace Source.Common.GarrysMod; + +public readonly struct JSValue +{ + public interface IArray + { + ReadOnlySpan GetData(); + } + + public interface IString + { + ReadOnlySpan GetData(); + } + + public interface IHashMap + { + bool Begin(out ReadOnlySpan key, out JSValue value); + bool Next(out ReadOnlySpan key, out JSValue value); + int Size(); + } + + public enum Type + { + Undefined, + Bool, + Number, + Array, + String, + HashMap + } + + readonly Type type; + readonly bool boolean; + readonly double number; + readonly object? obj; + + public JSValue() => type = Type.Undefined; + + public JSValue(bool value) { + type = Type.Bool; + boolean = value; + } + + public JSValue(double value) { + type = Type.Number; + number = value; + } + + public JSValue(IString str) { + type = Type.String; + obj = str; + } + + public JSValue(IArray array) { + type = Type.Array; + obj = array; + } + + public JSValue(IHashMap hashMap) { + type = Type.HashMap; + obj = hashMap; + } + + public Type GetJSType() => type; + public bool GetBool() => boolean; + public double GetNumber() => number; + + public ReadOnlySpan GetString() => ((IString)obj!).GetData(); + public IString? GetInternalString() => obj as IString; + + public ReadOnlySpan GetArray() => ((IArray)obj!).GetData(); + public IArray? GetInternalArray() => obj as IArray; + + public bool HashMap_Begin(out ReadOnlySpan key, out JSValue value) => ((IHashMap)obj!).Begin(out key, out value); + public bool HashMap_Next(out ReadOnlySpan key, out JSValue value) => ((IHashMap)obj!).Next(out key, out value); + public int HashMap_Size() => ((IHashMap)obj!).Size(); + public IHashMap? GetInternalHashMap() => obj as IHashMap; +} From 627a1e46ddc63f8bd33fa2a3794bdb6ca88fce09 Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Wed, 14 Oct 2026 14:17:34 -0700 Subject: [PATCH 03/38] add HTML loading to Get --- Source.Engine/GarrysMod/Get.cs | 32 +++++++++++++++++++++++++------- 1 file changed, 25 insertions(+), 7 deletions(-) diff --git a/Source.Engine/GarrysMod/Get.cs b/Source.Engine/GarrysMod/Get.cs index 5a2d39af9..f9dcd7cb3 100644 --- a/Source.Engine/GarrysMod/Get.cs +++ b/Source.Engine/GarrysMod/Get.cs @@ -10,6 +10,7 @@ using Steamworks; +using System.Reflection; using System.Runtime.InteropServices; namespace Source.Engine.GarrysMod; @@ -26,7 +27,8 @@ public class Get(IServiceProvider appSystemFactory, EngineParms host_parms) : IG IGMod_Audio? audio; // IAnalytics? analytics; IServerAddons? serverAddons; - IGMHTML? html; + IHtmlSystem? html; + Assembly? htmlModule; InlineArrayMaxPath gameDirParent; InlineArrayMaxPath gameDir; bool filterTextInitialized; @@ -74,7 +76,7 @@ public void OnLoadFailed(ReadOnlySpan module) { public IIntroScreen? IntroScreen() => introScreen; public IMaterialSystem? Materials() => materials; public IServerAddons? ServerAddons() => serverAddons; - public IGMHTML? HTML() => html; + public IHtmlSystem? HTML() => html; public ISteamHTTP? SteamHTTP() { #if !SWDS @@ -144,9 +146,8 @@ public void Initialize(IFileSystem fileSystem) { if (html == null) { if (!commandLine.CheckParm("-nochromium")) { Msg("Attempting to load Chromium...\n"); - // todo: LoadHTML("html_chromium.dll"); + LoadHTML("html_chromium"); } - LoadHTML("html_chromium"); // if (html == null && !commandLine.CheckParm("-noawesomium")) { // Msg("Attempting to load Awesomium...\n"); @@ -157,8 +158,7 @@ public void Initialize(IFileSystem fileSystem) { if (html == null) { Msg("Attempting to load Stub...\n"); LoadHTML("html_stub"); - // todo: LoadHTML("html_stub.dll"); - if (html == null) + if (html == null) Error("Couldn't find an HTML system."); } } @@ -170,8 +170,26 @@ public void Initialize(IFileSystem fileSystem) { StripLastDir(gameDirParent); } - private void LoadHTML(string name) { + bool LoadHTML(string name) { + string path = Path.Combine(AppContext.BaseDirectory, $"{name}.dll"); + if (!File.Exists(path)) + return false; + Assembly module; + try { + module = Assembly.LoadFrom(path); + } + catch (Exception) { + return false; + } + + IHtmlSystem? system = HtmlSystemExportAttribute.Find(module); + if (system == null) + return false; + + html = system; + htmlModule = module; + return true; } static void FixSlashes(Span str, char separator) { From 828ccd066b95ae8e1e9d6e230c89c7834fe748ff Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Wed, 14 Oct 2026 14:31:24 -0700 Subject: [PATCH 04/38] KeyedService approach + html stub Assembly.LoadFrom is a bad way of doing this imo --- HTML.Stub/HTML.Stub.csproj | 14 ++++++++++++ HTML.Stub/StubClient.cs | 30 ++++++++++++++++++++++++++ HTML.Stub/StubSystem.cs | 16 ++++++++++++++ Source.Common/GarrysMod/IHtmlSystem.cs | 14 ------------ Source.Engine/EngineBuilder.cs | 5 +++++ Source.Engine/GarrysMod/Get.cs | 22 ++----------------- Source.Launcher/Program.cs | 1 + Source.Launcher/Source.Launcher.csproj | 1 + Source.NET.slnx | 3 +++ 9 files changed, 72 insertions(+), 34 deletions(-) create mode 100644 HTML.Stub/HTML.Stub.csproj create mode 100644 HTML.Stub/StubClient.cs create mode 100644 HTML.Stub/StubSystem.cs diff --git a/HTML.Stub/HTML.Stub.csproj b/HTML.Stub/HTML.Stub.csproj new file mode 100644 index 000000000..2c791ac69 --- /dev/null +++ b/HTML.Stub/HTML.Stub.csproj @@ -0,0 +1,14 @@ + + + + net10.0 + enable + enable + Debug;Release;Debug (Dedicated);Release (Dedicated) + + + + + + + diff --git a/HTML.Stub/StubClient.cs b/HTML.Stub/StubClient.cs new file mode 100644 index 000000000..cea97767c --- /dev/null +++ b/HTML.Stub/StubClient.cs @@ -0,0 +1,30 @@ +using Source.Common.GarrysMod; + +namespace HTML.Stub; + +public class StubClient : IHtmlClient +{ + public void Close() { } + public void SetSize(int wide, int tall) { } + public void SetFocused(bool hasFocus) { } + public void SendKeyEvent(IHtmlClient.KeyEvent keyEvent) { } + public void SendMouseMoveEvent(IHtmlClient.MouseEvent mouseEvent, bool mouseLeave) { } + public void SendMouseWheelEvent(IHtmlClient.MouseEvent mouseEvent, int deltaX, int deltaY) { } + public void SendMouseClickEvent(IHtmlClient.MouseEvent mouseEvent, IHtmlClient.MouseButton mouseButton, bool mouseUp, int clickCount) { } + public void LoadUrl(ReadOnlySpan url) { } + public void SetHtml(ReadOnlySpan html) { } + public void Refresh() { } + public void Stop() { } + public void GoBack() { } + public void GoForward() { } + public void RunJavaScript(ReadOnlySpan code) { } + public void RegisterJavaScriptFunction(ReadOnlySpan objName, ReadOnlySpan funcName) { } + public void SetOpenLinksExternally(bool openLinksExternally) { } + public bool LockImageData() => false; + public void UnlockImageData() { } + public ReadOnlySpan GetImageData(out int imageWide, out int imageTall) { + imageWide = 0; + imageTall = 0; + return default; + } +} diff --git a/HTML.Stub/StubSystem.cs b/HTML.Stub/StubSystem.cs new file mode 100644 index 000000000..a454dace6 --- /dev/null +++ b/HTML.Stub/StubSystem.cs @@ -0,0 +1,16 @@ +using Source.Common.GarrysMod; + +namespace HTML.Stub; + +public class StubSystem : IHtmlSystem +{ + public static readonly IHtmlSystem g_pHtmlSystem = new StubSystem(); + + public bool Init(ReadOnlySpan baseDir, IHtmlResourceHandler resourceHandler) => true; + public void Shutdown() { } + public void Update() { } + public IHtmlClient CreateClient(IHtmlClientListener listener) => new StubClient(); + public JSValue CreateArray(ReadOnlySpan values) => new(); + public JSValue CreateString(ReadOnlySpan value) => new(); + public JSValue CreateHashMap(ReadOnlySpan keys, ReadOnlySpan values) => new(); +} diff --git a/Source.Common/GarrysMod/IHtmlSystem.cs b/Source.Common/GarrysMod/IHtmlSystem.cs index d7a3abff4..1f9fc0f3a 100644 --- a/Source.Common/GarrysMod/IHtmlSystem.cs +++ b/Source.Common/GarrysMod/IHtmlSystem.cs @@ -1,5 +1,3 @@ -using System.Reflection; - namespace Source.Common.GarrysMod; public interface IHtmlSystem @@ -15,15 +13,3 @@ public interface IHtmlSystem JSValue CreateString(ReadOnlySpan value); JSValue CreateHashMap(ReadOnlySpan keys, ReadOnlySpan values); } - -[AttributeUsage(AttributeTargets.Assembly)] -public sealed class HtmlSystemExportAttribute(Type type) : Attribute -{ - public Type Type => type; - - public static IHtmlSystem? Find(Assembly assembly) { - HtmlSystemExportAttribute? export = assembly.GetCustomAttribute(); - FieldInfo? field = export?.Type.GetField("g_pHtmlSystem", BindingFlags.Public | BindingFlags.Static); - return field?.GetValue(null) as IHtmlSystem; - } -} diff --git a/Source.Engine/EngineBuilder.cs b/Source.Engine/EngineBuilder.cs index a10e45c0b..0e365387a 100644 --- a/Source.Engine/EngineBuilder.cs +++ b/Source.Engine/EngineBuilder.cs @@ -71,6 +71,11 @@ public EngineBuilder WithComponent(T instance) where T : class { return this; } + public EngineBuilder WithKeyedComponent(object key, I instance) where I : class { + this.AddKeyedSingleton(key, instance); + return this; + } + HashSet injectedTypelist = []; void PreInject(IServiceCollection services) { if (injectedTypelist.Add(typeof(T))) { diff --git a/Source.Engine/GarrysMod/Get.cs b/Source.Engine/GarrysMod/Get.cs index f9dcd7cb3..5f9578b95 100644 --- a/Source.Engine/GarrysMod/Get.cs +++ b/Source.Engine/GarrysMod/Get.cs @@ -28,7 +28,6 @@ public class Get(IServiceProvider appSystemFactory, EngineParms host_parms) : IG // IAnalytics? analytics; IServerAddons? serverAddons; IHtmlSystem? html; - Assembly? htmlModule; InlineArrayMaxPath gameDirParent; InlineArrayMaxPath gameDir; bool filterTextInitialized; @@ -171,25 +170,8 @@ public void Initialize(IFileSystem fileSystem) { } bool LoadHTML(string name) { - string path = Path.Combine(AppContext.BaseDirectory, $"{name}.dll"); - if (!File.Exists(path)) - return false; - - Assembly module; - try { - module = Assembly.LoadFrom(path); - } - catch (Exception) { - return false; - } - - IHtmlSystem? system = HtmlSystemExportAttribute.Find(module); - if (system == null) - return false; - - html = system; - htmlModule = module; - return true; + html = appSystemFactory.GetKeyedService(name); + return html != null; } static void FixSlashes(Span str, char separator) { diff --git a/Source.Launcher/Program.cs b/Source.Launcher/Program.cs index 77bbf40ca..f55d8b7dc 100644 --- a/Source.Launcher/Program.cs +++ b/Source.Launcher/Program.cs @@ -87,6 +87,7 @@ public void Boot() { #if GMOD_DLL .WithComponent() .WithComponent() + .WithKeyedComponent("html_stub", HTML.Stub.StubSystem.g_pHtmlSystem) #endif .WithComponent() // Our game DLL's. Server/game impl, client impl, UI impl. diff --git a/Source.Launcher/Source.Launcher.csproj b/Source.Launcher/Source.Launcher.csproj index 293d23d5b..54bb183ea 100644 --- a/Source.Launcher/Source.Launcher.csproj +++ b/Source.Launcher/Source.Launcher.csproj @@ -40,6 +40,7 @@ + diff --git a/Source.NET.slnx b/Source.NET.slnx index b0328a0f5..9b8bac89e 100644 --- a/Source.NET.slnx +++ b/Source.NET.slnx @@ -113,6 +113,9 @@ + + + From 80454fc680c529e243e7434d64b9fd300ce0c76d Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Wed, 14 Oct 2026 14:31:41 -0700 Subject: [PATCH 05/38] Game HTML plumbing --- Game.Client/GarrysMod/HtmlPanel.cs | 456 +++++++++++++------ Game.Client/GarrysMod/HtmlResourceHandler.cs | 83 ++++ Game.Client/GarrysMod/LuaPanel.cs | 136 +++++- Game.Client/HLClient.cs | 8 + Game.Shared/GarrysMod/GarrysMod.cs | 4 + 5 files changed, 541 insertions(+), 146 deletions(-) create mode 100644 Game.Client/GarrysMod/HtmlResourceHandler.cs diff --git a/Game.Client/GarrysMod/HtmlPanel.cs b/Game.Client/GarrysMod/HtmlPanel.cs index 111c65edd..8099282ba 100644 --- a/Game.Client/GarrysMod/HtmlPanel.cs +++ b/Game.Client/GarrysMod/HtmlPanel.cs @@ -1,45 +1,21 @@ using Source; +using Source.Common.Bitmap; +using Source.Common.GarrysMod; +using Source.Common.GarrysMod.Lua; using Source.Common.GUI; using Source.Common.Input; using Source.Common.MaterialSystem; using Source.GUI.Controls; -namespace Game.Client.GarrysMod; +using static Source.Common.GarrysMod.Lua.PooledStrings; -public enum HtmlMouseButton -{ - Left = 0, - Middle = 1, - Right = 2 -} - -public enum HtmlKeyEventType -{ - RawKeyDown = 0, - KeyUp = 1, - Char = 2 -} - -[Flags] -public enum HtmlKeyModifiers -{ - None = 0, - LeftShift = 1 << 0, - LeftControl = 1 << 1, - LeftAlt = 1 << 2, - LeftMouse = 1 << 3, - MiddleMouse = 1 << 4, - RightMouse = 1 << 5, - RightShift = 1 << 7, - RightControl = 1 << 8, - RightAlt = 1 << 9, - KeyPad = 1 << 10 -} +namespace Game.Client.GarrysMod; -public class HtmlPanel : EditablePanel +public class HtmlPanel : EditablePanel, IHtmlClientListener { static HtmlPanel() => ChainToAnimationMap(); + readonly IHtmlClient? Client; TextureID TextureID; int TextureWide; int TextureTall; @@ -58,11 +34,11 @@ public HtmlPanel(Panel? parent, ReadOnlySpan panelName) : base(parent, pan Material = null; FinishedLoading = false; Loading = true; - // todo: create cef + Client = get.HTML()?.CreateClient(this); } public override void Dispose() { - // todo: release cef + Client?.Close(); // if (TextureID != -1) // Surface.DestroyTextureID(TextureID); // todo, I thought we had this?? Material?.DecrementReferenceCount(); @@ -72,49 +48,46 @@ public override void Dispose() { } public override void OnSizeChanged(int newWide, int newTall) { - if (newWide != 0 && newTall != 0) { - // todo: send to cef - } + if (newWide != 0 && newTall != 0) + Client?.SetSize(newWide, newTall); } public override void OnSetFocus() { - // todo: send to cef + Client?.SetFocused(true); base.OnSetFocus(); } public override void OnKillFocus(Panel? newPanel) { - // todo: send to cef + Client?.SetFocused(false); base.OnKillFocus(newPanel); } + IHtmlClient.MouseEvent MouseEvent() => new() { X = CursorX, Y = CursorY, Modifiers = GetKeyModifiers() }; + public override void OnCursorMoved(int x, int y) { CursorX = x; CursorY = y; - HtmlKeyModifiers modifiers = GetKeyModifiers(); - // todo: send to cef + Client?.SendMouseMoveEvent(MouseEvent(), false); } public override void OnMousePressed(ButtonCode code) { RequestFocus(); - if (!GetMouseButton(code, out HtmlMouseButton button)) + if (!GetMouseButton(code, out IHtmlClient.MouseButton button)) return; - HtmlKeyModifiers modifiers = GetKeyModifiers(); - // todo: send to cef (up = false, clicks = 1) + Client?.SendMouseClickEvent(MouseEvent(), button, false, 1); } public override void OnMouseDoublePressed(ButtonCode code) { RequestFocus(); - if (!GetMouseButton(code, out HtmlMouseButton button)) + if (!GetMouseButton(code, out IHtmlClient.MouseButton button)) return; - HtmlKeyModifiers modifiers = GetKeyModifiers(); - // todo: send to cef (up = false, clicks = 2) + Client?.SendMouseClickEvent(MouseEvent(), button, false, 2); } public override void OnMouseReleased(ButtonCode code) { - if (!GetMouseButton(code, out HtmlMouseButton button)) + if (!GetMouseButton(code, out IHtmlClient.MouseButton button)) return; - HtmlKeyModifiers modifiers = GetKeyModifiers(); - // todo: send to cef (up = true, clicks = 1) + Client?.SendMouseClickEvent(MouseEvent(), button, true, 1); } public override void OnMouseWheeled(int delta) { @@ -123,8 +96,7 @@ public override void OnMouseWheeled(int delta) { deltaX = delta * 100; else deltaY = delta * 100; - HtmlKeyModifiers modifiers = GetKeyModifiers(); - // todo: send to cef + Client?.SendMouseWheelEvent(MouseEvent(), deltaX, deltaY); } public override void OnKeyCodePressed(ButtonCode code) { } @@ -138,43 +110,66 @@ public override void OnKeyCodeTyped(ButtonCode code) { return; } - HtmlKeyModifiers modifiers = GetKeyModifiers(); + IHtmlClient.EventModifiers modifiers = GetKeyModifiers(); if (code >= ButtonCode.KeyPad0 && code <= ButtonCode.KeyPadDecimal) - modifiers |= HtmlKeyModifiers.KeyPad; - // todo: send to cef (HtmlKeyEventType.RawKeyDown, KeyCodeToVirtualKey(code), KeyCodeToScanCode(code)) + modifiers |= IHtmlClient.EventModifiers.Numpad; + + Client?.SendKeyEvent(new IHtmlClient.KeyEvent { + EventType = IHtmlClient.KeyEvent.Type.KeyDown, + WindowsKeyCode = KeyCodeToVirtualKey(code), + NativeKeyCode = KeyCodeToScanCode(code), + Modifiers = modifiers + }); } public override void OnKeyTyped(char unichar) { - HtmlKeyModifiers modifiers = GetKeyModifiers(); - // todo: send to cef (HtmlKeyEventType.Char) + Client?.SendKeyEvent(new IHtmlClient.KeyEvent { + EventType = IHtmlClient.KeyEvent.Type.KeyChar, + KeyChar = unichar, + Modifiers = GetKeyModifiers() + }); } public override void OnKeyCodeReleased(ButtonCode code) { if (code == ButtonCode.None || (code >= ButtonCode.KeyF1 && code <= ButtonCode.KeyF12)) return; - HtmlKeyModifiers modifiers = GetKeyModifiers(); + IHtmlClient.EventModifiers modifiers = GetKeyModifiers(); if (code >= ButtonCode.KeyPad0 && code <= ButtonCode.KeyPadDecimal) - modifiers |= HtmlKeyModifiers.KeyPad; - // todo: send to cef (HtmlKeyEventType.KeyUp, KeyCodeToVirtualKey(code), KeyCodeToScanCode(code)) + modifiers |= IHtmlClient.EventModifiers.Numpad; + + Client?.SendKeyEvent(new IHtmlClient.KeyEvent { + EventType = IHtmlClient.KeyEvent.Type.KeyUp, + WindowsKeyCode = KeyCodeToVirtualKey(code), + NativeKeyCode = KeyCodeToScanCode(code), + Modifiers = modifiers + }); + } + + unsafe void UploadTexture(ReadOnlySpan rgba, int wide, int tall) { + if (rgba.IsEmpty || wide <= 0 || tall <= 0) + return; + + fixed (byte* data = rgba) { + if (TextureID == -1 || TextureWide != wide || TextureTall != tall) { + if (TextureID != -1) + Surface.DestroyTextureID(TextureID); + Material?.DecrementReferenceCount(); + TextureID = -1; + Material = null; + TextureID = Surface.CreateNewTextureID(true); + Surface.DrawSetTextureRGBAEx(TextureID, (nint)data, wide, tall, ImageFormat.BGRA8888); + // todo: Material from texture mat info, IncrementReferenceCount + TextureWide = wide; + TextureTall = tall; + } + else + Surface.DrawUpdateRegionTextureRGBA(TextureID, 0, 0, (nint)data, wide, tall, ImageFormat.BGRA8888); + } } public override void Paint() { - // todo: cef texture upload - // if (TextureID == -1 || TextureWide != wide || TextureTall != tall) { - // if (TextureID != -1) - // Surface.DestroyTextureID(TextureID); - // Material?.DecrementReferenceCount(); - // TextureID = -1; - // Material = null; - // TextureID = Surface.CreateNewTextureID(true); - // Surface.DrawSetTextureRGBAEx(TextureID, rgba, wide, tall, ImageFormat.BGRA8888); - // todo: Material from texture mat info, IncrementReferenceCount - // TextureWide = wide; - // TextureTall = tall; - // } - // else - // Surface.DrawUpdateRegionTextureRGBA(TextureID, 0, 0, rgba, wide, tall, ImageFormat.BGRA8888); + UpdateHTMLTexture(); if (TextureID != -1) { Surface.DrawSetColor(255, 255, 255, 255); @@ -183,78 +178,65 @@ public override void Paint() { } } - public void OpenURL(ReadOnlySpan url) { - // todo: send to cef - } + public void OpenURL(ReadOnlySpan url) => Client?.LoadUrl(url); - public void SetHTML(ReadOnlySpan html) { - // todo: send to cef - } + public void SetHTML(ReadOnlySpan html) => Client?.SetHtml(html); - public void Refresh() { - // todo: send to cef - } + public void Refresh() => Client?.Refresh(); - public void StopLoading() { - // todo: send to cef - } + public void StopLoading() => Client?.Stop(); - public void GoBack() { - // todo: send to cef - } + public void GoBack() => Client?.GoBack(); - public void GoForward() { - // todo: send to cef - } + public void GoForward() => Client?.GoForward(); - public void RunJavascript(ReadOnlySpan script) { - // todo: send to cef - } + public void RunJavascript(ReadOnlySpan script) => Client?.RunJavaScript(script); - public void NewObject(ReadOnlySpan objName) { - // todo: send to cef - } + public void NewObjectCallback(ReadOnlySpan objName, ReadOnlySpan funcName) => Client?.RegisterJavaScriptFunction(objName, funcName); - public void NewObjectCallback(ReadOnlySpan objName, ReadOnlySpan funcName) { - // todo: send to cef - } + public void SetOpenLinksExternally(bool openLinksExternally) => Client?.SetOpenLinksExternally(openLinksExternally); public bool IsLoading() => Loading; public IMaterial? GetHTMLMaterial() => FinishedLoading ? Material : null; public void UpdateHTMLTexture() { - // todo: cef texture upload + if (Client == null || !Client.LockImageData()) + return; + + ReadOnlySpan rgba = Client.GetImageData(out int wide, out int tall); + UploadTexture(rgba, wide, tall); + Client.UnlockImageData(); } - static bool GetMouseButton(ButtonCode code, out HtmlMouseButton button) { + static bool GetMouseButton(ButtonCode code, out IHtmlClient.MouseButton button) { switch (code) { - case ButtonCode.MouseLeft: button = HtmlMouseButton.Left; return true; - case ButtonCode.MouseRight: button = HtmlMouseButton.Right; return true; - case ButtonCode.MouseMiddle: button = HtmlMouseButton.Middle; return true; + case ButtonCode.MouseLeft: button = IHtmlClient.MouseButton.Left; return true; + case ButtonCode.MouseRight: button = IHtmlClient.MouseButton.Right; return true; + case ButtonCode.MouseMiddle: button = IHtmlClient.MouseButton.Middle; return true; } button = default; return false; } - static HtmlKeyModifiers GetKeyModifiers() { - HtmlKeyModifiers modifiers = vguiInput.IsKeyDown(ButtonCode.KeyLShift) ? HtmlKeyModifiers.LeftShift : HtmlKeyModifiers.None; + static IHtmlClient.EventModifiers GetKeyModifiers() { + IHtmlClient.EventModifiers modifiers = vguiInput.IsKeyDown(ButtonCode.KeyLShift) ? IHtmlClient.EventModifiers.Shift : IHtmlClient.EventModifiers.None; if (vguiInput.IsKeyDown(ButtonCode.KeyRShift)) - modifiers |= HtmlKeyModifiers.RightShift; + modifiers |= IHtmlClient.EventModifiers.ShiftR; if (vguiInput.IsKeyDown(ButtonCode.KeyLControl)) - modifiers |= HtmlKeyModifiers.LeftControl; + modifiers |= IHtmlClient.EventModifiers.Control; if (vguiInput.IsKeyDown(ButtonCode.KeyRControl)) - modifiers |= HtmlKeyModifiers.RightControl; + modifiers |= IHtmlClient.EventModifiers.ControlR; if (vguiInput.IsKeyDown(ButtonCode.KeyLAlt)) - modifiers |= HtmlKeyModifiers.LeftAlt; + modifiers |= IHtmlClient.EventModifiers.Alt; if (vguiInput.IsKeyDown(ButtonCode.KeyRAlt)) - modifiers |= HtmlKeyModifiers.RightAlt; + modifiers |= IHtmlClient.EventModifiers.AltGr; if (vguiInput.IsMouseDown(ButtonCode.MouseLeft)) - modifiers |= HtmlKeyModifiers.LeftMouse; + modifiers |= IHtmlClient.EventModifiers.LeftMouse; if (vguiInput.IsMouseDown(ButtonCode.MouseMiddle)) - modifiers |= HtmlKeyModifiers.MiddleMouse; + modifiers |= IHtmlClient.EventModifiers.MiddleMouse; if (vguiInput.IsMouseDown(ButtonCode.MouseRight)) - modifiers |= HtmlKeyModifiers.RightMouse; + modifiers |= IHtmlClient.EventModifiers.RightMouse; return modifiers; } @@ -287,8 +269,16 @@ static HtmlKeyModifiers GetKeyModifiers() { static int KeyCodeToScanCode(ButtonCode code) => (uint)code < ScanCodes.Length ? ScanCodes[(int)code] : 0; static int KeyCodeToVirtualKey(ButtonCode code) => (uint)code < VirtualKeys.Length ? VirtualKeys[(int)code] : 0; - // todo: all callbacks below, lua hook - public void OnAddressChange(ReadOnlySpan url) { } + void CallStringHook(LUA_POOLEDSTRING hook, ReadOnlySpan value) { + if (!PushLuaHook(hook)) + return; + + PushLua(Lua!, LuaType.Panel); + Lua!.PushString(value); + Lua.CallInternalNoReturns(2); + } + + public void OnAddressChange(ReadOnlySpan address) => CallStringHook(LUA_POOLEDSTRING.OnChangeAddressBar, address); public void OnConsoleMessage(ReadOnlySpan message, ReadOnlySpan source, int line, int level) { ReadOnlySpan levelName = "log"; @@ -299,10 +289,22 @@ public void OnConsoleMessage(ReadOnlySpan message, ReadOnlySpan sour else if (level == 4) levelName = "error"; - if (message.StartsWith("RUNLUA:")) { - // todo: lua hook + if (message.StartsWith("RUNLUA:") && PushLuaHook(LUA_POOLEDSTRING.ConsoleMessage)) { + PushLua(Lua!, LuaType.Panel); + Lua!.PushString(message); + Lua.CallInternalNoReturns(2); + return; + } + + if (PushLuaHook(LUA_POOLEDSTRING.ConsoleMessage)) { + PushLua(Lua!, LuaType.Panel); + Lua!.PushString(message); + Lua.PushString(source); + Lua.PushNumber(line); + Lua.PushString(levelName); + Lua.CallInternalNoReturns(5); + return; } - // todo: lua hook ConColorMsg(new Color(255, 160, 255, 255), "[HTML] "); if (level == 1) @@ -320,37 +322,211 @@ public void OnConsoleMessage(ReadOnlySpan message, ReadOnlySpan sour ConColorMsg(new Color(255, 255, 255, 255), "{0}\n", new string(message)); } - public void OnTitleChange(ReadOnlySpan title) { } - public void OnTargetUrlChange(ReadOnlySpan url) { } + public void OnTitleChange(ReadOnlySpan title) => CallStringHook(LUA_POOLEDSTRING.OnChangeTitle, title); - public void OnCursorChange(int cursor) { + public void OnTargetUrlChange(ReadOnlySpan url) => CallStringHook(LUA_POOLEDSTRING.OnChangeTargetURL, url); + + public void OnCursorChange(IHtmlClientListener.CursorType cursor) { CursorCode code = cursor switch { - 1 => CursorCode.Crosshair, - 2 => CursorCode.Hand, - 3 => CursorCode.IBeam, - 4 => CursorCode.Hourglass, - 5 => CursorCode.SizeWE, - 6 => CursorCode.SizeNS, - 7 => CursorCode.SizeNWSE, - 8 => CursorCode.SizeNESW, - 9 => CursorCode.SizeAll, - 10 => CursorCode.No, - 11 => CursorCode.None, + IHtmlClientListener.CursorType.Crosshair => CursorCode.Crosshair, + IHtmlClientListener.CursorType.Hand => CursorCode.Hand, + IHtmlClientListener.CursorType.IBeam => CursorCode.IBeam, + IHtmlClientListener.CursorType.Hourglass => CursorCode.Hourglass, + IHtmlClientListener.CursorType.SizeEW => CursorCode.SizeWE, + IHtmlClientListener.CursorType.SizeNS => CursorCode.SizeNS, + IHtmlClientListener.CursorType.SizeNWSE => CursorCode.SizeNWSE, + IHtmlClientListener.CursorType.SizeNESW => CursorCode.SizeNESW, + IHtmlClientListener.CursorType.SizeAll => CursorCode.SizeAll, + IHtmlClientListener.CursorType.No => CursorCode.No, + IHtmlClientListener.CursorType.None => CursorCode.None, _ => CursorCode.Arrow }; SetCursor(code); } - public void OnBeginLoading(ReadOnlySpan url) { + public void OnLoadStart(ReadOnlySpan address) { Loading = true; + CallStringHook(LUA_POOLEDSTRING.OnBeginLoadingDocument, address); } - public void OnFinishLoading(ReadOnlySpan url) { + public void OnLoadEnd(ReadOnlySpan address) { Loading = false; FinishedLoading = true; + CallStringHook(LUA_POOLEDSTRING.OnFinishLoadingDocument, address); + } + + public void OnDocumentReady(ReadOnlySpan address) => CallStringHook(LUA_POOLEDSTRING.OnDocumentReady, address); + + public void OnCreateChildView(ReadOnlySpan sourceUrl, ReadOnlySpan targetUrl, bool isPopup) { + if (!PushLuaHook(LUA_POOLEDSTRING.OnChildViewCreated)) + return; + + PushLua(Lua!, LuaType.Panel); + Lua!.PushString(sourceUrl); + Lua.PushString(targetUrl); + Lua.PushBool(isPopup); + Lua.CallInternalNoReturns(4); + } + + public JSValue OnJavaScriptCall(ReadOnlySpan objName, ReadOnlySpan funcName, in JSValue parameters) { + if (parameters.GetJSType() != JSValue.Type.Array) + Error("HtmlPanel::OnJavaScriptCall encounted non array parameter list\n"); + + IHtmlSystem html = get.HTML()!; + + if (Lua == null) + return html.CreateArray([]); + + int top = Lua.Top(); + + if (!PushLuaHook(LUA_POOLEDSTRING.OnCallback)) + return html.CreateArray([]); + + PushLua(Lua, LuaType.Panel); + Lua.PushString(objName); + Lua.PushString(funcName); + + Lua.CreateTable(); + ReadOnlySpan args = parameters.GetArray(); + for (int i = 0; i < args.Length; i++) { + Lua.PushNumber(i + 1); + PushJSValue(Lua, args[i]); + Lua.SetTable(-3); + } + + if (!Lua.CallFunctionProtected(4, -1, true)) + return html.CreateArray([]); + + int returns = Lua.Top() - top; + JSValue[] values = new JSValue[Math.Max(returns, 0)]; + for (int i = 0; i < values.Length; i++) + if (!LuaToJSValue(Lua, html, out values[i], -values.Length + i)) + values[i] = default; + + Lua.Pop(values.Length); + return html.CreateArray(values); } - public void OnDocumentReady(ReadOnlySpan url) { } - public void OnChildViewCreated(ReadOnlySpan sourceUrl, ReadOnlySpan targetUrl, bool isPopup) { } - // todo: OnJavaScriptCall, lua hook + static void PushJSValue(ILuaInterface lua, in JSValue value, int depth = 0) { + if (depth > 16) { + lua.PushNil(); + return; + } + + switch (value.GetJSType()) { + case JSValue.Type.Bool: + lua.PushBool(value.GetBool()); + break; + case JSValue.Type.Number: + lua.PushNumber(value.GetNumber()); + break; + case JSValue.Type.String: + lua.PushString(value.GetString()); + break; + case JSValue.Type.Array: { + lua.CreateTable(); + ReadOnlySpan array = value.GetArray(); + for (int i = 0; i < array.Length; i++) { + lua.PushNumber(i + 1); + PushJSValue(lua, array[i], depth + 1); + lua.SetTable(-3); + } + break; + } + case JSValue.Type.HashMap: { + lua.CreateTable(); + if (value.HashMap_Begin(out ReadOnlySpan key, out JSValue entry)) { + do { + lua.PushString(key); + PushJSValue(lua, entry, depth + 1); + lua.SetTable(-3); + } + while (value.HashMap_Next(out key, out entry)); + } + break; + } + default: + lua.PushNil(); + break; + } + } + + static bool LuaToJSValue(ILuaInterface lua, IHtmlSystem html, out JSValue value, int index, int depth = 0) { + value = default; + + if (depth > 16) + return false; + + switch (lua.GetType(index)) { + case LuaType.Bool: + value = new JSValue(lua.GetBool(index)); + return true; + case LuaType.Number: + value = new JSValue(lua.GetNumber(index)); + return true; + case LuaType.String: + value = html.CreateString(lua.GetString(index)); + return true; + case LuaType.Table: + break; + default: + return true; + } + + lua.Push(index); + + int sequential = 0; + while (true) { + lua.PushNumber(sequential + 1); + lua.GetTable(-2); + bool isNil = lua.IsType(-1, LuaType.Nil); + lua.Pop(1); + if (isNil) + break; + sequential++; + } + + int total = 0; + lua.PushNil(); + while (lua.Next(-2)) { + lua.Pop(1); + total++; + } + + if (sequential == total) { + JSValue[] list = new JSValue[sequential]; + for (int i = 0; i < sequential; i++) { + lua.PushNumber(i + 1); + lua.GetTable(-2); + if (!LuaToJSValue(lua, html, out list[i], -1, depth + 1)) { + lua.Pop(2); + return false; + } + lua.Pop(1); + } + lua.Pop(1); + value = html.CreateArray(list); + return true; + } + + List keys = new(total); + List values = new(total); + lua.PushNil(); + while (lua.Next(-2)) { + lua.Push(-2); + keys.Add(lua.GetString(-1) ?? ""); + lua.Pop(1); + + if (!LuaToJSValue(lua, html, out JSValue entry, -1, depth + 1)) { + lua.Pop(3); + return false; + } + values.Add(entry); + lua.Pop(1); + } + lua.Pop(1); + + value = html.CreateHashMap(keys.ToArray(), values.ToArray()); + return true; + } } diff --git a/Game.Client/GarrysMod/HtmlResourceHandler.cs b/Game.Client/GarrysMod/HtmlResourceHandler.cs new file mode 100644 index 000000000..ebe70662c --- /dev/null +++ b/Game.Client/GarrysMod/HtmlResourceHandler.cs @@ -0,0 +1,83 @@ +using Source.Common.Filesystem; +using Source.Common.GarrysMod; + +namespace Game.Client.GarrysMod; + +public class HtmlResourceHandler : IHtmlResourceHandler +{ + public static readonly HtmlResourceHandler g_HtmlResourceHandler = new(); + + sealed class Resource(IFileHandle file) : HtmlResource + { + public readonly IFileHandle File = file; + } + + static IFileHandle? OpenMapImage(ReadOnlySpan path) { + if (path.IsEmpty) + return null; + + ReadOnlySpan name = path[1..]; + if (name.Contains('/')) + return null; + + IFileHandle? file = filesystem.Open($"maps/thumb/{name}.png", FileOpenOptions.Read | FileOpenOptions.Binary, "GAME"); + if (file != null) + return file; + + file = filesystem.Open($"maps/{name}.png", FileOpenOptions.Read | FileOpenOptions.Binary, "GAME"); + if (file != null) + return file; + + return filesystem.Open("maps/thumb/noicon.png", FileOpenOptions.Read | FileOpenOptions.Binary, "GAME"); + } + + public HtmlResource? OpenResource(ReadOnlySpan host, ReadOnlySpan path) { + IFileHandle? file; + + if (stricmp(host, "garrysmod") == 0) { + if (path.IsEmpty) + return null; + + ReadOnlySpan fileName = path[1..]; + + Span fullPath = stackalloc char[MAX_PATH]; + fullPath.Clear(); + ReadOnlySpan full = filesystem.RelativePathToFullPath(fileName, "GAME", fullPath); + + Span relativePath = stackalloc char[MAX_PATH]; + relativePath.Clear(); + bool relative = filesystem.FullPathToRelativePathEx(full, "GAME", relativePath); + + if (full.IsEmpty || !relative) + return null; + + file = filesystem.Open(fileName, FileOpenOptions.Read | FileOpenOptions.Binary, "GAME"); + } + else if (stricmp(host, "mapimage") == 0) + file = OpenMapImage(path); + else + return null; + + if (file == null) + return null; + + return new Resource(file); + } + + public void CloseResource(HtmlResource resource) => ((Resource)resource).File.Dispose(); + + public long GetLength(HtmlResource resource) => (uint)((Resource)resource).File.Stream.Length; + + public void ReadData(HtmlResource resource, Span destination) { + Stream stream = ((Resource)resource).File.Stream; + int total = 0; + while (total < destination.Length) { + int read = stream.Read(destination[total..]); + if (read <= 0) + break; + total += read; + } + } + + public void Message(ReadOnlySpan data) => Msg(data); +} diff --git a/Game.Client/GarrysMod/LuaPanel.cs b/Game.Client/GarrysMod/LuaPanel.cs index 96f128e3f..7762f1b50 100644 --- a/Game.Client/GarrysMod/LuaPanel.cs +++ b/Game.Client/GarrysMod/LuaPanel.cs @@ -1,6 +1,7 @@ using Source; using Source.Common.GarrysMod.Lua; using Source.Common.GUI; +using Source.Common.MaterialSystem; using Source.GUI.Controls; namespace Game.Client.GarrysMod; @@ -795,13 +796,8 @@ static int Panel__DrawTexturedRect(ILuaInterface lua) { [LuaMethod] static int Panel__NewObject(ILuaInterface lua) { Panel? panel = (Panel?)PanelClass.Get(1); - if (panel == null) { + if (panel == null) lua.Error("Tried to use a NULL Panel!"); - return 0; - } - - if (panel is HtmlPanel html) - html.NewObject(lua.CheckString(2)); return 0; } @@ -891,6 +887,134 @@ static int Panel__IsLoading(ILuaInterface lua) { return 1; } + [LuaMethod] + static int Panel__UpdateHTMLTexture(ILuaInterface lua) { + Panel? panel = (Panel?)PanelClass.Get(1); + if (panel == null) { + lua.Error("Tried to use a NULL Panel!"); + return 0; + } + + if (panel is HtmlPanel html) + html.UpdateHTMLTexture(); + return 0; + } + + [LuaMethod] + static int Panel__GetHTMLMaterial(ILuaInterface lua) { + Panel? panel = (Panel?)PanelClass.Get(1); + if (panel == null) { + lua.Error("Tried to use a NULL Panel!"); + return 0; + } + + if (panel is not HtmlPanel html) + return 0; + + IMaterial? material = html.GetHTMLMaterial(); + if (material == null) + return 0; + + LuaMaterial.Push(material); + return 1; + } + + [LuaMethod] + static int Panel__SetHTML(ILuaInterface lua) { + Panel? panel = (Panel?)PanelClass.Get(1); + if (panel == null) { + lua.Error("Tried to use a NULL Panel!"); + return 0; + } + + if (panel is HtmlPanel html) + html.SetHTML(lua.CheckString(2)); + return 0; + } + + [LuaMethod] + static int Panel__Refresh(ILuaInterface lua) { + Panel? panel = (Panel?)PanelClass.Get(1); + if (panel == null) { + lua.Error("Tried to use a NULL Panel!"); + return 0; + } + + if (panel is HtmlPanel html) + html.Refresh(); + return 0; + } + + [LuaMethod] + static int Panel__StopLoading(ILuaInterface lua) { + Panel? panel = (Panel?)PanelClass.Get(1); + if (panel == null) { + lua.Error("Tried to use a NULL Panel!"); + return 0; + } + + if (panel is HtmlPanel html) + html.StopLoading(); + return 0; + } + + [LuaMethod] + static int Panel__GoBack(ILuaInterface lua) { + Panel? panel = (Panel?)PanelClass.Get(1); + if (panel == null) { + lua.Error("Tried to use a NULL Panel!"); + return 0; + } + + if (panel is HtmlPanel html) + html.GoBack(); + return 0; + } + + [LuaMethod] + static int Panel__GoForward(ILuaInterface lua) { + Panel? panel = (Panel?)PanelClass.Get(1); + if (panel == null) { + lua.Error("Tried to use a NULL Panel!"); + return 0; + } + + if (panel is HtmlPanel html) + html.GoForward(); + return 0; + } + + [LuaMethod] + static int Panel__GoToHistoryOffset(ILuaInterface lua) { + Panel? panel = (Panel?)PanelClass.Get(1); + if (panel == null) { + lua.Error("Tried to use a NULL Panel!"); + return 0; + } + + if (panel is HtmlPanel) + Msg("TODO: HTMLPanel.GoToHistoryOffset is NYI.\n"); + return 0; + } + + static int RunJavascript(ILuaInterface lua) { + Panel? panel = (Panel?)PanelClass.Get(1); + if (panel == null) { + lua.Error("Tried to use a NULL Panel!"); + return 0; + } + + if (panel is HtmlPanel html) + html.RunJavascript(lua.CheckString(2)); + return 0; + } + + [LuaMethod] + static int Panel__Exec(ILuaInterface lua) => RunJavascript(lua); + + [LuaMethod] + static int Panel__RunJavascript(ILuaInterface lua) => RunJavascript(lua); + static readonly int[] ContentAlignmentToNumpad = [7, 8, 9, 4, 5, 6, 1, 2, 3]; [LuaMethod] diff --git a/Game.Client/HLClient.cs b/Game.Client/HLClient.cs index dc6ace73e..42cafef58 100644 --- a/Game.Client/HLClient.cs +++ b/Game.Client/HLClient.cs @@ -135,6 +135,7 @@ public bool Init() { randomgaussian.AttachToStream(random); #if GMOD_DLL + get.HTML()?.Init(get.GameDirParent(), HtmlResourceHandler.g_HtmlResourceHandler); get.IntroScreen()!.Start(); get.IntroScreen()!.Update("Start", true); garrysmod.InitializeMod(services); @@ -211,6 +212,9 @@ public bool Init() { public void Shutdown() { ClientVoiceMgr_Shutdown(); Game.Client.GarrysMod.GarrysMod.Lua.Kill(); +#if GMOD_DLL + get.HTML()?.Shutdown(); +#endif } public void VoiceStatus(int entindex, bool talking) { @@ -474,6 +478,10 @@ public int HudVidInit() { public void HudUpdate(bool active) { TimeUnit_t frameTime = gpGlobals.FrameTime; +#if GMOD_DLL + garrysmod.Update(); +#endif + GetClientVoiceMgr().Frame(frameTime); gHUD.UpdateHud(active); diff --git a/Game.Shared/GarrysMod/GarrysMod.cs b/Game.Shared/GarrysMod/GarrysMod.cs index f60abde49..6235cf015 100644 --- a/Game.Shared/GarrysMod/GarrysMod.cs +++ b/Game.Shared/GarrysMod/GarrysMod.cs @@ -128,6 +128,10 @@ public void InitializeMod(IServiceProvider services) { } #if CLIENT_DLL + public void Update() { + get.HTML()?.Update(); + } + public void LevelInit(ReadOnlySpan mapName) { get.Audio()?.StopAllPlayback(); From 2b6e6064b87e965fe7dd9ff9398de6ccec343813 Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Wed, 14 Oct 2026 14:40:54 -0700 Subject: [PATCH 06/38] Link html folder --- Game.Assets/Assets.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Game.Assets/Assets.cs b/Game.Assets/Assets.cs index 498313de0..b8861965c 100644 --- a/Game.Assets/Assets.cs +++ b/Game.Assets/Assets.cs @@ -38,6 +38,7 @@ public static List GetRequiredAssets() { #if GMOD_DLL new("sdn/gamemodes", "garrysmod/gamemodes", IsDirectory: true), new("sdn/lua", "garrysmod/lua", IsDirectory: true), + new("sdn/html", "garrysmod/html", IsDirectory: true), #endif new("sdn/cache/workshop", "garrysmod/cache/workshop", IsDirectory: true, Optional: false), new("sdn/settings", "garrysmod/settings", IsDirectory: true) From b7383ab93e77186ba88773d74a2407642f79f5db Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Wed, 14 Oct 2026 14:49:30 -0700 Subject: [PATCH 07/38] Fix a really nasty bug with FontTextureRegen.RegenerateTextureBits copying This resulted in copying being AWFUL on performance this also fixes @callumok2004's previous Steam HTML issues --- Source.MaterialSystem/Surface/TextureDictionary.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source.MaterialSystem/Surface/TextureDictionary.cs b/Source.MaterialSystem/Surface/TextureDictionary.cs index 152f8ad6b..1b0d7548d 100644 --- a/Source.MaterialSystem/Surface/TextureDictionary.cs +++ b/Source.MaterialSystem/Surface/TextureDictionary.cs @@ -43,7 +43,7 @@ public void RegenerateTextureBits(ITexture texture, IVTFTexture vtfTexture, in R for (int y = subRect.Y; y < ymax; ++y) { Span pchData = vtfTexture.ImageData(0, 0, 0, 0, y)[(subRect.X * nFormatBytes)..]; nint size = ImageLoader.GetMemRequired(subRect.Width, 1, 1, Format, false); - memcpy(pchData, TextureBits.AsSpan()[((y * Width + subRect.X) * nFormatBytes)..]); + memcpy(pchData, TextureBits.AsSpan()[((y * Width + subRect.X) * nFormatBytes)..], (int)size); } } else { From e80a833fe7f2e8af8d7c6079320fb75a2c360afe Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Wed, 14 Oct 2026 15:12:40 -0700 Subject: [PATCH 08/38] Menusystem WIP (mostly getting client/shared code in) --- Game.Client/GarrysMod/HtmlPanel.cs | 4 + Game.Client/GarrysMod/LuaAchievements.cs | 4 + Game.Client/GarrysMod/LuaFonts.cs | 4 + Game.Client/GarrysMod/LuaGui.cs | 4 + Game.Client/GarrysMod/LuaInput.cs | 4 + Game.Client/GarrysMod/LuaLanguage.cs | 4 + Game.Client/GarrysMod/LuaPanel.cs | 4 + Game.Client/GarrysMod/LuaRender.cs | 4 + Game.Client/GarrysMod/LuaSurface.cs | 4 + Game.Client/GarrysMod/LuaVGUI.cs | 4 + Game.MenuSystem/Game.MenuSystem.csproj | 39 +++++++--- Game.MenuSystem/LuaHelper.cs | 82 --------------------- Game.MenuSystem/MenuSystem.cs | 4 +- Game.Shared/GarrysMod/LuaAngle.cs | 4 +- Game.Shared/GarrysMod/LuaClass.cs | 4 +- Game.Shared/GarrysMod/LuaConCommand.cs | 4 +- Game.Shared/GarrysMod/LuaConVar.cs | 4 +- Game.Shared/GarrysMod/LuaEngine.cs | 4 +- Game.Shared/GarrysMod/LuaEnums.cs | 4 +- Game.Shared/GarrysMod/LuaFileLibrary.cs | 4 +- Game.Shared/GarrysMod/LuaGlobalFunctions.cs | 4 +- Game.Shared/GarrysMod/LuaHelper.cs | 4 +- Game.Shared/GarrysMod/LuaLibrary.cs | 4 +- Game.Shared/GarrysMod/LuaMaterial.cs | 4 +- Game.Shared/GarrysMod/LuaObject.cs | 6 +- Game.Shared/GarrysMod/LuaSql.cs | 4 +- Game.Shared/GarrysMod/LuaSystem.cs | 4 +- Game.Shared/GarrysMod/LuaTexture.cs | 4 +- Game.Shared/GarrysMod/LuaTimer.cs | 4 +- Game.Shared/GarrysMod/LuaUser.cs | 4 +- Game.Shared/GarrysMod/LuaUtil.cs | 4 +- Game.Shared/GarrysMod/LuaVector.cs | 4 +- 32 files changed, 130 insertions(+), 113 deletions(-) delete mode 100644 Game.MenuSystem/LuaHelper.cs diff --git a/Game.Client/GarrysMod/HtmlPanel.cs b/Game.Client/GarrysMod/HtmlPanel.cs index 8099282ba..5d8006143 100644 --- a/Game.Client/GarrysMod/HtmlPanel.cs +++ b/Game.Client/GarrysMod/HtmlPanel.cs @@ -9,7 +9,11 @@ using static Source.Common.GarrysMod.Lua.PooledStrings; +#if MENU_DLL +namespace Game.MenuSystem.GarrysMod; +#else namespace Game.Client.GarrysMod; +#endif public class HtmlPanel : EditablePanel, IHtmlClientListener { diff --git a/Game.Client/GarrysMod/LuaAchievements.cs b/Game.Client/GarrysMod/LuaAchievements.cs index 8616dd0d3..6d8e954bb 100644 --- a/Game.Client/GarrysMod/LuaAchievements.cs +++ b/Game.Client/GarrysMod/LuaAchievements.cs @@ -5,7 +5,11 @@ using Steamworks; +#if MENU_DLL +namespace Game.MenuSystem.GarrysMod; +#else namespace Game.Client.GarrysMod; +#endif public static partial class LuaAchievements { diff --git a/Game.Client/GarrysMod/LuaFonts.cs b/Game.Client/GarrysMod/LuaFonts.cs index eba9dee53..e4440cc68 100644 --- a/Game.Client/GarrysMod/LuaFonts.cs +++ b/Game.Client/GarrysMod/LuaFonts.cs @@ -1,7 +1,11 @@ using Source.Common.GUI; using Source.GUI.Controls; +#if MENU_DLL +namespace Game.MenuSystem.GarrysMod; +#else namespace Game.Client.GarrysMod; +#endif public struct LuaFont { diff --git a/Game.Client/GarrysMod/LuaGui.cs b/Game.Client/GarrysMod/LuaGui.cs index 01ea544be..013e875a2 100644 --- a/Game.Client/GarrysMod/LuaGui.cs +++ b/Game.Client/GarrysMod/LuaGui.cs @@ -2,7 +2,11 @@ using System.Numerics; +#if MENU_DLL +namespace Game.MenuSystem.GarrysMod; +#else namespace Game.Client.GarrysMod; +#endif public static partial class LuaGui { diff --git a/Game.Client/GarrysMod/LuaInput.cs b/Game.Client/GarrysMod/LuaInput.cs index 320fe501f..af02268b7 100644 --- a/Game.Client/GarrysMod/LuaInput.cs +++ b/Game.Client/GarrysMod/LuaInput.cs @@ -1,7 +1,11 @@ using Source.Common.GarrysMod.Lua; using Source.Common.Input; +#if MENU_DLL +namespace Game.MenuSystem.GarrysMod; +#else namespace Game.Client.GarrysMod; +#endif public static partial class LuaInput { diff --git a/Game.Client/GarrysMod/LuaLanguage.cs b/Game.Client/GarrysMod/LuaLanguage.cs index 958b449e1..f23c50ea2 100644 --- a/Game.Client/GarrysMod/LuaLanguage.cs +++ b/Game.Client/GarrysMod/LuaLanguage.cs @@ -4,7 +4,11 @@ using System.Runtime.CompilerServices; +#if MENU_DLL +namespace Game.MenuSystem.GarrysMod; +#else namespace Game.Client.GarrysMod; +#endif public static partial class LuaLanguage { diff --git a/Game.Client/GarrysMod/LuaPanel.cs b/Game.Client/GarrysMod/LuaPanel.cs index 7762f1b50..be61e578f 100644 --- a/Game.Client/GarrysMod/LuaPanel.cs +++ b/Game.Client/GarrysMod/LuaPanel.cs @@ -4,7 +4,11 @@ using Source.Common.MaterialSystem; using Source.GUI.Controls; +#if MENU_DLL +namespace Game.MenuSystem.GarrysMod; +#else namespace Game.Client.GarrysMod; +#endif public static partial class LuaVGUI { diff --git a/Game.Client/GarrysMod/LuaRender.cs b/Game.Client/GarrysMod/LuaRender.cs index ba9217012..2e9bd5bd8 100644 --- a/Game.Client/GarrysMod/LuaRender.cs +++ b/Game.Client/GarrysMod/LuaRender.cs @@ -11,7 +11,11 @@ using System.Numerics; +#if MENU_DLL +namespace Game.MenuSystem.GarrysMod; +#else namespace Game.Client.GarrysMod; +#endif public static partial class LuaRender { diff --git a/Game.Client/GarrysMod/LuaSurface.cs b/Game.Client/GarrysMod/LuaSurface.cs index 1bc436b0c..2bea0a819 100644 --- a/Game.Client/GarrysMod/LuaSurface.cs +++ b/Game.Client/GarrysMod/LuaSurface.cs @@ -8,7 +8,11 @@ using System.Runtime.CompilerServices; +#if MENU_DLL +namespace Game.MenuSystem.GarrysMod; +#else namespace Game.Client.GarrysMod; +#endif public static partial class LuaSurface { diff --git a/Game.Client/GarrysMod/LuaVGUI.cs b/Game.Client/GarrysMod/LuaVGUI.cs index f263e4b63..4340e32c9 100644 --- a/Game.Client/GarrysMod/LuaVGUI.cs +++ b/Game.Client/GarrysMod/LuaVGUI.cs @@ -2,7 +2,11 @@ using Source.Common.GUI; using Source.GUI.Controls; +#if MENU_DLL +namespace Game.MenuSystem.GarrysMod; +#else namespace Game.Client.GarrysMod; +#endif public static partial class LuaVGUI { diff --git a/Game.MenuSystem/Game.MenuSystem.csproj b/Game.MenuSystem/Game.MenuSystem.csproj index 2824bdaef..c9802aad7 100644 --- a/Game.MenuSystem/Game.MenuSystem.csproj +++ b/Game.MenuSystem/Game.MenuSystem.csproj @@ -1,18 +1,37 @@ - + - - net10.0 - enable - enable - Debug;Release;Debug (Dedicated);Release (Dedicated) - + + net10.0 + enable + enable + True + Debug;Release;Debug (Dedicated);Release (Dedicated) + - - - + + + + + + + + + + + $(DefineConstants);MENU_DLL + + + + + + + + + + diff --git a/Game.MenuSystem/LuaHelper.cs b/Game.MenuSystem/LuaHelper.cs deleted file mode 100644 index 7f8ec5088..000000000 --- a/Game.MenuSystem/LuaHelper.cs +++ /dev/null @@ -1,82 +0,0 @@ -global using static Game.MenuSystem.LuaGlobals; - -using Source; -using Source.Common.GarrysMod.Lua; - -namespace Game.MenuSystem; - -public static class LuaGlobals -{ - public static ILuaInterface? g_Lua; -} - -public static class LuaHelper -{ - public static bool IsInErrorCB; - - static ILuaObject NewTable(ILuaInterface lua) { - ILuaObject table = lua.CreateObject(); - lua.PreCreateTable(0, 0); - table.SetReference(-1); - lua.Pop(1); - return table; - } - - public static void CallOnLuaErrorHook(in LuaError error, string? addonTitle, ulong workshopID) { - if (g_Lua == null || g_Lua.Global() == null) - return; - - if (IsInErrorCB) { - Warning($"Error during OnLuaError on {error.Side}!\n"); - return; - } - - ILuaObject hook = g_Lua.CreateObject(); - g_Lua.Global().GetMember("hook", hook); - if (!hook.isTable()) { - hook.UnReference(); - return; - } - - ILuaObject run = g_Lua.CreateObject(); - hook.GetMember("Run", run); - if (!run.isFunction()) { - run.UnReference(); - hook.UnReference(); - return; - } - - run.Push(); - g_Lua.PushString("OnLuaError"); - g_Lua.PushString(error.Message); - g_Lua.PushString(error.Side); - - ILuaObject stack = NewTable(g_Lua); - for (int i = 0; i < error.Stack.Count;) { - ILuaObject entry = NewTable(g_Lua); - entry.SetMember("File", error.Stack[i].Source); - entry.SetMember("Line", (float)error.Stack[i].Line); - entry.SetMember("Function", error.Stack[i].Function); - i++; - stack.SetMember((float)i, entry); - entry.UnReference(); - } - - stack.Push(); - IsInErrorCB = true; - - if (addonTitle != null) { - g_Lua.PushString(addonTitle); - g_Lua.PushString(workshopID.ToString()); - g_Lua.CallInternalNoReturns(6); - } - else - g_Lua.CallInternalNoReturns(4); - - IsInErrorCB = false; - - stack.UnReference(); - run.UnReference(); - hook.UnReference(); - } -} diff --git a/Game.MenuSystem/MenuSystem.cs b/Game.MenuSystem/MenuSystem.cs index edb4285ac..fd853b153 100644 --- a/Game.MenuSystem/MenuSystem.cs +++ b/Game.MenuSystem/MenuSystem.cs @@ -18,9 +18,9 @@ public bool IsServerBlacklisted(ReadOnlySpan address, ReadOnlySpan h public void OnLuaError(in LuaError err, IAddonSystem.Information? addonInfo) { if (addonInfo.HasValue) - LuaHelper.CallOnLuaErrorHook(in err, addonInfo.Value.Title ?? "", addonInfo.Value.WorkshopID); + GarrysMod.LuaHelper.CallOnLuaErrorHook(in err, addonInfo.Value.Title ?? "", addonInfo.Value.WorkshopID); else - LuaHelper.CallOnLuaErrorHook(in err, null, 0); + GarrysMod.LuaHelper.CallOnLuaErrorHook(in err, null, 0); } public void SendProblemToMenu(ReadOnlySpan id, int severity, ReadOnlySpan parms) { diff --git a/Game.Shared/GarrysMod/LuaAngle.cs b/Game.Shared/GarrysMod/LuaAngle.cs index fedd10d23..723db6b4d 100644 --- a/Game.Shared/GarrysMod/LuaAngle.cs +++ b/Game.Shared/GarrysMod/LuaAngle.cs @@ -1,4 +1,4 @@ -#if CLIENT_DLL || GAME_DLL +#if CLIENT_DLL || GAME_DLL || MENU_DLL using Source.Common.GarrysMod.Lua; using Source.Common.Mathematics; @@ -8,6 +8,8 @@ #if CLIENT_DLL namespace Game.Client.GarrysMod; +#elif MENU_DLL +namespace Game.MenuSystem.GarrysMod; #else namespace Game.Server.GarrysMod; #endif diff --git a/Game.Shared/GarrysMod/LuaClass.cs b/Game.Shared/GarrysMod/LuaClass.cs index e21928d5d..251c741b7 100644 --- a/Game.Shared/GarrysMod/LuaClass.cs +++ b/Game.Shared/GarrysMod/LuaClass.cs @@ -1,8 +1,10 @@ -#if CLIENT_DLL || GAME_DLL +#if CLIENT_DLL || GAME_DLL || MENU_DLL using Source.Common.GarrysMod.Lua; #if CLIENT_DLL namespace Game.Client.GarrysMod; +#elif MENU_DLL +namespace Game.MenuSystem.GarrysMod; #else namespace Game.Server.GarrysMod; #endif diff --git a/Game.Shared/GarrysMod/LuaConCommand.cs b/Game.Shared/GarrysMod/LuaConCommand.cs index 8c6f3a289..97395bb14 100644 --- a/Game.Shared/GarrysMod/LuaConCommand.cs +++ b/Game.Shared/GarrysMod/LuaConCommand.cs @@ -1,10 +1,12 @@ -#if CLIENT_DLL || GAME_DLL +#if CLIENT_DLL || GAME_DLL || MENU_DLL using Source.Common.Commands; using Source.Common.GarrysMod.Lua; using Source.Common.Input; #if CLIENT_DLL namespace Game.Client.GarrysMod; +#elif MENU_DLL +namespace Game.MenuSystem.GarrysMod; #else namespace Game.Server.GarrysMod; #endif diff --git a/Game.Shared/GarrysMod/LuaConVar.cs b/Game.Shared/GarrysMod/LuaConVar.cs index 42dc1e0b7..3b901fbc9 100644 --- a/Game.Shared/GarrysMod/LuaConVar.cs +++ b/Game.Shared/GarrysMod/LuaConVar.cs @@ -1,9 +1,11 @@ -#if CLIENT_DLL || GAME_DLL +#if CLIENT_DLL || GAME_DLL || MENU_DLL using Source.Common.Commands; using Source.Common.GarrysMod.Lua; #if CLIENT_DLL namespace Game.Client.GarrysMod; +#elif MENU_DLL +namespace Game.MenuSystem.GarrysMod; #else namespace Game.Server.GarrysMod; #endif diff --git a/Game.Shared/GarrysMod/LuaEngine.cs b/Game.Shared/GarrysMod/LuaEngine.cs index 5cfffeed0..4ad11efde 100644 --- a/Game.Shared/GarrysMod/LuaEngine.cs +++ b/Game.Shared/GarrysMod/LuaEngine.cs @@ -1,9 +1,11 @@ -#if CLIENT_DLL || GAME_DLL +#if CLIENT_DLL || GAME_DLL || MENU_DLL using Source.Common.GarrysMod; using Source.Common.GarrysMod.Lua; #if CLIENT_DLL namespace Game.Client.GarrysMod; +#elif MENU_DLL +namespace Game.MenuSystem.GarrysMod; #else namespace Game.Server.GarrysMod; #endif diff --git a/Game.Shared/GarrysMod/LuaEnums.cs b/Game.Shared/GarrysMod/LuaEnums.cs index 99e89e73d..22ed797d1 100644 --- a/Game.Shared/GarrysMod/LuaEnums.cs +++ b/Game.Shared/GarrysMod/LuaEnums.cs @@ -1,4 +1,4 @@ -#if CLIENT_DLL || GAME_DLL +#if CLIENT_DLL || GAME_DLL || MENU_DLL using Game.Shared; using Source; @@ -24,6 +24,8 @@ #if CLIENT_DLL namespace Game.Client.GarrysMod; +#elif MENU_DLL +namespace Game.MenuSystem.GarrysMod; #else namespace Game.Server.GarrysMod; #endif diff --git a/Game.Shared/GarrysMod/LuaFileLibrary.cs b/Game.Shared/GarrysMod/LuaFileLibrary.cs index 29fa957df..97197cd8e 100644 --- a/Game.Shared/GarrysMod/LuaFileLibrary.cs +++ b/Game.Shared/GarrysMod/LuaFileLibrary.cs @@ -1,10 +1,12 @@ -#if CLIENT_DLL || GAME_DLL +#if CLIENT_DLL || GAME_DLL || MENU_DLL using Source.Common.Filesystem; using Source.Common.GarrysMod; using Source.Common.GarrysMod.Lua; #if CLIENT_DLL namespace Game.Client.GarrysMod; +#elif MENU_DLL +namespace Game.MenuSystem.GarrysMod; #else namespace Game.Server.GarrysMod; #endif diff --git a/Game.Shared/GarrysMod/LuaGlobalFunctions.cs b/Game.Shared/GarrysMod/LuaGlobalFunctions.cs index 9d66c8789..f602bd2ea 100644 --- a/Game.Shared/GarrysMod/LuaGlobalFunctions.cs +++ b/Game.Shared/GarrysMod/LuaGlobalFunctions.cs @@ -1,4 +1,4 @@ -#if CLIENT_DLL || GAME_DLL +#if CLIENT_DLL || GAME_DLL || MENU_DLL using Source; using Source.Common.Commands; using Source.Common.Mathematics; @@ -14,6 +14,8 @@ #if CLIENT_DLL namespace Game.Client.GarrysMod; +#elif MENU_DLL +namespace Game.MenuSystem.GarrysMod; #else namespace Game.Server.GarrysMod; #endif diff --git a/Game.Shared/GarrysMod/LuaHelper.cs b/Game.Shared/GarrysMod/LuaHelper.cs index dc4bf6881..cac63deaf 100644 --- a/Game.Shared/GarrysMod/LuaHelper.cs +++ b/Game.Shared/GarrysMod/LuaHelper.cs @@ -1,10 +1,12 @@ -#if CLIENT_DLL || GAME_DLL +#if CLIENT_DLL || GAME_DLL || MENU_DLL using Source; using Source.Common.Formats.Keyvalues; using Source.Common.GarrysMod.Lua; #if CLIENT_DLL namespace Game.Client.GarrysMod; +#elif MENU_DLL +namespace Game.MenuSystem.GarrysMod; #else namespace Game.Server.GarrysMod; #endif diff --git a/Game.Shared/GarrysMod/LuaLibrary.cs b/Game.Shared/GarrysMod/LuaLibrary.cs index a9d542272..0d7cd0bee 100644 --- a/Game.Shared/GarrysMod/LuaLibrary.cs +++ b/Game.Shared/GarrysMod/LuaLibrary.cs @@ -1,8 +1,10 @@ -#if CLIENT_DLL || GAME_DLL +#if CLIENT_DLL || GAME_DLL || MENU_DLL using Source.Common.GarrysMod.Lua; #if CLIENT_DLL namespace Game.Client.GarrysMod; +#elif MENU_DLL +namespace Game.MenuSystem.GarrysMod; #else namespace Game.Server.GarrysMod; #endif diff --git a/Game.Shared/GarrysMod/LuaMaterial.cs b/Game.Shared/GarrysMod/LuaMaterial.cs index 1cc851b1f..b30198077 100644 --- a/Game.Shared/GarrysMod/LuaMaterial.cs +++ b/Game.Shared/GarrysMod/LuaMaterial.cs @@ -1,4 +1,4 @@ -#if CLIENT_DLL || GAME_DLL +#if CLIENT_DLL || GAME_DLL || MENU_DLL using Source; using Source.Common.Formats.Keyvalues; using Source.Common.GarrysMod.Lua; @@ -10,6 +10,8 @@ #if CLIENT_DLL namespace Game.Client.GarrysMod; +#elif MENU_DLL +namespace Game.MenuSystem.GarrysMod; #else namespace Game.Server.GarrysMod; #endif diff --git a/Game.Shared/GarrysMod/LuaObject.cs b/Game.Shared/GarrysMod/LuaObject.cs index fcad9e334..0a9192321 100644 --- a/Game.Shared/GarrysMod/LuaObject.cs +++ b/Game.Shared/GarrysMod/LuaObject.cs @@ -1,6 +1,8 @@ -#if CLIENT_DLL || GAME_DLL +#if CLIENT_DLL || GAME_DLL || MENU_DLL #if CLIENT_DLL global using static Game.Client.GarrysMod.LuaGlobals; +#elif MENU_DLL +global using static Game.MenuSystem.GarrysMod.LuaGlobals; #else global using static Game.Server.GarrysMod.LuaGlobals; #endif @@ -17,6 +19,8 @@ #if CLIENT_DLL namespace Game.Client.GarrysMod; +#elif MENU_DLL +namespace Game.MenuSystem.GarrysMod; #else namespace Game.Server.GarrysMod; #endif diff --git a/Game.Shared/GarrysMod/LuaSql.cs b/Game.Shared/GarrysMod/LuaSql.cs index 48ca64a0d..ae3483345 100644 --- a/Game.Shared/GarrysMod/LuaSql.cs +++ b/Game.Shared/GarrysMod/LuaSql.cs @@ -1,10 +1,12 @@ -#if CLIENT_DLL || GAME_DLL +#if CLIENT_DLL || GAME_DLL || MENU_DLL using Source.Common.GarrysMod.Lua; using SQLitePCL; #if CLIENT_DLL namespace Game.Client.GarrysMod; +#elif MENU_DLL +namespace Game.MenuSystem.GarrysMod; #else namespace Game.Server.GarrysMod; #endif diff --git a/Game.Shared/GarrysMod/LuaSystem.cs b/Game.Shared/GarrysMod/LuaSystem.cs index 76a5e62e4..5aaccc5f3 100644 --- a/Game.Shared/GarrysMod/LuaSystem.cs +++ b/Game.Shared/GarrysMod/LuaSystem.cs @@ -1,8 +1,10 @@ -#if CLIENT_DLL || GAME_DLL +#if CLIENT_DLL || GAME_DLL || MENU_DLL using Source.Common.GarrysMod.Lua; #if CLIENT_DLL namespace Game.Client.GarrysMod; +#elif MENU_DLL +namespace Game.MenuSystem.GarrysMod; #else namespace Game.Server.GarrysMod; #endif diff --git a/Game.Shared/GarrysMod/LuaTexture.cs b/Game.Shared/GarrysMod/LuaTexture.cs index eca1e392b..dc30944d9 100644 --- a/Game.Shared/GarrysMod/LuaTexture.cs +++ b/Game.Shared/GarrysMod/LuaTexture.cs @@ -1,9 +1,11 @@ -#if CLIENT_DLL || GAME_DLL +#if CLIENT_DLL || GAME_DLL || MENU_DLL using Source.Common.GarrysMod.Lua; using Source.Common.MaterialSystem; #if CLIENT_DLL namespace Game.Client.GarrysMod; +#elif MENU_DLL +namespace Game.MenuSystem.GarrysMod; #else namespace Game.Server.GarrysMod; #endif diff --git a/Game.Shared/GarrysMod/LuaTimer.cs b/Game.Shared/GarrysMod/LuaTimer.cs index be8c15ab2..3338cc939 100644 --- a/Game.Shared/GarrysMod/LuaTimer.cs +++ b/Game.Shared/GarrysMod/LuaTimer.cs @@ -1,10 +1,12 @@ -#if CLIENT_DLL || GAME_DLL +#if CLIENT_DLL || GAME_DLL || MENU_DLL using Source; using Source.Common.Commands; using Source.Common.GarrysMod.Lua; #if CLIENT_DLL namespace Game.Client.GarrysMod; +#elif MENU_DLL +namespace Game.MenuSystem.GarrysMod; #else namespace Game.Server.GarrysMod; #endif diff --git a/Game.Shared/GarrysMod/LuaUser.cs b/Game.Shared/GarrysMod/LuaUser.cs index cb46cd229..2dacf8753 100644 --- a/Game.Shared/GarrysMod/LuaUser.cs +++ b/Game.Shared/GarrysMod/LuaUser.cs @@ -1,9 +1,11 @@ -#if CLIENT_DLL || GAME_DLL +#if CLIENT_DLL || GAME_DLL || MENU_DLL using Source.Common.GarrysMod; using Source.Common.GarrysMod.Lua; #if CLIENT_DLL namespace Game.Client.GarrysMod; +#elif MENU_DLL +namespace Game.MenuSystem.GarrysMod; #else namespace Game.Server.GarrysMod; #endif diff --git a/Game.Shared/GarrysMod/LuaUtil.cs b/Game.Shared/GarrysMod/LuaUtil.cs index 0a3fdb98d..0f10491b2 100644 --- a/Game.Shared/GarrysMod/LuaUtil.cs +++ b/Game.Shared/GarrysMod/LuaUtil.cs @@ -1,5 +1,5 @@ using Source; -#if CLIENT_DLL || GAME_DLL +#if CLIENT_DLL || GAME_DLL || MENU_DLL using Game.Shared; using Source.Common; @@ -20,6 +20,8 @@ #if CLIENT_DLL namespace Game.Client.GarrysMod; +#elif MENU_DLL +namespace Game.MenuSystem.GarrysMod; #else namespace Game.Server.GarrysMod; #endif diff --git a/Game.Shared/GarrysMod/LuaVector.cs b/Game.Shared/GarrysMod/LuaVector.cs index 2c918e80b..2b0568585 100644 --- a/Game.Shared/GarrysMod/LuaVector.cs +++ b/Game.Shared/GarrysMod/LuaVector.cs @@ -1,4 +1,4 @@ -#if CLIENT_DLL || GAME_DLL +#if CLIENT_DLL || GAME_DLL || MENU_DLL using Source.Common.GarrysMod.Lua; using Source.Common.Mathematics; @@ -8,6 +8,8 @@ #if CLIENT_DLL namespace Game.Client.GarrysMod; +#elif MENU_DLL +namespace Game.MenuSystem.GarrysMod; #else namespace Game.Server.GarrysMod; #endif From 9db5143e25454b95afb08e81df2e4e893249c313 Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Wed, 14 Oct 2026 15:22:19 -0700 Subject: [PATCH 09/38] Finish making necessary bindings menu-client shared --- Game.Client/GarrysMod/LuaAchievements.cs | 8 ++++ Game.Client/GarrysMod/LuaGui.cs | 2 + Game.Client/GarrysMod/LuaInput.cs | 2 + Game.Client/GarrysMod/LuaPanel.cs | 6 +++ Game.Client/GarrysMod/LuaRender.cs | 28 +++++++++++++ Game.Client/GarrysMod/LuaSurface.cs | 4 ++ Game.MenuSystem/SourceDllMain.cs | 44 +++++++++++++++++++++ Game.Shared/GarrysMod/LuaConCommand.cs | 2 + Game.Shared/GarrysMod/LuaEnums.cs | 14 ++++++- Game.Shared/GarrysMod/LuaFileLibrary.cs | 2 + Game.Shared/GarrysMod/LuaGlobalFunctions.cs | 16 ++++++++ Game.Shared/GarrysMod/LuaMaterial.cs | 6 +++ Game.Shared/GarrysMod/LuaUtil.cs | 10 +++++ 13 files changed, 143 insertions(+), 1 deletion(-) create mode 100644 Game.MenuSystem/SourceDllMain.cs diff --git a/Game.Client/GarrysMod/LuaAchievements.cs b/Game.Client/GarrysMod/LuaAchievements.cs index 6d8e954bb..8d52f5813 100644 --- a/Game.Client/GarrysMod/LuaAchievements.cs +++ b/Game.Client/GarrysMod/LuaAchievements.cs @@ -1,4 +1,6 @@ +#if !MENU_DLL using Game.Shared; +#endif using Source.Common; using Source.Common.GarrysMod.Lua; @@ -16,7 +18,9 @@ public static partial class LuaAchievements [LuaLibrary] static readonly LuaLibrary LL_Factory_achievements = new("achievements"); +#if !MENU_DLL static bool UnsetIncrementFlag; +#endif static IAchievement? GetAchievement(int index) { IAchievementMgr? mgr = engine.GetAchievementMgr(); @@ -25,10 +29,12 @@ public static partial class LuaAchievements return mgr.GetAchievementByIndex(index); } +#if !MENU_DLL static void IncrementAchievement(GMODAchievementID id) { if (engine.GetAchievementMgr()!.GetAchievementByID((int)id) is BaseAchievement achievement) achievement.IncrementCount(0); } +#endif [LuaFunction] static int Count(ILuaInterface lua) { @@ -89,6 +95,7 @@ static int IsAchieved(ILuaInterface lua) { return 1; } +#if !MENU_DLL static int IncrementFromNetMessage(GMODAchievementID id) { if (UnsetIncrementFlag || GarrysMod.RunningNetMessage) { IncrementAchievement(id); @@ -122,4 +129,5 @@ static int SpawnMenuOpen(ILuaInterface lua) { [LuaFunction] static int BalloonPopped(ILuaInterface lua) => IncrementFromLuaCmd(GMODAchievementID.GMA_BALLOONPOPPER); [LuaFunction] static int Remover(ILuaInterface lua) => IncrementFromLuaCmd(GMODAchievementID.GMA_REMOVER); +#endif } diff --git a/Game.Client/GarrysMod/LuaGui.cs b/Game.Client/GarrysMod/LuaGui.cs index 013e875a2..b656810e7 100644 --- a/Game.Client/GarrysMod/LuaGui.cs +++ b/Game.Client/GarrysMod/LuaGui.cs @@ -13,6 +13,7 @@ public static partial class LuaGui [LuaLibrary] static readonly LuaLibrary LL_Factory_gui = new("gui"); +#if !MENU_DLL [LuaFunction] static int EnableScreenClicker(ILuaInterface lua) { if (!g_Lua!.GetBool(1)) { @@ -28,6 +29,7 @@ static int EnableScreenClicker(ILuaInterface lua) { GModBase.GetMouseInput()!.SetMouseInputEnabled(false); return 0; } +#endif public static Vector3 ScreenToVector(int x, int y) { float halfWide = ScreenWidth() * 0.5f; diff --git a/Game.Client/GarrysMod/LuaInput.cs b/Game.Client/GarrysMod/LuaInput.cs index af02268b7..3075c379e 100644 --- a/Game.Client/GarrysMod/LuaInput.cs +++ b/Game.Client/GarrysMod/LuaInput.cs @@ -223,6 +223,7 @@ static int LookupKeyBinding(ILuaInterface lua) { return 1; } +#if !MENU_DLL [LuaFunction] static int TranslateAlias(ILuaInterface lua) { ReadOnlySpan alias = engine.GMOD_TranslateAlias(lua.CheckString(1)); @@ -245,4 +246,5 @@ static int SelectWeapon(ILuaInterface lua) { SelectWeapon(LuaEntity.Get_Entity(1, false)); return 0; } +#endif } diff --git a/Game.Client/GarrysMod/LuaPanel.cs b/Game.Client/GarrysMod/LuaPanel.cs index be61e578f..68ae8e83c 100644 --- a/Game.Client/GarrysMod/LuaPanel.cs +++ b/Game.Client/GarrysMod/LuaPanel.cs @@ -184,6 +184,7 @@ static void Panel__SetParent(ILuaInterface lua, Panel panel) { panel.SetParent(parent); } +#if !MENU_DLL [LuaMethod] static int Panel__ParentToHUD(ILuaInterface lua) { Panel? panel = Get_Panel(1); @@ -193,6 +194,7 @@ static int Panel__ParentToHUD(ILuaInterface lua) { panel.SetParent(GModBase.GetGModParentToHUDPanel()); return 0; } +#endif [LuaMethod] static int Panel__IsValid(ILuaInterface lua) { @@ -591,6 +593,7 @@ static int Panel__SetWrap(ILuaInterface lua) { return 0; } +#if !MENU_DLL [LuaMethod] static int Panel__SetModel(ILuaInterface lua) { Panel? panel = (Panel?)PanelClass.Get(1); @@ -602,6 +605,7 @@ static int Panel__SetModel(ILuaInterface lua) { spawnIcon.SetModel(lua.CheckString(2), (int)lua.CheckNumberOpt(3, 0), lua.CheckStringOpt(4, "")); return 0; } +#endif [LuaMethod] static int Panel__SetAllowNonAsciiCharacters(ILuaInterface lua) { @@ -891,6 +895,7 @@ static int Panel__IsLoading(ILuaInterface lua) { return 1; } +#if !MENU_DLL [LuaMethod] static int Panel__UpdateHTMLTexture(ILuaInterface lua) { Panel? panel = (Panel?)PanelClass.Get(1); @@ -922,6 +927,7 @@ static int Panel__GetHTMLMaterial(ILuaInterface lua) { LuaMaterial.Push(material); return 1; } +#endif [LuaMethod] static int Panel__SetHTML(ILuaInterface lua) { diff --git a/Game.Client/GarrysMod/LuaRender.cs b/Game.Client/GarrysMod/LuaRender.cs index 2e9bd5bd8..21c709d64 100644 --- a/Game.Client/GarrysMod/LuaRender.cs +++ b/Game.Client/GarrysMod/LuaRender.cs @@ -82,6 +82,7 @@ struct NamedRenderTarget return texture; } +#if !MENU_DLL [LuaGlobal] static int GetRenderTarget(ILuaInterface lua) { ITexture? texture = CreateNamedRenderTarget(lua.CheckString(1), (int)lua.CheckNumber(2), (int)lua.CheckNumber(3), RenderTargetSizeMode.NoChange, MaterialRenderTargetDepth.Separate, TextureFlags.Trilinear | TextureFlags.NoMip, 0, true, ImageFormat.Unknown); @@ -119,6 +120,7 @@ static int GetRenderTargetEx(ILuaInterface lua) { } return 0; } +#endif // todo: DrawSprite // todo: DrawQuadEasy @@ -132,12 +134,14 @@ static int GetRenderTargetEx(ILuaInterface lua) { // todo: SetMaterial // todo: SetLightmapTexture // todo: GetLightColor +#if !MENU_DLL [LuaFunction] static int GetAmbientLightColor(ILuaInterface lua) { engine.GetAmbientLightColor(out Vector3 color); LuaVector.Push_Vector(color); return 1; } +#endif // todo: ComputeDynamicLighting // todo: ComputeLighting // todo: GetSurfaceColor @@ -171,6 +175,7 @@ static int GetAmbientLightColor(ILuaInterface lua) { // todo: BindLocalCubemap static readonly Vector3[] SuppressedAmbientLight = [new(1, 1, 1), new(1, 1, 1), new(1, 1, 1), new(1, 1, 1), new(1, 1, 1), new(1, 1, 1)]; +#if !MENU_DLL [LuaFunction] static int SuppressEngineLighting(ILuaInterface lua) { bool suppress = lua.GetBool(1); @@ -190,10 +195,12 @@ static int UpdateScreenEffectTexture(ILuaInterface lua) { ViewScene.UpdateScreenEffectTexture(textureIndex, 0, 0, ScreenWidth(), ScreenHeight(), false); return 0; } +#endif // todo: UpdateRefractTexture // todo: GetRefractTexture // todo: UpdatePowerOfTwoTexture // todo: GetPowerOfTwoTexture +#if !MENU_DLL [LuaFunction("GetRenderTarget")] static int GetCurrentRenderTarget(ILuaInterface lua) { using MatRenderContextPtr renderContext = new(materials); @@ -230,8 +237,10 @@ static int SetRenderTargetEx(ILuaInterface lua) { renderContext.SetRenderTargetEx(id, texture); return 0; } +#endif static int RenderTargetStack; +#if !MENU_DLL [LuaFunction] static int PushRenderTarget(ILuaInterface lua) { ITexture? texture = null; @@ -298,10 +307,12 @@ static int GetMoBlurTex1(ILuaInterface lua) { LuaTexture.Push(RenderTexture.GetMoBlurTex1()); return 1; } +#endif // todo: GetMorphTex0 // todo: GetMorphTex1 // todo: GetSmallTex0 // todo: GetSmallTex1 +#if !MENU_DLL [LuaFunction] static int GetSuperFPTex(ILuaInterface lua) { LuaTexture.Push(RenderTexture.GetSuperFPTex(null)); @@ -313,11 +324,13 @@ static int GetSuperFPTex2(ILuaInterface lua) { LuaTexture.Push(RenderTexture.GetSuperFPTex2(null)); return 1; } +#endif // todo: SuppressEngineLighting // todo: SetLocalModelLights // todo: ResetModelLighting // todo: SetModelLighting // todo: SetAmbientLight +#if !MENU_DLL [LuaFunction] static int SetLightingOrigin(ILuaInterface lua) { ref Vector3 origin = ref LuaVector.Get_Vector(1); @@ -330,6 +343,7 @@ static void SetColorModulation([LuaGet] float r, [LuaGet] float g, [LuaGet] floa ReadOnlySpan color = [r, g, b]; render.SetColorModulation(color); } +#endif [LuaFunction] static (float, float, float) GetColorModulation() { @@ -337,6 +351,7 @@ static void SetColorModulation([LuaGet] float r, [LuaGet] float g, [LuaGet] floa return (color.X, color.Y, color.Z); } +#if !MENU_DLL [LuaFunction] static void SetBlend([LuaGet] float blend) => render.SetBlend(blend); @@ -539,6 +554,7 @@ static int RenderHUD(ILuaInterface lua) { LuaCam.SetInSurface3D(false); return 0; } +#endif [LuaFunction] static int SetViewPort(ILuaInterface lua) { @@ -691,6 +707,7 @@ static int PerformFullScreenStencilOperation(ILuaInterface lua) { return 0; } +#if !MENU_DLL [LuaFunction] static int FogMode(ILuaInterface lua) { double mode = lua.CheckNumber(1); @@ -759,6 +776,7 @@ static int GetFogDistances(ILuaInterface lua) { lua.PushNumber(fogZ); return 3; } +#endif // todo: GetFogMaxDensity // todo: FogMaxDensity @@ -775,6 +793,7 @@ static int CullMode(ILuaInterface lua) { return 0; } +#if !MENU_DLL [LuaFunction] static int ResetToneMappingScale(ILuaInterface lua) { double scale = lua.CheckNumber(1); @@ -812,6 +831,7 @@ static int GetToneMappingScaleLinear(ILuaInterface lua) { LuaVector.Push_Vector(renderContext.GetToneMappingScaleLinear()); return 1; } +#endif // todo: CapturePixels // todo: ReadPixel @@ -846,6 +866,7 @@ static int OverrideColorWriteEnable(ILuaInterface lua) { // todo: OverrideBlend // todo: OverrideBlendFunc +#if !MENU_DLL [LuaFunction] static int DepthRange(ILuaInterface lua) { double zNear = lua.CheckNumber(1); @@ -854,6 +875,7 @@ static int DepthRange(ILuaInterface lua) { renderContext.DepthRange((float)zNear, (float)zFar); return 0; } +#endif // todo: MaterialOverride // todo: MaterialOverrideByIndex // todo: DrawSphere @@ -870,6 +892,7 @@ static int DepthRange(ILuaInterface lua) { // todo: WorldMaterialOverride // todo: BrushMaterialOverride // todo: ModelMaterialOverride +#if !MENU_DLL [LuaFunction] static int SetLightingMode(ILuaInterface lua) { int mode = (int)lua.CheckNumber(1); @@ -881,6 +904,7 @@ static int SetLightingMode(ILuaInterface lua) { renderContext.SetIntRenderingParameter(0, mode); return 0; } +#endif // todo: Capture static readonly List FilterMinStack = [0]; static readonly List FilterMagStack = [0]; @@ -955,6 +979,7 @@ static int PopFilterMin(ILuaInterface lua) { return 0; } // todo: RedownloadAllLightmaps +#if !MENU_DLL [LuaFunction] static int SetWriteDepthToDestAlpha(ILuaInterface lua) { bool enable = lua.GetBool(1); @@ -962,7 +987,9 @@ static int SetWriteDepthToDestAlpha(ILuaInterface lua) { renderContext.SetIntRenderingParameter(10, enable ? 1 : 0); return 0; } +#endif // todo: RenderFlashlights +#if !MENU_DLL [LuaFunction] static int ComputePixelDiameterOfSphere(ILuaInterface lua) { ref Vector3 origin = ref LuaVector.Get_Vector(1); @@ -977,4 +1004,5 @@ static int IsTakingScreenshot(ILuaInterface lua) { lua.PushBool(engine.IsTakingScreenshot()); return 1; } +#endif } diff --git a/Game.Client/GarrysMod/LuaSurface.cs b/Game.Client/GarrysMod/LuaSurface.cs index 2bea0a819..b46deb5eb 100644 --- a/Game.Client/GarrysMod/LuaSurface.cs +++ b/Game.Client/GarrysMod/LuaSurface.cs @@ -1,4 +1,6 @@ +#if !MENU_DLL using Game.Client.HUD; +#endif using Source; using Source.Common.GarrysMod.Lua; @@ -291,6 +293,7 @@ static void SetMaterial(IMaterial material) { return (wide, tall); } +#if !MENU_DLL [LuaFunction] static int GetHUDTexture(ILuaInterface lua) { HudTexture? icon = gHUD.GetIcon(lua.CheckString(1)); @@ -299,6 +302,7 @@ static int GetHUDTexture(ILuaInterface lua) { lua.PushNumber((int)icon.TextureID); return 1; } +#endif [LuaFunction] static int DrawTexturedRect(ILuaInterface lua) { diff --git a/Game.MenuSystem/SourceDllMain.cs b/Game.MenuSystem/SourceDllMain.cs new file mode 100644 index 000000000..8d52ae1c2 --- /dev/null +++ b/Game.MenuSystem/SourceDllMain.cs @@ -0,0 +1,44 @@ +global using static Game.MenuSystem.SourceDllMain; + +using Source; +using Source.Common; +using Source.Common.Client; +using Source.Common.Commands; +using Source.Common.Engine; +using Source.Common.Filesystem; +using Source.Common.GameUI; +using Source.Common.GarrysMod; +using Source.Common.GUI; +using Source.Common.Input; +using Source.Common.Launcher; +using Source.Common.MaterialSystem; +using Source.Engine; + +namespace Game.MenuSystem; + +public static class SourceDllMain +{ + public static GlobalVarsBase gpGlobals = null!; + public static IGet get = null!; + public static IGarrysMod garrysmod = null!; + public static INetworkStringTableContainer? networkstringtable; + + [Dependency] public static IEngineClient engine { get; private set; } = null!; + [Dependency] public static IEngineVGui enginevgui { get; private set; } = null!; + [Dependency] public static IGameUIFuncs gameuifuncs { get; private set; } = null!; + [Dependency] public static IGameUI gameUI { get; private set; } = null!; + [Dependency] public static IMatSystemSurface surface { get; private set; } = null!; + [Dependency] public static ISurface Surface { get; private set; } = null!; + [Dependency] public static IVGui VGui { get; private set; } = null!; + [Dependency] public static IVGuiInput vguiInput { get; private set; } = null!; + [Dependency] public static IInputSystem inputsystem { get; private set; } = null!; + [Dependency] public static ISchemeManager SchemeManager { get; private set; } = null!; + [Dependency] public static ISchemeManager vguiSchemeManager { get; private set; } = null!; + [Dependency] public static ILocalize localize { get; private set; } = null!; + [Dependency] public static ILocalize Localize { get; private set; } = null!; + [Dependency] public static ICvar cvar { get; private set; } = null!; + [Dependency] public static IFileSystem filesystem { get; private set; } = null!; + [Dependency] public static IMaterialSystem materials { get; private set; } = null!; + [Dependency] public static ICommandLine commandLine { get; private set; } = null!; + [Dependency] public static ISystem system { get; private set; } = null!; +} diff --git a/Game.Shared/GarrysMod/LuaConCommand.cs b/Game.Shared/GarrysMod/LuaConCommand.cs index 97395bb14..3c57281b1 100644 --- a/Game.Shared/GarrysMod/LuaConCommand.cs +++ b/Game.Shared/GarrysMod/LuaConCommand.cs @@ -556,6 +556,7 @@ static int AddConsoleCommand(ILuaInterface lua) { return 0; } +#if !MENU_DLL [LuaGlobal] static int AddCSLuaFile(ILuaInterface lua) { #if GAME_DLL @@ -578,5 +579,6 @@ static int AddCSLuaFile(ILuaInterface lua) { #endif return 0; } +#endif } #endif diff --git a/Game.Shared/GarrysMod/LuaEnums.cs b/Game.Shared/GarrysMod/LuaEnums.cs index 22ed797d1..adba4d759 100644 --- a/Game.Shared/GarrysMod/LuaEnums.cs +++ b/Game.Shared/GarrysMod/LuaEnums.cs @@ -1,5 +1,7 @@ #if CLIENT_DLL || GAME_DLL || MENU_DLL +#if !MENU_DLL using Game.Shared; +#endif using Source; using Source.Common; @@ -33,7 +35,9 @@ namespace Game.Server.GarrysMod; public static class LuaEnumsGlobals { public static readonly LuaEnums LuaEnums = new(); +#if !MENU_DLL public static readonly LuaGameEnums LuaGameEnums = new(); +#endif } public class LuaEnums : LuaUser @@ -307,6 +311,7 @@ public override void InitLibraries(ILuaInterface lua) { global.SetMemberEnumValue($"{EF}_PARENT_ANIMATES", EntityEffects.ParentAnimates); global.SetMemberEnumValue($"{EF}_FOLLOWBONE", EntityEffects.FollowBone); +#if !MENU_DLL global.SetMemberEnumValue(nameof(Activity.ACT_INVALID), Activity.ACT_INVALID); global.SetMemberEnumValue(nameof(Activity.ACT_RESET), Activity.ACT_RESET); global.SetMemberEnumValue(nameof(Activity.ACT_IDLE), Activity.ACT_IDLE); @@ -1906,6 +1911,7 @@ public override void InitLibraries(ILuaInterface lua) { global.SetMemberEnumValue(nameof(Activity.ACT_GMOD_SHOWOFF_STAND_04), Activity.ACT_GMOD_SHOWOFF_STAND_04); global.SetMemberEnumValue(nameof(Activity.ACT_GMOD_SHOWOFF_DUCK_01), Activity.ACT_GMOD_SHOWOFF_DUCK_01); global.SetMemberEnumValue(nameof(Activity.ACT_GMOD_SHOWOFF_DUCK_02), Activity.ACT_GMOD_SHOWOFF_DUCK_02); +#endif global.SetMemberEnumValue($"{BLEND}_ZERO", ShaderBlendFactor.Zero); global.SetMemberEnumValue($"{BLEND}_ONE", ShaderBlendFactor.One); @@ -1944,7 +1950,7 @@ public override void InitLibraries(ILuaInterface lua) { table.SetMemberDouble("ANISOTROPIC", 3.0); global.SetMember("TEXFILTER", table); lua.DestroyObject(table); -#if CLIENT_DLL +#if CLIENT_DLL || MENU_DLL // TODO: Enum this!! global.SetMemberDouble("NODOCK", 0.0); global.SetMemberDouble("LEFT", 2.0); @@ -1953,7 +1959,11 @@ public override void InitLibraries(ILuaInterface lua) { global.SetMemberDouble("RIGHT", 3.0); global.SetMemberDouble("FILL", 1.0); +#if MENU_DLL + global.SetMember("MENU_DLL", true); +#else global.SetMember("CLIENT_DLL", true); +#endif #else global.SetMember("GAME_DLL", true); #endif @@ -1961,6 +1971,7 @@ public override void InitLibraries(ILuaInterface lua) { } // TODO: Clean this up, in the same way we cleaned up the above. +#if !MENU_DLL public class LuaGameEnums : LuaUser { public LuaGameEnums() => SetUsingLua(true); @@ -3058,3 +3069,4 @@ public override void InitLibraries(ILuaInterface lua) { } } #endif +#endif diff --git a/Game.Shared/GarrysMod/LuaFileLibrary.cs b/Game.Shared/GarrysMod/LuaFileLibrary.cs index 97197cd8e..4398126a4 100644 --- a/Game.Shared/GarrysMod/LuaFileLibrary.cs +++ b/Game.Shared/GarrysMod/LuaFileLibrary.cs @@ -764,6 +764,7 @@ static int Open(ILuaInterface lua) { return 1; } +#if !MENU_DLL [LuaFunction] static int AsyncRead(ILuaInterface lua) { string fileName = lua.CheckString(1); @@ -808,6 +809,7 @@ static int AsyncRead(ILuaInterface lua) { lua.PushNumber((double)filesystem.AsyncRead(request)); return 1; } +#endif [LuaFunction] static int Find(ILuaInterface lua) { diff --git a/Game.Shared/GarrysMod/LuaGlobalFunctions.cs b/Game.Shared/GarrysMod/LuaGlobalFunctions.cs index f602bd2ea..b30160380 100644 --- a/Game.Shared/GarrysMod/LuaGlobalFunctions.cs +++ b/Game.Shared/GarrysMod/LuaGlobalFunctions.cs @@ -103,6 +103,7 @@ public static void RGBtoHSV(int r, int g, int b, out float h, out float s, out f v = maxInt / 255.0f; } +#if !MENU_DLL [LuaGlobal] static int LocalToWorld(ILuaInterface lua) { Vector3 localPos = LuaVector.Get_Vector(1); @@ -118,6 +119,7 @@ static int LocalToWorld(ILuaInterface lua) { LuaAngle.Push_Angle(worldAng); return 2; } +#endif [LuaGlobal] static int HSVToColor(ILuaInterface lua) { @@ -158,6 +160,7 @@ static int include(ILuaInterface lua) { return g_Lua.Top() - top; } +#if !MENU_DLL [LuaGlobal] static int CompileString(ILuaInterface lua) { string code = g_Lua!.CheckString(1); @@ -206,6 +209,7 @@ static int DeriveGamemode(ILuaInterface lua) { gGM!.DeriveGamemode(name); return 0; } +#endif [LuaGlobal] static void require(string name) { @@ -218,6 +222,7 @@ static void require(string name) { static ConVar? hostnameCvar; #endif +#if !MENU_DLL [LuaGlobal] static int GetHostName(ILuaInterface lua) { #if CLIENT_DLL @@ -231,13 +236,16 @@ static int GetHostName(ILuaInterface lua) { return 1; #endif } +#endif #if CLIENT_DLL +#if !MENU_DLL [LuaGlobal] static int LocalPlayer(ILuaInterface lua) { LuaEntity.Push_Entity(C_BasePlayer.GetLocalPlayer()); return 1; } +#endif #endif static string ToStringArgs(LuaObject tostring, int top, string error) { @@ -369,11 +377,13 @@ static int FindMetaTable(ILuaInterface lua) { return 1; } +#if !MENU_DLL [LuaGlobal] static int TypeID(ILuaInterface lua) { g_Lua!.PushNumber((int)g_Lua.GetType(1)); return 1; } +#endif static int IsType(LuaType type) { g_Lua!.PushBool(g_Lua.IsType(1, type)); @@ -403,14 +413,18 @@ static double UnPredictedCurTime() { return gpGlobals.CurTime; } +#if !MENU_DLL [LuaGlobal] static float RealTime() => (float)gpGlobals.RealTime; +#endif [LuaGlobal] static float FrameTime() => (float)gpGlobals.FrameTime; +#if !MENU_DLL [LuaGlobal] static long FrameNumber() => gpGlobals.FrameCount; +#endif [LuaGlobal] static double SysTime() { @@ -510,6 +524,7 @@ static int RunConsoleCommand(ILuaInterface lua) { #if CLIENT_DLL static Vector3 EyePosition; +#if !MENU_DLL [LuaGlobal] static int EyePos(ILuaInterface lua) { if (IsCurrentViewAccessAllowed()) @@ -517,6 +532,7 @@ static int EyePos(ILuaInterface lua) { LuaVector.Push_Vector(EyePosition); return 1; } +#endif #endif public static void ReadStackFrom(ref LuaError error, ILuaInterface lua) { diff --git a/Game.Shared/GarrysMod/LuaMaterial.cs b/Game.Shared/GarrysMod/LuaMaterial.cs index b30198077..84c809849 100644 --- a/Game.Shared/GarrysMod/LuaMaterial.cs +++ b/Game.Shared/GarrysMod/LuaMaterial.cs @@ -177,6 +177,7 @@ static int IMaterial__SetTexture(ILuaInterface lua) { return 0; } +#if !MENU_DLL [LuaMethod] static int IMaterial__GetMatrix(ILuaInterface lua) { IMaterial? material = (IMaterial?)LC_IMaterial.Get(1); @@ -208,6 +209,7 @@ static int IMaterial__SetMatrix(ILuaInterface lua) { var.SetMatrixValue(LuaVMatrix.Get_VMatrix(3)); return 0; } +#endif [LuaMethod] static int IMaterial__GetInt(ILuaInterface lua) { @@ -418,6 +420,7 @@ static int IMaterial__Recompute(ILuaInterface lua) { return 0; } +#if !MENU_DLL [LuaMethod] static int IMaterial__GetKeyValues(ILuaInterface lua) { IMaterial? material = (IMaterial?)LC_IMaterial.Get(1); @@ -467,6 +470,7 @@ static int IMaterial__GetKeyValues(ILuaInterface lua) { } return 1; } +#endif static bool IsAllowedMaterialPath(ReadOnlySpan name) { Span buffer = stackalloc char[MAX_PATH]; @@ -579,6 +583,7 @@ public static void TableToKeyValues(ILuaObject? table, KeyValues kv, ILuaObject g_Lua.Pop(1); } +#if !MENU_DLL [LuaGlobal] static int CreateMaterial(ILuaInterface lua) { string name = lua.CheckString(1); @@ -626,5 +631,6 @@ static int CreateMaterial(ILuaInterface lua) { visited.UnReference(); return 1; } +#endif } #endif diff --git a/Game.Shared/GarrysMod/LuaUtil.cs b/Game.Shared/GarrysMod/LuaUtil.cs index 0f10491b2..32875b256 100644 --- a/Game.Shared/GarrysMod/LuaUtil.cs +++ b/Game.Shared/GarrysMod/LuaUtil.cs @@ -1,6 +1,8 @@ using Source; #if CLIENT_DLL || GAME_DLL || MENU_DLL +#if !MENU_DLL using Game.Shared; +#endif using Source.Common; using Source.Common.DataCache; @@ -31,6 +33,7 @@ public static partial class LuaUtil [LuaLibrary] static readonly LuaLibrary LL_Factory_util = new("util"); +#if !MENU_DLL public static bool UTIL_IsValidModel(ReadOnlySpan name) { if (name.IsEmpty || name[0] <= ' ' || name.Length <= 3) return false; @@ -98,6 +101,8 @@ public static bool UTIL_IsValidRagdollModel(ReadOnlySpan name) { return collide != null && collide.SolidCount > 1; } +#endif + [LuaFunction] static int AimVector(ILuaInterface lua) { QAngle angles = LuaAngle.Get_Angle(1); @@ -117,6 +122,7 @@ static int AimVector(ILuaInterface lua) { return 1; } +#if !MENU_DLL [LuaFunction] static int IntersectRayWithOBB(ILuaInterface lua) { Vector3 rayStart = LuaVector.Get_Vector(1); @@ -197,6 +203,8 @@ static int PrecacheSound(ILuaInterface lua) { [LuaFunction] static int NetworkStringToID(string name) => NetworkString.Get(name); +#endif + [LuaFunction] static int Base64Decode(ILuaInterface lua) { string str = lua.GetString(1) ?? ""; @@ -218,6 +226,7 @@ static int KeyValuesToTable(ILuaInterface lua) { return 1; } +#if !MENU_DLL #if GAME_DLL [LuaFunction] static int AddNetworkString(string name) => NetworkString.Add(name); @@ -382,5 +391,6 @@ static int TraceLine(ILuaInterface lua) { data.UnReference(); return 1; } +#endif } #endif From 58b4093157a8b8ffcdfecfe7024de0608adda5bb Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Wed, 14 Oct 2026 15:40:05 -0700 Subject: [PATCH 10/38] MenuSystem implementation --- Game.Client/GarrysMod/LuaFonts.cs | 4 + Game.Client/GarrysMod/LuaGui.cs | 2 + Game.Client/GarrysMod/LuaPanel.cs | 12 + Game.Client/GarrysMod/LuaRender.cs | 2 + Game.Client/GarrysMod/LuaSurface.cs | 6 + Game.Client/GarrysMod/LuaVGUI.cs | 18 ++ Game.Client/HLClient.cs | 5 +- Game.MenuSystem/AddonDownloadNotifications.cs | 140 ++++++++++++ Game.MenuSystem/LuaMenuCallback.cs | 44 ++++ Game.MenuSystem/MenuPanels.cs | 89 ++++++++ Game.MenuSystem/MenuSystem.cs | 205 ++++++++++++++++-- Game.Shared/GarrysMod/GarrysMod.cs | 11 +- Game.Shared/GarrysMod/LuaConCommand.cs | 8 +- Game.Shared/GarrysMod/LuaFileLibrary.cs | 4 + Game.Shared/GarrysMod/LuaGameCallback.cs | 78 +------ Game.Shared/GarrysMod/LuaGlobalFunctions.cs | 4 +- Game.Shared/GarrysMod/LuaHelper.cs | 77 +++++++ Game.Shared/GarrysMod/LuaObject.cs | 5 + Game.Shared/GarrysMod/LuaTimer.cs | 5 + Game.UI/BasePanel.cs | 34 +++ Game.UI/GameUI.cs | 8 +- Source.Common/GameUI/IGameUI.cs | 2 +- Source.Common/GarrysMod/IGarrysMod.cs | 1 + Source.Engine/Host.cs | 3 + 24 files changed, 656 insertions(+), 111 deletions(-) create mode 100644 Game.MenuSystem/AddonDownloadNotifications.cs create mode 100644 Game.MenuSystem/LuaMenuCallback.cs create mode 100644 Game.MenuSystem/MenuPanels.cs diff --git a/Game.Client/GarrysMod/LuaFonts.cs b/Game.Client/GarrysMod/LuaFonts.cs index e4440cc68..c6e13172c 100644 --- a/Game.Client/GarrysMod/LuaFonts.cs +++ b/Game.Client/GarrysMod/LuaFonts.cs @@ -46,7 +46,11 @@ public static void CreateFont(ReadOnlySpan name, ReadOnlySpan fontNa fontName = "Tahoma"; } +#if MENU_DLL + Panel basePanel = MenuPanels.GetMenuPanel()!; +#else Panel basePanel = GModBase.GetGModBasePanel(true)!; +#endif IFont? schemeFont = basePanel.GetScheme()!.GetFont(fontName); if (schemeFont != null && stricmp(Surface.GetFontName(schemeFont), fontName) != 0) { DevWarning($"Tried to create font '{name}' from a game font '{fontName}', not supported!\n"); diff --git a/Game.Client/GarrysMod/LuaGui.cs b/Game.Client/GarrysMod/LuaGui.cs index b656810e7..793f34ee2 100644 --- a/Game.Client/GarrysMod/LuaGui.cs +++ b/Game.Client/GarrysMod/LuaGui.cs @@ -31,6 +31,7 @@ static int EnableScreenClicker(ILuaInterface lua) { } #endif +#if !MENU_DLL public static Vector3 ScreenToVector(int x, int y) { float halfWide = ScreenWidth() * 0.5f; float dx = x - halfWide; @@ -40,6 +41,7 @@ public static Vector3 ScreenToVector(int x, int y) { Vector3 vec = ViewRender.g_VecVRight * dx + ViewRender.g_VecVForward * dz + ViewRender.g_VecVUp * dy; return Vector3.Normalize(vec); } +#endif [LuaFunction] static (int, int) MousePos() { diff --git a/Game.Client/GarrysMod/LuaPanel.cs b/Game.Client/GarrysMod/LuaPanel.cs index 68ae8e83c..994d8f547 100644 --- a/Game.Client/GarrysMod/LuaPanel.cs +++ b/Game.Client/GarrysMod/LuaPanel.cs @@ -172,11 +172,19 @@ static void Panel__SetParent(ILuaInterface lua, Panel panel) { if (!panel.LuaPanel || panel.IsMarkedForDeletion()) return; +#if MENU_DLL + Panel? parent = MenuPanels.GetMenuPanel(); +#else Panel? parent = GModBase.GetGModBasePanel(true); +#endif if (lua.GetType(2) == LuaType.Panel) parent = Get_Panel(2); +#if MENU_DLL + if (parent != null && parent != MenuPanels.GetMenuPanel() && parent != MenuPanels.GetOverlayPanel()) { +#else if (parent != null && parent != GModBase.GetGModBasePanel(true) && parent != HudGMod.g_HudGMod && parent != GModBase.GetGModParentToHUDPanel()) { +#endif if (!parent.LuaPanel || parent.IsMarkedForDeletion()) return; } @@ -1165,7 +1173,11 @@ static bool Panel__IsModal(Panel panel) { static void Panel__SetFontInternal(ILuaInterface lua, Panel panel) { IFont? font = LuaFonts.GetFont(lua.GetString(2)); if (font == null) { +#if MENU_DLL + font = MenuPanels.GetMenuPanel()!.GetScheme()!.GetFont(lua.GetString(2), false); +#else font = GModBase.GetGModBasePanel(true)!.GetScheme()!.GetFont(lua.GetString(2), false); +#endif if (font == null) { lua.ErrorNoHalt($"SetFontInternal: font doesn't exist ({lua.GetString(2)})\n"); return; diff --git a/Game.Client/GarrysMod/LuaRender.cs b/Game.Client/GarrysMod/LuaRender.cs index 21c709d64..b7292f070 100644 --- a/Game.Client/GarrysMod/LuaRender.cs +++ b/Game.Client/GarrysMod/LuaRender.cs @@ -345,11 +345,13 @@ static void SetColorModulation([LuaGet] float r, [LuaGet] float g, [LuaGet] floa } #endif +#if !MENU_DLL [LuaFunction] static (float, float, float) GetColorModulation() { Vector3 color = render.GetColorModulation(); return (color.X, color.Y, color.Z); } +#endif #if !MENU_DLL [LuaFunction] diff --git a/Game.Client/GarrysMod/LuaSurface.cs b/Game.Client/GarrysMod/LuaSurface.cs index b46deb5eb..f9f1aabbc 100644 --- a/Game.Client/GarrysMod/LuaSurface.cs +++ b/Game.Client/GarrysMod/LuaSurface.cs @@ -246,7 +246,11 @@ static int SetFont(ILuaInterface lua) { string name = lua.CheckString(1); CurrentFont = LuaFonts.GetFont(name); if (CurrentFont == null) { +#if MENU_DLL + CurrentFont = MenuPanels.GetMenuPanel()!.GetScheme()!.GetFont(name, false); +#else CurrentFont = GModBase.GetGModBasePanel(true)!.GetScheme()!.GetFont(name, false); +#endif if (CurrentFont == null) { lua.ErrorFromLua($"'{name}' isn't a valid font\n"); return 0; @@ -344,6 +348,7 @@ static int DrawTexturedRectRotated(ILuaInterface lua) { [LuaFunction] static int PlaySound(ILuaInterface lua) { ReadOnlySpan sound = lua.CheckString(1); +#if !MENU_DLL int index = soundemitterbase.GetSoundIndex(sound); if (soundemitterbase.IsValidIndex(index)) { ref SoundParametersInternal internalParams = ref soundemitterbase.InternalGetParametersForSound(index); @@ -351,6 +356,7 @@ static int PlaySound(ILuaInterface lua) { int pick = RandomInt(0, soundNames.Length - 1); sound = soundemitterbase.GetWaveName(soundNames[pick].Symbol); } +#endif surface.PlaySound(sound); return 0; } diff --git a/Game.Client/GarrysMod/LuaVGUI.cs b/Game.Client/GarrysMod/LuaVGUI.cs index 4340e32c9..2998d15bc 100644 --- a/Game.Client/GarrysMod/LuaVGUI.cs +++ b/Game.Client/GarrysMod/LuaVGUI.cs @@ -55,14 +55,22 @@ static int IsHoveringWorld(ILuaInterface lua) { lua.PushBool(false); return 1; } +#if MENU_DLL + Panel? world = MenuPanels.GetMenuPanel(); +#else Panel? world = GModBase.GetGModBasePanel(true); +#endif lua.PushBool(vguiInput.GetMouseOver() == world); return 1; } [LuaFunction] static int GetWorldPanel(ILuaInterface lua) { +#if MENU_DLL + Push_Panel(MenuPanels.GetMenuPanel()); +#else Push_Panel(GModBase.GetGModBasePanel(true)); +#endif return 1; } @@ -131,9 +139,13 @@ public static void Push_Panel(Panel? panel) { } public static bool IsValidPanel(Panel? panel) { +#if MENU_DLL + return MenuPanels.IsValidPanel(panel); +#else if (panel != null && panel != GModBase.GetGModBasePanel(true) && panel != HudGMod.g_HudGMod && panel != GModBase.GetGModParentToHUDPanel()) return panel.LuaPanel && !panel.IsMarkedForDeletion(); return true; +#endif } public static Panel? CreateControl(ReadOnlySpan className) { @@ -179,11 +191,13 @@ public static bool IsValidPanel(Panel? panel) { if (stricmp(className, "AchievementIcon") == 0) return null; // AchievementIcon +#if !MENU_DLL if (stricmp(className, "ModelImage") == 0) return new SpawnIcon(null, "ModelImage"); if (stricmp(className, "AvatarImage") == 0) return null; // AvatarImage +#endif if (stricmp(className, "HTML") == 0) return new HtmlPanel(null, "HtmlPanel"); @@ -211,7 +225,11 @@ static int Create(ILuaInterface lua) { else { if (lua.GetType(2) != LuaType.Nil) lua.ErrorFromLua($"bad argument #2 to 'Create' (Panel expected, got {lua.GetActualTypeName(2)})"); +#if MENU_DLL + panel.SetParent(MenuPanels.GetMenuPanel()); +#else panel.SetParent(GModBase.GetGModBasePanel(true)); +#endif } if (lua.GetType(3) == LuaType.String) diff --git a/Game.Client/HLClient.cs b/Game.Client/HLClient.cs index 42cafef58..ccd546605 100644 --- a/Game.Client/HLClient.cs +++ b/Game.Client/HLClient.cs @@ -213,6 +213,7 @@ public void Shutdown() { ClientVoiceMgr_Shutdown(); Game.Client.GarrysMod.GarrysMod.Lua.Kill(); #if GMOD_DLL + get.MenuSystem()?.Shutdown(); get.HTML()?.Shutdown(); #endif } @@ -478,10 +479,6 @@ public int HudVidInit() { public void HudUpdate(bool active) { TimeUnit_t frameTime = gpGlobals.FrameTime; -#if GMOD_DLL - garrysmod.Update(); -#endif - GetClientVoiceMgr().Frame(frameTime); gHUD.UpdateHud(active); diff --git a/Game.MenuSystem/AddonDownloadNotifications.cs b/Game.MenuSystem/AddonDownloadNotifications.cs new file mode 100644 index 000000000..426adf84d --- /dev/null +++ b/Game.MenuSystem/AddonDownloadNotifications.cs @@ -0,0 +1,140 @@ +#if MENU_DLL +using Game.MenuSystem.GarrysMod; + +using Source.Common.GarrysMod; + +using System.Globalization; + +namespace Game.MenuSystem; + +public class AddonDownloadNotifications : IAddonDownloadNotification +{ + static bool PushHookCall() { + LuaObject hook = new(); + g_Lua!.Global().GetMember("hook", hook); + if (!hook.isTable()) { + hook.UnReference(); + return false; + } + + LuaObject call = new(); + hook.GetMember("Call", call); + if (!call.isFunction()) { + call.UnReference(); + hook.UnReference(); + return false; + } + + call.Push(); + call.UnReference(); + hook.UnReference(); + return true; + } + + static bool Begin(ReadOnlySpan name) { + if (g_Lua == null || g_Lua.Global() == null || !PushHookCall()) + return false; + g_Lua.PushString(name); + return true; + } + + static void PushID(ulong id) => g_Lua!.PushString(id.ToString(CultureInfo.InvariantCulture)); + + public void Start() { + if (!Begin("WorkshopStart")) + return; + g_Lua!.CallInternalNoReturns(1); + } + + public void StartDownload(ulong wsid, ulong imgid, ReadOnlySpan title, ulong size) { + if (!Begin("WorkshopDownloadFile")) + return; + g_Lua!.PushNil(); + PushID(wsid); + PushID(imgid); + g_Lua.PushString(title); + g_Lua.PushNumber((long)size); + g_Lua.CallInternalNoReturns(6); + } + + public void FinishDownload(ulong wsid) { + if (!Begin("WorkshopDownloadedFile")) + return; + g_Lua!.PushNil(); + PushID(wsid); + g_Lua.CallInternalNoReturns(3); + } + + public void Finish() { + if (!Begin("WorkshopEnd")) + return; + g_Lua!.CallInternalNoReturns(1); + } + + public void DownloadProgress(ulong wsid, ulong imgid, ReadOnlySpan title, uint unk1, uint unk2) { + if (!Begin("WorkshopDownloadProgress")) + return; + g_Lua!.PushNil(); + PushID(wsid); + PushID(imgid); + g_Lua.PushString(title); + g_Lua.PushNumber(unk1); + g_Lua.PushNumber(unk2); + g_Lua.CallInternalNoReturns(7); + } + + public void ExtractProgress(ulong wsid, ulong imgid, ReadOnlySpan title, uint percent) { + if (!Begin("WorkshopExtractProgress")) + return; + g_Lua!.PushNil(); + PushID(wsid); + PushID(imgid); + g_Lua.PushString(title); + g_Lua.PushNumber(percent); + g_Lua.CallInternalNoReturns(6); + } + + public void DownloadTotals(int num, int max) { + if (!Begin("WorkshopDownloadTotals")) + return; + g_Lua!.PushNil(); + g_Lua.PushNumber(num); + g_Lua.PushNumber(max); + g_Lua.CallInternalNoReturns(4); + } + + public void SubscriptionsProgress(int num, int max) { + if (!Begin("WorkshopSubscriptionsProgress")) + return; + g_Lua!.PushNil(); + g_Lua.PushNumber(num); + g_Lua.PushNumber(max); + g_Lua.CallInternalNoReturns(4); + } + + public void SendMessage(ReadOnlySpan message) { + if (!Begin("WorkshopSubscriptionsMessage")) + return; + g_Lua!.PushNil(); + g_Lua.PushString(message); + g_Lua.CallInternalNoReturns(3); + } + + public void NotifySubscriptionChanges() { + if (!Begin("WorkshopSubscriptionsChanged")) + return; + g_Lua!.PushNil(); + g_Lua.CallInternalNoReturns(2); + } + + public void NotifyAddonConflict(ulong wsid1, ulong wsid2, ReadOnlySpan filename) { + if (!Begin("OnNotifyAddonConflict")) + return; + g_Lua!.PushNil(); + PushID(wsid1); + PushID(wsid2); + g_Lua.PushString(filename); + g_Lua.CallInternalNoReturns(5); + } +} +#endif diff --git a/Game.MenuSystem/LuaMenuCallback.cs b/Game.MenuSystem/LuaMenuCallback.cs new file mode 100644 index 000000000..67fa2271c --- /dev/null +++ b/Game.MenuSystem/LuaMenuCallback.cs @@ -0,0 +1,44 @@ +#if MENU_DLL +using Game.MenuSystem.GarrysMod; + +using Source; +using Source.Common.GarrysMod.Lua; + +namespace Game.MenuSystem; + +public class LuaMenuCallback : ILuaGameCallback +{ + public static readonly LuaMenuCallback g_MenuLuaCallback = new(); + + static readonly Color cMsgColor = new(120, 220, 100, 255); + static readonly Color cErrorColor = cMsgColor; + + public ILuaObject CreateLuaObject() => new LuaObject(); + + public void DestroyLuaObject(ILuaObject obj) => obj?.UnReference(); + + public void ErrorPrint(ReadOnlySpan error, bool print) => Dbg._ColorSpewMessage(SpewType.Message, in cErrorColor, error.ToString()); + + public void Msg(ReadOnlySpan msg, bool useless) => Dbg._ColorSpewMessage(SpewType.Message, in cMsgColor, msg.ToString()); + + public void MsgColour(ReadOnlySpan msg, in Color color) => Dbg._ColorSpewMessage(SpewType.Message, in color, msg.ToString()); + + public void LuaError(in LuaError error) { + get.MenuSystem()?.OnLuaError(in error, null); + + string stack = ""; + string indent = ""; + int i = 0; + foreach (LuaError.StackEntry entry in error.Stack) { + indent += " "; + string function = entry.Function.Length == 0 ? "unknown" : entry.Function; + string source = entry.Source.Length == 0 ? "filename" : entry.Source; + stack += $"{indent} {++i}. {function} - {source}:{entry.Line}\n"; + } + + ErrorPrint("\n[MENU ERROR] " + error.Message + "\n" + stack + "\n", true); + } + + public void InterfaceCreated(ILuaInterface iface) { } +} +#endif diff --git a/Game.MenuSystem/MenuPanels.cs b/Game.MenuSystem/MenuPanels.cs new file mode 100644 index 000000000..f50780155 --- /dev/null +++ b/Game.MenuSystem/MenuPanels.cs @@ -0,0 +1,89 @@ +#if MENU_DLL +using Source.Common.GUI; +using Source.GUI.Controls; + +namespace Game.MenuSystem; + +public class MenuScreenPanel : EditablePanel +{ + public MenuScreenPanel() : base(null, "GModMenuBasePanel") { } +} + +public class GModLoadingPanel : EditablePanel +{ + public GModLoadingPanel() : base(null, "LoadingScreenBasePanel") { } +} + +public class OverlayPanel : Panel +{ + public OverlayPanel() : base(null, "GModOverlayPopupPanel") { } + + public override void OnThink() { + if (IsMarkedForDeletion()) + return; + + Surface.MovePopupToFront(this); + MenuSystem.g_MenuSystem.Think(); + } +} + +public static class MenuPanels +{ + public static Panel? g_hMenuPanel; + public static Panel? g_hOverlayPanel; + public static Panel? g_hLoadingPanel; + + public static Panel? GetMenuPanel() { + if (g_hMenuPanel == null) + Warning("Trying to create VGUI too early!\n"); + return g_hMenuPanel; + } + + public static Panel? GetOverlayPanel() => g_hOverlayPanel; + + public static bool IsValidPanel(Panel? panel) { + if (panel != null && panel != GetMenuPanel() && panel != GetOverlayPanel()) + return panel.LuaPanel && !panel.IsMarkedForDeletion(); + return true; + } + + public static void CreateMenuPanels() { + gameUI.SetMainMenuOverride(null); + + if (g_hMenuPanel != null) { + g_hMenuPanel.SetParent((Panel?)null); + g_hMenuPanel.MarkForDeletion(); + g_hMenuPanel = null; + } + + if (g_hOverlayPanel != null) { + g_hOverlayPanel.SetParent((Panel?)null); + g_hOverlayPanel.DeletePanel(); + g_hOverlayPanel = null; + } + + MenuScreenPanel menuPanel = new(); + menuPanel.SetScheme(SchemeManager.LoadSchemeFromFile("resource/ClientScheme.res", "ClientScheme")!); + Surface.GetScreenSize(out int wide, out int tall); + menuPanel.SetSize(wide, tall); + menuPanel.SetPos(0, 0); + + OverlayPanel overlayPanel = new(); + Surface.GetScreenSize(out wide, out tall); + overlayPanel.SetSize(wide, tall); + overlayPanel.SetPos(0, 0); + g_hOverlayPanel = overlayPanel; + g_hOverlayPanel.SetParent(Surface.GetEmbeddedPanel()); + g_hOverlayPanel.MakePopup(true, false); + g_hOverlayPanel.SetKeyboardInputEnabled(false); + g_hOverlayPanel.SetMouseInputEnabled(false); + + gameUI.SetMainMenuOverride(menuPanel); + menuPanel.SetProportional(false); + menuPanel.SetKeyboardInputEnabled(true); + menuPanel.SetMouseInputEnabled(true); + menuPanel.MoveToFront(); + g_hMenuPanel = menuPanel; + } +} +#endif diff --git a/Game.MenuSystem/MenuSystem.cs b/Game.MenuSystem/MenuSystem.cs index fd853b153..393b9e64e 100644 --- a/Game.MenuSystem/MenuSystem.cs +++ b/Game.MenuSystem/MenuSystem.cs @@ -1,50 +1,215 @@ -using Source; +using Source; using Source.Common; using Source.Common.Engine; using Source.Common.GarrysMod; using Source.Common.GarrysMod.Lua; +#if MENU_DLL +using Game.MenuSystem.GarrysMod; + +using Source.GUI.Controls; +#endif + namespace Game.MenuSystem; public class MenuSystem : IMenuSystem { +#if MENU_DLL + public static MenuSystem g_MenuSystem = null!; + + bool WasInGame; + readonly AddonDownloadNotifications DownloadNotifications = new(); + int LuaStarts; + int LastFilesystemRefresh; + + public MenuSystem() => g_MenuSystem = this; + public int Init(IServiceProvider services, IGet get, IGarrysMod gmod, GlobalVarsBase vars) { - throw new NotImplementedException(); + SourceDllMain.gpGlobals = vars; + SourceDllMain.garrysmod = gmod; + SourceDllMain.get = get; + + filesystem.Addons().SetDownloadNotify(DownloadNotifications); + return 1; } - public bool IsServerBlacklisted(ReadOnlySpan address, ReadOnlySpan hostname, ReadOnlySpan description, ReadOnlySpan gamemode, ReadOnlySpan map) { - throw new NotImplementedException(); + public void Shutdown() { + filesystem.Addons().SetDownloadNotify(null); + CloseLua(); + DestroyLoadingPanel(); + DestroyMenuPanels(); } - public void OnLuaError(in LuaError err, IAddonSystem.Information? addonInfo) { - if (addonInfo.HasValue) - GarrysMod.LuaHelper.CallOnLuaErrorHook(in err, addonInfo.Value.Title ?? "", addonInfo.Value.WorkshopID); - else - GarrysMod.LuaHelper.CallOnLuaErrorHook(in err, null, 0); + public void SetupNetworkString(INetworkStringTableContainer networkStringTableContainer) => networkstringtable = networkStringTableContainer; + + static void CallHook(ReadOnlySpan name) { + if (g_Lua == null || g_Lua.Global() == null) + return; + + LuaObject hook = new(); + g_Lua.Global().GetMember("hook", hook); + if (hook.isTable()) { + LuaObject call = new(); + hook.GetMember("Call", call); + if (call.isFunction()) { + call.Push(); + g_Lua.PushString(name); + g_Lua.CallInternalNoReturns(1); + } + call.UnReference(); + } + hook.UnReference(); } - public void SendProblemToMenu(ReadOnlySpan id, int severity, ReadOnlySpan parms) { - // throw new NotImplementedException(); - Msg($"SendProblemToMenu not implemented! ({id.SliceNullTerminatedString()}, {severity}, {parms.SliceNullTerminatedString()})\n"); + public void Think() { + if (g_Lua != null && g_Lua.Global() != null) { + g_Lua.Cycle(); + LuaTimer.Cycle(); + CallHook("Think"); + } + + garrysmod.Update(); + + if (filesystem.LastFilesystemRefresh() != LastFilesystemRefresh) { + LastFilesystemRefresh = filesystem.LastFilesystemRefresh(); + CallHook("GameContentChanged"); + } + + WasInGame = engine.IsInGame(); } - public void ServerDetails(ReadOnlySpan unk1, ReadOnlySpan unk2, ReadOnlySpan unk3, int unk4, ReadOnlySpan unk5) { - throw new NotImplementedException(); + void CloseLua() { + if (g_Lua == null) + return; + + LuaStarts++; + get.LuaShared()!.UnMountLua("LuaMenu"); + get.LuaShared()!.CloseLuaInterface(g_Lua); + g_Lua = null; } - public void SetupNetworkString(INetworkStringTableContainer networkStringTableContainer) { - throw new NotImplementedException(); + public void StartLua() { + CloseLua(); + MenuPanels.CreateMenuPanels(); + + get.LuaShared()!.MountLua("LuaMenu"); + g_Lua = get.LuaShared()!.CreateLuaInterface(Realm.Menu, false); + g_Lua.Init(LuaMenuCallback.g_MenuLuaCallback, commandLine.CheckParm("-withjit")); + g_Lua.SetPathID("LuaMenu"); + g_Lua.SetType(2); + + g_Lua.Global().SetMember("CLIENT", true); + g_Lua.Global().SetMember("SERVER", false); + g_Lua.Global().SetMember("VERSION", (float)get.Version()); + g_Lua.Global().SetMember("VERSIONSTR", get.VersionStr()); + g_Lua.Global().SetMember("NETVERSIONSTR", engine.GetProductVersionString()); + g_Lua.Global().SetMember("BRANCH", get.Branch()); + + LuaObject debug = new(); + g_Lua.Global().GetMember("debug", debug); + if (debug.isTable()) + debug.SetMemberNil("getupvalue"); + debug.UnReference(); + + LuaUser.InitLuaLibraries(g_Lua); + LuaClass.InitLuaClasses(g_Lua); + + g_Lua.FindAndRunScript("includes/init_menu.lua", true, true, "!UNKNOWN", true); + g_Lua.FindAndRunScript("derma/init.lua", true, true, "!UNKNOWN", true); + g_Lua.FindAndRunScript("includes/vgui_base.lua", true, true, "!UNKNOWN", true); + g_Lua.FindAndRunScript("skins/default.lua", true, true, "!UNKNOWN", true); + g_Lua.FindAndRunScript("includes/menu.lua", true, true, "!UNKNOWN", true); + + CreateLoadingPanel(); + + CallHook("MenuStart"); } - public void Shutdown() { - throw new NotImplementedException(); + static void DestroyLoadingPanel() { + gameUI.SetLoadingBackgroundDialog(null); + if (MenuPanels.g_hLoadingPanel == null) + return; + + MenuPanels.g_hLoadingPanel.SetParent((Panel?)null); + MenuPanels.g_hLoadingPanel.MarkForDeletion(); + MenuPanels.g_hLoadingPanel = null; } - public void StartLua() { + static void DestroyMenuPanels() { + gameUI.SetMainMenuOverride(null); + + if (MenuPanels.g_hMenuPanel != null) { + MenuPanels.g_hMenuPanel.SetParent((Panel?)null); + MenuPanels.g_hMenuPanel.MarkForDeletion(); + MenuPanels.g_hMenuPanel = null; + } + + if (MenuPanels.g_hOverlayPanel != null) { + MenuPanels.g_hOverlayPanel.SetParent((Panel?)null); + MenuPanels.g_hOverlayPanel.DeletePanel(); + MenuPanels.g_hOverlayPanel = null; + } + } + + static void CreateLoadingPanel() { + DestroyLoadingPanel(); + + if (g_Lua == null || g_Lua.Global() == null) + return; + + GModLoadingPanel loading = new(); + Surface.GetScreenSize(out int wide, out int tall); + loading.SetSize(wide, tall); + loading.SetPos(0, 0); + MenuPanels.g_hLoadingPanel = loading; + loading.SetVisible(false); + loading.MakePopup(false, false); + gameUI.SetLoadingBackgroundDialog(loading); + + LuaObject getLoadPanel = new(); + g_Lua.Global().GetMember("GetLoadPanel", getLoadPanel); + if (getLoadPanel.isFunction()) { + LuaObject result = new(); + getLoadPanel.Push(); + if (g_Lua.CallInternalGet(0, result) && result.GetType() == LuaType.Panel) { + result.Push(); + Panel? panel = LuaVGUI.Get_Panel(-1); + g_Lua.Pop(1); + if (panel != null) { + panel.InvalidateLayout(false, true); + panel.SetParent(MenuPanels.g_hLoadingPanel); + } + g_Lua.Global().SetMemberNil("GetLoadPanel"); + } + result.UnReference(); + } + getLoadPanel.UnReference(); + } + + public void OnLuaError(in LuaError err, IAddonSystem.Information? addonInfo) { + if (addonInfo.HasValue) + LuaHelper.CallOnLuaErrorHook(in err, addonInfo.Value.Title ?? "", addonInfo.Value.WorkshopID); + else + LuaHelper.CallOnLuaErrorHook(in err, null, 0); + } +#else + public int Init(IServiceProvider services, IGet get, IGarrysMod gmod, GlobalVarsBase vars) => 1; + public void Shutdown() { } + public void SetupNetworkString(INetworkStringTableContainer networkStringTableContainer) { } + public void Think() { } + public void StartLua() { } + public void OnLuaError(in LuaError err, IAddonSystem.Information? addonInfo) { } +#endif + + public bool IsServerBlacklisted(ReadOnlySpan address, ReadOnlySpan hostname, ReadOnlySpan description, ReadOnlySpan gamemode, ReadOnlySpan map) { throw new NotImplementedException(); } - public void Think() { + public void SendProblemToMenu(ReadOnlySpan id, int severity, ReadOnlySpan parms) { + Msg($"SendProblemToMenu not implemented! ({id.SliceNullTerminatedString()}, {severity}, {parms.SliceNullTerminatedString()})\n"); + } + + public void ServerDetails(ReadOnlySpan unk1, ReadOnlySpan unk2, ReadOnlySpan unk3, int unk4, ReadOnlySpan unk5) { throw new NotImplementedException(); } } diff --git a/Game.Shared/GarrysMod/GarrysMod.cs b/Game.Shared/GarrysMod/GarrysMod.cs index 6235cf015..d0de0a9d7 100644 --- a/Game.Shared/GarrysMod/GarrysMod.cs +++ b/Game.Shared/GarrysMod/GarrysMod.cs @@ -104,7 +104,11 @@ public void InitializeMod(IServiceProvider services) { AddLanguageFiles(uiLanguage.SliceNullTerminatedString()); #endif get.IntroScreen()!.Update("Setup Menu System", true); - // todo: menu system init +#if CLIENT_DLL + if (get.MenuSystem()!.Init(services, get, this, gpGlobals) == 0) + Error("Error initializing Menu System"); + get.MenuSystem()!.SetupNetworkString(networkstringtable); +#endif get.IntroScreen()!.Update("Setting Convar Defaults", true); // todo: convar defaults #endif @@ -127,11 +131,14 @@ public void InitializeMod(IServiceProvider services) { filesystem.MarkPathIDByRequestOnly("DATA", true); } -#if CLIENT_DLL public void Update() { +#if CLIENT_DLL get.HTML()?.Update(); +#endif } +#if CLIENT_DLL + public void LevelInit(ReadOnlySpan mapName) { get.Audio()?.StopAllPlayback(); diff --git a/Game.Shared/GarrysMod/LuaConCommand.cs b/Game.Shared/GarrysMod/LuaConCommand.cs index 3c57281b1..73a463cd2 100644 --- a/Game.Shared/GarrysMod/LuaConCommand.cs +++ b/Game.Shared/GarrysMod/LuaConCommand.cs @@ -429,7 +429,7 @@ static void LuaConCommand(in TokenizedCommand args) { #if CLIENT_DLL C_BasePlayer? player = C_BasePlayer.GetLocalPlayer(); -#else +#elif !MENU_DLL BasePlayer? player = Util.GetCommandClient(); if (player == null && Util.GetCommandClientIndex() > 0) { Warning($"Warning: Player issued command but is now vanished (Command was \"{args.ArgS()}\")\n"); @@ -444,6 +444,7 @@ static void LuaConCommand(in TokenizedCommand args) { concommand.GetMember("Run", run); if (run.isFunction()) { ReadOnlySpan command = args.Arg(0); +#if !MENU_DLL if (command.Length > 0 && command[0] == '+') { if (args.ArgC() > 1) MarkButtonStatus((ButtonCode)atoi(args.Arg(1)), true); @@ -452,9 +453,14 @@ static void LuaConCommand(in TokenizedCommand args) { if (args.ArgC() > 1) MarkButtonStatus((ButtonCode)atoi(args.Arg(1)), false); } +#endif run.Push(); +#if MENU_DLL + g_Lua.PushNil(); +#else LuaEntity.Push_Entity(player); +#endif g_Lua.PushString(command); LuaTable arguments = new(null, (uint)args.ArgC()); diff --git a/Game.Shared/GarrysMod/LuaFileLibrary.cs b/Game.Shared/GarrysMod/LuaFileLibrary.cs index 4398126a4..d8bd0a938 100644 --- a/Game.Shared/GarrysMod/LuaFileLibrary.cs +++ b/Game.Shared/GarrysMod/LuaFileLibrary.cs @@ -255,10 +255,12 @@ static int File__Read(ILuaInterface lua) { if (!pastEnd && length > 0) toRead = length; else { +#if !MENU_DLL if (Game.Client.GarrysMod.GarrysMod.lua_strict.GetInt() != 0) { lua.ErrorFromLua($"File:Read() - Invalid requested size {(int)length}\n"); return 0; } +#endif toRead = pastEnd && size > pos ? size - pos : 0; } @@ -307,7 +309,9 @@ static int File__Write(ILuaInterface lua) { return 0; } +#if !MENU_DLL if (Game.Client.GarrysMod.GarrysMod.lua_strict.GetInt() != 0) +#endif lua.ErrorFromLua($"File:Write() - Invalid write size {data.Length}\n"); return 0; } diff --git a/Game.Shared/GarrysMod/LuaGameCallback.cs b/Game.Shared/GarrysMod/LuaGameCallback.cs index 84e1bd836..b22d8ab23 100644 --- a/Game.Shared/GarrysMod/LuaGameCallback.cs +++ b/Game.Shared/GarrysMod/LuaGameCallback.cs @@ -136,7 +136,7 @@ public static void SendQueuedErrors() { public void MsgColour(ReadOnlySpan msg, in Color color) => Dbg._ColorSpewMessage(SpewType.Message, in color, msg.ToString()); public void LuaError(in LuaError error) { - bool isAddon = GetAddonFromError(in error, out IAddonSystem.Information addon, out bool overriding); + bool isAddon = LuaHelper.GetAddonFromError(in error, out IAddonSystem.Information addon, out bool overriding); string stack = ""; string indent = ""; @@ -204,81 +204,5 @@ static void SendErrorToHTTPServer(ref LuaErrorToSend error) { throw new NotImplementedException(); } - - static bool GetLegacyAddon(string path, ref IAddonSystem.Information local) { - int start = path.IndexOf("addons/", StringComparison.Ordinal); - if (start == -1) - return false; - - start += 7; - int end = path.IndexOf('/', start); - if (end == -1) - return false; - - local.Title = path[start..end]; - return true; - } - - internal static bool GetAddonFromError(in LuaError error, out IAddonSystem.Information info, out bool overriding) { - IAddonSystem.Information local = new() { Title = "", File = "", Tags = "", Failure = "" }; - IAddonSystem.Information owner = default; - bool found = false; - bool overridingFile = false; - - int colon = error.Message.IndexOf(':'); - if (colon != -1) { - string file = error.Message[..colon]; - if (Bootil.String.Test.EndsWith(file, ".lua")) { - if (filesystem != null && filesystem.Addons() != null && filesystem.Addons().FindFileOwner(file, out owner)) - found = true; - else if (GetLegacyAddon(file, ref local)) { - owner = local; - found = true; - } - } - } - - foreach (LuaError.StackEntry entry in error.Stack) { - if (entry.Source.Length == 0) - continue; - - if (found || overridingFile) - break; - - if (filesystem != null && filesystem.Addons() != null) { - found = filesystem.Addons().FindFileOwner(entry.Source, out owner); - - LuaFile? cache = get.LuaShared()!.GetCache(entry.Source); - if (cache != null && cache.Time > 1) { - if (found) { - Warning($"Local file is overriding addon's file! {entry.Source} ({owner.Title})\n"); - found = false; - overridingFile = true; - continue; - } - } - else if (found) { - overridingFile = false; - continue; - } - } - - overridingFile = false; - found = GetLegacyAddon(entry.Source, ref local); - if (found) - owner = local; - } - - overriding = overridingFile; - - if (!found) { - info = default; - return false; - } - - info = owner; - info.Title ??= ""; - return true; - } } #endif diff --git a/Game.Shared/GarrysMod/LuaGlobalFunctions.cs b/Game.Shared/GarrysMod/LuaGlobalFunctions.cs index b30160380..e53491a21 100644 --- a/Game.Shared/GarrysMod/LuaGlobalFunctions.cs +++ b/Game.Shared/GarrysMod/LuaGlobalFunctions.cs @@ -348,7 +348,7 @@ static int ErrorNoHalt(ILuaInterface lua) { }; ReadStackFrom(ref error, g_Lua); - bool isAddon = LuaGameCallback.GetAddonFromError(in error, out IAddonSystem.Information addon, out _); + bool isAddon = LuaHelper.GetAddonFromError(in error, out IAddonSystem.Information addon, out _); get.MenuSystem()?.OnLuaError(in error, isAddon ? addon : null); LuaHelper.CallOnLuaErrorHook(in error, isAddon ? addon.Title : null, isAddon ? addon.WorkshopID : 0); @@ -513,7 +513,7 @@ static int RunConsoleCommand(ILuaInterface lua) { string result = buffer.ToString(); if (result.Length > 1023) result = result[..1023]; -#if CLIENT_DLL +#if CLIENT_DLL || MENU_DLL engine.ClientCmd(result); #else engine.ServerCommand(result); diff --git a/Game.Shared/GarrysMod/LuaHelper.cs b/Game.Shared/GarrysMod/LuaHelper.cs index cac63deaf..4138ec4af 100644 --- a/Game.Shared/GarrysMod/LuaHelper.cs +++ b/Game.Shared/GarrysMod/LuaHelper.cs @@ -1,6 +1,7 @@ #if CLIENT_DLL || GAME_DLL || MENU_DLL using Source; using Source.Common.Formats.Keyvalues; +using Source.Common.GarrysMod; using Source.Common.GarrysMod.Lua; #if CLIENT_DLL @@ -103,5 +104,81 @@ public static void CallOnLuaErrorHook(in LuaError error, string? addonTitle, ulo run.UnReference(); hook.UnReference(); } + + static bool GetLegacyAddon(string path, ref IAddonSystem.Information local) { + int start = path.IndexOf("addons/", StringComparison.Ordinal); + if (start == -1) + return false; + + start += 7; + int end = path.IndexOf('/', start); + if (end == -1) + return false; + + local.Title = path[start..end]; + return true; + } + + public static bool GetAddonFromError(in LuaError error, out IAddonSystem.Information info, out bool overriding) { + IAddonSystem.Information local = new() { Title = "", File = "", Tags = "", Failure = "" }; + IAddonSystem.Information owner = default; + bool found = false; + bool overridingFile = false; + + int colon = error.Message.IndexOf(':'); + if (colon != -1) { + string file = error.Message[..colon]; + if (Bootil.String.Test.EndsWith(file, ".lua")) { + if (filesystem != null && filesystem.Addons() != null && filesystem.Addons().FindFileOwner(file, out owner)) + found = true; + else if (GetLegacyAddon(file, ref local)) { + owner = local; + found = true; + } + } + } + + foreach (LuaError.StackEntry entry in error.Stack) { + if (entry.Source.Length == 0) + continue; + + if (found || overridingFile) + break; + + if (filesystem != null && filesystem.Addons() != null) { + found = filesystem.Addons().FindFileOwner(entry.Source, out owner); + + LuaFile? cache = get.LuaShared()!.GetCache(entry.Source); + if (cache != null && cache.Time > 1) { + if (found) { + Warning($"Local file is overriding addon's file! {entry.Source} ({owner.Title})\n"); + found = false; + overridingFile = true; + continue; + } + } + else if (found) { + overridingFile = false; + continue; + } + } + + overridingFile = false; + found = GetLegacyAddon(entry.Source, ref local); + if (found) + owner = local; + } + + overriding = overridingFile; + + if (!found) { + info = default; + return false; + } + + info = owner; + info.Title ??= ""; + return true; + } } #endif diff --git a/Game.Shared/GarrysMod/LuaObject.cs b/Game.Shared/GarrysMod/LuaObject.cs index 0a9192321..a2868bfa2 100644 --- a/Game.Shared/GarrysMod/LuaObject.cs +++ b/Game.Shared/GarrysMod/LuaObject.cs @@ -681,6 +681,10 @@ public void SetMemberMatrix(float key, in Matrix4x4 mat) { public IHandleEntity? GetMemberEntity(ReadOnlySpan name, IHandleEntity? def) => throw new NotImplementedException(); public IHandleEntity? GetMemberEntity(int key, IHandleEntity? def) => throw new NotImplementedException(); public void SetMemberEntity(float key, IHandleEntity? ent) => throw new NotImplementedException(); +#if MENU_DLL + public void SetMemberEntity(ReadOnlySpan name, IHandleEntity? ent) => throw new NotImplementedException(); + public IHandleEntity? GetEntity() => throw new NotImplementedException(); +#else public void SetMemberEntity(ReadOnlySpan name, IHandleEntity? ent) { if (!isTable()) return; @@ -696,6 +700,7 @@ public void SetMemberEntity(ReadOnlySpan name, IHandleEntity? ent) { g_Lua!.Pop(1); return ent; } +#endif public void SetEntity(IHandleEntity? ent) => throw new NotImplementedException(); public void SetMemberPhysObject(ReadOnlySpan name, IPhysicsObject? obj) => throw new NotImplementedException(); } diff --git a/Game.Shared/GarrysMod/LuaTimer.cs b/Game.Shared/GarrysMod/LuaTimer.cs index 3338cc939..b18f58ee2 100644 --- a/Game.Shared/GarrysMod/LuaTimer.cs +++ b/Game.Shared/GarrysMod/LuaTimer.cs @@ -64,8 +64,10 @@ public static partial class LuaTimer [LuaFunction] static int Check(ILuaInterface lua) { +#if !MENU_DLL if (Game.Client.GarrysMod.GarrysMod.lua_strict.GetInt() != 0) lua.ErrorFromLua("timer.Check is deprecated and does nothing. Do not use it."); +#endif return 0; } @@ -388,6 +390,9 @@ static void lua_dumptimers_sv(in TokenizedCommand args) { return; Dump(); } +#elif MENU_DLL + [ConCommand("lua_dumptimers_menu", "Dumps all the currently active Lua timers in the menu")] + static void lua_dumptimers_menu(in TokenizedCommand args) => Dump(); #else [ConCommand("lua_dumptimers_cl", "Dumps all the currently active Lua timers on the client")] static void lua_dumptimers_cl(in TokenizedCommand args) => Dump(); diff --git a/Game.UI/BasePanel.cs b/Game.UI/BasePanel.cs index c7a39eed9..b48dfb792 100644 --- a/Game.UI/BasePanel.cs +++ b/Game.UI/BasePanel.cs @@ -131,6 +131,28 @@ public void UpdateMenuItemState(bool isInGame, bool isMultiplayer) { IPanel? MainMenuOverridePanel; + public void SetMainMenuOverride(IPanel? panel) { + MainMenuOverridePanel = panel; + + if (MainMenuOverridePanel != null) + DeleteAllItems(); + } + + public override void OnCommand(ReadOnlySpan command) { + if (stricmp(command, "Open") == 0) { + if (MainMenuOverridePanel != null) { + MainMenuOverridePanel.MoveToFront(); + MainMenuOverridePanel.RequestFocus(); + } + else { + MoveToFront(); + RequestFocus(); + } + } + else + base.OnCommand(command); + } + public override void SetVisible(bool state) { if (MainMenuOverridePanel != null) { MainMenuOverridePanel.SetVisible(true); @@ -582,6 +604,7 @@ public override void OnClose() { public class BasePanel : Panel { GameMenu? GameMenu; + IPanel? MainMenuOverridePanel; readonly public IFileSystem FileSystem = Singleton(); readonly public IEngineClient engine = Singleton(); @@ -1048,6 +1071,14 @@ private void CreateGameMenu() { } } + public void SetMainMenuOverride(IPanel? panel) { + MainMenuOverridePanel = panel; + + GameMenu?.SetMainMenuOverride(panel); + + MainMenuOverridePanel?.SetParent(this); + } + public override void OnThink() { // KeyRepeat todo base.OnThink(); @@ -1100,6 +1131,9 @@ private void UpdateGameMenus() { GameMenu!.UpdateMenuItemState(isInGame, isMulti); + if (MainMenuOverridePanel != null) + Singleton().PostMessage(MainMenuOverridePanel, new KeyValues("UpdateMenu"), null); + InvalidateLayout(); GameMenu!.SetVisible(true); } diff --git a/Game.UI/GameUI.cs b/Game.UI/GameUI.cs index 6dca43f83..3e83c0669 100644 --- a/Game.UI/GameUI.cs +++ b/Game.UI/GameUI.cs @@ -137,10 +137,10 @@ public void RunFrame() { staticPanel.RunFrame(); } - public void SetMainMenuOverride(IPanel panel) { - //BasePanel? basePanel = BasePanel(); - //if (basePanel != null) - // basePanel.SetMainMenuOverride(panel); // todo + public void SetMainMenuOverride(IPanel? panel) { + BasePanel? basePanel = BasePanel(); + if (basePanel != null) + basePanel.SetMainMenuOverride(panel); } public bool SetShowProgressText(bool show) { diff --git a/Source.Common/GameUI/IGameUI.cs b/Source.Common/GameUI/IGameUI.cs index 25df639ca..76b6290ac 100644 --- a/Source.Common/GameUI/IGameUI.cs +++ b/Source.Common/GameUI/IGameUI.cs @@ -32,7 +32,7 @@ public interface IGameUI public void OnConfirmQuit(); public bool IsMainMenuVisible(); - public void SetMainMenuOverride(IPanel panel); + public void SetMainMenuOverride(IPanel? panel); bool IsInLevel(); bool IsInReplay(); bool IsConsoleUI(); diff --git a/Source.Common/GarrysMod/IGarrysMod.cs b/Source.Common/GarrysMod/IGarrysMod.cs index ceeeec93b..f26c93632 100644 --- a/Source.Common/GarrysMod/IGarrysMod.cs +++ b/Source.Common/GarrysMod/IGarrysMod.cs @@ -2,6 +2,7 @@ public interface IGarrysMod : IGameEventListener2 { + void Update(); void MD5String(Span outMD5, ReadOnlySpan unk1, ReadOnlySpan unk2, ReadOnlySpan unk3); void PlaySound(ReadOnlySpan sound); ReadOnlySpan GetMapName(); diff --git a/Source.Engine/Host.cs b/Source.Engine/Host.cs index 2c6d421fe..b19964d13 100644 --- a/Source.Engine/Host.cs +++ b/Source.Engine/Host.cs @@ -555,6 +555,9 @@ public void Init(bool dedicated) { Scr = engineAPI.InitSubsystem()!; Render = engineAPI.InitSubsystem()!; // engineAPI.InitSubsystem(); +#if GMOD_DLL + get.MenuSystem()?.StartLua(); +#endif } else { cl.SignOnState = SignOnState.None; From 8093bbc91721e3281d2f2a02622fc2e2dda81c3d Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:22:34 -0700 Subject: [PATCH 11/38] Further work needed for menusystem --- Game.Client/GarrysMod/LuaGui.cs | 139 +++++- Game.Client/GarrysMod/LuaPanel.cs | 445 ++++++++++++++++++++ Game.Client/GarrysMod/LuaRender.cs | 89 +++- Game.MenuSystem/LuaMenuGlobals.cs | 72 ++++ Game.Shared/GarrysMod/LuaConVar.cs | 3 + Game.Shared/GarrysMod/LuaEngine.cs | 89 +++- Game.Shared/GarrysMod/LuaGlobalFunctions.cs | 209 ++++++++- Game.Shared/GarrysMod/LuaMaterial.cs | 69 ++- Game.Shared/GarrysMod/LuaSystem.cs | 57 ++- Game.Shared/GarrysMod/LuaTexture.cs | 60 +++ Game.Shared/GarrysMod/LuaUtil.cs | 440 +++++++++++++++++++ Game.UI/BasePanel.cs | 2 +- Game.UI/GameUI.cs | 4 + Source.Common/Client/IEngineClient.cs | 3 + Source.Common/Engine/IEngineVGui.cs | 1 + Source.Common/GameUI/IGameUI.cs | 1 + Source.Engine/CdllEngineInterface.cs | 6 +- Source.Engine/Host.cs | 22 +- Source.Engine/VGuiBaseUIInterface.cs | 2 + Source.GUI.Controls/RichText.cs | 90 +++- Source.GUI.Controls/TextEntry.cs | 15 +- 21 files changed, 1777 insertions(+), 41 deletions(-) create mode 100644 Game.MenuSystem/LuaMenuGlobals.cs diff --git a/Game.Client/GarrysMod/LuaGui.cs b/Game.Client/GarrysMod/LuaGui.cs index 793f34ee2..8122b800e 100644 --- a/Game.Client/GarrysMod/LuaGui.cs +++ b/Game.Client/GarrysMod/LuaGui.cs @@ -1,5 +1,8 @@ using Source.Common.GarrysMod.Lua; +using Source.Common.GUI; +using Source.Common.Input; + using System.Numerics; #if MENU_DLL @@ -75,17 +78,117 @@ static void SetMousePos([LuaGet] int x, [LuaGet] int y) { vguiInput.SetCursorPos(x, y); } - // todo: ScreenToVector - // todo: InternalCursorMoved - // todo: InternalMousePressed - // todo: InternalMouseDoublePressed - // todo: InternalMouseReleased - // todo: InternalMouseWheeled - // todo: InternalKeyCodePressed - // todo: InternalKeyCodeTyped - // todo: InternalKeyTyped - // todo: InternalKeyCodeReleased - // todo: OpenURL +#if MENU_DLL + static bool CanInjectInput() { + IPanel? focus = vguiInput.GetFocus(); + if (focus == null) + return true; + return focus.IsVisible(); + } + + [LuaFunction] + static int InternalCursorMoved(ILuaInterface lua) { + if (!enginevgui.IsGameUIVisible() && CanInjectInput()) { + int y = (int)lua.CheckNumber(2); + vguiInput.InternalCursorMoved((int)lua.CheckNumber(1), y); + } + return 0; + } + + [LuaFunction] + static int InternalMousePressed(ILuaInterface lua) { + if (!enginevgui.IsGameUIVisible() && CanInjectInput()) { + ButtonCode code = (ButtonCode)(int)lua.CheckNumber(1); + vguiInput.SetMouseCodeState(code, MouseCodeState.Pressed); + vguiInput.InternalMousePressed(code); + } + return 0; + } + + [LuaFunction] + static int InternalMouseDoublePressed(ILuaInterface lua) { + if (!enginevgui.IsGameUIVisible() && CanInjectInput()) + vguiInput.InternalMouseDoublePressed((ButtonCode)(int)lua.CheckNumber(1)); + return 0; + } + + [LuaFunction] + static int InternalMouseReleased(ILuaInterface lua) { + if (!enginevgui.IsGameUIVisible() && CanInjectInput()) { + ButtonCode code = (ButtonCode)(int)lua.CheckNumber(1); + vguiInput.SetMouseCodeState(code, MouseCodeState.Released); + vguiInput.InternalMouseReleased(code); + } + return 0; + } + + [LuaFunction] + static int InternalMouseWheeled(ILuaInterface lua) { + if (!enginevgui.IsGameUIVisible() && CanInjectInput()) + vguiInput.InternalMouseWheeled((int)lua.CheckNumber(1)); + return 0; + } + + [LuaFunction] + static int InternalKeyCodePressed(ILuaInterface lua) { + if (!enginevgui.IsGameUIVisible() && CanInjectInput()) + vguiInput.InternalKeyCodePressed((ButtonCode)(int)lua.CheckNumber(1)); + return 0; + } + + [LuaFunction] + static int InternalKeyCodeTyped(ILuaInterface lua) { + if (!enginevgui.IsGameUIVisible() && CanInjectInput()) + vguiInput.InternalKeyCodeTyped((ButtonCode)(int)lua.CheckNumber(1)); + return 0; + } + + [LuaFunction] + static int InternalKeyTyped(ILuaInterface lua) { + if (!enginevgui.IsGameUIVisible() && CanInjectInput()) + vguiInput.InternalKeyTyped((char)(int)lua.CheckNumber(1)); + return 0; + } + + [LuaFunction] + static int InternalKeyCodeReleased(ILuaInterface lua) { + if (!enginevgui.IsGameUIVisible() && CanInjectInput()) + vguiInput.InternalKeyCodeReleased((ButtonCode)(int)lua.CheckNumber(1)); + return 0; + } + + public static void OpenURLExternal(string url) { + if (url.Length > 0x200) + return; + if (url.Contains('\n') || url.Contains('\r')) + return; + if (!url.StartsWith("http://") && !url.StartsWith("https://")) + return; + + if (Steamworks.SteamUtils.IsOverlayEnabled()) { + Steamworks.SteamFriends.ActivateGameOverlayToWebPage(url); + return; + } + + if (g_Lua == null || g_Lua.Global() == null) + return; + + LuaObject func = new(); + g_Lua.Global().GetMember("GMOD_OpenURLNoOverlay", func); + if (func.isFunction()) { + func.Push(); + g_Lua.PushString(url); + g_Lua.CallInternalNoReturns(1); + } + func.UnReference(); + } + + [LuaFunction] + static int OpenURL(ILuaInterface lua) { + OpenURLExternal(lua.CheckString(1).ToString()); + return 0; + } +#endif [LuaFunction] static bool IsGameUIVisible() => enginevgui.IsGameUIVisible(); @@ -99,6 +202,18 @@ static void ActivateGameUI() { engine.ClientCmd_Unrestricted("gameui_activate"); } - // todo: HideGameUI +#if MENU_DLL + [LuaFunction] + static int ShowConsole(ILuaInterface lua) { + enginevgui.ShowConsole(); + return 0; + } + + [LuaFunction] + static int HideGameUI(ILuaInterface lua) { + engine.ClientCmd_Unrestricted("gameui_hide"); + return 0; + } +#endif // todo: AddCaption } diff --git a/Game.Client/GarrysMod/LuaPanel.cs b/Game.Client/GarrysMod/LuaPanel.cs index 994d8f547..2c2ef5e58 100644 --- a/Game.Client/GarrysMod/LuaPanel.cs +++ b/Game.Client/GarrysMod/LuaPanel.cs @@ -205,6 +205,7 @@ static int Panel__ParentToHUD(ILuaInterface lua) { #endif [LuaMethod] + [LuaMethod("Valid")] static int Panel__IsValid(ILuaInterface lua) { Panel? panel = Get_Panel(1); lua.PushBool(panel != null && (!panel.IsMarkedForDeletion() || panel.RunningOnRemove)); @@ -1246,4 +1247,448 @@ static void Panel__SetCursor(Panel panel, [LuaGet] string? name) { else panel.SetCursor(stricmp(name, "up") == 0 ? CursorCode.Up : CursorCode.None); } + + static Panel? GetPanelOrError(ILuaInterface lua) { + Panel? panel = Get_Panel(1); + if (panel == null) + lua.Error("Tried to use a NULL Panel!"); + return panel; + } + + [LuaMethod] + static int Panel____gc(ILuaInterface lua) { + Panel? panel = Get_Panel(1); + if (panel != null) { + lua.ReleaseUserTypeObject(panel); + panel.LuaHandle = false; + } + lua.SetUserType(1, 0); + return 0; + } + + [LuaMethod] + static int Panel____eq(ILuaInterface lua) { + lua.PushBool(Get_Panel(1) == Get_Panel(2)); + return 1; + } + + [LuaMethod] + static int Panel__DoModal(ILuaInterface lua) { + GetPanelOrError(lua)?.DoModal(); + return 0; + } + + [LuaMethod] + static int Panel__LoadControlsFromString(ILuaInterface lua) { + lua.ErrorFromLua("Panel:LoadControlsFromString is deprecated. Do not use it."); + return 0; + } + + [LuaMethod] + static int Panel__LoadControlsFromFile(ILuaInterface lua) { + lua.ErrorFromLua("Panel:LoadControlsFromFile is deprecated. Do not use it."); + return 0; + } + + [LuaMethod] + static int Panel__GetFGColor(ILuaInterface lua) { + Panel? panel = GetPanelOrError(lua); + if (panel == null) + return 0; + lua.PushColor(panel.GetFgColor()); + return 1; + } + + [LuaMethod] + static int Panel__GetBGColor(ILuaInterface lua) { + Panel? panel = GetPanelOrError(lua); + if (panel == null) + return 0; + lua.PushColor(panel.GetBgColor()); + return 1; + } + + [LuaMethod] + static int Panel__KillFocus(ILuaInterface lua) { + Panel? panel = GetPanelOrError(lua); + if (panel != null && panel.HasFocus()) + panel.OnKillFocus(null); + return 0; + } + + [LuaMethod] + static int Panel__FocusNext(ILuaInterface lua) { + GetPanelOrError(lua)?.RequestFocusNext(); + return 0; + } + + [LuaMethod] + static int Panel__FocusPrevious(ILuaInterface lua) { + GetPanelOrError(lua)?.RequestFocusPrev(); + return 0; + } + + [LuaMethod] + static int Panel__GetBounds(ILuaInterface lua) { + Panel? panel = GetPanelOrError(lua); + if (panel == null) + return 0; + panel.GetBounds(out int x, out int y, out int w, out int h); + lua.PushNumber(x); + lua.PushNumber(y); + lua.PushNumber(w); + lua.PushNumber(h); + return 4; + } + + [LuaMethod] + static int Panel__SetAchievement(ILuaInterface lua) { + GetPanelOrError(lua); + return 0; + } + + [LuaMethod] + static int Panel__LoadTGAImage(ILuaInterface lua) { + GetPanelOrError(lua); + return 0; + } + + [LuaMethod] + static int Panel__SetURL(ILuaInterface lua) { + if (GetPanelOrError(lua) is URLLabel label) + label.SetURL(lua.GetString(2)); + return 0; + } + + [LuaMethod] + static int Panel__Find(ILuaInterface lua) { + Panel? panel = GetPanelOrError(lua); + if (panel == null) + return 0; + Panel? child = panel.FindChildByName(lua.CheckString(2), false); + if (child == null || !child.LuaPanel) + return 0; + Push_Panel(child); + return 1; + } + + [LuaMethod] + static int Panel__InsertClickableTextStart(ILuaInterface lua) { + if (GetPanelOrError(lua) is RichText richText) + richText.InsertClickableTextStart(lua.GetString(2)); + return 0; + } + + [LuaMethod] + static int Panel__InsertClickableTextEnd(ILuaInterface lua) { + if (GetPanelOrError(lua) is RichText richText) + richText.InsertClickableTextEnd(); + return 0; + } + + [LuaMethod] + static int Panel__InsertFade(ILuaInterface lua) { + if (GetPanelOrError(lua) is RichText richText) + richText.InsertFade((float)lua.GetNumber(2), (float)lua.GetNumber(3)); + return 0; + } + + [LuaMethod] + static int Panel__ResetAllFades(ILuaInterface lua) { + if (GetPanelOrError(lua) is RichText richText) + richText.ResetAllFades(lua.GetBool(2), lua.GetBool(3), lua.GetNumber(4)); + return 0; + } + + [LuaMethod] + static int Panel__SetToFullHeight(ILuaInterface lua) { + if (GetPanelOrError(lua) is RichText richText) + richText.SetToFullHeight(); + return 0; + } + + [LuaMethod] + static int Panel__InsertColorChange(ILuaInterface lua) { + if (GetPanelOrError(lua) is not RichText richText) + return 0; + int a = (int)lua.CheckNumber(5); + int b = (int)lua.CheckNumber(4); + int g = (int)lua.CheckNumber(3); + int r = (int)lua.CheckNumber(2); + richText.InsertColorChange(new Color((byte)r, (byte)g, (byte)b, (byte)a)); + return 0; + } + + [LuaMethod] + static int Panel__SetTextSelectionColors(ILuaInterface lua) { + if (GetPanelOrError(lua) is TextEntry textEntry) { + textEntry.SetSelectionTextColor(lua.GetColor(2)); + textEntry.SetSelectionBgColor(lua.GetColor(3)); + } + return 0; + } + + [LuaMethod] + static int Panel__AppendText(ILuaInterface lua) { + if (GetPanelOrError(lua) is RichText richText) + richText.InsertString(lua.GetString(2)); + return 0; + } + + [LuaMethod] + static int Panel__GotoTextStart(ILuaInterface lua) { + if (GetPanelOrError(lua) is RichText richText) + richText.GotoTextStart(); + return 0; + } + + [LuaMethod] + static int Panel__GotoTextEnd(ILuaInterface lua) { + if (GetPanelOrError(lua) is RichText richText) + richText.GotoTextEnd(); + return 0; + } + + [LuaMethod] + static int Panel__GetNumLines(ILuaInterface lua) { + Panel? panel = GetPanelOrError(lua); + if (panel is RichText richText) { + lua.PushNumber(richText.GetNumLines()); + return 1; + } + if (panel is TextEntry textEntry) { + lua.PushNumber(textEntry.GetNumLines()); + return 1; + } + return 0; + } + + [LuaMethod] + static int Panel__GetLineHeight(ILuaInterface lua) { + if (GetPanelOrError(lua) is not RichText richText) + return 0; + lua.PushNumber(richText.GetLineHeight()); + return 1; + } + + [LuaMethod] + static int Panel__SetLineHeight(ILuaInterface lua) { + if (GetPanelOrError(lua) is RichText richText) + richText.LineHeight = (short)(int)lua.GetNumber(2); + return 0; + } + + [LuaMethod] + static int Panel__AppendTextWithURLs(ILuaInterface lua) { + if (GetPanelOrError(lua) is RichText richText) + richText.InsertPossibleURLString(lua.GetString(2), lua.GetColor(3), lua.GetColor(4)); + return 0; + } + + [LuaMethod] + static int Panel__SetMaximumCharCount(ILuaInterface lua) { + Panel? panel = GetPanelOrError(lua); + if (panel is TextEntry textEntry) + textEntry.SetMaximumCharCount((int)lua.GetNumber(2)); + else if (panel is RichText richText) + richText.SetMaximumCharCount((int)lua.GetNumber(2)); + return 0; + } + + [LuaMethod] + static int Panel__GetMaximumCharCount(ILuaInterface lua) { + Panel? panel = GetPanelOrError(lua); + if (panel is TextEntry textEntry) { + lua.PushNumber(textEntry.GetMaximumCharCount()); + return 1; + } + if (panel is RichText richText) { + lua.PushNumber(richText.GetMaximumCharCount()); + return 1; + } + return 0; + } + + [LuaMethod] + static int Panel__GetSelectedTextRange(ILuaInterface lua) { + Panel? panel = GetPanelOrError(lua); + if (panel is TextEntry textEntry) { + textEntry.GetSelectedRange(out int start, out int end); + lua.PushNumber(start); + lua.PushNumber(end); + return 2; + } + if (panel is RichText richText) { + richText.GetSelectedRange(out int start, out int end); + lua.PushNumber(start); + lua.PushNumber(end); + return 2; + } + return 0; + } + + [LuaMethod] + static int Panel__SetUnderlineFont(ILuaInterface lua) { + if (GetPanelOrError(lua) is RichText richText) + richText.SetUnderlineFont(LuaFonts.GetFont(lua.GetString(2))); + return 0; + } + + [LuaMethod] + static int Panel__GetFont(ILuaInterface lua) { + Panel? panel = GetPanelOrError(lua); + IFont? font = panel switch { + Label label => label.GetFont(), + TextEntry textEntry => textEntry.GetFont(), + RichText richText => richText.GetFont(), + _ => null + }; + if (font == null) + return 0; + lua.PushString(Surface.GetFontName(font)); + return 1; + } + + [LuaMethod] + static int Panel__GetTextInset(ILuaInterface lua) { + if (GetPanelOrError(lua) is not Label label) + return 0; + label.GetTextInset(out int x, out int y); + lua.PushNumber(x); + lua.PushNumber(y); + return 2; + } + + [LuaMethod] + static int Panel__SetDrawLanguageIDAtLeft(ILuaInterface lua) { + if (GetPanelOrError(lua) is TextEntry textEntry) + textEntry.SetDrawLanguageIDAtLeft(lua.GetBool(2)); + return 0; + } + + [LuaMethod] + static int Panel__SetDrawLanguageID(ILuaInterface lua) { + if (GetPanelOrError(lua) is TextEntry textEntry) + textEntry.SetDrawLanguageID(lua.GetBool(2)); + return 0; + } + + [LuaMethod] + static int Panel__SelectAllOnFocus(ILuaInterface lua) { + if (GetPanelOrError(lua) is TextEntry textEntry) + textEntry.SelectAllOnFocusAlways(true); + return 0; + } + + [LuaMethod] + static int Panel__SelectAll(ILuaInterface lua) { + Panel? panel = GetPanelOrError(lua); + if (panel is TextEntry textEntry) + textEntry.SelectAllText(false); + else if (panel is RichText richText) + richText.SelectAllText(); + return 0; + } + + [LuaMethod] + static int Panel__SelectAllText(ILuaInterface lua) { + if (GetPanelOrError(lua) is TextEntry textEntry) + textEntry.SelectAllText(lua.GetBool(2)); + return 0; + } + + [LuaMethod] + static int Panel__SelectNone(ILuaInterface lua) { + Panel? panel = GetPanelOrError(lua); + if (panel is TextEntry textEntry) + textEntry.SelectNone(); + else if (panel is RichText richText) + richText.SelectNone(); + return 0; + } + + [LuaMethod] + static int Panel__CutSelected(ILuaInterface lua) { + Panel? panel = GetPanelOrError(lua); + if (panel is TextEntry textEntry) + textEntry.CutSelected(); + else if (panel is RichText richText) + richText.CutSelected(); + return 0; + } + + [LuaMethod] + static int Panel__CopySelected(ILuaInterface lua) { + Panel? panel = GetPanelOrError(lua); + if (panel is TextEntry textEntry) + textEntry.CopySelected(); + else if (panel is RichText richText) + richText.CopySelected(); + return 0; + } + + [LuaMethod] + static int Panel__Paste(ILuaInterface lua) { + if (GetPanelOrError(lua) is TextEntry textEntry) + textEntry.Paste(); + return 0; + } + + [LuaMethod] + static int Panel__Undo(ILuaInterface lua) { + if (GetPanelOrError(lua) is TextEntry textEntry) + textEntry.Undo(); + return 0; + } + + [LuaMethod] + static int Panel__SaveUndoState(ILuaInterface lua) { + if (GetPanelOrError(lua) is TextEntry textEntry) + textEntry.SaveUndoState(); + return 0; + } + + [LuaMethod] + static int Panel__IsMultiline(ILuaInterface lua) { + if (GetPanelOrError(lua) is not TextEntry textEntry) + return 0; + lua.PushBool(textEntry.IsMultiline()); + return 1; + } + + [LuaMethod] + static int Panel__GetScrollStartIndexes(ILuaInterface lua) { + if (GetPanelOrError(lua) is not TextEntry textEntry) + return 0; + lua.PushNumber(textEntry.GetCurrentStartIndex()); + lua.PushNumber(textEntry.GetCurrentStartLine()); + return 2; + } + + [LuaMethod] + static int Panel__SetTextHidden(ILuaInterface lua) { + if (GetPanelOrError(lua) is TextEntry textEntry) + textEntry.SetTextHidden(lua.GetBool(2)); + return 0; + } + + [LuaMethod] + static int Panel__SetPopupStayAtBack(ILuaInterface lua) { + Panel? panel = GetPanelOrError(lua); + if (panel != null && lua.GetBool(2)) + Surface.MovePopupToBack(panel); + return 0; + } + + [LuaMethod] + static int Panel__AddText(ILuaInterface lua) => 0; + +#if MENU_DLL + [LuaMethod] + static int Panel__SetOpenLinksExternally(ILuaInterface lua) { + if (GetPanelOrError(lua) is HtmlPanel html) + html.SetOpenLinksExternally(lua.GetBool(2)); + return 0; + } +#endif } diff --git a/Game.Client/GarrysMod/LuaRender.cs b/Game.Client/GarrysMod/LuaRender.cs index b7292f070..35647c517 100644 --- a/Game.Client/GarrysMod/LuaRender.cs +++ b/Game.Client/GarrysMod/LuaRender.cs @@ -568,8 +568,28 @@ static int SetViewPort(ILuaInterface lua) { renderContext.Viewport((int)x, (int)y, (int)w, (int)h); return 0; } - // todo: Clear - // todo: ClearDepth + [LuaFunction] + static int Clear(ILuaInterface lua) { + int r = (int)lua.CheckNumber(1); + int g = (int)lua.CheckNumber(2); + int b = (int)lua.CheckNumber(3); + int a = (int)lua.CheckNumber(4); + bool depth = lua.GetBool(5); + bool stencil = lua.GetBool(6); + using MatRenderContextPtr renderContext = new(materials); + renderContext.ClearColor3ub((byte)r, (byte)g, (byte)b); + renderContext.ClearColor4ub((byte)r, (byte)g, (byte)b, (byte)a); + renderContext.ClearBuffers(true, depth, stencil); + return 0; + } + + [LuaFunction] + static int ClearDepth(ILuaInterface lua) { + bool stencil = lua.GetType(1) == (int)LuaType.Nil || lua.GetBool(1); + using MatRenderContextPtr renderContext = new(materials); + renderContext.ClearBuffers(false, true, stencil); + return 0; + } // todo: RenderView // todo: GetViewSetup // todo: RenderHUD @@ -865,8 +885,69 @@ static int OverrideColorWriteEnable(ILuaInterface lua) { return 0; } - // todo: OverrideBlend - // todo: OverrideBlendFunc + [LuaFunction] + static int OverrideBlend(ILuaInterface lua) { + using (MatRenderContextPtr renderContext = new(materials)) { + renderContext.OverrideBlend(false, true, -1, -1, -1); + renderContext.OverrideBlendSeparateAlpha(false, true, -1, -1, -1); + } + + if (!lua.GetBool(1)) + return 0; + + int top = lua.Top(); + bool color = false, alpha = false; + int src = -1, dst = -1, op = -1, srcAlpha = -1, dstAlpha = -1, opAlpha = -1; + if (top > 1) { + color = true; + src = (int)lua.CheckNumber(2); + dst = (int)lua.CheckNumber(3); + op = (int)lua.CheckNumber(4); + } + if (top > 4) { + alpha = true; + srcAlpha = (int)lua.CheckNumber(5); + dstAlpha = (int)lua.CheckNumber(6); + opAlpha = (int)lua.CheckNumber(7); + } + + using (MatRenderContextPtr renderContext = new(materials)) { + renderContext.OverrideBlend(true, color, src, dst, op); + renderContext.OverrideBlendSeparateAlpha(true, alpha, srcAlpha, dstAlpha, opAlpha); + } + return 0; + } + + [LuaFunction] + static int OverrideBlendFunc(ILuaInterface lua) { + using (MatRenderContextPtr renderContext = new(materials)) { + renderContext.OverrideBlend(false, true, -1, -1, -1); + renderContext.OverrideBlendSeparateAlpha(false, true, -1, -1, -1); + } + + if (!lua.GetBool(1)) + return 0; + + int top = lua.Top(); + bool color = false, alpha = false; + int src = -1, dst = -1, srcAlpha = -1, dstAlpha = -1; + if (top > 1) { + color = true; + src = (int)lua.CheckNumber(2); + dst = (int)lua.CheckNumber(3); + } + if (top > 3) { + alpha = true; + srcAlpha = (int)lua.CheckNumber(4); + dstAlpha = (int)lua.CheckNumber(5); + } + + using (MatRenderContextPtr renderContext = new(materials)) { + renderContext.OverrideBlend(true, color, src, dst, -1); + renderContext.OverrideBlendSeparateAlpha(true, alpha, srcAlpha, dstAlpha, -1); + } + return 0; + } #if !MENU_DLL [LuaFunction] diff --git a/Game.MenuSystem/LuaMenuGlobals.cs b/Game.MenuSystem/LuaMenuGlobals.cs new file mode 100644 index 000000000..4bc187ee2 --- /dev/null +++ b/Game.MenuSystem/LuaMenuGlobals.cs @@ -0,0 +1,72 @@ +#if MENU_DLL +using Source; +using Source.Common.GarrysMod.Lua; +using Source.Common.Launcher; + +namespace Game.MenuSystem.GarrysMod; + +public static partial class LuaMenuGlobals +{ + [LuaGlobal] + static int GetAddonStatus(ILuaInterface lua) { + lua.PushBool(commandLine.FindParm("-noaddons") == 0); + lua.PushBool(commandLine.FindParm("-noworkshop") == 0); + return 2; + } + + [LuaGlobal] + static int GetDefaultLoadingHTML(ILuaInterface lua) { + lua.PushString("asset://garrysmod/html/loading.html"); + return 1; + } + + [LuaGlobal] + static int GetOverlayPanel(ILuaInterface lua) { + LuaVGUI.Push_Panel(MenuPanels.GetOverlayPanel()); + return 1; + } + + [LuaGlobal] + static int IsHostingGame(ILuaInterface lua) { + lua.PushBool(engine.IsHostingGame()); + return 1; + } + + [LuaGlobal] + static int IsInGame(ILuaInterface lua) { + lua.PushBool(engine.IsInGame()); + return 1; + } + + [LuaGlobal] + static int JoinServer(ILuaInterface lua) { + string? address = lua.CheckString(1); + if (address == null || address.Contains(';')) + return 0; + string command = $"connect {address} serverbrowser\n"; + if (command.Length > 255) + command = command[..255]; + engine.ClientCmd(command); + return 0; + } + + [LuaGlobal] + static int OpenFolder(ILuaInterface lua) { + string name = lua.CheckString(1); + if (name != "saves" && name != "demos" && name != "dupes") + return 0; + + Span path = stackalloc char[512]; + ReadOnlySpan fullPath = filesystem.RelativePathToFullPath(name, "MOD", path); + if (!fullPath.IsEmpty) + Singleton().ShellExecute("open", fullPath); + return 0; + } + + [LuaGlobal] + static int RunGameUICommand(ILuaInterface lua) { + gameUI.SendMainMenuCommand(lua.CheckString(1)); + return 0; + } +} +#endif diff --git a/Game.Shared/GarrysMod/LuaConVar.cs b/Game.Shared/GarrysMod/LuaConVar.cs index 3b901fbc9..18044a581 100644 --- a/Game.Shared/GarrysMod/LuaConVar.cs +++ b/Game.Shared/GarrysMod/LuaConVar.cs @@ -135,6 +135,9 @@ public static string ConVar__GetString(ConVar convar) { return (float)min; } +#if CLIENT_DLL || MENU_DLL + [LuaGlobal("GetConVar")] +#endif [LuaGlobal] static ConVar? GetConVar_Internal(string name) { if (!IsAllowedToGetConvarInfo(name) || stricmp("con_logfile", name) == 0) diff --git a/Game.Shared/GarrysMod/LuaEngine.cs b/Game.Shared/GarrysMod/LuaEngine.cs index 4ad11efde..86880b834 100644 --- a/Game.Shared/GarrysMod/LuaEngine.cs +++ b/Game.Shared/GarrysMod/LuaEngine.cs @@ -21,7 +21,7 @@ static int ActiveGamemode(ILuaInterface lua) { return 1; } -#if CLIENT_DLL +#if CLIENT_DLL || MENU_DLL [LuaFunction] static int IsRecordingDemo(ILuaInterface lua) { g_Lua!.PushBool(engine.IsRecordingDemo()); @@ -33,6 +33,93 @@ static int IsPlayingDemo(ILuaInterface lua) { g_Lua!.PushBool(engine.IsPlayingDemo()); return 1; } + + [LuaFunction] + static int GetDemoPlaybackTick(ILuaInterface lua) { + lua.PushNumber(engine.GetDemoPlaybackTick()); + return 1; + } + + [LuaFunction] + static int GetDemoPlaybackStartTick(ILuaInterface lua) { + lua.PushNumber(engine.GetDemoPlaybackStartTick()); + return 1; + } + + [LuaFunction] + static int GetDemoPlaybackTimeScale(ILuaInterface lua) { + lua.PushNumber(engine.GetDemoPlaybackTimeScale()); + return 1; + } + + [LuaFunction] + static int GetDemoPlaybackTotalTicks(ILuaInterface lua) { + lua.PushNumber(engine.GetDemoPlaybackTotalTicks()); + return 1; + } + + [LuaFunction] + static int TickInterval(ILuaInterface lua) { + lua.PushNumber(gpGlobals.IntervalPerTick); + return 1; + } + + [LuaFunction] + static int AbsoluteFrameTime(ILuaInterface lua) { + lua.PushNumber(gpGlobals.AbsoluteFrameTime); + return 1; + } + + [LuaFunction] + static int TickCount(ILuaInterface lua) { + lua.PushNumber(gpGlobals.TickCount); + return 1; + } + + [LuaFunction] + static int GetUserContent(ILuaInterface lua) { + LinkedList list = filesystem.Addons().GetUGCList(); + LuaTable table = new(null, (uint)list.Count); + int i = 1; + foreach (IAddonSystem.UGCInfo info in list) { + LuaTable entry = new(null, 0); + entry.SetMember("title", info.Title); + entry.SetMember("tags", info.Tags); + entry.SetMember("wsid", info.WorkshopID.ToString()); + entry.SetMember("timeadded", (double)info.TimeAdded); + entry.SetMember("type", info.Type switch { + Addon.AddonType.Dupe => "dupe", + Addon.AddonType.Save => "save", + Addon.AddonType.Demo => "demo", + _ => "unknown" + }); + table.SetMember((float)i, entry); + i++; + entry.UnReference(); + } + table.Push(); + table.UnReference(); + return 1; + } +#endif + +#if MENU_DLL + [LuaFunction] + static int SetMounted(ILuaInterface lua) { + bool mounted = lua.GetBool(2); + filesystem.Games().SetMount(new Steamworks.AppId_t((uint)(int)lua.CheckNumber(1)), mounted); + filesystem.Games().Save(); + filesystem.Games().Refresh(); + filesystem.DoFilesystemRefresh(); + return 0; + } + + [LuaFunction] + static int CurrentServerAddress(ILuaInterface lua) { + Source.Common.Networking.INetChannelInfo? channel = engine.GetNetChannelInfo(); + lua.PushString(channel == null ? "" : channel.GetAddress()); + return 1; + } #endif [LuaFunction] diff --git a/Game.Shared/GarrysMod/LuaGlobalFunctions.cs b/Game.Shared/GarrysMod/LuaGlobalFunctions.cs index e53491a21..a02d6e51e 100644 --- a/Game.Shared/GarrysMod/LuaGlobalFunctions.cs +++ b/Game.Shared/GarrysMod/LuaGlobalFunctions.cs @@ -1,4 +1,4 @@ -#if CLIENT_DLL || GAME_DLL || MENU_DLL +#if CLIENT_DLL || GAME_DLL || MENU_DLL using Source; using Source.Common.Commands; using Source.Common.Mathematics; @@ -326,7 +326,205 @@ static int MsgN(ILuaInterface lua) { } [LuaGlobal] - static int ErrorNoHalt(ILuaInterface lua) { + static int ErrorNoHalt(ILuaInterface lua) => ErrorNoHalt("ErrorNoHalt tostring ERROR"); + +#if CLIENT_DLL || MENU_DLL + [LuaGlobal] + static int Error(ILuaInterface lua) => ErrorNoHalt("Error() tostring ERROR"); + + [LuaGlobal] + static int ErrorNoHaltWithStack(ILuaInterface lua) { + int top = g_Lua!.Top(); + LuaObject tostring = new(); + g_Lua.Global().GetMember("tostring", tostring); + + StringBuilder buffer = new(); + for (int i = 1; i <= top; i++) { + LuaObject obj = new(i, LuaType.None); + tostring.Push(); + obj.Push(); + string str = g_Lua.CallInternalGetString(1) ?? "ErrorNoHaltWithStack tostring ERROR"; + buffer.Append(str.AsSpan(0, Math.Min(str.Length, Math.Max(0, 0x1000 - 1 - buffer.Length)))); + obj.UnReference(); + } + + g_Lua.ErrorFromLua(buffer.ToString()); + tostring.UnReference(); + return 0; + } + + [LuaGlobal] + static int DebugInfo(ILuaInterface lua) { + int pos = (int)lua.CheckNumber(1); + engine.Con_NPrintf(pos, lua.CheckString(2)); + return 0; + } + + [LuaGlobal] + static int IsConCommandBlocked(ILuaInterface lua) { + lua.PushBool(LuaConCommands.ConCommand_IsBlocked(lua.CheckString(1)) != null); + return 1; + } + + [LuaGlobal] + static int Localize(ILuaInterface lua) { + string token = "#" + lua.CheckString(1); + if (token.Length > 127) + token = token[..127]; + ReadOnlySpan localized = localize.Find(token); + if (!localized.IsEmpty) { + lua.PushString(localized); + return 1; + } + + lua.PushString(lua.CheckString(lua.GetType(2) == LuaType.String ? 2 : 1)); + return 1; + } + + [LuaGlobal] + [LuaGlobal("RunStringEx")] + static int RunString(ILuaInterface lua) { + string code = lua.CheckString(1); + string identifier = lua.CheckStringOpt(2, "RunString(Ex)"); + bool handleError = lua.GetType(3) == LuaType.Nil || lua.GetBool(3); + if (lua.RunStringEx(identifier, "", code, true, handleError, handleError, true)) + return 0; + return handleError ? 0 : 1; + } + + [LuaGlobal] + static int SetClipboardText(ILuaInterface lua) { + string text = lua.CheckString(1); + if (System.Text.Encoding.UTF8.GetByteCount(text) + 1 >= 0x100000) + return 0; + Singleton().SetClipboardText(text); + return 0; + } + + public static void RGBToHSL(int r, int g, int b, out float h, out float s, out float l) { + int max = b, min = b; + if (r > g) { + if (r > b) + max = r; + if (g < b) + min = g; + } + else { + if (g > b) + max = g; + if (r < b) + min = r; + } + + int sum = min + max; + l = (float)(sum * 0.5); + if (max == min) { + h = 0.0f; + s = 0.0f; + } + else { + float delta = max - min; + s = delta * 255.0f; + if (l >= 128.0f) + s /= 511 - min - max; + else + s /= sum; + + if (r == max) + h = (g - b) / delta; + else { + float inv = 1.0f / delta; + if (g == max) + h = (b - r) * inv + 2.0f; + else + h = (r - g) * inv + 4.0f; + } + + h *= 42.5f; + if (h < 0.0f) + h += 255.0f; + else if (h > 255.0f) + h += -255.0f; + } + + h *= 1.4117647f; + s *= 0.003921569f; + l *= 0.003921569f; + } + + public static Color HSLToColor(float hue, float saturation, float lightness) { + float hh = (float)(hue % 360.0); + float r, g, b; + if (hh < 120.0f) { + r = (120.0f - hh) * 0.016666668f; + g = hh * 0.016666668f; + b = 0.0f; + } + else if (hh < 240.0f) { + r = 0.0f; + g = (240.0f - hh) * 0.016666668f; + b = (hh - 120.0f) * 0.016666668f; + } + else { + r = (hh - 240.0f) * 0.016666668f; + g = 0.0f; + b = (360.0f - hh) * 0.016666668f; + } + + float twoS = saturation + saturation; + float oneMinusS = 1.0f - saturation; + r = Math.Min(r, 1.0f) * twoS + oneMinusS; + g = Math.Min(g, 1.0f) * twoS + oneMinusS; + b = Math.Min(b, 1.0f) * twoS + oneMinusS; + + if (lightness < 0.5f) { + float scale = lightness * 255.0f; + r *= scale; + g *= scale; + b *= scale; + } + else { + float oneMinusL = 1.0f - lightness; + float twoL = lightness + lightness; + r = (r * oneMinusL + twoL - 1.0f) * 255.0f; + g = (g * oneMinusL + twoL - 1.0f) * 255.0f; + b = (b * oneMinusL + twoL - 1.0f) * 255.0f; + } + + return new Color((byte)(int)r, (byte)(int)g, (byte)(int)b, 255); + } + + [LuaGlobal] + static int HSLToColor(ILuaInterface lua) { + float lightness = (float)lua.CheckNumber(3); + float saturation = (float)lua.CheckNumber(2); + float hue = (float)lua.CheckNumber(1); + lua.PushColor(HSLToColor(hue, saturation, lightness)); + return 1; + } + + [LuaGlobal] + static int ColorToHSL(ILuaInterface lua) { + LuaTable color = new(null, 0); + color.SetFromStack(1); + if (!color.isTable()) { + lua.TypeError("table", 1); + color.UnReference(); + return 0; + } + int b = (int)color.GetMemberFloat("b", 255.0f); + int g = (int)color.GetMemberFloat("g", 255.0f); + int r = (int)color.GetMemberFloat("r", 255.0f); + RGBToHSL(r, g, b, out float h, out float s, out float l); + lua.PushNumber(h); + lua.PushNumber(s); + lua.PushNumber(l); + color.UnReference(); + return 3; + } +#endif + + static int ErrorNoHalt(string toStringError) { int top = g_Lua!.Top(); LuaObject tostring = new(); g_Lua.Global().GetMember("tostring", tostring); @@ -336,7 +534,7 @@ static int ErrorNoHalt(ILuaInterface lua) { LuaObject obj = new(i, LuaType.None); tostring.Push(); obj.Push(); - string str = g_Lua.CallInternalGetString(1) ?? "ErrorNoHalt tostring ERROR"; + string str = g_Lua.CallInternalGetString(1) ?? toStringError; buffer.Append(str.AsSpan(0, Math.Min(str.Length, Math.Max(0, 0x1000 - 1 - buffer.Length)))); obj.UnReference(); } @@ -395,6 +593,9 @@ static int IsType(LuaType type) { [LuaGlobal] static int isstring(ILuaInterface lua) => IsType(LuaType.String); [LuaGlobal] static int istable(ILuaInterface lua) => IsType(LuaType.Table); [LuaGlobal] static int isfunction(ILuaInterface lua) => IsType(LuaType.Function); +#if MENU_DLL + [LuaGlobal("IsEntity")] +#endif [LuaGlobal] static int isentity(ILuaInterface lua) => IsType(LuaType.Entity); [LuaGlobal] static int isvector(ILuaInterface lua) => IsType(LuaType.Vector); [LuaGlobal] static int isangle(ILuaInterface lua) => IsType(LuaType.Angle); @@ -444,7 +645,7 @@ static double VGUIFrameTime() { #endif } -#if CLIENT_DLL +#if CLIENT_DLL || MENU_DLL [LuaGlobal] static int DisableClipping(ILuaInterface lua) { surface.GetClippingRect(out _, out _, out _, out _, out bool clippingDisabled); diff --git a/Game.Shared/GarrysMod/LuaMaterial.cs b/Game.Shared/GarrysMod/LuaMaterial.cs index 84c809849..888327085 100644 --- a/Game.Shared/GarrysMod/LuaMaterial.cs +++ b/Game.Shared/GarrysMod/LuaMaterial.cs @@ -408,6 +408,73 @@ static int IMaterial__SetString(ILuaInterface lua) { [LuaMethod] static int IMaterial__SetShader(ILuaInterface lua) => 0; + [LuaMethod] + static int IMaterial____gc(ILuaInterface lua) { + IMaterial? material = (IMaterial?)LC_IMaterial.Get(1); + if (material == null) + return 0; + material.DecrementReferenceCount(); + lua.SetUserType(1, 0); + return 0; + } + + [LuaMethod] + static int IMaterial____tostring(ILuaInterface lua) { + IMaterial? material = (IMaterial?)LC_IMaterial.Get(1); + if (material == null) + lua.PushString("Material [NULL]"); + else + lua.PushString($"Material [{material.GetName()}]"); + return 1; + } + + [LuaMethod] + static int IMaterial__GetColor4Part(ILuaInterface lua) { + IMaterial? material = (IMaterial?)LC_IMaterial.Get(1); + if (material == null) { + lua.Error("Tried to use a NULL IMaterial!"); + return 0; + } + + IMaterialVar var = material.FindVar("$basetexture", out bool found, false); + if (var == null || !found) + return 0; + + ITexture? texture = GetTextureValue(var); + if (texture == null) + return 0; + + Color color = default; + if (get.Resources() != null) + color = get.Resources()!.GetTextureColour(texture, (int)lua.CheckNumber(2), (int)lua.CheckNumber(3)); + lua.PushNumber(color.R); + lua.PushNumber(color.G); + lua.PushNumber(color.B); + lua.PushNumber(color.A); + return 4; + } + +#if MENU_DLL + [LuaMethod] + static int IMaterial__SetDynamicImage(ILuaInterface lua) { + IMaterial? material = (IMaterial?)LC_IMaterial.Get(1); + if (material == null) { + lua.Error("Tried to use a NULL IMaterial!"); + return 0; + } + + ReadOnlySpan url = lua.CheckString(2); + IMaterialVar var = material.FindVar("$basetexture", out _, true); + ITexture? texture = var?.GetTextureValue(); + if (texture == null) + return 0; + + get.Resources()!.SetImage(texture, url); + texture.Download(); + return 0; + } +#endif + [LuaMethod] static int IMaterial__Recompute(ILuaInterface lua) { IMaterial? material = (IMaterial?)LC_IMaterial.Get(1); @@ -453,7 +520,7 @@ static int IMaterial__GetKeyValues(ILuaInterface lua) { if (texture == null) lua.PushNil(); else - LuaTexture.LC_ITexture.Push(texture); + LuaTexture.Push(texture); break; } case MaterialVarType.Int: diff --git a/Game.Shared/GarrysMod/LuaSystem.cs b/Game.Shared/GarrysMod/LuaSystem.cs index 5aaccc5f3..abe9bba77 100644 --- a/Game.Shared/GarrysMod/LuaSystem.cs +++ b/Game.Shared/GarrysMod/LuaSystem.cs @@ -23,15 +23,54 @@ public static partial class LuaSystem [LuaFunction] static bool IsLinux() => OperatingSystem.IsLinux(); - // todo: HasFocus - // todo: BatteryPower - // todo: AppTime - // todo: UpTime - // todo: SteamTime - // todo: GetCountry -#if CLIENT_DLL - // todo: FlashWindow - // todo: IsWindowed +#if CLIENT_DLL || MENU_DLL + [LuaFunction] + static int HasFocus(ILuaInterface lua) { + lua.PushBool(engine.IsActiveApp()); + return 1; + } + + [LuaFunction] + static int BatteryPower(ILuaInterface lua) { + lua.PushNumber(Steamworks.SteamUtils.GetCurrentBatteryPower()); + return 1; + } + + [LuaFunction] + static int AppTime(ILuaInterface lua) { + lua.PushNumber(Steamworks.SteamUtils.GetSecondsSinceAppActive()); + return 1; + } + + [LuaFunction] + static int UpTime(ILuaInterface lua) { + lua.PushNumber(Steamworks.SteamUtils.GetSecondsSinceComputerActive()); + return 1; + } + + [LuaFunction] + static int SteamTime(ILuaInterface lua) { + lua.PushNumber(Steamworks.SteamUtils.GetServerRealTime()); + return 1; + } + + [LuaFunction] + static int GetCountry(ILuaInterface lua) { + lua.PushString(Steamworks.SteamUtils.GetIPCountry()); + return 1; + } + + [LuaFunction] + static int FlashWindow(ILuaInterface lua) { + engine.FlashWindow(); + return 0; + } + + [LuaFunction] + static int IsWindowed(ILuaInterface lua) { + lua.PushBool(engine.IsWindowedMode()); + return 1; + } #endif } #endif diff --git a/Game.Shared/GarrysMod/LuaTexture.cs b/Game.Shared/GarrysMod/LuaTexture.cs index dc30944d9..c72703d70 100644 --- a/Game.Shared/GarrysMod/LuaTexture.cs +++ b/Game.Shared/GarrysMod/LuaTexture.cs @@ -1,4 +1,5 @@ #if CLIENT_DLL || GAME_DLL || MENU_DLL +using Source; using Source.Common.GarrysMod.Lua; using Source.Common.MaterialSystem; @@ -28,5 +29,64 @@ public static void Push(ITexture? texture) { [LuaMethod] static string ITexture__GetName(ITexture texture) => new(texture.GetName()); + + [LuaMethod] + static int ITexture____gc(ILuaInterface lua) { + ITexture? texture = (ITexture?)LC_ITexture.Get(1); + if (texture == null) + return 0; + texture.DecrementReferenceCount(); + lua.SetUserType(1, 0); + return 0; + } + + [LuaMethod] + static int ITexture____tostring(ILuaInterface lua) { + ITexture? texture = (ITexture?)LC_ITexture.Get(1); + if (texture == null) + lua.PushString("Texture [NULL]"); + else + lua.PushString($"Texture [{texture.GetName()}]"); + return 1; + } + + [LuaMethod] + static int ITexture__GetMappingWidth(ITexture texture) => texture.GetMappingWidth(); + + [LuaMethod] + static int ITexture__GetMappingHeight(ITexture texture) => texture.GetMappingHeight(); + + [LuaMethod] + static bool ITexture__IsError(ITexture texture) => texture.IsError(); + + [LuaMethod] + static int ITexture__GetNumAnimationFrames(ITexture texture) => texture.GetNumAnimationFrames(); + + [LuaMethod] + static void ITexture__Download(ITexture texture) => texture.Download(); + + [LuaMethod] + static bool ITexture__IsErrorTexture(ITexture texture) { + TextureReference error = new(); + error.Init("error", "Other textures", true); + bool isError = error.Get() == texture; + error.Shutdown(); + return isError; + } + + [LuaMethod] + static int ITexture__GetColor(ILuaInterface lua) { + ITexture? texture = (ITexture?)LC_ITexture.Get(1); + if (texture == null) { + lua.Error("Tried to use a NULL ITexture!"); + return 0; + } + + Color color = default; + if (get.Resources() != null) + color = get.Resources()!.GetTextureColour(texture, (int)lua.CheckNumber(2), (int)lua.CheckNumber(3)); + lua.PushColor(color); + return 1; + } } #endif diff --git a/Game.Shared/GarrysMod/LuaUtil.cs b/Game.Shared/GarrysMod/LuaUtil.cs index 32875b256..46b6927c6 100644 --- a/Game.Shared/GarrysMod/LuaUtil.cs +++ b/Game.Shared/GarrysMod/LuaUtil.cs @@ -392,5 +392,445 @@ static int TraceLine(ILuaInterface lua) { return 1; } #endif +#if CLIENT_DLL || MENU_DLL + [LuaFunction] + static int KeyValuesToTablePreserveOrder(ILuaInterface lua) { + KeyValues kv = new("KeyValuesToTablePreserveOrder"); + kv.UsesEscapeSequences(lua.GetBool(2)); + kv.LoadFromBuffer("util.KeyValuesToTablePreserveOrder", lua.CheckString(1)); + LuaTable table = new(null, 0); + KeyValuesToTablePreserveOrder(kv, table, lua.GetBool(3)); + table.Push(); + table.UnReference(); + return 1; + } + + static void KeyValuesToTablePreserveOrder(KeyValues kv, LuaTable table, bool preserveKeyCase) { + int index = 1; + for (KeyValues? sub = kv.GetFirstSubKey(); sub != null; sub = sub.GetNextKey()) { + string name = sub.Name.Length > 511 ? sub.Name[..511] : sub.Name; + if (!preserveKeyCase) + name = name.ToLowerInvariant(); + + LuaTable entry = new(null, 0); + entry.SetMember("Key", name); + switch (sub.Type) { + case KeyValues.Types.Int: + entry.SetMember("Value", sub.GetInt()); + break; + case KeyValues.Types.Double: + entry.SetMember("Value", MathF.Floor(sub.GetFloat() * 10000.0f) / 10000.0f); + break; + case KeyValues.Types.None: { + LuaTable subTable = new(null, 0); + KeyValuesToTablePreserveOrder(sub, subTable, preserveKeyCase); + entry.SetMember("Value", subTable); + subTable.UnReference(); + break; + } + default: + entry.SetMember("Value", sub.GetString()); + break; + } + table.SetMember((float)index++, entry); + entry.UnReference(); + } + } + + static void TableToKeyValues(ILuaInterface lua, ILuaObject table, System.Text.StringBuilder output, string name, int depth) { + output.Append('\t', depth).Append('"').Append(name).Append("\"\n"); + output.Append('\t', depth).Append("{\n"); + + LuaObject key = new(); + LuaObject value = new(); + table.Push(); + lua.PushNil(); + while (lua.Next(-2)) { + value.SetFromStack(-1); + key.SetFromStack(-2); + lua.Pop(1); + string keyName = key.GetString() ?? ""; + if (value.isTable()) + TableToKeyValues(lua, value, output, keyName, depth + 1); + else + output.Append('\t', depth + 1).Append('"').Append(keyName).Append("\"\t\t\"").Append(value.GetString() ?? "").Append("\"\n"); + } + lua.Pop(1); + key.UnReference(); + value.UnReference(); + + output.Append('\t', depth).Append("}\n"); + } + + [LuaFunction] + static int TableToKeyValues(ILuaInterface lua) { + string name = lua.CheckStringOpt(2, "TableToKeyValues"); + ILuaObject? table = lua.GetObject(1); + if (table == null || !table.isTable()) { + lua.TypeError("table", 1); + return 0; + } + System.Text.StringBuilder output = new(); + TableToKeyValues(lua, table, output, name, 0); + lua.PushString(output.ToString()); + return 1; + } + + [LuaFunction] + static int Compress(ILuaInterface lua) { + if (lua.GetType(1) != LuaType.String) + lua.CheckString(1); + ReadOnlySpan data = lua.GetDataString(1); + if (data.IsEmpty) { + lua.PushString(""); + return 1; + } + using MemoryStream output = new(); + if (!Bootil.Compression.LZMA.Compress(data, output, 5, 0x10000)) + return 0; + lua.PushString(output.ToArray()); + return 1; + } + + [LuaFunction] + static int Decompress(ILuaInterface lua) { + if (lua.GetType(1) != LuaType.String) + lua.CheckString(1); + ReadOnlySpan data = lua.GetDataString(1); + if (data.IsEmpty) + return 0; + using MemoryStream output = new(); + if (!Bootil.Compression.LZMA.Extract(data, output)) + return 0; + lua.PushString(output.ToArray()); + return 1; + } + + [LuaFunction] + static int Base64Encode(ILuaInterface lua) { + if (lua.GetType(1) != LuaType.String) + lua.CheckString(1); + bool inline = lua.GetType(2) != LuaType.Nil && lua.GetBool(2); + string encoded = Convert.ToBase64String(lua.GetDataString(1)); + if (!inline) { + System.Text.StringBuilder wrapped = new(); + for (int i = 0; i < encoded.Length; i += 76) { + wrapped.Append(encoded, i, Math.Min(76, encoded.Length - i)); + wrapped.Append('\n'); + } + encoded = wrapped.ToString(); + } + lua.PushString(encoded); + return 1; + } + + static long LastTimerCycle; + + [LuaFunction] + static int TimerCycle(ILuaInterface lua) { + long now = System.Diagnostics.Stopwatch.GetTimestamp(); + long elapsed = now - LastTimerCycle; + LastTimerCycle = now; + lua.PushNumber(elapsed * 1000.0 / System.Diagnostics.Stopwatch.Frequency); + return 1; + } + + static string JSONNumber(double value) { + if (double.IsNaN(value) || double.IsInfinity(value)) + return "0"; + string str = value.ToString("R", System.Globalization.CultureInfo.InvariantCulture); + if (str.IndexOfAny(['.', 'E', 'e']) < 0) + str += ".0"; + return str; + } + + static string VectorNumber(float value) => value.ToString("0.######", System.Globalization.CultureInfo.InvariantCulture); + + static void JSONString(System.Text.StringBuilder output, string value) { + output.Append('"'); + foreach (char c in value) { + switch (c) { + case '"': output.Append("\\\""); break; + case '\\': output.Append("\\\\"); break; + case '\b': output.Append("\\b"); break; + case '\f': output.Append("\\f"); break; + case '\n': output.Append("\\n"); break; + case '\r': output.Append("\\r"); break; + case '\t': output.Append("\\t"); break; + default: + if (c < 0x20) + output.Append("\\u").Append(((int)c).ToString("X4")); + else + output.Append(c); + break; + } + } + output.Append('"'); + } + + static bool JSONValue(ILuaInterface lua, ILuaObject value, System.Text.StringBuilder output, bool pretty, int depth, HashSet visiting) { + switch (value.GetType()) { + case LuaType.Bool: + output.Append(value.GetBool() ? "true" : "false"); + return true; + case LuaType.Number: + output.Append(JSONNumber(value.GetDouble())); + return true; + case LuaType.String: + JSONString(output, value.GetString() ?? ""); + return true; + case LuaType.Vector: { + value.Push(); + System.Numerics.Vector3 vec = LuaVector.Get_Vector(-1); + lua.Pop(1); + JSONString(output, $"[{VectorNumber(vec.X)} {VectorNumber(vec.Y)} {VectorNumber(vec.Z)}]"); + return true; + } + case LuaType.Angle: { + value.Push(); + Source.Common.Mathematics.QAngle ang = LuaAngle.Get_Angle(-1); + lua.Pop(1); + JSONString(output, $"{{{VectorNumber(ang.X)} {VectorNumber(ang.Y)} {VectorNumber(ang.Z)}}}"); + return true; + } + case LuaType.Table: + return JSONTable(lua, value, output, pretty, depth + 1, visiting); + default: + return false; + } + } + + static bool JSONTable(ILuaInterface lua, ILuaObject table, System.Text.StringBuilder output, bool pretty, int depth, HashSet visiting) { + if (depth > 3000) { + lua.ErrorFromLua("JSON Depth is too high! > 3000"); + return false; + } + + + List<(LuaObject Key, LuaObject Value)> entries = []; + table.Push(); + lua.PushNil(); + while (lua.Next(-2)) { + LuaObject value = new(-1, LuaType.None); + LuaObject key = new(-2, LuaType.None); + lua.Pop(1); + entries.Add((key, value)); + } + lua.Pop(1); + + bool isArray = entries.Count > 0; + for (int i = 0; i < entries.Count && isArray; i++) { + if (entries[i].Key.GetType() != LuaType.Number) + isArray = false; + } + if (isArray) { + HashSet keys = [.. entries.Select(e => e.Key.GetDouble())]; + for (int i = 1; i <= entries.Count; i++) { + if (!keys.Contains(i)) { + isArray = false; + break; + } + } + if (isArray) + entries.Sort((a, b) => a.Key.GetDouble().CompareTo(b.Key.GetDouble())); + } + + output.Append(isArray ? '[' : '{'); + bool first = true; + foreach ((LuaObject key, LuaObject value) in entries) { + if (!isArray && key.GetType() != LuaType.String && key.GetType() != LuaType.Number) + continue; + int mark = output.Length; + if (!first) + output.Append(','); + if (pretty) + output.Append('\n').Append('\t', depth); + if (!isArray) { + JSONString(output, key.GetType() == LuaType.Number ? JSONKey(key.GetDouble()) : key.GetString() ?? ""); + output.Append(':'); + if (pretty) + output.Append(' '); + } + if (!JSONValue(lua, value, output, pretty, depth, visiting)) + output.Length = mark; + else + first = false; + } + if (pretty && !first) + output.Append('\n').Append('\t', depth - 1); + output.Append(isArray ? ']' : '}'); + + foreach ((LuaObject key, LuaObject value) in entries) { + key.UnReference(); + value.UnReference(); + } + return true; + } + + static string JSONKey(double key) { + if (key == Math.Floor(key) && Math.Abs(key) < 1e15) + return ((long)key).ToString(System.Globalization.CultureInfo.InvariantCulture); + return key.ToString("R", System.Globalization.CultureInfo.InvariantCulture); + } + + [LuaFunction] + static int TableToJSON(ILuaInterface lua) { + LuaObject table = new(1, LuaType.None); + if (!table.isTable()) { + lua.TypeError("table", 1); + table.UnReference(); + return 0; + } + System.Text.StringBuilder output = new(); + bool ok = JSONTable(lua, table, output, lua.GetBool(2), 1, []); + table.UnReference(); + if (!ok) + return 0; + lua.PushString(output.ToString()); + return 1; + } + + static bool TryParseVector(string str, char open, char close, out float x, out float y, out float z) { + x = y = z = 0; + if (str.Length < 2 || str[0] != open || str[^1] != close) + return false; + string[] parts = str[1..^1].Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (parts.Length != 3) + return false; + var inv = System.Globalization.CultureInfo.InvariantCulture; + return float.TryParse(parts[0], System.Globalization.NumberStyles.Float, inv, out x) + && float.TryParse(parts[1], System.Globalization.NumberStyles.Float, inv, out y) + && float.TryParse(parts[2], System.Globalization.NumberStyles.Float, inv, out z); + } + + static void PushJSONElement(ILuaInterface lua, System.Text.Json.JsonElement element, int depth, bool ignoreLimits, bool ignoreConversions) { + switch (element.ValueKind) { + case System.Text.Json.JsonValueKind.Object: + case System.Text.Json.JsonValueKind.Array: + if (!ignoreLimits && depth > 5000) { + lua.ErrorFromLua("JSON Depth is too high! > 5000"); + lua.PushNil(); + return; + } + LuaTable table = new(null, 0); + if (element.ValueKind == System.Text.Json.JsonValueKind.Array) { + int i = 1; + foreach (System.Text.Json.JsonElement item in element.EnumerateArray()) { + table.Push(); + lua.PushNumber(i++); + PushJSONElement(lua, item, depth + 1, ignoreLimits, ignoreConversions); + lua.SetTable(-3); + lua.Pop(1); + } + } + else { + foreach (System.Text.Json.JsonProperty property in element.EnumerateObject()) { + table.Push(); + if (double.TryParse(property.Name, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out double numKey)) + lua.PushNumber(numKey); + else + lua.PushString(property.Name); + PushJSONElement(lua, property.Value, depth + 1, ignoreLimits, ignoreConversions); + lua.SetTable(-3); + lua.Pop(1); + } + } + table.Push(); + table.UnReference(); + return; + case System.Text.Json.JsonValueKind.String: { + string str = element.GetString() ?? ""; + if (!ignoreConversions) { + if (TryParseVector(str, '[', ']', out float x, out float y, out float z)) { + LuaVector.Push_Vector(new System.Numerics.Vector3(x, y, z)); + return; + } + if (TryParseVector(str, '{', '}', out x, out y, out z)) { + LuaAngle.Push_Angle(new Source.Common.Mathematics.QAngle(x, y, z)); + return; + } + } + lua.PushString(str); + return; + } + case System.Text.Json.JsonValueKind.Number: + lua.PushNumber(element.GetDouble()); + return; + case System.Text.Json.JsonValueKind.True: + lua.PushBool(true); + return; + case System.Text.Json.JsonValueKind.False: + lua.PushBool(false); + return; + default: + lua.PushNil(); + return; + } + } + + [LuaFunction] + static int JSONToTable(ILuaInterface lua) { + string json = lua.CheckString(1); + bool ignoreLimits = lua.GetBool(2); + bool ignoreConversions = lua.GetBool(3); + System.Text.Json.JsonDocument document; + try { + document = System.Text.Json.JsonDocument.Parse(json, new System.Text.Json.JsonDocumentOptions { MaxDepth = int.MaxValue, AllowTrailingCommas = false }); + } + catch (System.Text.Json.JsonException) { + return 0; + } + using (document) { + if (document.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object && document.RootElement.ValueKind != System.Text.Json.JsonValueKind.Array) + return 0; + PushJSONElement(lua, document.RootElement, 1, ignoreLimits, ignoreConversions); + } + return 1; + } +#endif + +#if MENU_DLL + [LuaFunction] + static int FullPathToRelative_Menu(ILuaInterface lua) { + string path = lua.CheckString(1); + string pathID = lua.CheckStringOpt(2, "MOD"); + Span relative = stackalloc char[MAX_PATH]; + if (!filesystem.FullPathToRelativePathEx(path, pathID, relative)) { + lua.PushNil(); + return 1; + } + lua.PushString(((ReadOnlySpan)relative).SliceNullTerminatedString()); + return 1; + } + + [LuaFunction] + static int RelativePathToFull_Menu(ILuaInterface lua) { + string path = lua.CheckString(1); + string pathID = lua.CheckStringOpt(2, "MOD"); + Span full = stackalloc char[MAX_PATH]; + ReadOnlySpan result = filesystem.RelativePathToFullPath(path, pathID, full); + if (result.IsEmpty) { + lua.PushNil(); + return 1; + } + lua.PushString(result); + return 1; + } + + [LuaFunction] + static int RelativePathToGMA_Menu(ILuaInterface lua) { + string path = lua.CheckString(1); + if (!filesystem.Addons().FindFileOwner(path, out Source.Common.GarrysMod.IAddonSystem.Information info)) + return 0; + LuaTable table = new(null, 0); + table.SetMember("ID", info.WorkshopID.ToString()); + table.SetMember("File", info.File ?? ""); + table.SetMember("Title", info.Title ?? ""); + table.SetMember("Author", info.Creator.ToString()); + table.Push(); + table.UnReference(); + return 1; + } +#endif } #endif diff --git a/Game.UI/BasePanel.cs b/Game.UI/BasePanel.cs index b48dfb792..cd13eca38 100644 --- a/Game.UI/BasePanel.cs +++ b/Game.UI/BasePanel.cs @@ -638,7 +638,7 @@ static void Gamemenucommand(in TokenizedCommand args) { g_BasePanel?.RunMenuCommand(args[1]); } - private void RunMenuCommand(ReadOnlySpan command) { + public void RunMenuCommand(ReadOnlySpan command) { DevMsg($"Incoming BasePanel message '{command}'\n"); switch (command) { case "OpenGameMenu": PostMessage(GameMenu, new("Command", "command", "open")); break; diff --git a/Game.UI/GameUI.cs b/Game.UI/GameUI.cs index 3e83c0669..bf3470c8d 100644 --- a/Game.UI/GameUI.cs +++ b/Game.UI/GameUI.cs @@ -137,6 +137,10 @@ public void RunFrame() { staticPanel.RunFrame(); } + public void SendMainMenuCommand(ReadOnlySpan command) { + BasePanel()?.RunMenuCommand(command); + } + public void SetMainMenuOverride(IPanel? panel) { BasePanel? basePanel = BasePanel(); if (basePanel != null) diff --git a/Source.Common/Client/IEngineClient.cs b/Source.Common/Client/IEngineClient.cs index 08e41ec99..5d37a1eed 100644 --- a/Source.Common/Client/IEngineClient.cs +++ b/Source.Common/Client/IEngineClient.cs @@ -486,6 +486,9 @@ public interface IEngineClient float GetPlayerVoiceVolume(CSteamID steamID); void SetPlayerVoiceVolume(CSteamID steamID, float volume); bool NET_IsHostLocal( ReadOnlySpan hostName ); +#if GMOD_DLL + bool IsHostingGame(); +#endif bool IsDedicatedServer(); uint GetProtocolVersion(); diff --git a/Source.Common/Engine/IEngineVGui.cs b/Source.Common/Engine/IEngineVGui.cs index 8d1b1e75f..a2cb3b3f3 100644 --- a/Source.Common/Engine/IEngineVGui.cs +++ b/Source.Common/Engine/IEngineVGui.cs @@ -28,5 +28,6 @@ public interface IEngineVGui void UpdateButtonState(in InputEvent ev); #if GMOD_DLL void UpdateCustomProgressBar(float progress, ReadOnlySpan desc); + void ShowConsole(); #endif } diff --git a/Source.Common/GameUI/IGameUI.cs b/Source.Common/GameUI/IGameUI.cs index 76b6290ac..761d99b5d 100644 --- a/Source.Common/GameUI/IGameUI.cs +++ b/Source.Common/GameUI/IGameUI.cs @@ -33,6 +33,7 @@ public interface IGameUI public bool IsMainMenuVisible(); public void SetMainMenuOverride(IPanel? panel); + public void SendMainMenuCommand(ReadOnlySpan command); bool IsInLevel(); bool IsInReplay(); bool IsConsoleUI(); diff --git a/Source.Engine/CdllEngineInterface.cs b/Source.Engine/CdllEngineInterface.cs index 0b01bff2a..3fc58375c 100644 --- a/Source.Engine/CdllEngineInterface.cs +++ b/Source.Engine/CdllEngineInterface.cs @@ -135,6 +135,10 @@ public bool IsInGame() { return cl.IsActive(); } +#if GMOD_DLL + public bool IsHostingGame() => Host.HostingGame; +#endif + public double GetLastTimeStamp() { return cl.LastServerTickTime; } @@ -523,7 +527,7 @@ public ReadOnlySpan GetMapEntitiesString() { public uint GetEngineBuildNumber() => Protocol.VERSION; public ReadOnlySpan GetProductVersionString() { - throw new NotImplementedException(); + return GetSteamInfIDVersionInfo().PatchVersion; } public void GrabPreColorCorrectedFrame(int x, int y, int width, int height) { diff --git a/Source.Engine/Host.cs b/Source.Engine/Host.cs index b19964d13..7ba31f54c 100644 --- a/Source.Engine/Host.cs +++ b/Source.Engine/Host.cs @@ -864,6 +864,10 @@ internal readonly unsafe ReadOnlySpan GetLine() { } } +#if GMOD_DLL + public bool HostingGame; +#endif + public bool NewGame(ReadOnlySpan mapName, bool loadGame, bool backgroundLevel, ReadOnlySpan oldMap = default, ReadOnlySpan landmark = default, bool oldSave = false) { Common.TimestampedLog("Host_NewGame"); Span previousMapName = stackalloc char[MAX_PATH]; @@ -881,11 +885,17 @@ public bool NewGame(ReadOnlySpan mapName, bool loadGame, bool backgroundLe if (!modelloader.Map_IsValid(_mapFile)) { #if !SWDS Scr.EndLoadingPlaque(); +#endif +#if GMOD_DLL + HostingGame = false; #endif return false; } DevMsg("---- Host_NewGame ----\n"); +#if GMOD_DLL + HostingGame = true; +#endif host_map.SetValue(_mapName); if (!loadGame) { HostState.RunGameInit(); @@ -899,8 +909,12 @@ public bool NewGame(ReadOnlySpan mapName, bool loadGame, bool backgroundLe g_DownloadListGenerator.OnLevelLoadStart(mapName); - if (!sv.SpawnServer(mapName, _mapFile, null)) + if (!sv.SpawnServer(mapName, _mapFile, null)) { +#if GMOD_DLL + HostingGame = false; +#endif return false; + } sv.LevelMainMenuBackground = backgroundLevel; serverGlobalVariables.CurTime = sv.GetTime(); @@ -918,8 +932,12 @@ public bool NewGame(ReadOnlySpan mapName, bool loadGame, bool backgroundLe serverGlobalVariables.CurTime = sv.GetTime(); } - if (!SV.ActivateServer()) + if (!SV.ActivateServer()) { +#if GMOD_DLL + HostingGame = false; +#endif return false; + } if (!sv.IsDedicated()) { Common.TimestampedLog("Stuff 'connect localhost' to console"); diff --git a/Source.Engine/VGuiBaseUIInterface.cs b/Source.Engine/VGuiBaseUIInterface.cs index e724fbe4b..52832fb4b 100644 --- a/Source.Engine/VGuiBaseUIInterface.cs +++ b/Source.Engine/VGuiBaseUIInterface.cs @@ -82,7 +82,9 @@ public interface IEngineVGuiInternal : IEngineVGui void Paint(PaintMode paintMode); void ActivateGameUI(); bool HideGameUI(); +#if !GMOD_DLL void ShowConsole(); +#endif void HideConsole(); bool ShouldPause(); } diff --git a/Source.GUI.Controls/RichText.cs b/Source.GUI.Controls/RichText.cs index dbf4f2312..8049e2f9e 100644 --- a/Source.GUI.Controls/RichText.cs +++ b/Source.GUI.Controls/RichText.cs @@ -717,7 +717,7 @@ public int PixelToCursorSpace(int cx, int cy) { //{ //} - private bool GetSelectedRange(out int start, out int end) { + public bool GetSelectedRange(out int start, out int end) { if (Select[0] == -1) { start = end = -1; return false; @@ -823,6 +823,92 @@ private int GetStartDrawIndex(out int lineBreakIndexIndex) { public int GetLineHeight() => Surface.GetFontTall(Font); #endif public int GetNumLines() => LineBreaks.Count; + public int GetMaximumCharCount() => MaxCharCount; + public IFont? GetFont() => Font; + + public void SelectAllText() { + CursorPos = 0; + Select[0] = 0; + Select[1] = TextStream.Count; + } + + public void InsertPossibleURLString(ReadOnlySpan text, Color urlTextColor, Color normalTextColor) { + InsertColorChange(normalTextColor); + + string str = text.ToString(); + int pos = 0; + while (pos < str.Length) { + pos = ParseTextStringForUrls(str, pos, out string urlText, out string url, out bool clickable); + + if (clickable) { + InsertClickableTextStart(url); + InsertColorChange(urlTextColor); + } + + InsertString(urlText); + + if (clickable) { + InsertColorChange(normalTextColor); + InsertClickableTextEnd(); + } + } + } + + static int ParseTextStringForUrls(string text, int startPos, out string urlText, out string url, out bool clickable) { + int i = startPos; + while (i < text.Length) { + bool urlFound = false; + ReadOnlySpan rest = text.AsSpan(i); + + if (rest.StartsWith("", StringComparison.Ordinal); + if (textEnd < i) + textEnd = text.Length; + urlText = text[i..textEnd]; + i = Math.Min(textEnd + "".Length, text.Length); + return i; + } + else if (rest.StartsWith("www.", StringComparison.OrdinalIgnoreCase)) { + if (text.IndexOf('.', Math.Min(i + 5, text.Length)) >= 0) + urlFound = true; + } + else if (rest.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || rest.StartsWith("ftp://", StringComparison.OrdinalIgnoreCase) + || rest.StartsWith("steam://", StringComparison.OrdinalIgnoreCase) || rest.StartsWith("steambeta://", StringComparison.OrdinalIgnoreCase) + || rest.StartsWith("mailto:", StringComparison.OrdinalIgnoreCase) || rest.StartsWith("\\\\", StringComparison.OrdinalIgnoreCase)) + urlFound = true; + + if (urlFound) { + if (i == startPos) { + clickable = true; + int end = i; + while (end < text.Length && !char.IsWhiteSpace(text[end])) + end++; + urlText = text[i..end]; + url = urlText; + return end; + } + break; + } + + i++; + } + + clickable = false; + urlText = text[startPos..i]; + url = urlText; + return i; + } public void SetUnderlineFont(IFont? font) => FontUnderline = font; public void SetToFullHeight() { @@ -902,7 +988,7 @@ public virtual void CopySelected() { RequestFocus(); } - private void SelectNone() { + public void SelectNone() { Select[0] = -1; Repaint(); } diff --git a/Source.GUI.Controls/TextEntry.cs b/Source.GUI.Controls/TextEntry.cs index 580cc1c56..228cf69e4 100644 --- a/Source.GUI.Controls/TextEntry.cs +++ b/Source.GUI.Controls/TextEntry.cs @@ -1032,7 +1032,7 @@ private void ScrollRight() { LayoutVerticalScrollBarSlider(); } - private void Undo() { + public void Undo() { CursorPos = UndoCursorPos; // I have a bad feeling about this... @@ -1370,7 +1370,7 @@ private void RecalculateLineBreaks() { LayoutVerticalScrollBarSlider(); } - private void SaveUndoState() { + public void SaveUndoState() { UndoCursorPos = CursorPos; UndoTextStream.Clear(); UndoTextStream.AddRange(TextStream); @@ -1618,7 +1618,7 @@ private void Delete() { LayoutVerticalScrollBarSlider(); } - private void CopySelected() { + public void CopySelected() { if (HideText) return; @@ -1649,7 +1649,7 @@ public virtual void CutSelected() { FireActionSignal(); } - private void Paste() { + public void Paste() { if (!IsEditable()) return; @@ -1954,6 +1954,9 @@ private bool SelectCheck(bool fromMouse = false) { return ret; } + public int GetNumLines() => LineBreaks.Count; + public IFont? GetFont() => Font; + public void SelectNone() { Select[0] = -1; Repaint(); @@ -2006,6 +2009,10 @@ public override void SetCaretPos(int pos) { public void SetAllowNonAsciiCharacters(bool state) => AllowNonAsciiCharacters = state; public void SetAllowNumericInputOnly(bool state) => AllowNumericInputOnly = state; public void SelectAllOnFirstFocus(bool state) => ShouldSelectAllOnFirstFocus = state; + public bool IsMultiline() => Multiline; + public int GetCurrentStartIndex() => CurrentStartIndex; + public int GetCurrentStartLine() => CurrentStartLine; + public void SelectAllOnFocusAlways(bool state) { ShouldSelectAllOnFirstFocus = state; ShouldSelectAllOnFocusAlways = state; From 0bfb8cd282f6d1f3ccec86e78d577d4b23f0e535 Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:48:29 -0700 Subject: [PATCH 12/38] Seems like menusystem doesnt use s_BannedConvars Keeping it like this in case there are actually convars menusystem blocks, need to double check --- Game.Shared/GarrysMod/LuaConCommand.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Game.Shared/GarrysMod/LuaConCommand.cs b/Game.Shared/GarrysMod/LuaConCommand.cs index 73a463cd2..d692aa257 100644 --- a/Game.Shared/GarrysMod/LuaConCommand.cs +++ b/Game.Shared/GarrysMod/LuaConCommand.cs @@ -15,6 +15,7 @@ public static partial class LuaConCommands { static readonly string[] s_BannedConvars = [ +#if CLIENT_DLL || GAME_DLL "crosshair_setup", "hud_fastswitch", "hud_quickinfo", @@ -347,6 +348,7 @@ public static partial class LuaConCommands "test_loop", "plugin_load", "sv_allow_wait_command", +#endif ]; static readonly bool[] g_bKeyState = new bool[(int)ButtonCode.KeyCount]; From e932c134902dd7da00ac533a50b37306587d2e51 Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:57:18 -0700 Subject: [PATCH 13/38] Update HardwareConfig.cs --- Source.ShaderAPI.Gl46/HardwareConfig.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source.ShaderAPI.Gl46/HardwareConfig.cs b/Source.ShaderAPI.Gl46/HardwareConfig.cs index fc39fad1f..d0599b525 100644 --- a/Source.ShaderAPI.Gl46/HardwareConfig.cs +++ b/Source.ShaderAPI.Gl46/HardwareConfig.cs @@ -322,7 +322,7 @@ public bool SupportsVertexAndPixelShaders() { } public bool SupportsVertexShaders_2_0() { - throw new NotImplementedException(); + return true; } public nint TextureMemorySize() { From 9bfbc8d2f1831dbb37d0bc3f99b4bd6d12ab058e Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Wed, 14 Oct 2026 17:14:15 -0700 Subject: [PATCH 14/38] more missing functionality --- Game.MenuSystem/GMODGetAPIManifest.cs | 78 ++++++++++++++++++++ Game.MenuSystem/LuaMenuGlobals.cs | 23 ++++++ Game.MenuSystem/MenuSystem.cs | 2 +- Source.Common/Formats/Keyvalues/KeyValues.cs | 2 +- Source.Common/Steam/Steamworks.cs | 3 + Source.GUI.Controls/Label.cs | 11 +++ 6 files changed, 117 insertions(+), 2 deletions(-) create mode 100644 Game.MenuSystem/GMODGetAPIManifest.cs diff --git a/Game.MenuSystem/GMODGetAPIManifest.cs b/Game.MenuSystem/GMODGetAPIManifest.cs new file mode 100644 index 000000000..50ea4f5bd --- /dev/null +++ b/Game.MenuSystem/GMODGetAPIManifest.cs @@ -0,0 +1,78 @@ +#if MENU_DLL +using Game.MenuSystem.GarrysMod; + +using Source.Common.GarrysMod.Lua; +using Source.Common.Steam; + +using Steamworks; + +namespace Game.MenuSystem; + +public class GMODGetAPIManifest +{ + readonly int LuaStarts; + readonly LuaObject Callback = new(); + readonly CallResult RequestCompleted; + + GMODGetAPIManifest() { + LuaStarts = MenuSystem.g_MenuSystem.LuaStarts; + RequestCompleted = CallResult.Create(OnRequestCompleted); + } + + public static void Request(ILuaObject callback) { + GMODGetAPIManifest request = new(); + request.Callback.Set(callback); + + if (!request.Callback.isFunction()) { + Warning("GetAPIManifest no callback!\n"); + request.Delete(); + return; + } + + if (!SteamworksExts.HasSteamHTTP()) { + Warning("GetAPIManifest no HTTP!\n"); + request.Delete(); + return; + } + + HTTPRequestHandle handle = SteamHTTP.CreateHTTPRequest(EHTTPMethod.k_EHTTPMethodGET, "https://api.facepunch.com/api/public/manifest?public_key=RWsOQQrO860EaGY3qPsSsBQSev3gNO0KrcF3kv4Rl5frjE9OuUKQgAsRutxMZ4aU"); + SteamHTTP.SendHTTPRequest(handle, out SteamAPICall_t call); + request.RequestCompleted.Set(call); + } + + void OnRequestCompleted(HTTPRequestCompleted_t result, bool ioFailure) { + if (LuaStarts != MenuSystem.g_MenuSystem.LuaStarts) { + Warning("GetAPIManifest no Lua!\n"); + Delete(); + return; + } + + if (!result.m_bRequestSuccessful) { + Warning("Failed to request data from Facepunch servers!\n"); + Delete(); + return; + } + + byte[] body = new byte[result.m_unBodySize]; + if (!SteamHTTP.GetHTTPResponseBodyData(result.m_hRequest, body, result.m_unBodySize)) + Warning("Failed to read data from Facepunch servers!\n"); + else { + int length = Array.IndexOf(body, (byte)0); + ReadOnlySpan manifest = length < 0 ? body : body.AsSpan(0, length); + + if (Callback.isFunction()) { + Callback.Push(); + g_Lua!.PushString(manifest); + g_Lua.CallInternalNoReturns(1); + } + } + + Delete(); + } + + void Delete() { + RequestCompleted.Dispose(); + Callback.UnReference(); + } +} +#endif diff --git a/Game.MenuSystem/LuaMenuGlobals.cs b/Game.MenuSystem/LuaMenuGlobals.cs index 4bc187ee2..70cd5f5cf 100644 --- a/Game.MenuSystem/LuaMenuGlobals.cs +++ b/Game.MenuSystem/LuaMenuGlobals.cs @@ -7,6 +7,14 @@ namespace Game.MenuSystem.GarrysMod; public static partial class LuaMenuGlobals { + [LuaGlobal] + static int GetAPIManifest(ILuaInterface lua) { + ILuaObject? callback = lua.GetObject(1); + if (callback != null && callback.isFunction()) + GMODGetAPIManifest.Request(callback); + return 0; + } + [LuaGlobal] static int GetAddonStatus(ILuaInterface lua) { lua.PushBool(commandLine.FindParm("-noaddons") == 0); @@ -32,6 +40,21 @@ static int IsHostingGame(ILuaInterface lua) { return 1; } + [LuaGlobal] + static int GetLoadStatus(ILuaInterface lua) { + // todo + Warning("GetLoadStatus TODO\n"); + lua.PushString("GetLoadStatus TODO"); + return 1; + } + [LuaGlobal] + static int NumDownloadables(ILuaInterface lua) { + // todo + Warning("NumDownloadables TODO\n"); + lua.PushString("NumDownloadables TODO"); + return 1; + } + [LuaGlobal] static int IsInGame(ILuaInterface lua) { lua.PushBool(engine.IsInGame()); diff --git a/Game.MenuSystem/MenuSystem.cs b/Game.MenuSystem/MenuSystem.cs index 393b9e64e..2be36de21 100644 --- a/Game.MenuSystem/MenuSystem.cs +++ b/Game.MenuSystem/MenuSystem.cs @@ -19,7 +19,7 @@ public class MenuSystem : IMenuSystem bool WasInGame; readonly AddonDownloadNotifications DownloadNotifications = new(); - int LuaStarts; + public int LuaStarts; int LastFilesystemRefresh; public MenuSystem() => g_MenuSystem = this; diff --git a/Source.Common/Formats/Keyvalues/KeyValues.cs b/Source.Common/Formats/Keyvalues/KeyValues.cs index cc1282ac6..1ff497ba2 100644 --- a/Source.Common/Formats/Keyvalues/KeyValues.cs +++ b/Source.Common/Formats/Keyvalues/KeyValues.cs @@ -709,7 +709,7 @@ public void SetString(ReadOnlySpan keyName, ReadOnlySpan value) { if (value.IsEmpty) value = ""; - dat.Value = new string(value); + dat.Value = new string(value.SliceNullTerminatedString()); dat.Type = Types.String; } } diff --git a/Source.Common/Steam/Steamworks.cs b/Source.Common/Steam/Steamworks.cs index d0334e306..047f8a494 100644 --- a/Source.Common/Steam/Steamworks.cs +++ b/Source.Common/Steam/Steamworks.cs @@ -26,6 +26,7 @@ public class SteamworksExts static GetPtrFn CSteamAPIContext_GetSteamClient; static GetPtrFn CSteamAPIContext_GetSteamUser; static GetPtrFn CSteamGameServerAPIContext_GetSteamClient; + static GetPtrFn CSteamAPIContext_GetSteamHTTP; static GetPtrFn RetrievePtrFn(string searchClass, string searchMethod) { Type typeSearch; @@ -51,11 +52,13 @@ static SteamworksExts() { CSteamAPIContext_GetSteamClient = RetrievePtrFn("CSteamAPIContext", "GetSteamClient"); CSteamAPIContext_GetSteamUser = RetrievePtrFn("CSteamAPIContext", "GetSteamUser"); CSteamGameServerAPIContext_GetSteamClient = RetrievePtrFn("CSteamGameServerAPIContext", "GetSteamClient"); + CSteamAPIContext_GetSteamHTTP = RetrievePtrFn("CSteamAPIContext", "GetSteamHTTP"); } public static IntPtr GetSteamUser() => CSteamAPIContext_GetSteamUser(); public static bool HasSteamClient() => CSteamAPIContext_GetSteamClient() != IntPtr.Zero; public static bool HasSteamGameServer() => CSteamGameServerAPIContext_GetSteamClient() != IntPtr.Zero; + public static bool HasSteamHTTP() => CSteamAPIContext_GetSteamHTTP() != IntPtr.Zero; } diff --git a/Source.GUI.Controls/Label.cs b/Source.GUI.Controls/Label.cs index 73f062bef..754ddb104 100644 --- a/Source.GUI.Controls/Label.cs +++ b/Source.GUI.Controls/Label.cs @@ -37,6 +37,17 @@ public Label(Panel? parent, ReadOnlySpan panelName, ReadOnlySpan tex RegisterColorAsOverridable(DisabledFgColor2, "disabledfgcolor2_override"); } + public override bool RequestInfo(KeyValues outputData) { + if (0 == stricmp(outputData.Name, "GetText")) { + Span buf = stackalloc char[256]; + TextImage!.GetText(buf); + outputData.SetString("text", buf); + return true; + } + + return base.RequestInfo(outputData); + } + public nint AddImage(IImage? textImage, int offset) { nint newImage = Images.Count; Images.Add(new() { From 0cea0fee37e7d274a410c8febfdc21fa34014634 Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Wed, 14 Oct 2026 21:08:38 -0700 Subject: [PATCH 15/38] Link backgrounds folder --- Game.Assets/Assets.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Game.Assets/Assets.cs b/Game.Assets/Assets.cs index b8861965c..7c768eaf9 100644 --- a/Game.Assets/Assets.cs +++ b/Game.Assets/Assets.cs @@ -36,9 +36,10 @@ public static List GetRequiredAssets() { new("sdn/resource", "garrysmod/resource", IsDirectory: true), new("sdn/scenes", "garrysmod/scenes", IsDirectory: true), #if GMOD_DLL + new("sdn/backgrounds", "garrysmod/backgrounds", IsDirectory: true), new("sdn/gamemodes", "garrysmod/gamemodes", IsDirectory: true), - new("sdn/lua", "garrysmod/lua", IsDirectory: true), new("sdn/html", "garrysmod/html", IsDirectory: true), + new("sdn/lua", "garrysmod/lua", IsDirectory: true), #endif new("sdn/cache/workshop", "garrysmod/cache/workshop", IsDirectory: true, Optional: false), new("sdn/settings", "garrysmod/settings", IsDirectory: true) From 27fc808b349eb87c63ea16be75c398a525b86222 Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Wed, 14 Oct 2026 21:18:53 -0700 Subject: [PATCH 16/38] Add GetDownloadables --- Game.MenuSystem/LuaMenuGlobals.cs | 19 +++++++++++++++++++ Game.Shared/GarrysMod/LuaPlayer.cs | 3 ++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/Game.MenuSystem/LuaMenuGlobals.cs b/Game.MenuSystem/LuaMenuGlobals.cs index 70cd5f5cf..9a286ec39 100644 --- a/Game.MenuSystem/LuaMenuGlobals.cs +++ b/Game.MenuSystem/LuaMenuGlobals.cs @@ -1,7 +1,9 @@ #if MENU_DLL using Source; +using Source.Common.Engine; using Source.Common.GarrysMod.Lua; using Source.Common.Launcher; +using Source.Common.Networking; namespace Game.MenuSystem.GarrysMod; @@ -28,6 +30,23 @@ static int GetDefaultLoadingHTML(ILuaInterface lua) { return 1; } + [LuaGlobal] + static int GetDownloadables(ILuaInterface lua) { + INetworkStringTable? downloadables = networkstringtable!.FindTable(Protocol.DOWNLOADABLE_FILE_TABLENAME); + if (downloadables == null) + return 0; + + int count = downloadables.GetNumStrings(); + lua.PreCreateTable(count, 0); + for (int i = 0; i < count; i++) { + lua.PushNumber(i + 1); + lua.PushString(downloadables.GetString(i)); + lua.SetTable(-3); + } + + return 1; + } + [LuaGlobal] static int GetOverlayPanel(ILuaInterface lua) { LuaVGUI.Push_Panel(MenuPanels.GetOverlayPanel()); diff --git a/Game.Shared/GarrysMod/LuaPlayer.cs b/Game.Shared/GarrysMod/LuaPlayer.cs index 78eead4fc..cc76b4aba 100644 --- a/Game.Shared/GarrysMod/LuaPlayer.cs +++ b/Game.Shared/GarrysMod/LuaPlayer.cs @@ -1,4 +1,5 @@ using Source; + #if CLIENT_DLL || GAME_DLL using Game.Shared; @@ -686,7 +687,7 @@ static int GetCount(ILuaInterface lua) { #if GAME_DLL if (player.Connected != PlayerConnectedState.Disconnected) #endif - count++; + count++; } g_Lua!.PushNumber(count); return 1; From b0db47418028c99847befca00f76c9d20210cda9 Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Thu, 15 Oct 2026 11:35:09 -0700 Subject: [PATCH 17/38] missing newline --- Source.Engine/MaterialProxyFactory.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source.Engine/MaterialProxyFactory.cs b/Source.Engine/MaterialProxyFactory.cs index 98ec1653b..b454c2320 100644 --- a/Source.Engine/MaterialProxyFactory.cs +++ b/Source.Engine/MaterialProxyFactory.cs @@ -14,7 +14,7 @@ public class MaterialProxyFactory : IMaterialProxyFactory #else IMaterialProxy? materialProxy = LookupProxy(proxyName); if (materialProxy == null) { - ConDMsg($"Can't find material proxy \"{proxyName}\""); + ConDMsg($"Can't find material proxy \"{proxyName}\"\n"); return null; } From 7f9b298d6ebc308f9bc97e15e1e93d81e592e5fb Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Thu, 15 Oct 2026 11:35:48 -0700 Subject: [PATCH 18/38] Guard PushLua against cross-Lua-interface --- Source.GUI.Controls/Panel.cs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/Source.GUI.Controls/Panel.cs b/Source.GUI.Controls/Panel.cs index cc9c19bd8..e64ed9ca7 100644 --- a/Source.GUI.Controls/Panel.cs +++ b/Source.GUI.Controls/Panel.cs @@ -1494,6 +1494,11 @@ public void PushLua(ILuaInterface lua, LuaType type) { ClearLuaReferences(); } + if (LuaObject != null && Lua != lua) { + lua.PushNil(); + return; + } + if (LuaObject != null) { if (LuaObject.GetType() == LuaType.Panel) { LuaObject.Push(); @@ -1526,6 +1531,22 @@ protected bool PushLuaHook(LUA_POOLEDSTRING name) { return false; } + public virtual void OnActivate() { + if (!PushLuaHook(LUA_POOLEDSTRING.OnActivate)) + return; + + PushLua(Lua!, LuaType.Panel); + Lua!.CallInternalNoReturns(1); + } + + public virtual void OnDeactivate() { + if (!PushLuaHook(LUA_POOLEDSTRING.OnDeactivate)) + return; + + PushLua(Lua!, LuaType.Panel); + Lua!.CallInternalNoReturns(1); + } + bool CanCallLuaHook([NotNullWhen(true)] ILuaObject? hook) => Lua != null && LuaTable != null && !LuaTable.isNil() && !IsMarkedForDeletion() && hook != null && hook.isFunction(); public void ClearLuaReferences() { @@ -3072,6 +3093,10 @@ public virtual void OnMessage(KeyValues message, IPanel? from) { case "OnScreenSizeChanged": OnScreenSizeChanged(message.GetInt("oldwide"), message.GetInt("oldtall")); break; case "Command": OnCommand(message.GetString("command")); break; case "DialogVariables": OnDialogVariablesChanged(message); break; +#if GMOD_DLL + case "activate": OnActivate(); break; + case "deactivate": OnDeactivate(); break; +#endif #if DEBUG default: DevMsg(3, $"Unhandled message '{message.Name}' from {from}"); From 96127db8971ee9d7edbed17b3d3a268ab613d439 Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Thu, 15 Oct 2026 11:36:27 -0700 Subject: [PATCH 19/38] Add GetSteamUGC to steamworks intermediate --- Source.Common/Steam/Steamworks.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Source.Common/Steam/Steamworks.cs b/Source.Common/Steam/Steamworks.cs index 047f8a494..b9f66969f 100644 --- a/Source.Common/Steam/Steamworks.cs +++ b/Source.Common/Steam/Steamworks.cs @@ -27,6 +27,7 @@ public class SteamworksExts static GetPtrFn CSteamAPIContext_GetSteamUser; static GetPtrFn CSteamGameServerAPIContext_GetSteamClient; static GetPtrFn CSteamAPIContext_GetSteamHTTP; + static GetPtrFn CSteamAPIContext_GetSteamUGC; static GetPtrFn RetrievePtrFn(string searchClass, string searchMethod) { Type typeSearch; @@ -53,9 +54,11 @@ static SteamworksExts() { CSteamAPIContext_GetSteamUser = RetrievePtrFn("CSteamAPIContext", "GetSteamUser"); CSteamGameServerAPIContext_GetSteamClient = RetrievePtrFn("CSteamGameServerAPIContext", "GetSteamClient"); CSteamAPIContext_GetSteamHTTP = RetrievePtrFn("CSteamAPIContext", "GetSteamHTTP"); + CSteamAPIContext_GetSteamUGC = RetrievePtrFn("CSteamAPIContext", "GetSteamUGC"); } public static IntPtr GetSteamUser() => CSteamAPIContext_GetSteamUser(); + public static IntPtr GetSteamUGC() => CSteamAPIContext_GetSteamUGC(); public static bool HasSteamClient() => CSteamAPIContext_GetSteamClient() != IntPtr.Zero; public static bool HasSteamGameServer() => CSteamGameServerAPIContext_GetSteamClient() != IntPtr.Zero; public static bool HasSteamHTTP() => CSteamAPIContext_GetSteamHTTP() != IntPtr.Zero; From 42cd27bdee712b114406d9e87da2369bda2e7bf7 Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Thu, 15 Oct 2026 11:36:43 -0700 Subject: [PATCH 20/38] New Common types --- Source.Common/GarrysMod/IGet.cs | 9 ++++++++- Source.Common/GarrysMod/IMenuSystem.cs | 2 +- Source.Common/GarrysMod/IResources.cs | 4 ++++ 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/Source.Common/GarrysMod/IGet.cs b/Source.Common/GarrysMod/IGet.cs index 2e5b8be11..306d43753 100644 --- a/Source.Common/GarrysMod/IGet.cs +++ b/Source.Common/GarrysMod/IGet.cs @@ -7,7 +7,14 @@ namespace Source.Common.GarrysMod; -public interface IMotionSensor; // todo +public interface IMotionSensor +{ + bool IsActive(); + bool Start(); + void Stop(); + int NumSensors(); + IMaterial? GetColourMaterial(); +} public interface IGet { diff --git a/Source.Common/GarrysMod/IMenuSystem.cs b/Source.Common/GarrysMod/IMenuSystem.cs index 83761fe20..7fbc422e5 100644 --- a/Source.Common/GarrysMod/IMenuSystem.cs +++ b/Source.Common/GarrysMod/IMenuSystem.cs @@ -10,7 +10,7 @@ public interface IMenuSystem void SetupNetworkString(INetworkStringTableContainer networkStringTableContainer); void Think(); void StartLua(); - void ServerDetails(ReadOnlySpan unk1, ReadOnlySpan unk2, ReadOnlySpan unk3, int unk4, ReadOnlySpan unk5); + void ServerDetails(ReadOnlySpan serverName, ReadOnlySpan loadingURL, ReadOnlySpan mapName, byte maxPlayers, short playerSlots, ReadOnlySpan gamemode); void OnLuaError(in LuaError err, IAddonSystem.Information? addonInfo); void SendProblemToMenu(ReadOnlySpan id, int severity, ReadOnlySpan parms); bool IsServerBlacklisted(ReadOnlySpan address, ReadOnlySpan hostname, ReadOnlySpan description, ReadOnlySpan gamemode, ReadOnlySpan map); diff --git a/Source.Common/GarrysMod/IResources.cs b/Source.Common/GarrysMod/IResources.cs index e1bc3110e..d1da81a42 100644 --- a/Source.Common/GarrysMod/IResources.cs +++ b/Source.Common/GarrysMod/IResources.cs @@ -25,6 +25,10 @@ public interface IVideoWriter bool ManualFiling(); ReadOnlySpan FileExtension(); + + int Width { get; } + int Height { get; } + bool RecordSound { get; set; } } public interface IVideoHolly From 435fdadcf6261d01080ee57ff79aab2e8d6d230c Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Thu, 15 Oct 2026 11:51:41 -0700 Subject: [PATCH 21/38] New Lua libraries HTTP, material fixes, motionsensor, permissions, steamworks, IVideoWriter NOTE: The clientside implementations of menu functions are guesses! They may differ! NEED TO CHECK!!! NOTE: The clientside (not menu) were NOT decompiled and need to be decompiled later. --- Game.MenuSystem/Game.MenuSystem.csproj | 2 +- Game.Shared/GarrysMod/LuaHTTPRequest.cs | 308 +++++ Game.Shared/GarrysMod/LuaMaterial.cs | 32 + Game.Shared/GarrysMod/LuaMotionSensor.cs | 64 + Game.Shared/GarrysMod/LuaObject.cs | 5 + Game.Shared/GarrysMod/LuaPermissions.cs | 221 ++++ Game.Shared/GarrysMod/LuaSteamworks.cs | 1422 ++++++++++++++++++++++ Game.Shared/GarrysMod/LuaVideoWriter.cs | 76 ++ 8 files changed, 2129 insertions(+), 1 deletion(-) create mode 100644 Game.Shared/GarrysMod/LuaHTTPRequest.cs create mode 100644 Game.Shared/GarrysMod/LuaMotionSensor.cs create mode 100644 Game.Shared/GarrysMod/LuaPermissions.cs create mode 100644 Game.Shared/GarrysMod/LuaSteamworks.cs create mode 100644 Game.Shared/GarrysMod/LuaVideoWriter.cs diff --git a/Game.MenuSystem/Game.MenuSystem.csproj b/Game.MenuSystem/Game.MenuSystem.csproj index c9802aad7..7a94582e1 100644 --- a/Game.MenuSystem/Game.MenuSystem.csproj +++ b/Game.MenuSystem/Game.MenuSystem.csproj @@ -17,7 +17,7 @@ - + diff --git a/Game.Shared/GarrysMod/LuaHTTPRequest.cs b/Game.Shared/GarrysMod/LuaHTTPRequest.cs new file mode 100644 index 000000000..8045a6537 --- /dev/null +++ b/Game.Shared/GarrysMod/LuaHTTPRequest.cs @@ -0,0 +1,308 @@ +#if CLIENT_DLL || GAME_DLL || MENU_DLL +using Source; +using Source.Common.GarrysMod.Lua; +using Source.Common.Steam; + +using Steamworks; + +#if GAME_DLL +using SteamHTTP = Steamworks.SteamGameServerHTTP; +#endif + +#if CLIENT_DLL +namespace Game.Client.GarrysMod; +#elif MENU_DLL +namespace Game.MenuSystem.GarrysMod; +#else +namespace Game.Server.GarrysMod; +#endif + +public class LuaHTTPRequest +{ + static readonly string[] MaliciousEndpoints = [ + "kvac.cz", "gvac.cz", "scriptenforcer.net", "kvacdoor", "panelpetitvac", "cometedoor.site", "anti-leak.cz", "lkpanel.me", + "gblk.ga", "vcmod.xyz", "lunodoors.com", "gmodstore.xyz", "patchfix.xyz", "weaponstore.xyz", "kvcdoor" + ]; + + static readonly string[] LocalPrefixes = [ + "://0.", "://0000.", "://0/", "://0:", "://0x", "://[", "://10.", "://172.16.", "://192.168.", "://127.", "://localhost" + ]; + + static readonly string[] ResponseHeaders = [ + "Connection", "Content-Encoding", "Content-Type", "Date", "Server", "Transfer-Encoding", "Vary", "Cache-Control", "Expires", + "Get-Dictionary", "Status", "Version", "Pragma", "Set-Cookie", "X-Powered-By", "X-UA-Compatible", "Age", "Allow", "Last-Modified", + "Location", "Refresh", "Warning", "Via", "Access-Control-Allow-Origin", "Accept-Ranges", "Content-Range", "Content-Location", + "Content-MD5", "Content-Length", "Retry-After", "X-RateLimit-Limit", "X-RateLimit-Remaining", "X-RateLimit-Reset", + "X-Rate-Limit-Limit", "X-Rate-Limit-Remaining", "X-Rate-Limit-Reset", "ETag" + ]; + + readonly int LuaStarts; + HTTPRequestHandle Request; + readonly LuaObject Table = new(); + readonly string Url; + readonly CallResult RequestCompleted; + + LuaHTTPRequest(ILuaObject table) { + LuaStarts = g_LuaStarts; + Table.Set(table); + Url = Table.GetMemberStr("url", "") ?? ""; + RequestCompleted = CallResult.Create(OnComplete); + + if (Url.Length == 0) { + Fail("invalid url"); + return; + } + + if (!Url.StartsWith("http://", StringComparison.Ordinal) && !Url.StartsWith("https://", StringComparison.Ordinal)) { + Fail("invalid url format"); + return; + } + + if (IsMaliciousEndpoint(Url)) { + g_Lua!.ErrorFromLua($"Attempted request to known malicious code endpoint '{Url}'! Blocking!"); + Fail("malicious url"); + return; + } + + if (IsLocalResource(Url)) { + Fail("requests to local resources are not allowed"); + return; + } + + Send(); + } + + static bool IsMaliciousEndpoint(string url) { + string lower = url.ToLowerInvariant(); + foreach (string endpoint in MaliciousEndpoints) { + if (lower.Contains(endpoint, StringComparison.Ordinal)) + return true; + } + return false; + } + + static bool IsNumericHost(string host) { + if (host.Length == 0) + return false; + return double.TryParse(host, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out _); + } + + static bool IsLocalResource(string url) { + string lower = url.ToLowerInvariant(); + foreach (string prefix in LocalPrefixes) { + if (lower.Contains(prefix, StringComparison.Ordinal)) + return true; + } + + int scheme = lower.IndexOf("://", StringComparison.Ordinal); + if (scheme < 0) + return false; + + int start = scheme + 3; + int slash = start < lower.Length ? lower.IndexOf('/', start) : -1; + int colon = start < lower.Length ? lower.IndexOf(':', start) : -1; + int end = lower.Length; + if (slash >= 0) + end = Math.Min(end, slash); + if (colon >= 0) + end = Math.Min(end, colon); + + string host = start <= end ? lower[start..end] : ""; + if (IsNumericHost(host)) + return true; + if (host.EndsWith(".localhost", StringComparison.Ordinal)) + return true; + return host.Contains('@'); + } + + void CallFailed(string reason) { + LuaObject failed = new(); + Table.GetMember("failed", failed); + if (failed.isFunction()) { + failed.Push(); + g_Lua!.PushString(reason); + g_Lua.CallInternalNoReturns(1); + } + failed.UnReference(); + } + + void Fail(string? reason) { + CallFailed(reason ?? "unknown"); + Delete(); + } + + static EHTTPMethod MethodFromName(string method) => method switch { + "get" => EHTTPMethod.k_EHTTPMethodGET, + "put" => EHTTPMethod.k_EHTTPMethodPUT, + "head" => EHTTPMethod.k_EHTTPMethodHEAD, + "post" => EHTTPMethod.k_EHTTPMethodPOST, + "delete" => EHTTPMethod.k_EHTTPMethodDELETE, + "options" => EHTTPMethod.k_EHTTPMethodOPTIONS, + "patch" => EHTTPMethod.k_EHTTPMethodPATCH, + _ => EHTTPMethod.k_EHTTPMethodInvalid + }; + + void ForEachStringPair(ReadOnlySpan member, Action action) { + LuaObject table = new(); + Table.GetMember(member, table); + if (table.isTable()) { + ILuaInterface lua = g_Lua!; + table.Push(); + lua.PushNil(); + while (lua.Next(-2)) { + if (lua.IsType(-2, LuaType.String) && lua.IsType(-1, LuaType.String)) + action(lua.GetString(-2)!, lua.GetString(-1)!); + lua.Pop(1); + } + lua.Pop(1); + } + table.UnReference(); + } + + void Send() { + string method = (Table.GetMemberStr("method", "get") ?? "get").ToLowerInvariant(); + Request = SteamHTTP.CreateHTTPRequest(MethodFromName(method), Url); + if (Request == HTTPRequestHandle.Invalid) { + Fail("invalid request"); + return; + } + + ForEachStringPair("headers", (key, value) => SteamHTTP.SetHTTPRequestHeaderValue(Request, key, value)); + ForEachStringPair("parameters", (key, value) => SteamHTTP.SetHTTPRequestGetOrPostParameter(Request, key, value)); + + string type = Table.GetMemberStr("type", "text/plain; charset=utf-8") ?? ""; + int timeout = Math.Clamp(Table.GetMemberInt("timeout", 60), 1, 3600); + SteamHTTP.SetHTTPRequestNetworkActivityTimeout(Request, (uint)timeout); + + LuaObject body = new(); + Table.GetMember("body", body); + if (body.isString()) { + if (type.Length == 0) { + body.UnReference(); + Fail("invalid body content type"); + return; + } + + body.Push(); + byte[] bytes = g_Lua!.GetStringBytes(-1).ToArray(); + g_Lua.Pop(1); + SteamHTTP.SetHTTPRequestRawPostBody(Request, type, bytes, (uint)bytes.Length); + } + body.UnReference(); + + if (!SteamHTTP.SendHTTPRequest(Request, out SteamAPICall_t call)) { + Fail("invalid request"); + return; + } + + RequestCompleted.Set(call); + } + + void OnComplete(HTTPRequestCompleted_t result, bool ioFailure) { + if (!ThreadInMainThread()) + Warning("CLuaHTTPRequest::OnComplete not in main thread?\n"); + + if (LuaStarts != g_LuaStarts) { + Delete(); + return; + } + + if (ioFailure) { + Fail("error"); + return; + } + + if (!result.m_bRequestSuccessful) { + SteamHTTP.GetHTTPRequestWasTimedOut(result.m_hRequest, out bool timedOut); + Fail(timedOut ? "timeout" : "unsuccessful"); + return; + } + + LuaTable headers = new(); + foreach (string name in ResponseHeaders) { + if (!SteamHTTP.GetHTTPResponseHeaderSize(Request, name, out uint size)) + continue; + + byte[] value = new byte[size]; + if (SteamHTTP.GetHTTPResponseHeaderValue(Request, name, value, size)) { + int length = Array.IndexOf(value, (byte)0); + headers.SetMember(name, length < 0 ? value : value.AsSpan(0, length)); + } + } + + SteamHTTP.GetHTTPResponseBodySize(result.m_hRequest, out uint bodySize); + byte[] responseBody = new byte[bodySize]; + SteamHTTP.GetHTTPResponseBodyData(result.m_hRequest, responseBody, bodySize); + + LuaObject success = new(); + Table.GetMember("success", success); + if (success.isFunction()) { + success.Push(); + g_Lua!.PushNumber((int)result.m_eStatusCode); + g_Lua.PushString(responseBody); + headers.Push(); + g_Lua.CallInternalNoReturns(3); + } + success.UnReference(); + headers.UnReference(); + + Delete(); + } + + void Delete() { + RequestCompleted.Dispose(); + if (Request != HTTPRequestHandle.Invalid) { + SteamHTTP.ReleaseHTTPRequest(Request); + Request = HTTPRequestHandle.Invalid; + } + Table.UnReference(); + } + + public static void Create(ILuaObject table) => _ = new LuaHTTPRequest(table); +} + +public static partial class LuaHTTP +{ + static void CallFailed(ILuaObject table, string reason) { + LuaObject failed = new(); + table.GetMember("failed", failed); + if (failed.isFunction()) { + failed.Push(); + g_Lua!.PushString(reason); + g_Lua.CallInternalNoReturns(1); + } + failed.UnReference(); + } + + [LuaGlobal] + static int HTTP(ILuaInterface lua) { + ILuaObject? table = lua.GetObject(1); + if (table == null || !table.isTable()) { + lua.TypeError("table", 1); + lua.PushBool(false); + return 1; + } + + if (commandLine.FindParm("-disablehttp") != 0) { + CallFailed(table, "HTTP is disabled by -disablehttp"); + lua.ErrorFromLua($"HTTP function blocked by -disablehttp launch parameter. URL: {table.GetMemberStr("url", "")}\n"); + lua.PushBool(false); + return 1; + } + +#if GAME_DLL + if (!SteamworksExts.HasSteamGameServer()) { +#else + if (!SteamworksExts.HasSteamHTTP()) { +#endif + lua.ErrorFromLua("HTTP failed - ISteamHTTP isn't available!\n"); + lua.PushBool(false); + return 1; + } + + LuaHTTPRequest.Create(table); + lua.PushBool(true); + return 1; + } +} +#endif diff --git a/Game.Shared/GarrysMod/LuaMaterial.cs b/Game.Shared/GarrysMod/LuaMaterial.cs index 888327085..765acf18f 100644 --- a/Game.Shared/GarrysMod/LuaMaterial.cs +++ b/Game.Shared/GarrysMod/LuaMaterial.cs @@ -561,6 +561,38 @@ static bool IsAllowedMaterialPath(ReadOnlySpan name) { return false; } +#if MENU_DLL + [LuaGlobal] + static int AddonMaterial(ILuaInterface lua) { + string path = "../" + lua.CheckString(1); + if (!IsAllowedMaterialPath(path)) + path = ""; + + IMaterial? material = get.Resources()!.FindMaterial(path, "010101", true, true, false); + if (material == null) + return 0; + + material.GetMappingHeight(); + Push(material); + return 1; + } + + [LuaGlobal] + static int DynamicMaterial(ILuaInterface lua) { + string name = lua.CheckString(1); + if (string.IsNullOrEmpty(name)) + return 0; + + string parameters = lua.CheckStringOpt(2, ""); + IMaterial? material = get.Resources()!.FindMaterial(name, parameters, true, false, true); + if (material == null) + return 0; + + Push(material); + return 1; + } +#endif + [LuaGlobal] static int Material(ILuaInterface lua) { string? name = lua.GetString(1); diff --git a/Game.Shared/GarrysMod/LuaMotionSensor.cs b/Game.Shared/GarrysMod/LuaMotionSensor.cs new file mode 100644 index 000000000..de25a04f5 --- /dev/null +++ b/Game.Shared/GarrysMod/LuaMotionSensor.cs @@ -0,0 +1,64 @@ +#if CLIENT_DLL || GAME_DLL || MENU_DLL +using Source.Common.GarrysMod; +using Source.Common.GarrysMod.Lua; +using Source.Common.MaterialSystem; + +#if CLIENT_DLL +namespace Game.Client.GarrysMod; +#elif MENU_DLL +namespace Game.MenuSystem.GarrysMod; +#else +namespace Game.Server.GarrysMod; +#endif + +public static partial class LuaMotionSensor +{ + [LuaLibrary] + static readonly LuaLibrary LL_Factory_motionsensor = new("motionsensor"); + +#if CLIENT_DLL || MENU_DLL + [LuaFunction] + static int IsAvailable(ILuaInterface lua) { + if (commandLine.FindParm("-kinectdebug") != 0) { + Msg("motionsesnor - isavailable\n"); + Msg($"motionsesnor - G={get}\n"); + Msg($"motionsesnor - MS={get.MotionSensor()}\n"); + } + + IMotionSensor? sensor = get.MotionSensor(); + if (sensor == null) { + if (commandLine.FindParm("-kinectdebug") != 0) + Msg("motionsesnor - returning false\n"); + g_Lua!.PushBool(false); + return 1; + } + + if (commandLine.FindParm("-kinectdebug") != 0) + Msg($"num sensors: - {sensor.NumSensors()}\n"); + + g_Lua!.PushBool(sensor.NumSensors() > 0); + return 1; + } + + [LuaFunction] + static int Start(ILuaInterface lua) { + get.MotionSensor()?.Start(); + return 0; + } + + [LuaFunction] + static int GetColourMaterial(ILuaInterface lua) { + IMotionSensor? sensor = get.MotionSensor(); + if (sensor == null || sensor.NumSensors() == 0 || !sensor.IsActive()) + return 0; + + IMaterial? material = sensor.GetColourMaterial(); + if (material == null) + return 0; + + LuaMaterial.Push(material); + return 1; + } +#endif +} +#endif diff --git a/Game.Shared/GarrysMod/LuaObject.cs b/Game.Shared/GarrysMod/LuaObject.cs index a2868bfa2..10b31394d 100644 --- a/Game.Shared/GarrysMod/LuaObject.cs +++ b/Game.Shared/GarrysMod/LuaObject.cs @@ -29,6 +29,11 @@ public static class LuaGlobals { public static ILuaInterface? g_Lua; public static int g_LuaID; +#if MENU_DLL + public static int g_LuaStarts => Game.MenuSystem.MenuSystem.g_MenuSystem.LuaStarts; +#else + public static int g_LuaStarts => g_LuaID; +#endif } public class LuaObject : ILuaObject diff --git a/Game.Shared/GarrysMod/LuaPermissions.cs b/Game.Shared/GarrysMod/LuaPermissions.cs new file mode 100644 index 000000000..3c4e8cfbb --- /dev/null +++ b/Game.Shared/GarrysMod/LuaPermissions.cs @@ -0,0 +1,221 @@ +#if CLIENT_DLL || MENU_DLL +using Source; +using Source.Common.GarrysMod.Lua; +using Source.Common.Networking; +using Source.Common.Utilities; + +#if CLIENT_DLL +namespace Game.Client.GarrysMod; +#else +namespace Game.MenuSystem.GarrysMod; +#endif + +public static partial class LuaPermissions +{ + [LuaLibrary] + static readonly LuaLibrary LL_Factory_permissions = new("permissions"); + + const string PermissionsFile = "settings/permissions.bin"; + const int InvalidPermission = 8; + + static readonly string[] PermissionNames = ["connect", "voicerecord", "workshopdownload", "javascript", "escapemenu", "filewrite", "motionsensor"]; + + static readonly SortedDictionary Permanent = new(StringComparer.Ordinal); + static readonly SortedDictionary Temporary = new(StringComparer.Ordinal); + static bool Loaded; + + static int PermissionFromName(ReadOnlySpan name) { + if (name.SequenceEqual("connect")) + return 0; + if (name.SequenceEqual("voicerecord")) + return 1; + if (name.SequenceEqual("motionsensor")) + return 6; + return InvalidPermission; + } + + static uint Index(SortedDictionary map, string address) { + if (!map.TryGetValue(address, out uint mask)) + map[address] = mask = 0; + return mask; + } + + static string? GetServerAddress() { + INetChannelInfo? nci = engine.GetNetChannelInfo(); + if (nci == null) + return null; + ReadOnlySpan address = nci.GetAddress(); + return address.IsEmpty ? null : new string(address); + } + + static void Load() { + if (Loaded) + return; + Loaded = true; + + long size = filesystem.Size(PermissionsFile, "MOD"); + if (size <= 0) + return; + + byte[] data = new byte[size]; + if (!filesystem.ReadFile(PermissionsFile, "MOD", data, 0)) + return; + + UtlBuffer buf = new(data, UtlBuffer.BufferFlags.ReadOnly); + uint count = buf.GetUnsignedInt(); + Span address = stackalloc char[256]; + for (uint i = 0; i < count; i++) { + buf.GetString(address); + uint mask = buf.GetUnsignedInt(); + Permanent.TryAdd(new string(((ReadOnlySpan)address).SliceNullTerminatedString()), mask); + } + } + +#if MENU_DLL + static void Save() { + UtlBuffer buf = new(); + buf.PutUnsignedInt((uint)Permanent.Count); + foreach (KeyValuePair entry in Permanent) { + if (entry.Value == 0 || entry.Key == "loopback") + continue; + buf.PutString(entry.Key); + buf.PutUnsignedInt(entry.Value); + } + filesystem.WriteFile(PermissionsFile, "MOD", buf.Base().AsSpan(0, buf.TellPut())); + } + + static void CallPermissionsChanged() => MenuSystem.CallHook("OnPermissionsChanged"); + + static void Connect(ReadOnlySpan address) { + string trimmed = new string(address).Trim(" \t;".ToCharArray()); + if (trimmed.Contains(';')) + return; + + string command = $"connect {trimmed} serverbrowser\n"; + if (command.Length > 255) + command = command[..255]; + engine.ClientCmd(command); + + Temporary[trimmed] = Index(Temporary, trimmed) | 1; + } + +#endif + + static bool IsGranted(string name) { + int permission = PermissionFromName(name); + if (permission == InvalidPermission) { + g_Lua!.ErrorFromLua($"Invalid permission '{name}'!"); + return false; + } + + Load(); + + string? address = GetServerAddress(); + if (address == null) + return false; + + uint mask = Index(Permanent, address) | Index(Temporary, address); + return (mask & (1u << permission)) != 0; + } + +#if MENU_DLL + [LuaFunction] + static int Connect(ILuaInterface lua) { + string address = lua.CheckString(1); + lua.CheckStringOpt(2, null); + Connect(address); + return 0; + } + +#endif + + [LuaFunction] + static int IsGranted(ILuaInterface lua) { + lua.PushBool(IsGranted(lua.CheckString(1))); + return 1; + } + +#if MENU_DLL + [LuaFunction] + static int Grant(ILuaInterface lua) { + Load(); + + string name = g_Lua!.CheckString(1); + bool temporary = g_Lua.GetType(2) != LuaType.Nil && g_Lua.GetBool(2); + + string? address = GetServerAddress(); + if (address == null) + return 0; + + int permission = PermissionFromName(name); + if (permission == InvalidPermission) { + g_Lua.ErrorFromLua($"Invalid permission '{name}'!"); + return 0; + } + + if (temporary) + Temporary[address] = Index(Temporary, address) | (1u << permission); + else { + Permanent[address] = Index(Permanent, address) | (1u << permission); + Save(); + } + + CallPermissionsChanged(); + return 0; + } + + [LuaFunction] + static int Revoke(ILuaInterface lua) { + Load(); + + string name = g_Lua!.CheckString(1); + string? address = g_Lua.CheckString(2); + if (address == null) + return 0; + + int permission = PermissionFromName(name); + if (permission == InvalidPermission) { + g_Lua.ErrorFromLua($"Invalid permission '{name}'!"); + return 0; + } + + uint clear = ~(1u << permission); + Temporary[address] = Index(Temporary, address) & clear; + Permanent[address] = Index(Permanent, address) & clear; + Save(); + + CallPermissionsChanged(); + return 0; + } + + static void PushPermissionTable(ILuaInterface lua, SortedDictionary map) { + lua.CreateTable(); + foreach (KeyValuePair entry in map) { + if (entry.Value == 0) + continue; + + List names = []; + for (int i = 0; i < PermissionNames.Length; i++) { + if ((entry.Value & (1u << i)) != 0) + names.Add(PermissionNames[i]); + } + + lua.PushString(string.Join(',', names)); + lua.SetField(-2, entry.Key); + } + } + + [LuaFunction] + static int GetAll(ILuaInterface lua) { + Load(); + + lua.CreateTable(); + PushPermissionTable(lua, Permanent); + lua.SetField(-2, "permanent"); + PushPermissionTable(lua, Temporary); + lua.SetField(-2, "temporary"); + return 1; + } +#endif +} +#endif diff --git a/Game.Shared/GarrysMod/LuaSteamworks.cs b/Game.Shared/GarrysMod/LuaSteamworks.cs new file mode 100644 index 000000000..b8ccbf939 --- /dev/null +++ b/Game.Shared/GarrysMod/LuaSteamworks.cs @@ -0,0 +1,1422 @@ +#if CLIENT_DLL || GAME_DLL || MENU_DLL +using Bootil.Compression; + +using Source; +using Source.Common.Filesystem; +using Source.Common.GarrysMod; +using Source.Common.GarrysMod.Lua; +using Source.Common.Steam; + +using Steamworks; + +using System.Runtime.InteropServices; + +#if CLIENT_DLL +namespace Game.Client.GarrysMod; +#elif MENU_DLL +namespace Game.MenuSystem.GarrysMod; +#else +namespace Game.Server.GarrysMod; +#endif + +#if CLIENT_DLL || MENU_DLL +abstract class LuaCallbackRequest +{ + protected readonly int LuaStarts = g_LuaStarts; + protected readonly LuaObject Callback = new(); + + protected bool LuaValid => LuaStarts == g_LuaStarts; + + protected void Call(LuaObject table) { + Callback.Push(); + table.Push(); + g_Lua!.CallInternalNoReturns(1); + } + + protected void CallNoArgs() { + if (!LuaValid) + return; + Callback.Push(); + g_Lua!.CallInternalNoReturns(0); + } + + protected void CallError(int error) { + LuaTable table = new(); + table.SetMember("error", error); + Call(table); + table.UnReference(); + } + + protected void CallError(ReadOnlySpan error) { + LuaTable table = new(); + table.SetMember("error", error); + Call(table); + table.UnReference(); + } +} + +#if MENU_DLL +public static class WorkshopFavoritesCache +{ + public static readonly List Favorites = []; + static uint Page; + static bool Busy; + static readonly CallResult QueryCompleted = CallResult.Create(OnQueryCompleted); + + public static void Refresh() { + if (Busy || !SteamworksExts.HasSteamClient()) + return; + Page = 0; + Busy = true; + Query(); + } + + static void Query() { + CSteamID steamID = SteamUser.GetSteamID(); + UGCQueryHandle_t handle = SteamUGC.CreateQueryUserUGCRequest(steamID.GetAccountID(), EUserUGCList.k_EUserUGCList_Favorited, EUGCMatchingUGCType.k_EUGCMatchingUGCType_Items_ReadyToUse, EUserUGCListSortOrder.k_EUserUGCListSortOrder_CreationOrderDesc, new AppId_t(4000), new AppId_t(4000), Page / 50 + 1); + if (handle == UGCQueryHandle_t.Invalid) { + Warning("SteamUGFavoritesCache invalid UGC handle!\n"); + return; + } + + SteamUGC.SetReturnOnlyIDs(handle, true); + SteamAPICall_t call = SteamUGC.SendQueryUGCRequest(handle); + if (call == SteamAPICall_t.Invalid) { + Warning("SteamUGFavoritesCache invalid handle\n"); + return; + } + + QueryCompleted.Set(call); + } + + static void OnQueryCompleted(SteamUGCQueryCompleted_t result, bool ioFailure) { + if (result.m_eResult != EResult.k_EResultOK) { + Warning($"SteamUGFavoritesCache failed! {LuaSteamworks.EResultString(result.m_eResult)}\n"); + return; + } + + if (result.m_unNumResultsReturned < 1) + return; + + for (uint i = 0; i <= result.m_unNumResultsReturned; i++) { + if (SteamUGC.GetQueryUGCResult(result.m_handle, i, out SteamUGCDetails_t details)) + Favorites.Add(details.m_nPublishedFileId.m_PublishedFileId); + } + + SteamUGC.ReleaseQueryUGCRequest(result.m_handle); + + uint page = Page + result.m_unNumResultsReturned; + if (page < result.m_unTotalMatchingResults) { + Page = page; + Query(); + } + else + Busy = false; + } +} +#endif + +class UGCDownloadJob : LuaCallbackRequest +{ + const int GMATimestampOffset = 13; + + public readonly ulong ID; + SteamUGCDetails_t Details; + LZMA.ExtractionThread? Extraction; + readonly CallResult ItemInfo; + Callback? ItemDownloaded; + + public UGCDownloadJob(ulong id, LuaObject callback) { + Callback.Set(callback); + ID = id; + ItemInfo = CallResult.Create(OnItemInfo); + UGCDownloadManager.SetActive(this); + + UGCQueryHandle_t handle = SteamUGC.CreateQueryUGCDetailsRequest([new PublishedFileId_t(ID)], 1); + SteamAPICall_t call = handle == UGCQueryHandle_t.Invalid ? SteamAPICall_t.Invalid : SteamUGC.SendQueryUGCRequest(handle); + if (call == SteamAPICall_t.Invalid) { + CallNoArgs(); + Destroy(); + } + else + ItemInfo.Set(call); + + filesystem.Addons().Notify()?.StartDownload(ID, 0, ID.ToString(), 0); + } + + void Destroy() { + if (UGCDownloadManager.Active != null) { + filesystem.Addons().Notify()?.FinishDownload(UGCDownloadManager.Active.ID); + UGCDownloadManager.Active = null; + } + UGCDownloadManager.ProcessQueue(); + + ItemInfo.Dispose(); + ItemDownloaded?.Dispose(); + ItemDownloaded = null; + Callback.UnReference(); + } + + void Fail() { + CallNoArgs(); + Destroy(); + } + + void OnItemInfo(SteamUGCQueryCompleted_t result, bool ioFailure) { + if (ioFailure) { + Warning($"steamworks.DownloadUGC: OnResult received null result for {ID}\n"); + Destroy(); + return; + } + + if (!LuaValid) { + SteamUGC.ReleaseQueryUGCRequest(result.m_handle); + Destroy(); + return; + } + + if (result.m_eResult != EResult.k_EResultOK) { + SteamUGC.ReleaseQueryUGCRequest(result.m_handle); + Warning($"steamworks.DownloadUGC: Failed to get addon info for {ID}, {LuaSteamworks.EResultString(result.m_eResult)}\n"); + Fail(); + return; + } + + for (uint i = 0; i < result.m_unNumResultsReturned; i++) { + if (!SteamUGC.GetQueryUGCResult(result.m_handle, i, out SteamUGCDetails_t details)) { + Warning($"DownloadUGC: GetQueryUGCResult failed for item {ID}\n"); + continue; + } + + if (details.m_nPublishedFileId.m_PublishedFileId != ID) { + Warning($"DownloadUGC: OnItemInfo got wrong ID {details.m_nPublishedFileId.m_PublishedFileId}, expected {ID}\n"); + continue; + } + + Details = details; + filesystem.Addons().Notify()?.StartDownload(ID, Details.m_hPreviewFile.m_UGCHandle, Details.m_rgchTitle, (ulong)Details.m_nFileSize); + StartDownload(); + break; + } + + SteamUGC.ReleaseQueryUGCRequest(result.m_handle); + } + + void StartDownload() { + PublishedFileId_t fileID = new(ID); + uint state = SteamUGC.GetItemState(fileID); + if ((state & (uint)(EItemState.k_EItemStateInstalled | EItemState.k_EItemStateNeedsUpdate)) == (uint)EItemState.k_EItemStateInstalled) { + if (SteamUGC.GetItemInstallInfo(fileID, out _, out _, 260, out uint timeStamp) && timeStamp != Details.m_rtimeUpdated) + state |= (uint)EItemState.k_EItemStateNeedsUpdate; + } + + if ((state & 0xe) == (uint)EItemState.k_EItemStateInstalled) { + OnInstalled(); + return; + } + + if ((state & (uint)EItemState.k_EItemStateInstalled) != 0 && (state & (uint)EItemState.k_EItemStateLegacyItem) != 0 && (state & (uint)EItemState.k_EItemStateNeedsUpdate) == 0) { + string path = $"cache/workshop/{ID}.gma"; + using IFileHandle? file = filesystem.Open(path, FileOpenOptions.Read | FileOpenOptions.Binary, "MOD"); + if (file != null) { + Span timestamp = stackalloc byte[4]; + file.Stream.Seek(GMATimestampOffset, SeekOrigin.Begin); + timestamp.Clear(); + file.Stream.ReadAtLeast(timestamp, 4, false); + file.Dispose(); + + if (BitConverter.ToUInt32(timestamp) == Details.m_rtimeUpdated) { + if (!SteamUGC.GetItemInstallInfo(fileID, out _, out _, 260, out _)) + Warning($"steamworks.DownloadUGC: Failed to GetItemInstallInfo for '{Details.m_rgchTitle}' ({ID}) to mark as used\n"); + Finish(path); + return; + } + } + } + + if (SteamUGC.DownloadItem(fileID, true)) { + ItemDownloaded?.Dispose(); + ItemDownloaded = Callback.Create(OnItemDownloaded); + return; + } + + Warning($"steamworks.DownloadUGC: Failed to initialize download for addon {ID}\n"); + Fail(); + } + + void OnItemDownloaded(DownloadItemResult_t result) { + if (!LuaValid) { + Destroy(); + return; + } + + if (result.m_eResult != EResult.k_EResultOK) { + Warning($"steamworks.DownloadUGC: Failed to download addon {ID}, {LuaSteamworks.EResultString(result.m_eResult)}\n"); + Fail(); + return; + } + + if (result.m_nPublishedFileId.m_PublishedFileId != ID || result.m_unAppID.m_AppId != 4000) + return; + + if ((SteamUGC.GetItemState(new PublishedFileId_t(ID)) & (uint)EItemState.k_EItemStateLegacyItem) != 0) + OnLegacyInstalled(); + else + OnInstalled(); + } + + void OnInstalled() { + string path = filesystem.Addons().GetAddonFilepath(ID, false); + if (string.IsNullOrEmpty(path)) { + Warning($"steamworks.DownloadUGC: Failed to get SteamUGC file for {ID}\n"); + Fail(); + return; + } + + Finish(path); + } + + void OnLegacyInstalled() { + if (!SteamUGC.GetItemInstallInfo(new PublishedFileId_t(ID), out _, out string folder, 260, out _)) { + Warning($"steamworks.DownloadUGC: Failed to GetItemInstallInfo for {ID}\n"); + Fail(); + return; + } + + long size = filesystem.Size(folder, null); + byte[] data = size > 0 ? new byte[size] : []; + if (size < 0 || !filesystem.ReadFile(folder, null, data, 0)) { + Warning($"steamworks.DownloadUGC: Failed to read addon file '{folder}' for {ID}\n"); + Fail(); + return; + } + + int length = data.Length; + if (length <= 0) { + Warning($"steamworks.DownloadUGC: This should never happen: Addon {Details.m_rgchTitle} ({ID}) is 0 bytes!?\n"); + Fail(); + return; + } + + if (BitConverter.ToUInt32(data, length - 4) == 0xbeefcace) + length -= 8; + else + Warning($"Addon {Details.m_rgchTitle} ({ID}) was created with a 3rd party tool, which might cause install/load issues.\n"); + + string outFile = $"{get.GameDir()}/cache/workshop/{ID}.gma".Replace('\\', '/'); + Extraction = new LZMA.ExtractionThread(data.AsSpan(0, length), outFile); + } + + public void Think() { + if (SteamUGC.GetItemDownloadInfo(new PublishedFileId_t(ID), out ulong downloaded, out ulong total) && total > 0) + filesystem.Addons().Notify()?.DownloadProgress(ID, 0, "", (uint)downloaded, (uint)total); + + if (Extraction == null) + return; + + if (!Extraction.IsDone()) { + filesystem.Addons().Notify()?.ExtractProgress(ID, 0, "", (uint)(int)Extraction.GetProgress()); + return; + } + + string path = $"cache/workshop/{ID}.gma"; + if (!Extraction.Success()) { + Warning($"steamworks.DownloadUGC: Extraction failed.. Oh oh! ({path})\n"); + Extraction = null; + Fail(); + return; + } + + Extraction = null; + + IFileHandle? file = filesystem.Open(path, FileOpenOptions.ReadEx | FileOpenOptions.Binary, null); + if (file == null) { + Warning($"steamworks.DownloadUGC: This should not happen - failed to write timestamp to '{path}'!\n"); + Finish(path); + return; + } + + int type; + using (file) { + file.Stream.Seek(2, SeekOrigin.Begin); + type = file.Stream.ReadByte(); + if (type == 'A') { + file.Stream.Seek(GMATimestampOffset, SeekOrigin.Begin); + file.Stream.Write(BitConverter.GetBytes(Details.m_rtimeUpdated)); + } + } + + string oldPath = path; + string? newPath = type switch { + 'S' => $"cache/workshop/{ID}.gms", + 'P' => $"cache/workshop/{ID}.dupe", + 'O' => $"cache/workshop/{ID}.dem", + _ => null + }; + + if (newPath != null) { + path = newPath; + filesystem.RenameFile(oldPath, path, null); + } + + Finish(path); + } + + void Finish(string path) { + if (!LuaValid) { + Destroy(); + return; + } + + path = path.Replace('\\', '/'); + int index = path.IndexOf("steamapps/workshop/content/4000", StringComparison.Ordinal); + if (index != -1) + path = path[(index + "steamapps/workshop/".Length)..]; + + Callback.Push(); + g_Lua!.PushString(path); + g_Lua.CallInternalNoReturns(1); + Destroy(); + } +} + +static class UGCDownloadManager +{ + struct QueuedDownload + { + public int Reference; + public ulong ID; + } + + static readonly List Queue = []; + public static UGCDownloadJob? Active; + static int LuaStarts; + static int Total; + + static void ValidateLuaStarts() { + if (LuaStarts == g_LuaStarts) + return; + Queue.Clear(); + Active = null; + LuaStarts = g_LuaStarts; + } + + public static void SetActive(UGCDownloadJob job) { + if (Active != null) + Warning("DownloadUGCManager::SetActive: There's already a download! This should never happpen\n"); + else + Active = job; + } + + public static void Enqueue(ulong id, int reference) { + ValidateLuaStarts(); + Queue.Add(new QueuedDownload { Reference = reference, ID = id }); + Total++; + filesystem.Addons().Notify()?.DownloadTotals(Queue.Count, Total); + ProcessQueue(); + } + + public static void ProcessQueue() { + if (LuaStarts != g_LuaStarts) { + Queue.Clear(); + Active = null; + LuaStarts = 0; + } + else if (Active != null) + return; + + if (Queue.Count == 0) { + filesystem.Addons().Notify()?.Finish(); + Total = 0; + return; + } + + QueuedDownload next = Queue[0]; + Queue[0] = Queue[^1]; + Queue.RemoveAt(Queue.Count - 1); + + g_Lua!.ReferencePush(next.Reference); + LuaObject callback = new(); + callback.SetFromStack(-1); + g_Lua.ReferenceFree(next.Reference); + g_Lua.Pop(1); + + filesystem.Addons().Notify()?.DownloadTotals(Queue.Count, Total); + _ = new UGCDownloadJob(next.ID, callback); + callback.UnReference(); + } + + public static void Think() => Active?.Think(); +} +#if MENU_DLL +class UGCPublisher : LuaCallbackRequest +{ + static readonly string[] BadWords = [ + "sex", "fuck", "nigger", "reich", "nazi", "swastika", "penis", "peen", "dick", "cock", "faggot", "gay", "naked", "nude", "18+", "+18", + "21+", "xxx", "goatse", "blowjob", "blow job", "samus", "shit", "miranda", "lawson", "boob", "fingering", "fingered", "back door action", + "got wood", "humping", "oral", "peinus", "alma", "mileena", "wank", "fap", "jacking", "jerking", "masturb", "masterb", "\"fun\"", "lolipop", + "strip", "miku", "honoka", "fnaf", "pony", "splatoon", "sans", "undertale", "achievement", "achiev", "reupload", "crash", "lag", "pls rate", + "please rate", "pls like", "please like", "pls upvote", "please upvote", "liek", "kill myself", "kys" + ]; + + ulong ID; + readonly string File; + readonly string Image; + readonly string Title; + readonly string Description; + readonly string Changes; + readonly List Tags = []; + readonly CallResult ItemUpdated; + readonly CallResult ItemCreated; + + static bool ContainsBadWords(string text) { + string lower = text.ToLowerInvariant(); + foreach (string word in BadWords) { + if (lower.Contains(word, StringComparison.Ordinal)) + return true; + } + return lower.Length > 10 && !lower.Contains(' '); + } + + public UGCPublisher(string file, string image, string title, string description, LuaObject tags, LuaObject callback, ulong id, string changes) { + Callback.Set(callback); + ID = id; + File = file; + Image = image; + Title = title; + Description = description; + Changes = changes; + ItemUpdated = CallResult.Create(OnItemUpdated); + ItemCreated = CallResult.Create(OnItemCreated); + + if (ContainsBadWords(Title) || ContainsBadWords(Description)) { + if (LuaValid) { + Callback.Push(); + g_Lua!.PushNil(); + g_Lua.PushString("badwords"); + g_Lua.CallInternalNoReturns(2); + } + Destroy(); + return; + } + + for (int i = 1; ; i++) { + string? tag = tags.GetMemberStr(i, null); + if (tag == null) + break; + Tags.Add(tag); + } + + if (ID != 0) { + StartUpdate(); + return; + } + + Changes = "Initial creation"; + SteamAPICall_t call = SteamUGC.CreateItem(new AppId_t(4000), EWorkshopFileType.k_EWorkshopFileTypeCommunity); + if (call == SteamAPICall_t.Invalid) { + Fail("badhandle"); + return; + } + + ItemCreated.Set(call); + } + + void Destroy() { + ItemCreated.Dispose(); + ItemUpdated.Dispose(); + Tags.Clear(); + Callback.UnReference(); + } + + void Fail(ReadOnlySpan reason) { + if (LuaValid) { + Callback.Push(); + g_Lua!.PushNil(); + g_Lua.PushString(reason); + g_Lua.CallInternalNoReturns(2); + } + Destroy(); + } + + void OnItemCreated(CreateItemResult_t result, bool ioFailure) { + if (result.m_bUserNeedsToAcceptWorkshopLegalAgreement) { + Fail("termsofservice"); + return; + } + + if (result.m_eResult != EResult.k_EResultOK) { + Warning($"steamworks.Publish failed to create ID - {LuaSteamworks.EResultString(result.m_eResult)}!\n"); + Fail("createid"); + return; + } + + ID = result.m_nPublishedFileId.m_PublishedFileId; + StartUpdate(); + } + + void StartUpdate() { + UGCUpdateHandle_t handle = SteamUGC.StartItemUpdate(new AppId_t(4000), new PublishedFileId_t(ID)); + if (handle == UGCUpdateHandle_t.Invalid) { + Fail("badupdatehandle"); + return; + } + + SteamUGC.SetItemTitle(handle, Title); + SteamUGC.SetItemDescription(handle, Description); + SteamUGC.SetItemPreview(handle, Image); + SteamUGC.SetItemContent(handle, File); + SteamUGC.SetItemTags(handle, Tags); + + SteamAPICall_t call = SteamUGC.SubmitItemUpdate(handle, Changes); + if (call == SteamAPICall_t.Invalid) { + Fail("badsubmitupdatehandle"); + return; + } + + ItemUpdated.Set(call); + } + + void OnItemUpdated(SubmitItemUpdateResult_t result, bool ioFailure) { + if (result.m_bUserNeedsToAcceptWorkshopLegalAgreement) { + Fail("termsofservice"); + return; + } + + if (result.m_eResult != EResult.k_EResultOK) { + Warning($"steamworks.Publish failed to update file - {LuaSteamworks.EResultString(result.m_eResult)}!\n"); + Fail("cantupdate"); + return; + } + + if (LuaValid) { + Callback.Push(); + g_Lua!.PushNumber(result.m_nPublishedFileId.m_PublishedFileId); + g_Lua.CallInternalNoReturns(1); + } + Destroy(); + } +} +#endif + +class UGCFileInfoRequest : LuaCallbackRequest +{ + static readonly string[] ContentDescriptorNames = ["suggestive", "gore", "adult_only", "nudity", "general_mature"]; + + readonly ulong ID; + readonly CallResult QueryCompleted; + + public UGCFileInfoRequest(ulong id, LuaObject callback, bool fullInfo) { + ID = id; + Callback.Set(callback); + QueryCompleted = CallResult.Create(OnQueryCompleted); + + UGCQueryHandle_t handle = SteamUGC.CreateQueryUGCDetailsRequest([new PublishedFileId_t(id)], 1); + if (handle == UGCQueryHandle_t.Invalid) { + CallError(-1); + Destroy(); + return; + } + + SteamUGC.SetReturnChildren(handle, true); + if (fullInfo) { + SteamUGC.SetReturnLongDescription(handle, true); + SteamUGC.SetReturnAdditionalPreviews(handle, true); + } + + SteamAPICall_t call = SteamUGC.SendQueryUGCRequest(handle); + if (call == SteamAPICall_t.Invalid) { + CallError(-2); + Destroy(); + return; + } + + QueryCompleted.Set(call); + } + + void Destroy() { + QueryCompleted.Dispose(); + Callback.UnReference(); + } + + void OnQueryCompleted(SteamUGCQueryCompleted_t result, bool ioFailure) { + if (!LuaValid) { + Destroy(); + return; + } + + if (ioFailure || result.m_eResult != EResult.k_EResultOK) { + Warning($"steamworks.FileInfo() failed ({LuaSteamworks.EResultString(result.m_eResult)})\n"); + CallError((int)result.m_eResult); + } + else if (result.m_unNumResultsReturned != 1) + CallError(-3); + else if (!SteamUGC.GetQueryUGCResult(result.m_handle, 0, out SteamUGCDetails_t details)) + CallError(-4); + else if (details.m_nPublishedFileId.m_PublishedFileId == 0) + CallError(-5); + else if (details.m_nPublishedFileId.m_PublishedFileId == ID) + PushDetails(result.m_handle, in details); + + SteamUGC.ReleaseQueryUGCRequest(result.m_handle); + Destroy(); + } + + void PushDetails(UGCQueryHandle_t handle, in SteamUGCDetails_t details) { + SteamFriends.RequestUserInformation(new CSteamID(details.m_ulSteamIDOwner), true); + + LuaTable table = new(); + table.SetMember("id", details.m_nPublishedFileId.m_PublishedFileId.ToString()); + table.SetMember("title", details.m_rgchTitle); + table.SetMember("description", details.m_rgchDescription); + table.SetMember("fileid", (details.m_hFile.m_UGCHandle == ulong.MaxValue ? 0 : details.m_hFile.m_UGCHandle).ToString()); + table.SetMember("previewid", details.m_hPreviewFile.m_UGCHandle.ToString()); + table.SetMember("owner", details.m_ulSteamIDOwner.ToString()); + table.SetMember("created", (float)details.m_rtimeCreated); + table.SetMember("updated", (float)details.m_rtimeUpdated); + table.SetMember("banned", details.m_bBanned); + table.SetMember("tags", details.m_rgchTags); + table.SetMember("size", (float)(uint)details.m_nFileSize); + table.SetMember("visibility", (float)(int)details.m_eVisibility); + table.SetMember("previewsize", (float)details.m_nPreviewFileSize); + + if (string.IsNullOrEmpty(details.m_rgchTitle)) { + table.SetMember("title", "Hidden addon"); + table.SetMember("description", "This workshop item was hidden by its author. You may not be able to use it."); + } + + Addon.FileSystem addons = filesystem.Addons(); + ulong id = details.m_nPublishedFileId.m_PublishedFileId; + if (addons.IsSubscribed(id)) { + table.SetMember("installed", addons.IsSubscribed(id)); + table.SetMember("disabled", !addons.ShouldMount(id)); + } + else { + table.SetMember("installed", false); + table.SetMember("disabled", false); + } + + table.SetMember("score", details.m_flScore); + table.SetMember("up", (float)details.m_unVotesUp); + table.SetMember("down", (float)details.m_unVotesDown); + table.SetMember("total", (float)(details.m_unVotesUp + details.m_unVotesDown)); + + table.SetMember("previewurl", SteamUGC.GetQueryUGCPreviewURL(handle, 0, out string previewURL, 0x200) ? previewURL : ""); + + PublishedFileId_t[] children = new PublishedFileId_t[details.m_unNumChildren]; + bool hasChildren = SteamUGC.GetQueryUGCChildren(handle, 0, children, details.m_unNumChildren); + LuaTable childTable = new(); + if (hasChildren) { + for (int i = 0; i < children.Length; i++) + childTable.SetMemberDouble(i + 1, children[i].m_PublishedFileId); + } + table.SetMember("children", childTable); + childTable.UnReference(); + + uint previews = SteamUGC.GetQueryUGCNumAdditionalPreviews(handle, 0); + if (previews != 0) { + LuaTable previewTable = new(); + for (uint i = 0; i < previews; i++) { + if (!SteamUGC.GetQueryUGCAdditionalPreview(handle, 0, i, out string url, 0x200, out _, 0, out EItemPreviewType type)) + continue; + LuaTable preview = new(); + preview.SetMember("url", url); + preview.SetMember("type", (int)type); + previewTable.SetMember(i + 1, preview); + preview.UnReference(); + } + table.SetMember("extra_previews", previewTable); + previewTable.UnReference(); + } + + table.SetMember("ownername", SteamFriends.GetFriendPersonaName(new CSteamID(details.m_ulSteamIDOwner)) ?? "Unnammed Player"); + + EUGCContentDescriptorID[] descriptors = new EUGCContentDescriptorID[8]; + uint descriptorCount = SteamUGC.GetQueryUGCContentDescriptors(handle, 0, descriptors, 8); + LuaTable descriptorTable = new(); + for (int i = 0; i < descriptorCount; i++) { + int descriptor = (int)descriptors[i]; + if (descriptor >= 1 && descriptor <= 5) + descriptorTable.SetMember(i + 1, ContentDescriptorNames[descriptor - 1]); + else + descriptorTable.SetMemberDouble(i + 1, descriptor); + } + table.SetMember("content_descriptors", descriptorTable); + descriptorTable.UnReference(); + + Call(table); + table.UnReference(); + } +} +#if MENU_DLL +class UGCFileUserInfoRequest : LuaCallbackRequest +{ + readonly ulong ID; + readonly CallResult VoteResult; + + public UGCFileUserInfoRequest(ulong id, LuaObject callback) { + ID = id; + Callback.Set(callback); + VoteResult = CallResult.Create(OnVoteResult); + + SteamAPICall_t call = SteamUGC.GetUserItemVote(new PublishedFileId_t(id)); + if (call == SteamAPICall_t.Invalid) { + CallError("Invalid API Call Handle"); + Destroy(); + return; + } + + VoteResult.Set(call); + } + + void Destroy() { + VoteResult.Dispose(); + Callback.UnReference(); + } + + void OnVoteResult(GetUserItemVoteResult_t result, bool ioFailure) { + if (!LuaValid) { + Destroy(); + return; + } + + if (ioFailure || result.m_eResult != EResult.k_EResultOK) + CallError(LuaSteamworks.EResultString(result.m_eResult)); + else if (result.m_nPublishedFileId.m_PublishedFileId == ID) { + LuaTable table = new(); + table.SetMember("voted_up", result.m_bVotedUp); + table.SetMember("voted_down", result.m_bVotedDown); + table.SetMember("favorite", WorkshopFavoritesCache.Favorites.Contains(ID)); + Call(table); + table.UnReference(); + } + + Destroy(); + } +} +#endif + +class UGCListRequest : LuaCallbackRequest +{ + readonly uint NumRetrieve; + uint Offset; + readonly uint Days; + ulong UserID; + readonly EUGCQuery QueryType; + readonly EUserUGCList ListType; + readonly string Search; + readonly List Tags = []; + readonly LuaTable Results = new(); + uint Collected; + uint Total; + readonly CallResult QueryCompleted; + + public UGCListRequest(string type, LuaObject tags, uint offset, uint numRetrieve, uint days, ulong userID, LuaObject callback, string search) { + QueryCompleted = CallResult.Create(OnQueryCompleted); + Offset = offset; + NumRetrieve = Math.Min(numRetrieve, 50); + Days = Math.Min(days, 365); + UserID = userID; + Callback.Set(callback); + Search = search; + + QueryType = 0; + ListType = 0; + if (type == "popular" && Days > 0) + QueryType = (EUGCQuery)10; + else if (type == "trending") + QueryType = (EUGCQuery)3; + else if (type == "latest") + QueryType = (EUGCQuery)1; + else if (type == "friends") + QueryType = (EUGCQuery)5; + else if (type == "followed") { + QueryType = (EUGCQuery)7; + ListType = (EUserUGCList)8; + } + else if (type == "friend_favs") + QueryType = (EUGCQuery)4; + else if (type == "favorite") { + ListType = (EUserUGCList)5; + UserID = 1; + } + + if (Days == 0) + Days = 7; + + for (int i = 1; ; i++) { + string? tag = tags.GetMemberStr(i, null); + if (tag == null) + break; + Tags.Add(tag); + } + + Run(); + } + + void Run() { + UGCQueryHandle_t handle; + uint page = Offset / 50 + 1; + if (UserID == 0) + handle = SteamUGC.CreateQueryAllUGCRequest(QueryType, EUGCMatchingUGCType.k_EUGCMatchingUGCType_Items_ReadyToUse, new AppId_t(4000), new AppId_t(4000), page); + else { + AccountID_t accountID; + if (UserID == 1) { + if (!SteamworksExts.HasSteamClient() || SteamworksExts.GetSteamUser() == IntPtr.Zero) { + Warning("Couldn't get UGC list for local player, no SteamUser API!\n"); + Finish(); + return; + } + accountID = SteamUser.GetSteamID().GetAccountID(); + } + else + accountID = new AccountID_t((uint)UserID); + + handle = SteamUGC.CreateQueryUserUGCRequest(accountID, ListType, EUGCMatchingUGCType.k_EUGCMatchingUGCType_Items_ReadyToUse, 0, new AppId_t(4000), new AppId_t(4000), page); + } + + if (handle == UGCQueryHandle_t.Invalid) { + Warning("k_UGCQueryHandleInvalid!\n"); + Finish(); + return; + } + + SteamUGC.SetRankedByTrendDays(handle, Days); + SteamUGC.SetReturnOnlyIDs(handle, true); + if (Search.Length != 0) + SteamUGC.SetSearchText(handle, Search); + if ((int)QueryType is 0 or 1 or 3) + SteamUGC.AddExcludedTag(handle, "ServerContent"); + foreach (string tag in Tags) + SteamUGC.AddRequiredTag(handle, tag); + + SteamAPICall_t call = SteamUGC.SendQueryUGCRequest(handle); + if (call == SteamAPICall_t.Invalid) { + Finish(); + return; + } + + QueryCompleted.Set(call); + } + + void OnQueryCompleted(SteamUGCQueryCompleted_t result, bool ioFailure) { + if (result.m_eResult != EResult.k_EResultOK) { + Warning($"steamworks.GetList failed! {LuaSteamworks.EResultString(result.m_eResult)}\n"); + Finish(); + return; + } + + Total = result.m_unTotalMatchingResults; + for (uint i = 0; i <= result.m_unNumResultsReturned; i++) { + if (i < Offset % 50) + continue; + if (Collected >= NumRetrieve) + break; + if (SteamUGC.GetQueryUGCResult(result.m_handle, i, out SteamUGCDetails_t details)) + Results.SetMember(Collected++, details.m_nPublishedFileId.m_PublishedFileId.ToString()); + } + + SteamUGC.ReleaseQueryUGCRequest(result.m_handle); + + if (Collected < NumRetrieve && Collected < Total && Offset + Collected < Total) { + Offset += Collected; + Run(); + return; + } + + Finish(); + } + + void Finish() { + if (LuaValid) { + LuaTable table = new(); + table.SetMember("totalresults", (float)Total); + table.SetMember("numresults", (float)Collected); + table.SetMember("results", Results); + Call(table); + table.UnReference(); + } + + QueryCompleted.Dispose(); + Results.UnReference(); + Callback.UnReference(); + } +} + +class UGCRemoteDownload : LuaCallbackRequest +{ + readonly ulong Handle; + readonly bool Uncompress; + readonly CallResult DownloadResult; + + public UGCRemoteDownload(ulong handle, bool uncompress, LuaObject callback, SteamAPICall_t call) { + Handle = handle; + Uncompress = uncompress; + Callback.Set(callback); + DownloadResult = CallResult.Create(OnDownloaded); + DownloadResult.Set(call); + } + + void Destroy() { + DownloadResult.Dispose(); + Callback.UnReference(); + } + + void OnDownloaded(RemoteStorageDownloadUGCResult_t result, bool ioFailure) { + if (!LuaValid || result.m_eResult != EResult.k_EResultOK) { + CallNoArgs(); + Destroy(); + return; + } + + UGCHandle_t handle = new(Handle); + SteamRemoteStorage.GetUGCDetails(handle, out _, out _, out int size, out _); + byte[] data = new byte[Math.Max(size, 0)]; + int read = SteamRemoteStorage.UGCRead(handle, data, size, 0, EUGCReadAction.k_EUGCRead_Close); + if (read == 0) { + CallNoArgs(); + Destroy(); + return; + } + + string path = $"cache/workshop/{Handle}.cache"; + if (Uncompress) { + using MemoryStream output = new(); + LZMA.Extract(data.AsSpan(0, read), output); + filesystem.WriteFile(path, "MOD", output.GetBuffer().AsSpan(0, (int)output.Length)); + } + else + filesystem.WriteFile(path, "MOD", data.AsSpan(0, read)); + + Callback.Push(); + g_Lua!.PushString(path); + g_Lua.CallInternalNoReturns(1); + Destroy(); + } +} + +class PlayerInfoRequest : LuaCallbackRequest +{ + readonly CSteamID SteamID; + readonly Callback PersonaStateChange; + + public PlayerInfoRequest(CSteamID steamID, LuaObject callback) { + SteamID = steamID; + Callback.Set(callback); + PersonaStateChange = Callback.Create(OnPersonaStateChange); + } + + void OnPersonaStateChange(PersonaStateChange_t change) { + if (change.m_ulSteamID != SteamID.m_SteamID || (change.m_nChangeFlags & EPersonaChange.k_EPersonaChangeName) == 0) + return; + + if (LuaValid && Callback.isFunction()) { + Callback.Push(); + g_Lua!.PushString(SteamFriends.GetFriendPersonaName(SteamID)); + g_Lua.CallInternalNoReturns(1); + } + + PersonaStateChange.Dispose(); + Callback.UnReference(); + } +} +#endif + +public static partial class LuaSteamworks +{ + [LuaLibrary] + static readonly LuaLibrary LL_Factory_steamworks = new("steamworks"); + +#if CLIENT_DLL || MENU_DLL + static readonly List UnusedItems = []; + + [DllImport("steam_api64", CallingConvention = CallingConvention.Cdecl, EntryPoint = "SteamAPI_ISteamUGC_GetDownloadedItems")] + static unsafe extern uint ISteamUGC_GetDownloadedItems(IntPtr instancePtr, ulong* pvecPublishedFileIDs, uint cMaxEntries); + + public static string EResultString(EResult result) => (int)result switch { + 1 => "OK", + 2 => "Generic failure", + 3 => "No internet connection", + 6 => "Logged in elsewhere", + 8 => "Invalid parameter (Weird symbols in name/descrption?)", + 9 => "File not found", + 10 => "Method is busy", + 15 => "Access denied (Item hidden/banned?)", + 16 => "Timed out", + 17 => "Item/user is banned", + 18 => "Account not found", + 20 => "Service unavailable", + 21 => "Not logged on", + 24 => "Insufficient privilege", + 25 => "Limit exceeded", + 34 => "Log on session replaced (Your GSLT is used elsewhere)", + 37 => "Input/output failure", + 51 => "Operation suspended", + 52 => "Operation cancelled", + 54 => "Disk drive full", + 86 => "Item(GSLT?) deleted", + 93 => "Time is not synched", + 102 => "GSL token banned", + 103 => "GS owner denied", + 106 => "GSL token expired", + 112 => "Limited user account", + _ => $"Steam error code {(int)result}" + }; + + static ulong ParseID(ReadOnlySpan str) { + str = str.TrimStart(" \t\n\v\f\r"); + bool negative = false; + if (str.Length > 0 && (str[0] == '+' || str[0] == '-')) { + negative = str[0] == '-'; + str = str[1..]; + } + + int digits = 0; + while (digits < str.Length && char.IsAsciiDigit(str[digits])) + digits++; + + if (digits == 0 || !ulong.TryParse(str[..digits], out ulong value)) + return 0; + return negative ? unchecked(0 - value) : value; + } + + static ulong CheckID(ILuaInterface lua, int stackPos) => ParseID(lua.CheckString(stackPos)); + + static bool CheckUGC(ILuaInterface lua) { + if (get.SteamUGC() != null) + return true; + lua.ErrorFromLua("Calling steamworks functions too early.\n"); + return false; + } + + static LuaObject CheckFunction(ILuaInterface lua, int stackPos) { + LuaObject func = new(stackPos, LuaType.None); + if (!func.isFunction()) + lua.TypeError("function", stackPos); + return func; + } + + [LuaFunction] + static int GetPlayerName(ILuaInterface lua) { + ulong id = CheckID(lua, 1); + lua.PushString(SteamFriends.GetFriendPersonaName(new CSteamID(id))); + return 1; + } + + [LuaFunction] + static int RequestPlayerInfo(ILuaInterface lua) { + ulong id = CheckID(lua, 1); + if (id == 0) + return 0; + + CSteamID steamID = new(id); + LuaObject callback = new(2, LuaType.None); + if (!SteamFriends.RequestUserInformation(steamID, true)) { + if (callback.isFunction()) { + callback.Push(); + lua.PushString(SteamFriends.GetFriendPersonaName(steamID)); + lua.CallInternalNoReturns(1); + } + } + else + _ = new PlayerInfoRequest(steamID, callback); + + callback.UnReference(); + return 0; + } + + [LuaFunction] + static int ViewFile(ILuaInterface lua) { + ulong id = CheckID(lua, 1); + if (id == 0) + return 0; + SteamFriends.ActivateGameOverlayToWebPage($"https://steamcommunity.com/sharedfiles/filedetails/?id={id}"); + return 0; + } + + [LuaFunction] + static int OpenWorkshop(ILuaInterface lua) { + SteamFriends.ActivateGameOverlayToWebPage("http://steamcommunity.com/app/4000/workshop/"); + return 0; + } + +#if MENU_DLL + [LuaFunction] + static int Subscribe(ILuaInterface lua) { + ulong id = CheckID(lua, 1); + if (id == 0) + return 0; + SteamUGC.SubscribeItem(new PublishedFileId_t(id)); + return 0; + } + + [LuaFunction] + static int Unsubscribe(ILuaInterface lua) { + ulong id = CheckID(lua, 1); + if (id == 0) + return 0; + SteamUGC.UnsubscribeItem(new PublishedFileId_t(id)); + return 0; + } + + [LuaFunction] + static int Vote(ILuaInterface lua) { + ulong id = CheckID(lua, 1); + if (id == 0) + return 0; + SteamUGC.SetUserItemVote(new PublishedFileId_t(id), lua.GetBool(2)); + return 0; + } + + [LuaFunction] + static int SetFavorite(ILuaInterface lua) { + ulong id = CheckID(lua, 1); + if (id == 0) + return 0; + + if (lua.GetBool(2)) { + SteamUGC.AddItemToFavorites(new AppId_t(4000), new PublishedFileId_t(id)); + WorkshopFavoritesCache.Favorites.Add(id); + } + else { + SteamUGC.RemoveItemFromFavorites(new AppId_t(4000), new PublishedFileId_t(id)); + WorkshopFavoritesCache.Favorites.Remove(id); + } + return 0; + } + + [LuaFunction] + static int SetFilePlayed(ILuaInterface lua) { + ulong id = CheckID(lua, 1); + if (id == 0) + return 0; + SteamRemoteStorage.SetUserPublishedFileAction(new PublishedFileId_t(id), EWorkshopFileAction.k_EWorkshopFileActionPlayed); + return 1; + } + + [LuaFunction] + static int SetFileCompleted(ILuaInterface lua) { + ulong id = CheckID(lua, 1); + if (id == 0) + return 0; + SteamRemoteStorage.SetUserPublishedFileAction(new PublishedFileId_t(id), EWorkshopFileAction.k_EWorkshopFileActionCompleted); + return 1; + } +#endif + + [LuaFunction] + static int IsSubscribed(ILuaInterface lua) { + lua.PushBool(filesystem.Addons().IsSubscribed(CheckID(lua, 1))); + return 1; + } + + [LuaFunction] + static int ShouldMountAddon(ILuaInterface lua) { + lua.PushBool(filesystem.Addons().ShouldMount(CheckID(lua, 1))); + return 1; + } + +#if MENU_DLL + [LuaFunction] + static int SetShouldMountAddon(ILuaInterface lua) { + filesystem.Addons().SetShouldMount(CheckID(lua, 1), lua.GetBool(2)); + return 0; + } + + [LuaFunction] + static int ApplyAddons(ILuaInterface lua) { + filesystem.Addons().Save(); + filesystem.Addons().Clear(); + filesystem.Addons().Refresh(); + filesystem.Gamemodes().Refresh(); + filesystem.DoFilesystemRefresh(); + return 0; + } + + [LuaFunction] + static int MarkDownloadedItemAsUnused(ILuaInterface lua) { + if (!CheckUGC(lua)) + return 0; + + ulong id = CheckID(lua, 1); + if (!UnusedItems.Contains(id)) + UnusedItems.Add(id); + SteamUGC.MarkDownloadedItemAsUnused(new PublishedFileId_t(id)); + return 0; + } + + [LuaFunction] + static unsafe int GetDownloadedItems(ILuaInterface lua) { + if (!CheckUGC(lua)) + return 0; + + uint numDownloaded = SteamUGC.GetNumDownloadedItems(); + ulong[] downloaded = new ulong[numDownloaded]; + uint gotDownloaded; + fixed (ulong* ids = downloaded) + gotDownloaded = ISteamUGC_GetDownloadedItems(SteamworksExts.GetSteamUGC(), ids, numDownloaded); + if (gotDownloaded != numDownloaded) + Warning("GetDownloadedItems: download count mismatch?\n"); + + uint numSubscribed = SteamUGC.GetNumSubscribedItems(); + PublishedFileId_t[] subscribed = new PublishedFileId_t[numSubscribed]; + if (SteamUGC.GetSubscribedItems(subscribed, numSubscribed) != numSubscribed) + Warning("GetDownloadedItems: subscription count mismatch?\n"); + + lua.CreateTable(); + if (numDownloaded == numSubscribed) + return 1; + + int key = 1; + foreach (ulong id in downloaded) { + if (Array.Exists(subscribed, s => s.m_PublishedFileId == id) || UnusedItems.Contains(id)) + continue; + lua.PushNumber(key++); + lua.PushString(id.ToString()); + lua.RawSet(-3); + } + return 1; + } +#endif + + [LuaFunction] + static int FileInfo(ILuaInterface lua) { + if (!CheckUGC(lua)) + return 0; + + ulong id = CheckID(lua, 1); + LuaObject callback = CheckFunction(lua, 2); + bool fullInfo = lua.GetBool(3); + if (id != 0) + _ = new UGCFileInfoRequest(id, callback, fullInfo); + callback.UnReference(); + return 0; + } + + [LuaFunction] + static int VoteInfo(ILuaInterface lua) { + if (!CheckUGC(lua)) + return 0; + + ulong id = CheckID(lua, 1); + LuaObject callback = CheckFunction(lua, 2); + if (id != 0) + _ = new UGCFileInfoRequest(id, callback, false); + callback.UnReference(); + return 0; + } + +#if MENU_DLL + [LuaFunction] + static int FileUserInfo(ILuaInterface lua) { + ulong id = CheckID(lua, 1); + LuaObject callback = CheckFunction(lua, 2); + if (id != 0) + _ = new UGCFileUserInfoRequest(id, callback); + callback.UnReference(); + return 0; + } +#endif + + [LuaFunction] + static int GetList(ILuaInterface lua) { + if (!CheckUGC(lua)) + return 0; + + string type = lua.CheckString(1); + LuaObject tags = new(2, LuaType.None); + uint offset = (uint)(int)lua.CheckNumber(3); + uint numRetrieve = (uint)(int)lua.CheckNumber(4); + uint days = (uint)(int)lua.CheckNumber(5); + string userID = lua.CheckStringOpt(6, "0"); + LuaObject callback = CheckFunction(lua, 7); + string search = lua.CheckStringOpt(8, ""); + + _ = new UGCListRequest(type, tags, offset, numRetrieve, days, ParseID(userID), callback, search); + callback.UnReference(); + tags.UnReference(); + return 0; + } + + [LuaFunction] + static int Download(ILuaInterface lua) { + ulong handle = CheckID(lua, 1); + bool uncompress = lua.GetBool(2); + LuaObject callback = CheckFunction(lua, 3); + + if (handle == 0 || handle >= 0xFFFFFFFFFFFFFFFE) { + callback.UnReference(); + return 0; + } + + string path = $"cache/workshop/{handle}.cache"; + if (filesystem.FileExists(path, "MOD")) { + callback.Push(); + lua.PushString(path); + lua.CallInternalNoReturns(1); + } + else + _ = new UGCRemoteDownload(handle, uncompress, callback, SteamRemoteStorage.UGCDownload(new UGCHandle_t(handle), 1)); + + callback.UnReference(); + return 0; + } + + [LuaFunction] + static int DownloadUGC(ILuaInterface lua) { + ulong id = CheckID(lua, 1); + if (id == 0) + return 0; + + ILuaObject? callback = lua.GetObject(2); + if (callback == null || !callback.isFunction()) { + lua.TypeError("function", 2); + return 0; + } + + callback.Push(); + int reference = lua.ReferenceCreate(); + lua.Pop(1); + lua.Pop(1); + UGCDownloadManager.Enqueue(id, reference); + return 0; + } + +#if MENU_DLL + [LuaFunction] + static int Publish(ILuaInterface lua) { + string file = lua.CheckString(1); + string image = lua.CheckString(2); + string title = lua.CheckString(3); + string description = lua.CheckString(4); + LuaObject tags = new(5, LuaType.None); + LuaObject callback = new(6, LuaType.None); + + if (!callback.isFunction()) { + lua.TypeError("function", 6); + return 0; + } + + ulong id = lua.GetType(7) != LuaType.Nil ? ParseID(lua.CheckString(7)) : 0; + string changes = lua.CheckStringOpt(8, "None given."); + + Span fullFile = stackalloc char[260]; + ReadOnlySpan filePath = filesystem.RelativePathToFullPath(file, "MOD", fullFile); + if (filePath.IsEmpty) + Warning($"Warning! Failed to get full path for '{file}'!\n"); + + Span fullImage = stackalloc char[260]; + ReadOnlySpan imagePath = filesystem.RelativePathToFullPath(image, "MOD", fullImage); + if (imagePath.IsEmpty) + Warning($"Warning! Failed to get full path for '{file}'!\n"); + + _ = new UGCPublisher(new string(filePath.SliceNullTerminatedString()), new string(imagePath.SliceNullTerminatedString()), title, description, tags, callback, id, changes); + + callback.UnReference(); + tags.UnReference(); + return 0; + } +#endif +#endif +} +#endif diff --git a/Game.Shared/GarrysMod/LuaVideoWriter.cs b/Game.Shared/GarrysMod/LuaVideoWriter.cs new file mode 100644 index 000000000..8c740d760 --- /dev/null +++ b/Game.Shared/GarrysMod/LuaVideoWriter.cs @@ -0,0 +1,76 @@ +#if CLIENT_DLL || MENU_DLL +using Source.Common.Commands; +using Source.Common.GarrysMod; +using Source.Common.GarrysMod.Lua; + +#if CLIENT_DLL +namespace Game.Client.GarrysMod; +#else +namespace Game.MenuSystem.GarrysMod; +#endif + +public static partial class LuaVideoWriter +{ + [LuaClass(typeof(IVideoWriter), NullError = "Tried to use a NULL IVideoWriter!")] + public static readonly LuaClass LC_IVideoWriter = new("IVideoWriter", LuaType.Video, null, null); + + public static float FpsMaxRestore = -1.0f; + + [LuaMethod] + static int IVideoWriter____gc(ILuaInterface lua) { + IVideoWriter? writer = (IVideoWriter?)LC_IVideoWriter.Get(1); + if (writer != null) { + writer.Finish(); + writer.Delete(); + } + lua.SetUserType(1, 0); + return 0; + } + + [LuaMethod] + static void IVideoWriter__Finish(IVideoWriter writer) { + writer.Finish(); + if (FpsMaxRestore > -1.0f) { + ConVarRef fpsMax = new("fps_max"); + fpsMax.SetValue(FpsMaxRestore); + } + } + + [LuaMethod] + static int IVideoWriter__AddFrame(ILuaInterface lua) { + IVideoWriter? writer = (IVideoWriter?)LC_IVideoWriter.Get(1); + if (writer == null) { + lua.Error("Tried to use a NULL IVideoWriter!"); + return 0; + } + + float frameTime = (float)lua.CheckNumber(2); + if (lua.GetBool(3)) { + garrysmod.StartVideoScale(writer.Width, writer.Height); + writer.AddFrame(0, 0, frameTime); + garrysmod.EndVideoScale(writer.Width, writer.Height); + } + else + writer.AddFrame(0, 0, frameTime); + return 0; + } + + [LuaMethod] + static int IVideoWriter__Width(IVideoWriter writer) => writer.Width; + + [LuaMethod] + static int IVideoWriter__Height(IVideoWriter writer) => writer.Height; + + [LuaMethod] + static int IVideoWriter__SetRecordSound(ILuaInterface lua) { + IVideoWriter? writer = (IVideoWriter?)LC_IVideoWriter.Get(1); + if (writer == null) { + lua.Error("Tried to use a NULL IVideoWriter!"); + return 0; + } + + writer.RecordSound = lua.GetBool(2); + return 1; + } +} +#endif From f6b5e73a02e5a40dbf79c98438a53cfe53b90704 Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Thu, 15 Oct 2026 11:52:36 -0700 Subject: [PATCH 22/38] Update GarrysMod.cs --- Game.Shared/GarrysMod/GarrysMod.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Game.Shared/GarrysMod/GarrysMod.cs b/Game.Shared/GarrysMod/GarrysMod.cs index d0de0a9d7..9ee6a93db 100644 --- a/Game.Shared/GarrysMod/GarrysMod.cs +++ b/Game.Shared/GarrysMod/GarrysMod.cs @@ -583,6 +583,7 @@ public void Think() { #if CLIENT_DLL LuaTimer.Cycle(); LuaFileLibrary.AsyncCycle(); + UGCDownloadManager.Think(); #else Game.Server.GarrysMod.LuaNetworkedVars.g_LuaNetworkedVars?.Cycle(); Game.Server.GarrysMod.LuaTimer.Cycle(); From 93ac387ead18619447e1f8713750a486ae780442 Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Thu, 15 Oct 2026 11:53:05 -0700 Subject: [PATCH 23/38] More menusystem missing bits --- Game.MenuSystem/LuaMenuGlobals.cs | 226 ++++++++++++- Game.MenuSystem/LuaServerList.cs | 520 ++++++++++++++++++++++++++++++ Game.MenuSystem/MenuPanels.cs | 19 ++ Game.MenuSystem/MenuSystem.cs | 79 ++++- 4 files changed, 833 insertions(+), 11 deletions(-) create mode 100644 Game.MenuSystem/LuaServerList.cs diff --git a/Game.MenuSystem/LuaMenuGlobals.cs b/Game.MenuSystem/LuaMenuGlobals.cs index 9a286ec39..a06daf490 100644 --- a/Game.MenuSystem/LuaMenuGlobals.cs +++ b/Game.MenuSystem/LuaMenuGlobals.cs @@ -3,7 +3,14 @@ using Source.Common.Engine; using Source.Common.GarrysMod.Lua; using Source.Common.Launcher; +using Source.Common.Formats.Keyvalues; +using Source.Common.GUI; using Source.Common.Networking; +using Source.Engine; +using Source.GUI.Controls; + +using System.Net; +using System.Text; namespace Game.MenuSystem.GarrysMod; @@ -59,18 +66,225 @@ static int IsHostingGame(ILuaInterface lua) { return 1; } + static IPanel? FindChildByName(IPanel? parent, ReadOnlySpan name) { + if (parent == null) + return null; + + int count = parent.GetChildCount(); + for (int i = 0; i < count; i++) { + IPanel child = parent.GetChild(i); + if (child.GetName().SequenceEqual(name)) + return child; + + IPanel? found = FindChildByName(child, name); + if (found != null) + return found; + } + + return null; + } + + [LuaGlobal] + static int CancelLoading(ILuaInterface lua) { + IPanel? root = enginevgui.GetPanel(VGuiPanelType.Root); + if (root == null) + return 0; + + IPanel? dialog = FindChildByName(root, "LoadingDialog"); + if (dialog != null) + dialog.SendMessage(new KeyValues("Command", "command", "Cancel"), dialog); + return 0; + } + [LuaGlobal] static int GetLoadStatus(ILuaInterface lua) { - // todo - Warning("GetLoadStatus TODO\n"); - lua.PushString("GetLoadStatus TODO"); + IPanel? root = enginevgui.GetPanel(VGuiPanelType.Root); + if (root == null) + return 0; + + IPanel? dialog = FindChildByName(root, "LoadingDialog"); + if (dialog == null) + return 0; + + IPanel? label = FindChildByName(dialog, "InfoLabel"); + if (label is not Panel infoLabel) + return 0; + + KeyValues data = new("GetText"); + if (!infoLabel.RequestInfo(data)) + return 0; + + KeyValues? text = data.FindKey("text"); + if (text == null) + return 0; + + lua.PushString(text.GetString()); return 1; } + [LuaGlobal] static int NumDownloadables(ILuaInterface lua) { - // todo - Warning("NumDownloadables TODO\n"); - lua.PushString("NumDownloadables TODO"); + if (networkstringtable == null) + return 0; + + INetworkStringTable? downloadables = networkstringtable.FindTable(Protocol.DOWNLOADABLE_FILE_TABLENAME); + if (downloadables == null) { + lua.PushNumber(0); + return 0; + } + + lua.PushNumber(downloadables.GetNumStrings()); + return 1; + } + + [LuaGlobal] + static int TranslateDownloadableName(ILuaInterface lua) { + if (networkstringtable == null) + return 0; + + INetworkStringTable? luaFiles = networkstringtable.FindTable("client_lua_files"); + if (luaFiles == null) + return 0; + + Span fileBase = stackalloc char[64]; + lua.CheckString(1).FileBase(fileBase); + + for (int i = 0; i < luaFiles.GetNumStrings(); i++) { + ReadOnlySpan entry = luaFiles.GetString(i); + if (strncmp(fileBase, entry, entry.SliceNullTerminatedString().Length) == 0) { + lua.PushString("Lua Cache File"); + return 1; + } + } + + return 0; + } + + static byte[]? ReadWholeFile(ReadOnlySpan fileName, ReadOnlySpan pathID) { + long size = filesystem.Size(fileName, pathID); + if (size <= 0) + return null; + + byte[] data = new byte[size]; + return filesystem.ReadFile(fileName, pathID, data, 0) ? data : null; + } + + static string ReadFixedString(ReadOnlySpan data) { + int end = data.IndexOf((byte)0); + return Encoding.UTF8.GetString(end < 0 ? data : data[..end]); + } + + [LuaGlobal] + static int GetDemoFileDetails(ILuaInterface lua) { + byte[]? data = ReadWholeFile(lua.CheckString(1), "GAME"); + if (data == null || data.Length < 0x430) + return 0; + + ReadOnlySpan header = data; + if (header[0] != 'G' || header[1] != 'M' || header[2] != 'O' || header[3] != 'D') + return 0; + + lua.CreateTable(); + lua.PushNumber(BitConverter.ToInt32(header[0x8..])); + lua.SetField(-2, "demoprotocol"); + lua.PushNumber(BitConverter.ToInt32(header[0xc..])); + lua.SetField(-2, "networkprotocol"); + lua.PushString(ReadFixedString(header.Slice(0x10, 260))); + lua.SetField(-2, "servername"); + lua.PushString(ReadFixedString(header.Slice(0x114, 260))); + lua.SetField(-2, "clientname"); + lua.PushString(ReadFixedString(header.Slice(0x218, 260))); + lua.SetField(-2, "mapname"); + lua.PushString(ReadFixedString(header.Slice(0x31c, 260))); + lua.SetField(-2, "gamedirectory"); + lua.PushNumber(BitConverter.ToSingle(header[0x420..])); + lua.SetField(-2, "playback_time"); + lua.PushNumber(BitConverter.ToInt32(header[0x424..])); + lua.SetField(-2, "playback_ticks"); + lua.PushNumber(BitConverter.ToInt32(header[0x428..])); + lua.SetField(-2, "playback_frames"); + lua.PushNumber(BitConverter.ToInt32(header[0x42c..])); + lua.SetField(-2, "signonlength"); + return 1; + } + + static string ReadBufferString(ReadOnlySpan data, ref int get, int maxChars) { + int end = data[get..].IndexOf((byte)0); + int length = end < 0 ? data.Length - get : end; + string str = Encoding.UTF8.GetString(data.Slice(get, Math.Min(length, maxChars - 1))); + get = Math.Min(data.Length, get + length + 1); + return str; + } + + [LuaGlobal] + static int GetSaveFileDetails(ILuaInterface lua) { + byte[]? data = ReadWholeFile(lua.CheckString(1), "GAME"); + if (data == null) { + Msg("GetSaveFileDetails: Couldn't open file"); + return 0; + } + + if (data.Length < 4 || data[0] != 'G' || data[1] != 'M' || data[2] != 'S' || data[3] != '3') { + Msg("GetSaveFileDetails/ReadFromBuffer: Invalid save file"); + return 0; + } + + int get = 4; + string map = ReadBufferString(data, ref get, 512); + if (data.AsSpan(get).StartsWith("WSID:"u8)) { + get += 5; + ReadBufferString(data, ref get, 64); + } + + lua.CreateTable(); + lua.PushString(map); + lua.SetField(-2, "map"); + lua.PushNumber(0); + lua.SetField(-2, "time"); + lua.PushNumber(data.Length - get); + lua.SetField(-2, "size"); + return 1; + } + + const string AddonPresetsFile = "settings/addonpresets.txt"; + + [LuaGlobal] + static int LoadAddonPresets(ILuaInterface lua) { + byte[]? data = ReadWholeFile(AddonPresetsFile, "MOD"); + if (data == null) { + Msg("GetSaveFileDetails: Couldn't open file"); + return 0; + } + + int end = Array.IndexOf(data, (byte)0); + lua.PushString(end < 0 ? data : data.AsSpan(0, end)); + return 1; + } + + [LuaGlobal] + static int SaveAddonPresets(ILuaInterface lua) { + string presets = lua.CheckString(1); + filesystem.WriteFile(AddonPresetsFile, "MOD", Encoding.UTF8.GetBytes(presets)); + return 0; + } + + [LuaGlobal] + static int CanAddServerToFavorites(ILuaInterface lua) { + INetChannelInfo? nci = engine.GetNetChannelInfo(); + if (nci == null || nci.IsLoopback()) { + lua.PushBool(false); + return 1; + } + + bool canAdd = false; + ReadOnlySpan address = nci.GetAddress(); + if (!address.SequenceEqual("loopback") && IPEndPoint.TryParse(address, out IPEndPoint? endpoint)) { + byte[] ip = endpoint.Address.MapToIPv4().GetAddressBytes(); + bool localhost = ip[0] == 127 && ip[1] == 0 && ip[2] == 0 && ip[3] == 1; + canAdd = !localhost && endpoint.Port != 0 && !endpoint.Address.Equals(IPAddress.Any); + } + + lua.PushBool(canAdd); return 1; } diff --git a/Game.MenuSystem/LuaServerList.cs b/Game.MenuSystem/LuaServerList.cs new file mode 100644 index 000000000..cfc3152e7 --- /dev/null +++ b/Game.MenuSystem/LuaServerList.cs @@ -0,0 +1,520 @@ +#if MENU_DLL +using Source; +using Source.Common.GarrysMod.Lua; +using Source.Common.Networking; +using Source.Common.Steam; + +using Steamworks; + +using System.Net; +using System.Net.Sockets; +using System.Text; + +namespace Game.MenuSystem.GarrysMod; + +public static partial class LuaServerList +{ + [LuaLibrary] + static readonly LuaLibrary LL_Factory_serverlist = new("serverlist"); + + static readonly HashSet ActiveQueries = []; + static readonly Dictionary FavoritesCache = []; + static double LastFavoritesRefresh; + + static bool ParseAddress(ReadOnlySpan address, bool useDNS, out uint ip, out ushort port) { + ip = 0; + port = 0; + + ReadOnlySpan host = address; + int colon = address.LastIndexOf(':'); + if (colon >= 0) { + host = address[..colon]; + if (!ushort.TryParse(address[(colon + 1)..], out port)) + port = 0; + } + + if (!IPAddress.TryParse(host, out IPAddress? parsed)) { + if (!useDNS) + return false; + try { + parsed = Dns.GetHostAddresses(new string(host)).FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork); + } + catch (SocketException) { + parsed = null; + } + if (parsed == null) + return false; + } + + byte[] bytes = parsed.MapToIPv4().GetAddressBytes(); + ip = (uint)(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3]); + return true; + } + + static bool IsValidAddress(uint ip, ushort port) => ip != 0 && port != 0; + + static ulong FavoriteKey(uint ip, ushort port) => (ulong)port << 32 | ip; + + static string AddressToString(uint ip, ushort port) => $"{ip >> 24}.{(ip >> 16) & 0xff}.{(ip >> 8) & 0xff}.{ip & 0xff}:{port}"; + + static void RefreshFavorites() { + if (LastFavoritesRefresh + 10.0 > Platform.Time && FavoritesCache.Count != 0) + return; + + FavoritesCache.Clear(); + LastFavoritesRefresh = Platform.Time; + + int count = SteamMatchmaking.GetFavoriteGameCount(); + for (int i = 0; i < count; i++) { + SteamMatchmaking.GetFavoriteGame(i, out AppId_t appID, out uint ip, out ushort connPort, out _, out uint flags, out _); + if ((appID.m_AppId == 4000 || appID.m_AppId == 0) && (flags & Steamworks.Constants.k_unFavoriteFlagFavorite) != 0) + FavoritesCache[FavoriteKey(ip, connPort)] = true; + } + } + + static void ClearFavorites() => FavoritesCache.Clear(); + + static void SetFavorite(uint ip, ushort port, bool favorite) { + if (favorite) + SteamMatchmaking.AddFavoriteGame(SteamUtils.GetAppID(), ip, port, port, Steamworks.Constants.k_unFavoriteFlagFavorite, (uint)DateTimeOffset.UtcNow.ToUnixTimeSeconds()); + else + SteamMatchmaking.RemoveFavoriteGame(SteamUtils.GetAppID(), ip, port, port, Steamworks.Constants.k_unFavoriteFlagFavorite); + } + + [LuaFunction] + static int AddCurrentServerToFavorites(ILuaInterface lua) { + if (!SteamworksExts.HasSteamClient()) { + Warning("Failed to add server to favorites.\n"); + return 0; + } + + INetChannelInfo? nci = engine.GetNetChannelInfo(); + if (nci == null) + return 0; + + bool add = lua.GetBool(1); + ParseAddress(nci.GetAddress(), false, out uint ip, out ushort port); + SetFavorite(ip, port, add); + ClearFavorites(); + RefreshFavorites(); + return 0; + } + + [LuaFunction] + static int AddServerToFavorites(ILuaInterface lua) { + if (!SteamworksExts.HasSteamClient()) { + Warning("Failed to add server to favorites.\n"); + return 0; + } + + ParseAddress(lua.CheckString(1), false, out uint ip, out ushort port); + SetFavorite(ip, port, true); + ClearFavorites(); + RefreshFavorites(); + return 0; + } + + [LuaFunction] + static int RemoveServerFromFavorites(ILuaInterface lua) { + if (!SteamworksExts.HasSteamClient()) { + Warning("Failed to remove server from favorites.\n"); + return 0; + } + + ParseAddress(lua.CheckString(1), false, out uint ip, out ushort port); + SetFavorite(ip, port, false); + ClearFavorites(); + RefreshFavorites(); + return 0; + } + + [LuaFunction] + static int IsServerFavorite(ILuaInterface lua) { + if (!SteamworksExts.HasSteamClient()) { + Warning("IsServerFavorite: SteamMatchmaking does not exist!\n"); + lua.PushBool(false); + return 1; + } + + RefreshFavorites(); + ParseAddress(lua.CheckString(1), false, out uint ip, out ushort port); + lua.PushBool(FavoritesCache.GetValueOrDefault(FavoriteKey(ip, port))); + return 1; + } + + [LuaFunction] + static int IsCurrentServerFavorite(ILuaInterface lua) { + if (!SteamworksExts.HasSteamClient()) { + Warning("IsCurrentServerFavorite: No SteamUtils or SteamMatchmaking!\n"); + lua.PushBool(false); + return 1; + } + + INetChannelInfo? nci = engine.GetNetChannelInfo(); + if (nci == null) { + lua.PushBool(false); + return 1; + } + + RefreshFavorites(); + ParseAddress(nci.GetAddress(), false, out uint ip, out ushort port); + lua.PushBool(FavoritesCache.GetValueOrDefault(FavoriteKey(ip, port))); + return 1; + } + + static string FindTag(string tags, string prefix, int maxLength = int.MaxValue) { + int index = tags.IndexOf(prefix, StringComparison.Ordinal); + if (index < 0) + return ""; + + int start = index + prefix.Length; + int end = start < tags.Length ? tags.IndexOfAny([' ', ',', ';'], start) : -1; + int length = (end < 0 ? tags.Length : end) - start; + return tags.Substring(start, Math.Max(0, Math.Min(length, maxLength))); + } + + static readonly byte[] InvalidDescriptionBytes = Encoding.UTF8.GetBytes(",./*\\#~`¬{}=+_[]()\""); + + static bool DescriptionNeedsReplacing(string description) { + byte[] bytes = Encoding.UTF8.GetBytes(description); + if (bytes.Length < 3 || bytes.Length > 32) + return true; + return bytes.AsSpan().IndexOfAny(InvalidDescriptionBytes) >= 0; + } + + public static int PushServerDetails(ILuaInterface lua, gameserveritem_t server) { + if (server.m_nMaxPlayers <= 1) + server.m_nMaxPlayers = 2; + else if (server.m_nMaxPlayers > 128) + server.m_nMaxPlayers = 128; + + server.m_nPlayers = Math.Clamp(server.m_nPlayers, 0, 128); + server.m_nBotPlayers = Math.Clamp(server.m_nBotPlayers, 0, 128); + if (server.m_nBotPlayers > server.m_nPlayers) + server.m_nBotPlayers = server.m_nPlayers; + + string tags = server.GetGameTags(); + string gamemode = FindTag(tags, "gm:"); + string workshopID = FindTag(tags, "gmws:"); + string version = FindTag(tags, "ver:"); + string location = FindTag(tags, "loc:", 5); + string category = FindTag(tags, "gmc:"); + + string description = server.GetGameDescription(); + if (DescriptionNeedsReplacing(description)) + description = gamemode; + + bool anonymous = !(server.m_steamID.IsValid() && server.m_steamID.GetEAccountType() == EAccountType.k_EAccountTypeGameServer); + + string address = AddressToString(server.m_NetAdr.GetIP(), server.m_NetAdr.GetConnectionPort()); + string name = server.GetServerName(); + + lua.PushNumber(server.m_nPing); + lua.PushString(name.Length == 0 ? address : name); + lua.PushString(description); + lua.PushString(server.GetMap()); + lua.PushNumber(server.m_nPlayers); + lua.PushNumber(server.m_nMaxPlayers); + lua.PushNumber(server.m_nBotPlayers); + lua.PushBool(server.m_bPassword); + lua.PushNumber(server.m_ulTimeLastPlayed); + lua.PushString(address); + lua.PushString(gamemode); + lua.PushString(workshopID); + lua.PushBool(anonymous); + lua.PushNumber(server.m_nServerVersion); + lua.PushString(version); + lua.PushString(location); + lua.PushString(category); + return 17; + } + + class ServerListQuery + { + readonly int LuaStarts = MenuSystem.g_MenuSystem.LuaStarts; + readonly HashSet<(uint, ulong)> SeenSteamIDs = []; + readonly HashSet<(uint, ushort)> SeenAddresses = []; + readonly List Requests = []; + readonly LuaObject Data = new(); + readonly ISteamMatchmakingServerListResponse Response; + + public ServerListQuery(ILuaObject data) { + Response = new(ServerResponded, ServerFailedToRespond, RefreshComplete); + ActiveQueries.Add(this); + Data.Set(data); + + AppId_t appID = new((uint)Data.GetMemberInt("AppID", 4000)); + string type = Data.GetMemberStr("Type", "internet") ?? ""; + string gameDir = Data.GetMemberStr("GameDir", "garrysmod") ?? ""; + MatchMakingKeyValuePair_t[] filters = [new() { m_szKey = "gamedir", m_szValue = gameDir }]; + + switch (type) { + case "internet": Requests.Add(SteamMatchmakingServers.RequestInternetServerList(appID, filters, (uint)filters.Length, Response)); break; + case "lan": Requests.Add(SteamMatchmakingServers.RequestLANServerList(appID, Response)); break; + case "favorite": Requests.Add(SteamMatchmakingServers.RequestFavoritesServerList(appID, filters, (uint)filters.Length, Response)); break; + case "history": Requests.Add(SteamMatchmakingServers.RequestHistoryServerList(appID, filters, (uint)filters.Length, Response)); break; + case "friends": Requests.Add(SteamMatchmakingServers.RequestFriendsServerList(appID, filters, (uint)filters.Length, Response)); break; + } + } + + bool LuaValid() => LuaStarts == MenuSystem.g_MenuSystem.LuaStarts; + + void ServerResponded(HServerListRequest request, int index) { + if (!LuaValid()) { + Delete(); + return; + } + + gameserveritem_t server = SteamMatchmakingServers.GetServerDetails(request, index); + if (server == null) + return; + + if (!server.m_bHadSuccessfulResponse) { + ServerFailedToRespond(request, index); + return; + } + + if (server.GetGameTags().Contains("hltv:1", StringComparison.Ordinal)) + return; + + uint ip = server.m_NetAdr.GetIP(); + ushort port = server.m_NetAdr.GetConnectionPort(); + if (SeenSteamIDs.Contains((ip, server.m_steamID.m_SteamID)) || SeenAddresses.Contains((ip, port))) + return; + + SeenSteamIDs.Add((ip, server.m_steamID.m_SteamID)); + SeenAddresses.Add((ip, port)); + + LuaObject callback = new(); + Data.GetMember("Callback", callback); + if (callback.isFunction()) { + ILuaInterface lua = g_Lua!; + callback.Push(); + int args = PushServerDetails(lua, server); + LuaObject result = new(); + if (lua.CallInternalGet(args, result) && !result.isNil() && !result.GetBool()) { + foreach (HServerListRequest pending in Requests.ToArray()) + SteamMatchmakingServers.CancelQuery(pending); + } + result.UnReference(); + } + callback.UnReference(); + } + + void ServerFailedToRespond(HServerListRequest request, int index) { + if (!LuaValid()) { + Delete(); + return; + } + + gameserveritem_t server = SteamMatchmakingServers.GetServerDetails(request, index); + if (server == null) + return; + + LuaObject callback = new(); + Data.GetMember("CallbackFailed", callback); + if (callback.isFunction()) { + callback.Push(); + g_Lua!.PushString(AddressToString(server.m_NetAdr.GetIP(), server.m_NetAdr.GetQueryPort())); + LuaObject result = new(); + g_Lua.CallInternalGet(1, result); + result.UnReference(); + } + callback.UnReference(); + } + + void RefreshComplete(HServerListRequest request, EMatchMakingServerResponse response) { + Requests.Remove(request); + SteamMatchmakingServers.ReleaseRequest(request); + if (Requests.Count != 0) + return; + + if (LuaValid()) { + LuaObject finished = new(); + Data.GetMember("Finished", finished); + if (finished.isFunction()) { + finished.Push(); + g_Lua!.CallInternalNoReturns(0); + } + finished.UnReference(); + } + + Delete(); + } + + void Delete() { + foreach (HServerListRequest request in Requests) + SteamMatchmakingServers.ReleaseRequest(request); + Requests.Clear(); + Data.UnReference(); + ActiveQueries.Remove(this); + } + } + + [LuaFunction] + static int Query(ILuaInterface lua) { + ILuaObject? data = lua.GetObject(1); + if (data != null && data.isTable()) + _ = new ServerListQuery(data); + return 0; + } + + class PingQuery + { + readonly int LuaStarts = MenuSystem.g_MenuSystem.LuaStarts; + readonly LuaObject Callback = new(); + readonly ISteamMatchmakingPingResponse Response; + HServerQuery Query = HServerQuery.Invalid; + + public PingQuery(string address, ILuaObject callback) { + Response = new(ServerResponded, ServerFailedToRespond); + ActiveQueries.Add(this); + Callback.Set(callback); + + if (!SteamworksExts.HasSteamClient() || !ParseAddress(address, true, out uint ip, out ushort port) || !IsValidAddress(ip, port)) { + ServerFailedToRespond(); + return; + } + + Query = SteamMatchmakingServers.PingServer(ip, port, Response); + } + + void ServerResponded(gameserveritem_t server) { + Query = HServerQuery.Invalid; + if (LuaStarts == MenuSystem.g_MenuSystem.LuaStarts) { + Callback.Push(); + g_Lua!.CallInternalNoReturns(PushServerDetails(g_Lua, server)); + } + Delete(); + } + + void ServerFailedToRespond() { + if (LuaStarts == MenuSystem.g_MenuSystem.LuaStarts) { + Callback.Push(); + g_Lua!.CallInternalNoReturns(0); + } + Delete(); + } + + void Delete() { + if (Query != HServerQuery.Invalid) + SteamMatchmakingServers.CancelServerQuery(Query); + Query = HServerQuery.Invalid; + Callback.UnReference(); + ActiveQueries.Remove(this); + } + } + + [LuaFunction] + static int PingServer(ILuaInterface lua) { + string address = lua.CheckString(1); + ILuaObject? callback = lua.GetObject(2); + if (callback != null && callback.isFunction()) + _ = new PingQuery(address, callback); + return 0; + } + + class PlayerQuery + { + readonly int LuaStarts = MenuSystem.g_MenuSystem.LuaStarts; + readonly LuaTable Results = new(); + readonly LuaObject Callback = new(); + readonly ISteamMatchmakingPlayersResponse Response; + int Index = 1; + + public PlayerQuery(string address, ILuaObject callback) { + Response = new(AddPlayerToList, PlayersFailedToRespond, PlayersRefreshComplete); + ActiveQueries.Add(this); + Callback.Set(callback); + + ParseAddress(address, true, out uint ip, out ushort port); + SteamMatchmakingServers.PlayerDetails(ip, port, Response); + } + + void AddPlayerToList(string name, int score, float timePlayed) { + if (LuaStarts != MenuSystem.g_MenuSystem.LuaStarts) + return; + + LuaTable player = new(); + player.SetMember("name", name); + player.SetMember("score", (float)score); + player.SetMember("time", timePlayed); + Results.SetMember(Index, player); + player.UnReference(); + Index++; + } + + void Finish(bool failed) { + if (LuaStarts == MenuSystem.g_MenuSystem.LuaStarts) { + Callback.Push(); + Results.Push(); + g_Lua!.PushBool(failed); + g_Lua.CallInternalNoReturns(2); + } + + Callback.UnReference(); + Results.UnReference(); + ActiveQueries.Remove(this); + } + + void PlayersFailedToRespond() => Finish(true); + void PlayersRefreshComplete() => Finish(false); + } + + [LuaFunction] + static int PlayerList(ILuaInterface lua) { + string address = lua.CheckString(1); + ILuaObject? callback = lua.GetObject(2); + if (callback != null && callback.isFunction()) + _ = new PlayerQuery(address, callback); + return 0; + } + + class RulesQuery + { + readonly int LuaStarts = MenuSystem.g_MenuSystem.LuaStarts; + readonly LuaTable Results = new(); + readonly LuaObject Callback = new(); + readonly ISteamMatchmakingRulesResponse Response; + + public RulesQuery(string address, ILuaObject callback) { + Response = new(RulesResponded, RulesFailedToRespond, RulesRefreshComplete); + ActiveQueries.Add(this); + Callback.Set(callback); + + ParseAddress(address, true, out uint ip, out ushort port); + SteamMatchmakingServers.ServerRules(ip, port, Response); + } + + void RulesResponded(string rule, string value) { + if (LuaStarts == MenuSystem.g_MenuSystem.LuaStarts) + Results.SetMember(rule, value); + } + + void Finish(bool failed) { + if (LuaStarts == MenuSystem.g_MenuSystem.LuaStarts) { + Callback.Push(); + Results.Push(); + g_Lua!.PushBool(failed); + g_Lua.CallInternalNoReturns(2); + } + + Callback.UnReference(); + Results.UnReference(); + ActiveQueries.Remove(this); + } + + void RulesFailedToRespond() => Finish(true); + void RulesRefreshComplete() => Finish(false); + } + + [LuaFunction] + static int ServerRules(ILuaInterface lua) { + string address = lua.CheckString(1); + ILuaObject? callback = lua.GetObject(2); + if (callback != null && callback.isFunction()) + _ = new RulesQuery(address, callback); + return 0; + } +} +#endif diff --git a/Game.MenuSystem/MenuPanels.cs b/Game.MenuSystem/MenuPanels.cs index f50780155..594f7008a 100644 --- a/Game.MenuSystem/MenuPanels.cs +++ b/Game.MenuSystem/MenuPanels.cs @@ -1,4 +1,5 @@ #if MENU_DLL +using Source.Common.Formats.Keyvalues; using Source.Common.GUI; using Source.GUI.Controls; @@ -12,6 +13,24 @@ public MenuScreenPanel() : base(null, "GModMenuBasePanel") { } public class GModLoadingPanel : EditablePanel { public GModLoadingPanel() : base(null, "LoadingScreenBasePanel") { } + + public override void OnActivate() { + if (GetChildCount() == 0) + return; + + Panel? child = GetChild(0); + if (child != null) + PostMessage(child, new KeyValues("activate")); + } + + public override void OnDeactivate() { + if (GetChildCount() == 0) + return; + + Panel? child = GetChild(0); + if (child != null) + PostMessage(child, new KeyValues("deactivate")); + } } public class OverlayPanel : Panel diff --git a/Game.MenuSystem/MenuSystem.cs b/Game.MenuSystem/MenuSystem.cs index 2be36de21..28519954c 100644 --- a/Game.MenuSystem/MenuSystem.cs +++ b/Game.MenuSystem/MenuSystem.cs @@ -7,6 +7,10 @@ #if MENU_DLL using Game.MenuSystem.GarrysMod; +using Source.Common.Steam; + +using Steamworks; + using Source.GUI.Controls; #endif @@ -42,7 +46,7 @@ public void Shutdown() { public void SetupNetworkString(INetworkStringTableContainer networkStringTableContainer) => networkstringtable = networkStringTableContainer; - static void CallHook(ReadOnlySpan name) { + internal static void CallHook(ReadOnlySpan name) { if (g_Lua == null || g_Lua.Global() == null) return; @@ -76,6 +80,8 @@ public void Think() { } WasInGame = engine.IsInGame(); + + UGCDownloadManager.Think(); } void CloseLua() { @@ -123,6 +129,8 @@ public void StartLua() { CreateLoadingPanel(); CallHook("MenuStart"); + + WorkshopFavoritesCache.Refresh(); } static void DestroyLoadingPanel() { @@ -202,14 +210,75 @@ public void OnLuaError(in LuaError err, IAddonSystem.Information? addonInfo) { } #endif public bool IsServerBlacklisted(ReadOnlySpan address, ReadOnlySpan hostname, ReadOnlySpan description, ReadOnlySpan gamemode, ReadOnlySpan map) { - throw new NotImplementedException(); +#if MENU_DLL + if (g_Lua == null || g_Lua.Global() == null) + return false; + + LuaObject func = new(); + g_Lua.Global().GetMember("IsServerBlacklisted", func); + if (!func.isFunction()) { + func.UnReference(); + return false; + } + + func.Push(); + g_Lua.PushString(address); + g_Lua.PushString(hostname); + g_Lua.PushString(map); + g_Lua.PushString(gamemode); + g_Lua.PushString(description); + + LuaObject result = new(); + g_Lua.CallInternalGet(5, result); + bool blacklisted = !result.isNil(); + result.UnReference(); + func.UnReference(); + return blacklisted; +#else + return false; +#endif } public void SendProblemToMenu(ReadOnlySpan id, int severity, ReadOnlySpan parms) { - Msg($"SendProblemToMenu not implemented! ({id.SliceNullTerminatedString()}, {severity}, {parms.SliceNullTerminatedString()})\n"); +#if MENU_DLL + if (g_Lua == null || g_Lua.Global() == null) + return; + + LuaObject func = new(); + g_Lua.Global().GetMember("FireProblemFromEngine", func); + if (func.isFunction()) { + func.Push(); + g_Lua.PushString(id); + g_Lua.PushNumber(severity); + g_Lua.PushString(parms); + g_Lua.CallInternalNoReturns(3); + } + func.UnReference(); +#endif } - public void ServerDetails(ReadOnlySpan unk1, ReadOnlySpan unk2, ReadOnlySpan unk3, int unk4, ReadOnlySpan unk5) { - throw new NotImplementedException(); + public void ServerDetails(ReadOnlySpan serverName, ReadOnlySpan loadingURL, ReadOnlySpan mapName, byte maxPlayers, short playerSlots, ReadOnlySpan gamemode) { +#if MENU_DLL + filesystem.Gamemodes().OnJoinServer(gamemode); + + if (g_Lua == null || g_Lua.Global() == null) + return; + + LuaObject func = new(); + g_Lua.Global().GetMember("GameDetails", func); + if (func.isFunction()) { + string steamID = (SteamworksExts.HasSteamClient() ? SteamUser.GetSteamID().m_SteamID : 0).ToString(); + func.Push(); + g_Lua.PushString(serverName); + g_Lua.PushString(loadingURL); + g_Lua.PushString(mapName); + g_Lua.PushNumber(maxPlayers); + g_Lua.PushNumber(playerSlots > 0 ? playerSlots : maxPlayers); + g_Lua.PushString(steamID); + g_Lua.PushString(gamemode); + g_Lua.CallInternalNoReturns(7); + } + func.UnReference(); +#endif } } From 52f17c989a5bce16e8f3430aacd5b18d467a4f34 Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Thu, 15 Oct 2026 11:53:34 -0700 Subject: [PATCH 24/38] Fix popup bugs in materialsystem This was affecting the console and html panels not playing nice --- .../Surface/MatSystemSurface.cs | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/Source.MaterialSystem/Surface/MatSystemSurface.cs b/Source.MaterialSystem/Surface/MatSystemSurface.cs index 47e08dfb9..286e65c24 100644 --- a/Source.MaterialSystem/Surface/MatSystemSurface.cs +++ b/Source.MaterialSystem/Surface/MatSystemSurface.cs @@ -1114,6 +1114,7 @@ public void PaintTraverseEx(IPanel panel, bool paintPopups) { StartDrawing(); renderContext.ClearBuffers(false, true, true); +#if !GMOD_DLL renderContext.SetStencilEnable(true); renderContext.SetStencilFailOperation(StencilOperation.Keep); renderContext.SetStencilZFailOperation(StencilOperation.Keep); @@ -1122,6 +1123,7 @@ public void PaintTraverseEx(IPanel panel, bool paintPopups) { renderContext.SetStencilReferenceValue(0); renderContext.SetStencilTestMask(0xFFFFFFFF); renderContext.SetStencilWriteMask(0xFFFFFFFF); +#endif } float oldZPos = zPos; @@ -1141,6 +1143,28 @@ public void PaintTraverseEx(IPanel panel, bool paintPopups) { if (paintPopups) { int popups = GetPopupCount(); +#if GMOD_DLL + int stencilRef = 254; + for (int i = 0; i < popups; ++i) { + IPanel? popupPanel = GetPopup(i); + + if (popupPanel == null) + continue; + + if (!popupPanel.IsFullyVisible()) + continue; + + if (!IsPanelUnderRestrictedPanel(popupPanel)) + continue; + + if (stencilRef == 1) + Warning("Too many popups! Rendering will be bad!\n"); + --stencilRef; + + zPos = i / (float)popups; + popupPanel.PaintTraverse(true); + } +#else if (popups > 254) Warning("Too many popups! Rendering will be bad!\n"); @@ -1165,6 +1189,7 @@ public void PaintTraverseEx(IPanel panel, bool paintPopups) { zPos = i / (float)popups; popupPanel.PaintTraverse(true); } +#endif } zPos = oldZPos; From 3b55c9b51b5b48baa229b3967fa92867bd8f81c2 Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Thu, 15 Oct 2026 11:54:06 -0700 Subject: [PATCH 25/38] Fix glTextureSubImage2D errors, make them more verbose This fixes the tsunami of mips failing on some vtf textures --- Source.ShaderAPI.Gl46/ShaderAPIGl46.cs | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs b/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs index a3c3a2fcd..dca5a8f11 100644 --- a/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs +++ b/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs @@ -2102,7 +2102,8 @@ public void TexImageFromVTF(IVTFTexture? vtf, int vtfFrame) { } } else { - for (int i = 0; i < vtf.MipCount(); i++) { + int mipCount = Math.Min(vtf.MipCount(), Math.Max(tex.Levels, 1)); + for (int i = 0; i < mipCount; i++) { info.Level = i; LoadTextureFromVTF(in info, vtf, vtfFrame); } @@ -2128,7 +2129,7 @@ private unsafe void LoadCubeTextureFromVTF(in TextureLoadInfo info, IVTFTexture glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); - int mipCount = vtf.MipCount(); + int mipCount = Math.Min(vtf.MipCount(), Math.Max(GetTexture(info.TextureHandle).Levels, 1)); for (int mip = 0; mip < mipCount; ++mip) { vtf.ComputeMipLevelDimensions(mip, out int w, out int h, out _); for (int face = 0; face < 6; ++face) { @@ -2217,6 +2218,7 @@ public unsafe void CreateTextures( texture.Width = width; texture.Height = height; texture.Depth = depth; + texture.Levels = mipCount; texture.Count = count; texture.CountIndex = i; @@ -2558,7 +2560,7 @@ private unsafe void BlitSurfaceBits(ref TextureLoadInfo info, int xOffset, int y var err = glGetError(); // System.Diagnostics.Debug.Assert(err == 0); if (err != 0) - Warning($"glTextureSubImage2D error: {err}\n"); + Warning($"glTextureSubImage2D error: {err} (blit tex {info.Texture} mip {mip} rect {xOffset},{yOffset} {width >> mip}x{height >> mip}, src {srcFormat} stride {srcStride})\n"); } public void SetModifyTexture(uint textureID) { @@ -2577,12 +2579,16 @@ public unsafe void TexSubImage2D(int mip, int face, int x, int y, int z, int wid glPixelStorei(GL_UNPACK_ROW_LENGTH, srcStride / srcFormat.SizeInBytes()); ConvertDataToAcceptableGLFormat(srcFormat, imageData, out srcFormat, out Span convertedData); fixed (byte* data = convertedData) - glTextureSubImage2D(GetModifyTexture(), mip, x, y, width >> mip, height >> mip, ImageLoader.GetGLImageUploadFormat(srcFormat), ImageLoader.GetGLImageUploadType(srcFormat), data); + glTextureSubImage2D(GetModifyTexture(), mip, x, y, Math.Max(width >> mip, 1), Math.Max(height >> mip, 1), ImageLoader.GetGLImageUploadFormat(srcFormat), ImageLoader.GetGLImageUploadType(srcFormat), data); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); var err = glGetError(); // System.Diagnostics.Debug.Assert(err == 0); - if (err != 0) - Warning($"glTextureSubImage2D error: {err}\n"); + if (err != 0) { + InternalTextureInfo tex = GetTexture(ModifyTextureHandle); + int levels = 0; + glGetTextureParameteriv(GetModifyTexture(), GL_TEXTURE_IMMUTABLE_LEVELS, &levels); + Warning($"glTextureSubImage2D error: {err} ('{tex.DebugName.String()}' {tex.Width}x{tex.Height} {tex.Format} levels {levels}, mip {mip} rect {x},{y} {width >> mip}x{height >> mip}, src {srcFormat} stride {srcStride})\n"); + } } readonly ThreadLocal tempTransformBuffers = new ThreadLocal(() => new byte[1024 * 1024]); From c440724c2059dcc91133fe79bd753b5e9df6d21f Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Thu, 15 Oct 2026 11:54:34 -0700 Subject: [PATCH 26/38] Add prototype Chromium This is a basic version; it apparently only would work on Windows (didn't realize this API uses C++/CLI... should've realized sooner). I am evaluating a better approach. This likely will end up meaning a CEF version bump, but not like I'm complaining as long as it works --- ChromiumProcess/ChromiumApp.cs | 27 + ChromiumProcess/ChromiumProcess.csproj | 25 + ChromiumProcess/HtmlBridge.cs | 310 +++++++++ ChromiumProcess/Program.cs | 12 + ChromiumProcess/app.manifest | 26 + HTML.Chromium/ChromiumBrowser.cs | 854 +++++++++++++++++++++++++ HTML.Chromium/ChromiumClient.cs | 145 +++++ HTML.Chromium/ChromiumSystem.cs | 258 ++++++++ HTML.Chromium/HTML.Chromium.csproj | 31 + HTML.Chromium/HtmlResourceHandler.cs | 72 +++ HTML.Chromium/ImageData.cs | 59 ++ HTML.Chromium/JSObjects.cs | 57 ++ HTML.Chromium/MessageQueue.cs | 39 ++ HTML.Chromium/ModuleResolver.cs | 15 + HTML.Chromium/ResourceHandler.cs | 145 +++++ Source.Launcher/Program.cs | 3 + Source.Launcher/Source.Launcher.csproj | 1 + Source.NET.slnx | 6 + 18 files changed, 2085 insertions(+) create mode 100644 ChromiumProcess/ChromiumApp.cs create mode 100644 ChromiumProcess/ChromiumProcess.csproj create mode 100644 ChromiumProcess/HtmlBridge.cs create mode 100644 ChromiumProcess/Program.cs create mode 100644 ChromiumProcess/app.manifest create mode 100644 HTML.Chromium/ChromiumBrowser.cs create mode 100644 HTML.Chromium/ChromiumClient.cs create mode 100644 HTML.Chromium/ChromiumSystem.cs create mode 100644 HTML.Chromium/HTML.Chromium.csproj create mode 100644 HTML.Chromium/HtmlResourceHandler.cs create mode 100644 HTML.Chromium/ImageData.cs create mode 100644 HTML.Chromium/JSObjects.cs create mode 100644 HTML.Chromium/MessageQueue.cs create mode 100644 HTML.Chromium/ModuleResolver.cs create mode 100644 HTML.Chromium/ResourceHandler.cs diff --git a/ChromiumProcess/ChromiumApp.cs b/ChromiumProcess/ChromiumApp.cs new file mode 100644 index 000000000..e4f7775e7 --- /dev/null +++ b/ChromiumProcess/ChromiumApp.cs @@ -0,0 +1,27 @@ +using CefSharp; +using CefSharp.RenderProcess; + +using System.Security.Cryptography; + +namespace ChromiumProcess; + +class ChromiumApp : IRenderProcessHandler +{ + readonly string? Secret = Environment.GetEnvironmentVariable(HtmlBridge.SecretVariable); + HtmlBridge.RegistryReader? Registry; + + public void OnContextCreated(IBrowser browser, IFrame frame, IV8Context context) { + context.Execute("delete this.print;delete this.openDatabase;", "", 0, out _); + + if (browser == null || string.IsNullOrEmpty(Secret)) + return; + + Registry ??= new HtmlBridge.RegistryReader(Secret); + string nonce = Convert.ToHexString(RandomNumberGenerator.GetBytes(16)); + context.Execute(HtmlBridge.BootstrapScript(Secret, Registry.Read(browser.Identifier), frame.Identifier, nonce), "", 0, out _); + } + + public void OnContextReleased(IBrowser browser, IFrame frame, IV8Context context) { } + + public void OnWebKitInitialized() { } +} diff --git a/ChromiumProcess/ChromiumProcess.csproj b/ChromiumProcess/ChromiumProcess.csproj new file mode 100644 index 000000000..f27c5b25d --- /dev/null +++ b/ChromiumProcess/ChromiumProcess.csproj @@ -0,0 +1,25 @@ + + + + WinExe + net10.0 + enable + enable + Debug;Release;Debug (Dedicated);Release (Dedicated) + win-x64 + false + false + app.manifest + + + + + + + + + $(PkgCefSharp_Common_NETCore)\runtimes\win-x64\native\CefSharp.BrowserSubprocess.Core.dll + + + + diff --git a/ChromiumProcess/HtmlBridge.cs b/ChromiumProcess/HtmlBridge.cs new file mode 100644 index 000000000..62a21f49e --- /dev/null +++ b/ChromiumProcess/HtmlBridge.cs @@ -0,0 +1,310 @@ +using System.IO.MemoryMappedFiles; +using System.Text; +using System.Text.Json; + +namespace ChromiumProcess; + +public static class HtmlBridge +{ + public const string SecretVariable = "SOURCENET_HTML_BRIDGE"; + const int RegistryCapacity = 4 * 1024 * 1024; + + public static string ApiName(string secret) => $"__SN{secret}"; + public static string BridgeName(string secret) => $"__SN{secret}_b"; + static string RegistryName(string secret) => $"Local\\SourceNET_HTML_{secret}"; + static string RegistryLockName(string secret) => $"Local\\SourceNET_HTML_{secret}_lock"; + + public static string Quote(string value) => JsonSerializer.Serialize(value); + + public static string BootstrapScript(string secret, IReadOnlyList<(string Obj, string Func)> registered, long frameId, string nonce) { + StringBuilder list = new("["); + for (int i = 0; i < registered.Count; i++) { + if (i > 0) + list.Append(','); + list.Append('[').Append(Quote(registered[i].Obj)).Append(',').Append(Quote(registered[i].Func)).Append(']'); + } + list.Append(']'); + + return $"({Bootstrap})(this,{Quote(ApiName(secret))},{Quote(BridgeName(secret))},{list},{Quote(frameId.ToString())},{Quote(nonce)});"; + } + + public static string RegisterScript(string secret, string objName, string funcName) + => $"(function(b){{if(b)b.r({Quote(objName)},{Quote(funcName)});}})(window[{Quote(BridgeName(secret))}]);"; + + public static string CallbackScript(string secret, int callbackId, string nonce, string encodedArgs) + => $"(function(b){{if(b)b.c({callbackId},{Quote(nonce)},{encodedArgs});}})(window[{Quote(BridgeName(secret))}]);"; + + const string Bootstrap = """ + function (G, apiName, bridgeName, registered, frameId, nonce) { + var defineProperty = Object.defineProperty; + var keys = Object.keys; + var isArray = Array.isArray; + var apply = Reflect.apply; + var stringify = JSON.stringify; + var toNumber = Number; + var toString = String; + var callbacks = Object.create(null); + var nextCallbackId = 0; + var FAIL = {}; + + function serialize(value, depth) { + if (depth > 16) + throw FAIL; + if (value === null || value === undefined) + return 0; + var type = typeof value; + if (type === 'boolean') + return [1, value]; + if (type === 'number') + return [2, (value === value && value !== Infinity && value !== -Infinity) ? value : toString(value)]; + if (type === 'string') + return [3, value]; + if (isArray(value)) { + var length = value.length, list = []; + for (var i = 0; i < length; i++) + list[i] = serialize(value[i], depth + 1); + return [4, list]; + } + if (type === 'object' || type === 'function') { + var names = keys(value), map = []; + for (var j = 0; j < names.length; j++) { + var entry; + try { + entry = value[names[j]]; + } + catch (e) { + entry = null; + } + map[j] = [names[j], serialize(entry, depth + 1)]; + } + return [5, map]; + } + return 0; + } + + function deserialize(value, depth) { + if (depth > 16) + throw FAIL; + if (value === 0) + return undefined; + switch (value[0]) { + case 1: + case 3: + return value[1]; + case 2: + return typeof value[1] === 'string' ? toNumber(value[1]) : value[1]; + case 4: { + var list = []; + for (var i = 0; i < value[1].length; i++) + list[i] = deserialize(value[1][i], depth + 1); + return list; + } + case 5: { + var object = {}; + for (var j = 0; j < value[1].length; j++) + defineProperty(object, value[1][j][0], { value: deserialize(value[1][j][1], depth + 1), writable: true, enumerable: true, configurable: true }); + return object; + } + } + return undefined; + } + + function createCallback(func) { + if (callbacks[nextCallbackId] !== undefined) + return -1; + var callbackId = nextCallbackId; + callbacks[callbackId] = func; + nextCallbackId++; + if (nextCallbackId >= 16384) + nextCallbackId = 0; + return callbackId; + } + + function execute(objName, funcName, args) { + var count = args.length, list = []; + try { + for (var i = 0; i < count; i++) + list[i] = serialize(args[i], 0); + } + catch (e) { + if (e === FAIL) + throw new Error('failed to serialize parameters (did you return a deeply nested structure?)'); + throw e; + } + + var callbackId = -1; + if (count > 0 && typeof args[count - 1] === 'function') { + callbackId = createCallback(args[count - 1]); + list.length = count - 1; + } + + var api = G[apiName]; + if (api && typeof api.PostMessage === 'function') + api.PostMessage(stringify(['ExecuteFunction', objName, funcName, callbackId, list, frameId, nonce])); + } + + function registerFunction(objName, funcName) { + try { + var obj = G[objName]; + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + obj = {}; + defineProperty(G, objName, { value: obj, writable: true, enumerable: true, configurable: true }); + } + var func = function () { return execute(objName, funcName, arguments); }; + defineProperty(func, 'name', { value: objName + '#' + funcName }); + defineProperty(obj, funcName, { value: func, writable: true, enumerable: true, configurable: true }); + } + catch (e) { } + } + + function executeCallback(callbackId, callbackNonce, encodedArgs) { + if (callbackNonce !== nonce) + return; + var func = callbacks[callbackId]; + if (func === undefined) + return; + delete callbacks[callbackId]; + + var args = []; + try { + for (var i = 0; i < encodedArgs.length; i++) + args[i] = deserialize(encodedArgs[i], 0); + } + catch (e) { + return; + } + apply(func, G, args); + } + + var bridge = Object.create(null); + bridge.c = executeCallback; + bridge.r = registerFunction; + try { + defineProperty(G, bridgeName, { value: bridge }); + } + catch (e) { } + + for (var k = 0; k < registered.length; k++) + registerFunction(registered[k][0], registered[k][1]); + } + """; + + public sealed class RegistryWriter : IDisposable + { + readonly MemoryMappedFile File; + readonly MemoryMappedViewAccessor View; + readonly Mutex Lock; + readonly Dictionary> Registrations = []; + + public RegistryWriter(string secret) { + File = MemoryMappedFile.CreateNew(RegistryName(secret), RegistryCapacity); + View = File.CreateViewAccessor(); + Lock = new Mutex(false, RegistryLockName(secret)); + Flush(); + } + + public void Add(int browserId, string objName, string funcName) { + lock (Registrations) { + if (!Registrations.TryGetValue(browserId, out List<(string, string)>? list)) + Registrations[browserId] = list = []; + list.Add((objName, funcName)); + Flush(); + } + } + + public void Remove(int browserId) { + lock (Registrations) { + if (Registrations.Remove(browserId)) + Flush(); + } + } + + void Flush() { + using MemoryStream stream = new(); + using (Utf8JsonWriter writer = new(stream)) { + writer.WriteStartObject(); + foreach (KeyValuePair> pair in Registrations) { + writer.WriteStartArray(pair.Key.ToString()); + foreach ((string obj, string func) in pair.Value) { + writer.WriteStartArray(); + writer.WriteStringValue(obj); + writer.WriteStringValue(func); + writer.WriteEndArray(); + } + writer.WriteEndArray(); + } + writer.WriteEndObject(); + } + + ReadOnlySpan data = stream.GetBuffer().AsSpan(0, (int)stream.Length); + if (data.Length + sizeof(int) > RegistryCapacity) + return; + + try { + Lock.WaitOne(); + } + catch (AbandonedMutexException) { } + try { + View.WriteArray(sizeof(int), stream.GetBuffer(), 0, data.Length); + View.Write(0, data.Length); + } + finally { + Lock.ReleaseMutex(); + } + } + + public void Dispose() { + View.Dispose(); + File.Dispose(); + Lock.Dispose(); + } + } + + public sealed class RegistryReader(string secret) + { + MemoryMappedFile? File; + MemoryMappedViewAccessor? View; + Mutex? Lock; + + public IReadOnlyList<(string Obj, string Func)> Read(int browserId) { + try { + File ??= MemoryMappedFile.OpenExisting(RegistryName(secret), MemoryMappedFileRights.Read); + View ??= File.CreateViewAccessor(0, 0, MemoryMappedFileAccess.Read); + Lock ??= Mutex.OpenExisting(RegistryLockName(secret)); + } + catch (Exception) { + return []; + } + + bool acquired; + try { + acquired = Lock.WaitOne(1000); + } + catch (AbandonedMutexException) { + acquired = true; + } + if (!acquired) + return []; + + byte[] data; + try { + int length = View.ReadInt32(0); + if (length <= 0 || length + sizeof(int) > RegistryCapacity) + return []; + data = new byte[length]; + View.ReadArray(sizeof(int), data, 0, length); + } + finally { + Lock.ReleaseMutex(); + } + + List<(string, string)> result = []; + using JsonDocument document = JsonDocument.Parse(data); + if (!document.RootElement.TryGetProperty(browserId.ToString(), out JsonElement list)) + return result; + foreach (JsonElement entry in list.EnumerateArray()) + result.Add((entry[0].GetString() ?? "", entry[1].GetString() ?? "")); + return result; + } + } +} diff --git a/ChromiumProcess/Program.cs b/ChromiumProcess/Program.cs new file mode 100644 index 000000000..15f229f0a --- /dev/null +++ b/ChromiumProcess/Program.cs @@ -0,0 +1,12 @@ +using CefSharp.BrowserSubprocess; + +namespace ChromiumProcess; + +static class Program +{ + static int Main(string[] args) { + SubProcess.EnableHighDPISupport(); + BrowserSubprocessExecutable executable = new(); + return executable.Main(args, new ChromiumApp()); + } +} diff --git a/ChromiumProcess/app.manifest b/ChromiumProcess/app.manifest new file mode 100644 index 000000000..239090107 --- /dev/null +++ b/ChromiumProcess/app.manifest @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + true/PM + PerMonitorV2,PerMonitor + + + diff --git a/HTML.Chromium/ChromiumBrowser.cs b/HTML.Chromium/ChromiumBrowser.cs new file mode 100644 index 000000000..d2961ca92 --- /dev/null +++ b/HTML.Chromium/ChromiumBrowser.cs @@ -0,0 +1,854 @@ +using CefSharp; +using CefSharp.Enums; +using CefSharp.OffScreen; +using CefSharp.Structs; + +using ChromiumProcess; + +using Source.Common.GarrysMod; + +using System.Diagnostics; +using System.Globalization; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Text.Json; + +using Range = CefSharp.Structs.Range; +using Size = CefSharp.Structs.Size; + +namespace HTML.Chromium; + +public class ChromiumBrowser : ILifeSpanHandler, ILoadHandler, IDisplayHandler, IRequestHandler, IContextMenuHandler, IDialogHandler, IJsDialogHandler +{ + static readonly JsonDocumentOptions MessageOptions = new() { MaxDepth = 256 }; + + static readonly string[] BlockedJavaScriptHosts = [ + "steampowered", + "steamcommunity", + "valvesoftware", + "steamgames", + "discord.", + "discordapp", + "watchanimeattheoffice", + "bigbeans.solutions", + "dis.gd", + "10.", + "172.16.", + "192.168.", + "127.", + "localhost", + ]; + + static bool CefValueToJSValue(out JSValue outValue, JsonElement inValue, int depth = 0) { + outValue = default; + + if (depth > 16) + return false; + + if (inValue.ValueKind != JsonValueKind.Array || inValue.GetArrayLength() < 2) + return true; + + JsonElement value = inValue[1]; + switch (inValue[0].GetInt32()) { + case 1: + outValue = new JSValue(value.GetBoolean()); + break; + case 2: + if (value.ValueKind == JsonValueKind.String) { + outValue = new JSValue(value.GetString() switch { + "Infinity" => double.PositiveInfinity, + "-Infinity" => double.NegativeInfinity, + _ => double.NaN + }); + } + else + outValue = new JSValue(value.GetDouble()); + break; + case 3: + outValue = JSString.Create(value.GetString() ?? ""); + break; + case 4: { + JSValue[] outList = new JSValue[value.GetArrayLength()]; + int i = 0; + foreach (JsonElement entry in value.EnumerateArray()) { + if (!CefValueToJSValue(out outList[i], entry, depth + 1)) + return false; + i++; + } + outValue = JSArray.Create(outList); + break; + } + case 5: { + Dictionary outMap = new(value.GetArrayLength()); + foreach (JsonElement entry in value.EnumerateArray()) { + if (!CefValueToJSValue(out JSValue mapValue, entry[1], depth + 1)) + return false; + outMap.TryAdd(entry[0].GetString() ?? "", mapValue); + } + outValue = JSHashMap.Create(outMap); + break; + } + } + + return true; + } + + static bool CefListToJSValues(out JSValue[] outList, JsonElement inList) { + outList = new JSValue[inList.GetArrayLength()]; + + int i = 0; + foreach (JsonElement entry in inList.EnumerateArray()) { + if (!CefValueToJSValue(out outList[i], entry)) + return false; + i++; + } + + return true; + } + + static bool JSValueToCefValue(Utf8JsonWriter outValue, in JSValue inValue, int depth = 0) { + if (depth > 16) + return false; + + switch (inValue.GetJSType()) { + case JSValue.Type.Undefined: + outValue.WriteNumberValue(0); + break; + case JSValue.Type.Bool: + outValue.WriteStartArray(); + outValue.WriteNumberValue(1); + outValue.WriteBooleanValue(inValue.GetBool()); + outValue.WriteEndArray(); + break; + case JSValue.Type.Number: { + double number = inValue.GetNumber(); + outValue.WriteStartArray(); + outValue.WriteNumberValue(2); + if (double.IsFinite(number)) + outValue.WriteNumberValue(number); + else + outValue.WriteStringValue(double.IsNaN(number) ? "NaN" : number > 0 ? "Infinity" : "-Infinity"); + outValue.WriteEndArray(); + break; + } + case JSValue.Type.String: + outValue.WriteStartArray(); + outValue.WriteNumberValue(3); + outValue.WriteStringValue(inValue.GetString()); + outValue.WriteEndArray(); + break; + case JSValue.Type.Array: + outValue.WriteStartArray(); + outValue.WriteNumberValue(4); + outValue.WriteStartArray(); + foreach (JSValue x in inValue.GetArray()) + if (!JSValueToCefValue(outValue, x, depth + 1)) + return false; + outValue.WriteEndArray(); + outValue.WriteEndArray(); + break; + case JSValue.Type.HashMap: { + outValue.WriteStartArray(); + outValue.WriteNumberValue(5); + outValue.WriteStartArray(); + if (inValue.HashMap_Begin(out ReadOnlySpan key, out JSValue value)) { + do { + outValue.WriteStartArray(); + outValue.WriteStringValue(key); + if (!JSValueToCefValue(outValue, value, depth + 1)) + return false; + outValue.WriteEndArray(); + } + while (inValue.HashMap_Next(out key, out value)); + } + outValue.WriteEndArray(); + outValue.WriteEndArray(); + break; + } + default: + outValue.WriteNumberValue(0); + break; + } + + return true; + } + + static bool JSValuesToCefList(out string outList, ReadOnlySpan inList) { + outList = ""; + + using MemoryStream stream = new(); + try { + using Utf8JsonWriter writer = new(stream); + writer.WriteStartArray(); + foreach (JSValue x in inList) + if (!JSValueToCefValue(writer, x)) + return false; + writer.WriteEndArray(); + } + catch (ArgumentException) { + return false; + } + catch (InvalidOperationException) { + return false; + } + + outList = Encoding.UTF8.GetString(stream.GetBuffer(), 0, (int)stream.Length); + return true; + } + + static CefEventFlags GetModifiers(IHtmlClient.EventModifiers modifiers) { + CefEventFlags chromiumModifiers = 0; + + if ((modifiers & IHtmlClient.EventModifiers.Shift) != 0) + chromiumModifiers |= CefEventFlags.ShiftDown | CefEventFlags.IsLeft; + + if ((modifiers & IHtmlClient.EventModifiers.ShiftR) != 0) + chromiumModifiers |= CefEventFlags.ShiftDown | CefEventFlags.IsRight; + + if ((modifiers & IHtmlClient.EventModifiers.Control) != 0) + chromiumModifiers |= CefEventFlags.ControlDown | CefEventFlags.IsLeft; + + if ((modifiers & IHtmlClient.EventModifiers.ControlR) != 0) + chromiumModifiers |= CefEventFlags.ControlDown | CefEventFlags.IsRight; + + if ((modifiers & IHtmlClient.EventModifiers.Alt) != 0) + chromiumModifiers |= CefEventFlags.AltDown | CefEventFlags.IsLeft; + + if ((modifiers & IHtmlClient.EventModifiers.AltGr) != 0) + chromiumModifiers |= CefEventFlags.AltDown | CefEventFlags.IsRight; + + if ((modifiers & IHtmlClient.EventModifiers.LeftMouse) != 0) + chromiumModifiers |= CefEventFlags.LeftMouseButton; + + if ((modifiers & IHtmlClient.EventModifiers.MiddleMouse) != 0) + chromiumModifiers |= CefEventFlags.MiddleMouseButton; + + if ((modifiers & IHtmlClient.EventModifiers.RightMouse) != 0) + chromiumModifiers |= CefEventFlags.RightMouseButton; + + if ((modifiers & IHtmlClient.EventModifiers.Numpad) != 0) + chromiumModifiers |= CefEventFlags.IsKeyPad; + + return chromiumModifiers; + } + + static bool TryParseScheme(string url, out string scheme) { + if (Uri.TryCreate(url, UriKind.Absolute, out Uri? uri)) { + scheme = uri.Scheme; + return true; + } + + scheme = ""; + return false; + } + + int Wide = 512; + int Tall = 512; + + int PopupX; + int PopupY; + int PopupWide; + int PopupTall; + byte[]? PopupData; + + readonly MessageQueue MessageQueue = new(); + + readonly ImageData ImageData = new(); + + ChromiumWebBrowser? WebBrowser; + IBrowser? Browser; + IBrowserHost? BrowserHost; + + bool OpenLinksExternally; + + readonly string BridgeSecret; + readonly HtmlBridge.RegistryWriter? Registry; + readonly HashSet<(string Obj, string Func)> RegisteredFunctions = []; + readonly List PendingTasks = []; + readonly ResourceRequestHandler ResourceRequest; + readonly RenderHandler Render; + + public ChromiumBrowser(string bridgeSecret, HtmlBridge.RegistryWriter? registry) { + BridgeSecret = bridgeSecret; + Registry = registry; + ResourceRequest = new ResourceRequestHandler(); + Render = new RenderHandler(this); + } + + public void CreateBrowser(IBrowserSettings browserSettings) { + WebBrowser = new ChromiumWebBrowser("", null, null, false); + + WebBrowser.RenderHandler?.Dispose(); + WebBrowser.RenderHandler = Render; + WebBrowser.LifeSpanHandler = this; + WebBrowser.LoadHandler = this; + WebBrowser.DisplayHandler = this; + WebBrowser.RequestHandler = this; + WebBrowser.MenuHandler = this; + WebBrowser.DialogHandler = this; + WebBrowser.JsDialogHandler = this; + WebBrowser.JavascriptObjectRepository.Settings.JavascriptBindingApiGlobalObjectName = HtmlBridge.ApiName(BridgeSecret); + WebBrowser.JavascriptMessageReceived += OnJavascriptMessageReceived; + + WindowInfo windowInfo = new(); + windowInfo.SetAsWindowless(0); + + WebBrowser.CreateBrowser(windowInfo, browserSettings); + } + + public ImageData GetImageData() => ImageData; + + public MessageQueue GetMessageQueue() => MessageQueue; + + public void QueueMessage(in MessageQueue.Message message) { + MessageQueue.Lock(); + MessageQueue.Push(message); + MessageQueue.Unlock(); + } + + void RunOrDefer(Action task) { + if (Browser == null) { + PendingTasks.Add(task); + return; + } + + task(); + } + + public void Close() { + PendingTasks.Clear(); + + if (Browser != null) + Registry?.Remove(Browser.Identifier); + + BrowserHost?.CloseBrowser(true); + WebBrowser?.Dispose(); + WebBrowser = null; + } + + public void SetSize(int wide, int tall) { + Wide = wide; + Tall = tall; + RunOrDefer(() => BrowserHost!.WasResized()); + } + + public void SetFocused(bool hasFocus) => RunOrDefer(() => BrowserHost!.SendFocusEvent(hasFocus)); + + public void SendKeyEvent(IHtmlClient.KeyEvent keyEvent) { + KeyEvent chromiumKeyEvent = new() { + Modifiers = GetModifiers(keyEvent.Modifiers) + }; + + switch (keyEvent.EventType) { + case IHtmlClient.KeyEvent.Type.KeyChar: + chromiumKeyEvent.Type = KeyEventType.Char; + chromiumKeyEvent.WindowsKeyCode = keyEvent.WindowsKeyCode; + chromiumKeyEvent.NativeKeyCode = keyEvent.NativeKeyCode; + break; + case IHtmlClient.KeyEvent.Type.KeyDown: + chromiumKeyEvent.Type = KeyEventType.KeyDown; + chromiumKeyEvent.WindowsKeyCode = keyEvent.WindowsKeyCode; + chromiumKeyEvent.NativeKeyCode = keyEvent.NativeKeyCode; + break; + case IHtmlClient.KeyEvent.Type.KeyUp: + chromiumKeyEvent.Type = KeyEventType.KeyUp; + chromiumKeyEvent.WindowsKeyCode = keyEvent.WindowsKeyCode; + chromiumKeyEvent.NativeKeyCode = keyEvent.NativeKeyCode; + break; + } + + RunOrDefer(() => BrowserHost!.SendKeyEvent(chromiumKeyEvent)); + } + + public void SendMouseMoveEvent(IHtmlClient.MouseEvent gmodMouseEvent, bool mouseLeave) { + MouseEvent mouseEvent = new(gmodMouseEvent.X, gmodMouseEvent.Y, GetModifiers(gmodMouseEvent.Modifiers)); + RunOrDefer(() => BrowserHost!.SendMouseMoveEvent(mouseEvent, mouseLeave)); + } + + public void SendMouseWheelEvent(IHtmlClient.MouseEvent gmodMouseEvent, int deltaX, int deltaY) { + MouseEvent mouseEvent = new(gmodMouseEvent.X, gmodMouseEvent.Y, GetModifiers(gmodMouseEvent.Modifiers)); + RunOrDefer(() => BrowserHost!.SendMouseWheelEvent(mouseEvent, deltaX, deltaY)); + } + + public void SendMouseClickEvent(IHtmlClient.MouseEvent gmodMouseEvent, IHtmlClient.MouseButton gmodButtonType, bool mouseUp, int clickCount) { + MouseEvent mouseEvent = new(gmodMouseEvent.X, gmodMouseEvent.Y, GetModifiers(gmodMouseEvent.Modifiers)); + + MouseButtonType buttonType = gmodButtonType switch { + IHtmlClient.MouseButton.Middle => MouseButtonType.Middle, + IHtmlClient.MouseButton.Right => MouseButtonType.Right, + _ => MouseButtonType.Left, + }; + + RunOrDefer(() => BrowserHost!.SendMouseClickEvent(mouseEvent, buttonType, mouseUp, clickCount)); + } + + public void LoadUrl(string url) => RunOrDefer(() => Browser!.MainFrame.LoadUrl(url)); + + public void SetHtml(string html) { + string url = $"asset://html/?{Convert.ToBase64String(Encoding.UTF8.GetBytes(html))}"; + RunOrDefer(() => Browser!.MainFrame.LoadUrl(url)); + } + + public void Refresh() => RunOrDefer(() => Browser!.Reload()); + + public void Stop() => RunOrDefer(() => Browser!.StopLoad()); + + public void GoBack() => RunOrDefer(() => Browser!.GoBack()); + + public void GoForward() => RunOrDefer(() => Browser!.GoForward()); + + public void RunJavaScript(string code) { + RunOrDefer(() => { + IFrame mainFrame = Browser!.MainFrame; + string url = mainFrame.Url ?? ""; + + int slash = url.Length >= 9 ? url.IndexOf('/', 8) : -1; + string host = slash == -1 ? url : url[..slash]; + + foreach (string blocked in BlockedJavaScriptHosts) + if (host.Contains(blocked, StringComparison.Ordinal)) + return; + + mainFrame.ExecuteJavaScriptAsync(code, "Lua File", 1); + }); + } + + public void RegisterJavaScriptFunction(string objName, string funcName) { + RunOrDefer(() => { + lock (RegisteredFunctions) + RegisteredFunctions.Add((objName, funcName)); + Registry?.Add(Browser!.Identifier, objName, funcName); + + string script = HtmlBridge.RegisterScript(BridgeSecret, objName, funcName); + foreach (long frameId in Browser!.GetFrameIdentifiers()) { + IFrame? frame = Browser.GetFrame(frameId); + if (frame != null && frame.IsValid) + frame.ExecuteJavaScriptAsync(script); + } + }); + } + + public void SetOpenLinksExternally(bool openLinksExternally) => OpenLinksExternally = openLinksExternally; + + public void ExecuteCallback(int callbackId, long frameId, string nonce, JSValue paramsArray) { + if (Browser == null) + return; + + ReadOnlySpan paramsVector = paramsArray.GetJSType() == JSValue.Type.Array ? paramsArray.GetArray() : default; + if (!JSValuesToCefList(out string cefArgs, paramsVector)) + return; + + IFrame? frame = Browser.GetFrame(frameId); + if (frame == null || !frame.IsValid) + return; + + frame.ExecuteJavaScriptAsync(HtmlBridge.CallbackScript(BridgeSecret, callbackId, nonce, cefArgs)); + } + + void OnJavascriptMessageReceived(object? sender, JavascriptMessageReceivedEventArgs e) { + if (e.Message is not string message) + return; + + JsonDocument document; + try { + document = JsonDocument.Parse(message, MessageOptions); + } + catch (JsonException) { + return; + } + + using (document) { + JsonElement args = document.RootElement; + if (args.ValueKind != JsonValueKind.Array || args.GetArrayLength() != 7) + return; + + if (args[0].ValueKind != JsonValueKind.String || args[0].GetString() != "ExecuteFunction") + return; + + if (args[1].ValueKind != JsonValueKind.String || args[2].ValueKind != JsonValueKind.String || args[3].ValueKind != JsonValueKind.Number || args[4].ValueKind != JsonValueKind.Array + || args[5].ValueKind != JsonValueKind.String || args[6].ValueKind != JsonValueKind.String) + return; + + string objName = args[1].GetString()!; + string funcName = args[2].GetString()!; + lock (RegisteredFunctions) { + if (!RegisteredFunctions.Contains((objName, funcName))) + return; + } + + if (!args[3].TryGetInt32(out int callbackId) || callbackId < -1 || callbackId >= 16384) + return; + + if (!long.TryParse(args[5].GetString(), NumberStyles.Integer, CultureInfo.InvariantCulture, out long frameId)) + return; + + if (!CefListToJSValues(out JSValue[] values, args[4])) + return; + + MessageQueue.Message msg = new() { + Type = MessageQueue.Type.OnJavaScriptCall, + String1 = objName, + String2 = funcName, + Integer = callbackId, + FrameId = frameId, + Nonce = args[6].GetString()!, + JSParams = JSArray.Create(values) + }; + + QueueMessage(msg); + } + } + + public void OnAfterCreated(IWebBrowser chromiumWebBrowser, IBrowser browser) { + Browser = browser; + BrowserHost = browser.GetHost(); + + Action[] pending = [.. PendingTasks]; + PendingTasks.Clear(); + foreach (Action task in pending) + task(); + } + + public bool DoClose(IWebBrowser chromiumWebBrowser, IBrowser browser) => false; + + public void OnBeforeClose(IWebBrowser chromiumWebBrowser, IBrowser browser) { + Browser = null; + BrowserHost = null; + } + + public bool OnBeforePopup(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, string targetUrl, string targetFrameName, WindowOpenDisposition targetDisposition, bool userGesture, IPopupFeatures popupFeatures, IWindowInfo windowInfo, IBrowserSettings browserSettings, ref bool noJavascriptAccess, out IWebBrowser newBrowser) { + string sourceUrl = frame.Url; + + MessageQueue.Message msg = new() { + Type = MessageQueue.Type.OnCreateChildView, + String1 = sourceUrl, + String2 = targetUrl, + Integer = targetDisposition == WindowOpenDisposition.NewPopup ? 1 : 0 + }; + QueueMessage(msg); + + newBrowser = null!; + return true; + } + + public void OnLoadingStateChange(IWebBrowser chromiumWebBrowser, LoadingStateChangedEventArgs loadingStateChangedArgs) { } + + public void OnFrameLoadStart(IWebBrowser chromiumWebBrowser, FrameLoadStartEventArgs frameLoadStartArgs) { + IFrame frame = frameLoadStartArgs.Frame; + if (!frame.IsMain) + return; + + MessageQueue.Message msg = new() { + Type = MessageQueue.Type.OnLoadStart, + String1 = frame.Url + }; + QueueMessage(msg); + } + + public void OnFrameLoadEnd(IWebBrowser chromiumWebBrowser, FrameLoadEndEventArgs frameLoadEndArgs) { + IFrame frame = frameLoadEndArgs.Frame; + if (!frame.IsMain) + return; + + MessageQueue.Message msg = new() { + Type = MessageQueue.Type.OnLoadEnd, + String1 = frame.Url + }; + QueueMessage(msg); + + frame.ExecuteJavaScriptAsync("WebSocket = undefined;", "haha", 0); + } + + public void OnLoadError(IWebBrowser chromiumWebBrowser, LoadErrorEventArgs loadErrorArgs) { + IFrame frame = loadErrorArgs.Frame; + if (!frame.IsMain) + return; + + MessageQueue.Message msg = new() { + Type = MessageQueue.Type.OnLoadEnd, + String1 = frame.Url + }; + QueueMessage(msg); + + frame.ExecuteJavaScriptAsync("WebSocket = undefined;", "haha", 0); + } + + public void OnAddressChanged(IWebBrowser chromiumWebBrowser, AddressChangedEventArgs addressChangedArgs) { + IFrame? mainFrame = addressChangedArgs.Browser?.MainFrame; + if (mainFrame != null && mainFrame.Url != addressChangedArgs.Address) + return; + + MessageQueue.Message msg = new() { + Type = MessageQueue.Type.OnAddressChange, + String1 = addressChangedArgs.Address + }; + QueueMessage(msg); + } + + public bool OnAutoResize(IWebBrowser chromiumWebBrowser, IBrowser browser, Size newSize) => false; + + public bool OnCursorChange(IWebBrowser chromiumWebBrowser, IBrowser browser, nint cursor, CursorType type, CursorInfo customCursorInfo) { + IHtmlClientListener.CursorType gmodCursor = type switch { + CursorType.Pointer => IHtmlClientListener.CursorType.Default, + CursorType.Cross => IHtmlClientListener.CursorType.Crosshair, + CursorType.Hand => IHtmlClientListener.CursorType.Hand, + CursorType.IBeam => IHtmlClientListener.CursorType.IBeam, + CursorType.Wait => IHtmlClientListener.CursorType.Hourglass, + CursorType.Move => IHtmlClientListener.CursorType.SizeAll, + CursorType.EastResize or CursorType.WestResize or CursorType.EastWestResize => IHtmlClientListener.CursorType.SizeEW, + CursorType.NorthResize or CursorType.SouthResize or CursorType.NorthSouthResize => IHtmlClientListener.CursorType.SizeNS, + CursorType.NortheastResize or CursorType.SouthwestResize or CursorType.NortheastSouthwestResize => IHtmlClientListener.CursorType.SizeNESW, + CursorType.NorthwestResize or CursorType.SoutheastResize or CursorType.NorthwestSoutheastResize => IHtmlClientListener.CursorType.SizeNWSE, + CursorType.ColumnResize => IHtmlClientListener.CursorType.SizeEW, + CursorType.RowResize => IHtmlClientListener.CursorType.SizeNS, + CursorType.NotAllowed => IHtmlClientListener.CursorType.No, + CursorType.None => IHtmlClientListener.CursorType.None, + CursorType.MiddlePanning or CursorType.EastPanning or CursorType.NorthPanning or CursorType.NortheastPanning or CursorType.NorthwestPanning + or CursorType.SouthPanning or CursorType.SoutheastPanning or CursorType.SouthwestPanning or CursorType.WestPanning => IHtmlClientListener.CursorType.SizeAll, + _ => IHtmlClientListener.CursorType.Default + }; + + MessageQueue.Message msg = new() { + Type = MessageQueue.Type.OnCursorChange, + Integer = (int)gmodCursor + }; + QueueMessage(msg); + return true; + } + + public void OnTitleChanged(IWebBrowser chromiumWebBrowser, TitleChangedEventArgs titleChangedArgs) { + MessageQueue.Message msg = new() { + Type = MessageQueue.Type.OnTitleChange, + String1 = titleChangedArgs.Title + }; + QueueMessage(msg); + } + + public void OnFaviconUrlChange(IWebBrowser chromiumWebBrowser, IBrowser browser, IList urls) { } + + public void OnFullscreenModeChange(IWebBrowser chromiumWebBrowser, IBrowser browser, bool fullscreen) { } + + public void OnLoadingProgressChange(IWebBrowser chromiumWebBrowser, IBrowser browser, double progress) { } + + public bool OnTooltipChanged(IWebBrowser chromiumWebBrowser, ref string text) => false; + + public void OnStatusMessage(IWebBrowser chromiumWebBrowser, StatusMessageEventArgs statusMessageArgs) { } + + public bool OnConsoleMessage(IWebBrowser chromiumWebBrowser, ConsoleMessageEventArgs consoleMessageArgs) { + MessageQueue.Message msg = new() { + Type = MessageQueue.Type.OnConsoleMessage, + String1 = consoleMessageArgs.Message, + String2 = consoleMessageArgs.Source, + Integer = consoleMessageArgs.Line, + Integer2 = (int)consoleMessageArgs.Level + }; + QueueMessage(msg); + + return false; + } + + void OnPopupShow(bool show) { + if (BrowserHost == null) + return; + + if (!show) { + PopupX = 0; + PopupY = 0; + PopupWide = 0; + PopupTall = 0; + PopupData = null; + + BrowserHost.Invalidate(PaintElementType.View); + } + } + + void OnPopupSize(Rect rect) { + PopupX = rect.X; + PopupY = rect.Y; + } + + void OnPaint(PaintElementType type, nint buffer, int width, int height) { + if (width <= 0 || height <= 0) + return; + + switch (type) { + case PaintElementType.Popup: + PopupData = new byte[width * height * 4]; + System.Runtime.InteropServices.Marshal.Copy(buffer, PopupData, 0, PopupData.Length); + PopupWide = width; + PopupTall = height; + + BrowserHost?.Invalidate(PaintElementType.View); + return; + + case PaintElementType.View: + ImageData.Lock(); + ImageData.SetData(buffer, width, height); + + if (PopupWide > 0 && PopupTall > 0 && + PopupX < width && PopupY < height && + (PopupX + PopupWide) > 0 && (PopupY + PopupTall) > 0) { + ImageData.CopyImage(PopupData, PopupX, PopupY, PopupWide, PopupTall); + } + + ImageData.SetDirty(true); + ImageData.Unlock(); + return; + } + } + + public bool OnOpenUrlFromTab(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, string targetUrl, WindowOpenDisposition targetDisposition, bool userGesture) { + if (targetDisposition == WindowOpenDisposition.NewPopup || targetDisposition == WindowOpenDisposition.NewForegroundTab || targetDisposition == WindowOpenDisposition.NewBackgroundTab) { + string sourceUrl = frame.Url; + + MessageQueue.Message msg = new() { + Type = MessageQueue.Type.OnCreateChildView, + String1 = sourceUrl, + String2 = targetUrl, + Integer = targetDisposition == WindowOpenDisposition.NewPopup ? 1 : 0 + }; + QueueMessage(msg); + + return true; + } + + return false; + } + + public bool OnBeforeBrowse(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, bool userGesture, bool isRedirect) { + string url = request.Url; + if (!TryParseScheme(url, out string strScheme)) + return true; + + if (url == "chrome://credits/") + return false; + + if (strScheme != "http" && strScheme != "https" && strScheme != "asset") + return true; + + if (OpenLinksExternally) { + try { + Process.Start(new ProcessStartInfo(url) { UseShellExecute = true }); + } + catch (Exception) { } + return true; + } + + return false; + } + + public void OnDocumentAvailableInMainFrame(IWebBrowser chromiumWebBrowser, IBrowser browser) { } + + public IResourceRequestHandler GetResourceRequestHandler(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, bool isNavigation, bool isDownload, string requestInitiator, ref bool disableDefaultHandling) => ResourceRequest; + + public bool GetAuthCredentials(IWebBrowser chromiumWebBrowser, IBrowser browser, string originUrl, bool isProxy, string host, int port, string realm, string scheme, IAuthCallback callback) => false; + + public bool OnQuotaRequest(IWebBrowser chromiumWebBrowser, IBrowser browser, string originUrl, long newSize, IRequestCallback callback) => false; + + public bool OnCertificateError(IWebBrowser chromiumWebBrowser, IBrowser browser, CefErrorCode errorCode, string requestUrl, ISslInfo sslInfo, IRequestCallback callback) => false; + + public bool OnSelectClientCertificate(IWebBrowser chromiumWebBrowser, IBrowser browser, bool isProxy, string host, int port, X509Certificate2Collection certificates, ISelectClientCertificateCallback callback) => false; + + public void OnPluginCrashed(IWebBrowser chromiumWebBrowser, IBrowser browser, string pluginPath) { } + + public void OnRenderViewReady(IWebBrowser chromiumWebBrowser, IBrowser browser) { } + + public void OnRenderProcessTerminated(IWebBrowser chromiumWebBrowser, IBrowser browser, CefTerminationStatus status) { } + + public void OnBeforeContextMenu(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model) => model.Clear(); + + public bool OnContextMenuCommand(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags) => false; + + public void OnContextMenuDismissed(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame) { } + + public bool RunContextMenu(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model, IRunContextMenuCallback callback) => false; + + public bool OnFileDialog(IWebBrowser chromiumWebBrowser, IBrowser browser, CefFileDialogMode mode, CefFileDialogFlags flags, string title, string defaultFilePath, List acceptFilters, int selectedAcceptFilter, IFileDialogCallback callback) { + callback.Cancel(); + return true; + } + + public bool OnJSDialog(IWebBrowser chromiumWebBrowser, IBrowser browser, string originUrl, CefJsDialogType dialogType, string messageText, string defaultPromptText, IJsDialogCallback callback, ref bool suppressMessage) { + suppressMessage = true; + return false; + } + + public bool OnBeforeUnloadDialog(IWebBrowser chromiumWebBrowser, IBrowser browser, string messageText, bool isReload, IJsDialogCallback callback) { + callback.Continue(true, ""); + return true; + } + + public void OnResetDialogState(IWebBrowser chromiumWebBrowser, IBrowser browser) { } + + public void OnDialogClosed(IWebBrowser chromiumWebBrowser, IBrowser browser) { } + + sealed class ResourceRequestHandler : IResourceRequestHandler + { + public ICookieAccessFilter GetCookieAccessFilter(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request) => null!; + + public CefReturnValue OnBeforeResourceLoad(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback) { + string sourceUrl = request.Url; + + if (!TryParseScheme(sourceUrl, out string strScheme)) + return CefReturnValue.Cancel; + + if (sourceUrl == "chrome://credits/" || + sourceUrl == "chrome://resources/js/cr.js" || + sourceUrl == "chrome://credits/credits.js") { + return CefReturnValue.Continue; + } + + if (strScheme != "http" && strScheme != "https" && strScheme != "asset") + return CefReturnValue.Cancel; + + return CefReturnValue.Continue; + } + + public IResourceHandler GetResourceHandler(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request) => null!; + + public void OnResourceRedirect(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IResponse response, ref string newUrl) { } + + public bool OnResourceResponse(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IResponse response) => false; + + public IResponseFilter GetResourceResponseFilter(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IResponse response) => null!; + + public void OnResourceLoadComplete(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IResponse response, UrlRequestStatus status, long receivedContentLength) { } + + public bool OnProtocolExecution(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request) => false; + + public void Dispose() { } + } + + sealed class RenderHandler(ChromiumBrowser owner) : IRenderHandler + { + public ScreenInfo? GetScreenInfo() => null; + + public Rect GetViewRect() => new(0, 0, owner.Wide, owner.Tall); + + public bool GetScreenPoint(int viewX, int viewY, out int screenX, out int screenY) { + screenX = viewX; + screenY = viewY; + return false; + } + + public void OnAcceleratedPaint(PaintElementType type, Rect dirtyRect, nint sharedHandle) { } + + public void OnPaint(PaintElementType type, Rect dirtyRect, nint buffer, int width, int height) => owner.OnPaint(type, buffer, width, height); + + public void OnCursorChange(nint cursor, CursorType type, CursorInfo customCursorInfo) { } + + public bool StartDragging(IDragData dragData, DragOperationsMask mask, int x, int y) => false; + + public void UpdateDragCursor(DragOperationsMask operation) { } + + public void OnPopupShow(bool show) => owner.OnPopupShow(show); + + public void OnPopupSize(Rect rect) => owner.OnPopupSize(rect); + + public void OnImeCompositionRangeChanged(Range selectedRange, Rect[] characterBounds) { } + + public void OnVirtualKeyboardRequested(IBrowser browser, TextInputMode inputMode) { } + + public void Dispose() { } + } +} diff --git a/HTML.Chromium/ChromiumClient.cs b/HTML.Chromium/ChromiumClient.cs new file mode 100644 index 000000000..b82ecb76b --- /dev/null +++ b/HTML.Chromium/ChromiumClient.cs @@ -0,0 +1,145 @@ +using CefSharp; + +using Source.Common.GarrysMod; + +namespace HTML.Chromium; + +public class ChromiumClient : IHtmlClient +{ + readonly ChromiumBrowser Browser; + readonly IHtmlClientListener Listener; + bool Closed; + + public ChromiumClient(ChromiumBrowser browser, IHtmlClientListener listener) { + Browser = browser; + Listener = listener; + ChromiumSystem.g_ChromiumSystem.OnClientOpen(this); + } + + static void PostTask(Action task) => Cef.UIThreadTaskFactory.StartNew(task); + + public void Update() { + MessageQueue messageQueue = Browser.GetMessageQueue(); + + messageQueue.Lock(); + try { + while (!Closed && !messageQueue.Empty()) { + MessageQueue.Message msg = messageQueue.Pop(); + + switch (msg.Type) { + case MessageQueue.Type.OnAddressChange: + Listener.OnAddressChange(msg.String1); + break; + case MessageQueue.Type.OnConsoleMessage: + Listener.OnConsoleMessage(msg.String1, msg.String2, msg.Integer, msg.Integer2); + break; + case MessageQueue.Type.OnTitleChange: + Listener.OnTitleChange(msg.String1); + break; + case MessageQueue.Type.OnCursorChange: + Listener.OnCursorChange((IHtmlClientListener.CursorType)msg.Integer); + break; + case MessageQueue.Type.OnLoadStart: + Listener.OnLoadStart(msg.String1); + break; + case MessageQueue.Type.OnLoadEnd: + Listener.OnDocumentReady(msg.String1); + Listener.OnLoadEnd(msg.String1); + break; + case MessageQueue.Type.OnCreateChildView: + Listener.OnCreateChildView(msg.String1, msg.String2, msg.Integer != 0); + break; + case MessageQueue.Type.OnJavaScriptCall: + HandleJavaScriptCall(msg.String1, msg.String2, msg.JSParams, msg.Integer, msg.FrameId, msg.Nonce); + break; + } + } + } + finally { + messageQueue.Unlock(); + } + } + + void HandleJavaScriptCall(string objName, string funcName, in JSValue paramArray, int callbackId, long frameId, string nonce) { + JSValue retArray = Listener.OnJavaScriptCall(objName, funcName, paramArray); + + if (callbackId == -1) + return; + + PostTask(() => Browser.ExecuteCallback(callbackId, frameId, nonce, retArray)); + } + + public void Close() { + PostTask(Browser.Close); + + ChromiumSystem.g_ChromiumSystem.OnClientClose(this); + Closed = true; + } + + public void SetSize(int wide, int tall) => PostTask(() => Browser.SetSize(wide, tall)); + + public void SetFocused(bool hasFocus) => PostTask(() => Browser.SetFocused(hasFocus)); + + public void SendKeyEvent(IHtmlClient.KeyEvent keyEvent) => PostTask(() => Browser.SendKeyEvent(keyEvent)); + + public void SendMouseMoveEvent(IHtmlClient.MouseEvent mouseEvent, bool mouseLeave) => PostTask(() => Browser.SendMouseMoveEvent(mouseEvent, mouseLeave)); + + public void SendMouseWheelEvent(IHtmlClient.MouseEvent mouseEvent, int deltaX, int deltaY) => PostTask(() => Browser.SendMouseWheelEvent(mouseEvent, deltaX, deltaY)); + + public void SendMouseClickEvent(IHtmlClient.MouseEvent mouseEvent, IHtmlClient.MouseButton mouseButton, bool mouseUp, int clickCount) => PostTask(() => Browser.SendMouseClickEvent(mouseEvent, mouseButton, mouseUp, clickCount)); + + public void LoadUrl(ReadOnlySpan url) { + string str = new(url); + PostTask(() => Browser.LoadUrl(str)); + } + + public void SetHtml(ReadOnlySpan html) { + string str = new(html); + PostTask(() => Browser.SetHtml(str)); + } + + public void Refresh() => PostTask(Browser.Refresh); + + public void Stop() => PostTask(Browser.Stop); + + public void GoBack() => PostTask(Browser.GoBack); + + public void GoForward() => PostTask(Browser.GoForward); + + public void RunJavaScript(ReadOnlySpan code) { + string str = new(code); + PostTask(() => Browser.RunJavaScript(str)); + } + + public void RegisterJavaScriptFunction(ReadOnlySpan objName, ReadOnlySpan funcName) { + string obj = new(objName); + string func = new(funcName); + PostTask(() => Browser.RegisterJavaScriptFunction(obj, func)); + } + + public void SetOpenLinksExternally(bool openLinksExternally) => PostTask(() => Browser.SetOpenLinksExternally(openLinksExternally)); + + public bool LockImageData() { + ImageData imageData = Browser.GetImageData(); + + imageData.Lock(); + + if (!imageData.IsDirty()) { + imageData.Unlock(); + return false; + } + + return true; + } + + public void UnlockImageData() { + ImageData imageData = Browser.GetImageData(); + imageData.SetDirty(false); + imageData.Unlock(); + } + + public ReadOnlySpan GetImageData(out int imageWide, out int imageTall) { + ImageData imageData = Browser.GetImageData(); + return imageData.GetData(out imageWide, out imageTall); + } +} diff --git a/HTML.Chromium/ChromiumSystem.cs b/HTML.Chromium/ChromiumSystem.cs new file mode 100644 index 000000000..a12f0128e --- /dev/null +++ b/HTML.Chromium/ChromiumSystem.cs @@ -0,0 +1,258 @@ +using CefSharp; +using CefSharp.Enums; +using CefSharp.OffScreen; + +using ChromiumProcess; + +using Microsoft.Win32.SafeHandles; + +using Source.Common.GarrysMod; + +using System.Runtime.InteropServices; +using System.Security.Cryptography; + +namespace HTML.Chromium; + +public partial class ChromiumSystem : IHtmlSystem +{ + static readonly bool ResolverInstalled = ModuleResolver.Install(); + public static readonly ChromiumSystem g_ChromiumSystem = new(); + public static readonly IHtmlSystem g_pHtmlSystem = g_ChromiumSystem; + + readonly List ActiveClients = []; + + readonly Lock RequestsLock = new(); + List Requests = []; + + public string BridgeSecret { get; private set; } = ""; + public HtmlBridge.RegistryWriter? Registry { get; private set; } + + static void OnBeforeCommandLineProcessing(CefSettings settings) { + settings.CefCommandLineArgs.Add("disable-gpu"); + settings.CefCommandLineArgs.Add("disable-gpu-compositing"); + settings.CefCommandLineArgs.Add("disable-smooth-scrolling"); + settings.CefCommandLineArgs.Add("enable-begin-frame-scheduling"); + settings.CefCommandLineArgs.Add("enable-system-flash"); + + settings.CefCommandLineArgs["disable-features"] = "TouchpadAndWheelScrollLatching,AsyncWheelEvents"; + + settings.CefCommandLineArgs["autoplay-policy"] = "no-user-gesture-required"; + + settings.CefCommandLineArgs["enable-blink-features"] = "HTMLImports"; + + settings.CefCommandLineArgs["disable-site-isolation-trials"] = ""; + } + + static void OnRegisterCustomSchemes(CefSettings settings) { + settings.RegisterScheme(new CefCustomScheme("asset", SchemeOptions.Standard | SchemeOptions.CspBypassing)); + } + + [LibraryImport("kernel32.dll", EntryPoint = "GetFinalPathNameByHandleW", StringMarshalling = StringMarshalling.Utf16)] + private static partial uint GetFinalPathNameByHandle(SafeFileHandle hFile, [Out] char[] lpszFilePath, uint cchFilePath, uint dwFlags); + + static string? GetFinalDirectoryPath(string path) { + try { + using SafeFileHandle handle = Win32CreateDirectoryHandle(path); + if (handle.IsInvalid) + return null; + char[] buffer = new char[260]; + uint length = GetFinalPathNameByHandle(handle, buffer, (uint)buffer.Length, 0); + if (length == 0 || length >= buffer.Length) + return null; + return new string(buffer, 0, (int)length); + } + catch (Exception) { + return null; + } + } + + [LibraryImport("kernel32.dll", EntryPoint = "CreateFileW", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)] + private static partial SafeFileHandle CreateFile(string lpFileName, uint dwDesiredAccess, uint dwShareMode, nint lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, nint hTemplateFile); + + static SafeFileHandle Win32CreateDirectoryHandle(string path) { + const uint GENERIC_READ = 0x80000000; + const uint FILE_SHARE_READ = 0x00000001; + const uint OPEN_EXISTING = 3; + const uint FILE_FLAG_BACKUP_SEMANTICS = 0x02000000; + return CreateFile(path, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0); + } + + public bool Init(ReadOnlySpan pBaseDir, IHtmlResourceHandler resourceHandler) { + ResourceHandler.g_pHtmlResourceHandler = resourceHandler; + + CefSettings settings = new(); + settings.EnableAudio(); + + string strBaseDir = new(pBaseDir); + string moduleDir = Path.GetDirectoryName(typeof(ChromiumSystem).Assembly.Location)!; + string strChromiumDir = moduleDir; + + settings.RemoteDebuggingPort = 0; + settings.WindowlessRenderingEnabled = true; + settings.CommandLineArgsDisabled = true; + settings.LogSeverity = LogSeverity.Default; + + bool useTempDir = false; + + string? finalBaseDir = GetFinalDirectoryPath(strBaseDir); + if (finalBaseDir != null) { + if (finalBaseDir.StartsWith(@"\\?\UNC", StringComparison.Ordinal)) + useTempDir = true; + else + strBaseDir = finalBaseDir[4..]; + } + + string? finalChromiumDir = GetFinalDirectoryPath(strChromiumDir); + if (finalChromiumDir != null) { + if (finalChromiumDir.StartsWith(@"\\?\UNC", StringComparison.Ordinal)) + useTempDir = true; + else + strChromiumDir = finalChromiumDir[4..]; + } + + string chromiumDir = strChromiumDir; + + if (useTempDir) { + resourceHandler.Message("Copying Chromium resources to temporary directory...\n"); + + try { + string targetPath = Path.Combine(Path.GetTempPath(), "gmod-resources"); + Directory.CreateDirectory(targetPath); + + foreach (string file in Directory.EnumerateFiles(strChromiumDir, "*.pak")) + File.Copy(file, Path.Combine(targetPath, Path.GetFileName(file)), true); + + string locales = Path.Combine(strChromiumDir, "locales"); + string targetLocales = Path.Combine(targetPath, "locales"); + Directory.CreateDirectory(targetLocales); + foreach (string file in Directory.EnumerateFiles(locales)) + File.Copy(file, Path.Combine(targetLocales, Path.GetFileName(file)), true); + + chromiumDir = targetPath; + } + catch (Exception) { + return false; + } + } + + settings.UserAgent = "Mozilla/5.0 (Windows NT; Valve Source Client) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36 GMod/13"; + + settings.ResourcesDirPath = chromiumDir; + settings.LocalesDirPath = Path.Combine(chromiumDir, "locales"); + + settings.MultiThreadedMessageLoop = true; + + settings.LogFile = Path.Combine(strBaseDir, "chromium.log"); + + settings.BrowserSubprocessPath = Path.Combine(moduleDir, "ChromiumProcess.exe"); + + OnBeforeCommandLineProcessing(settings); + OnRegisterCustomSchemes(settings); + + BridgeSecret = Convert.ToHexString(RandomNumberGenerator.GetBytes(8)); + Environment.SetEnvironmentVariable(HtmlBridge.SecretVariable, BridgeSecret); + try { + Registry = new HtmlBridge.RegistryWriter(BridgeSecret); + } + catch (Exception) { + return false; + } + + CefSharpSettings.ShutdownOnExit = false; + + try { + if (!Cef.Initialize(settings, performDependencyCheck: false, browserProcessHandler: null)) + return false; + } + catch (Exception e) { + resourceHandler.Message($"Chromium failed to initialize: {e.Message}\n"); + return false; + } + + { + ResourceHandlerFactory factory = new(); + IRequestContext context = Cef.GetGlobalRequestContext(); + + context.RegisterSchemeHandlerFactory("asset", "garrysmod", factory); + Cef.AddCrossOriginWhitelistEntry("asset://garrysmod", "http", "", true); + Cef.AddCrossOriginWhitelistEntry("asset://garrysmod", "https", "", true); + Cef.AddCrossOriginWhitelistEntry("asset://garrysmod", "asset", "", true); + + context.RegisterSchemeHandlerFactory("asset", "mapimage", factory); + Cef.AddCrossOriginWhitelistEntry("asset://mapimage", "http", "", true); + Cef.AddCrossOriginWhitelistEntry("asset://mapimage", "https", "", true); + Cef.AddCrossOriginWhitelistEntry("asset://mapimage", "asset", "", true); + } + + { + HtmlResourceHandlerFactory factory = new(); + IRequestContext context = Cef.GetGlobalRequestContext(); + + context.RegisterSchemeHandlerFactory("asset", "html", factory); + Cef.AddCrossOriginWhitelistEntry("asset://html", "http", "", true); + Cef.AddCrossOriginWhitelistEntry("asset://html", "https", "", true); + Cef.AddCrossOriginWhitelistEntry("asset://html", "asset", "", true); + } + + return true; + } + + public void Shutdown() { + Cef.Shutdown(); + Registry?.Dispose(); + Registry = null; + } + + public IHtmlClient CreateClient(IHtmlClientListener listener) { + BrowserSettings browserSettings = new() { + DefaultEncoding = "UTF-8", + WindowlessFrameRate = 60, + JavascriptAccessClipboard = CefState.Disabled, + JavascriptCloseWindows = CefState.Disabled, + UniversalAccessFromFileUrls = CefState.Disabled, + FileAccessFromFileUrls = CefState.Disabled, + WebGl = CefState.Disabled + }; + + ChromiumBrowser cefClient = new(BridgeSecret, Registry); + + cefClient.CreateBrowser(browserSettings); + + return new ChromiumClient(cefClient, listener); + } + + public void Update() { + List requests; + lock (RequestsLock) { + requests = Requests; + Requests = []; + } + + foreach (ResourceHandler request in requests) + request.Handle(); + + foreach (ChromiumClient client in ActiveClients.ToArray()) + client.Update(); + } + + public void OnClientOpen(ChromiumClient client) => ActiveClients.Add(client); + public void OnClientClose(ChromiumClient client) => ActiveClients.Remove(client); + + public void QueueRequest(ResourceHandler resourceHandler) { + lock (RequestsLock) + Requests.Add(resourceHandler); + } + + public JSValue CreateArray(ReadOnlySpan values) => JSArray.Create(values.ToArray()); + + public JSValue CreateString(ReadOnlySpan value) => JSString.Create(new string(value)); + + public JSValue CreateHashMap(ReadOnlySpan keys, ReadOnlySpan values) { + Dictionary container = new(keys.Length); + + for (int i = 0; i < keys.Length; i++) + container[keys[i]] = values[i]; + + return JSHashMap.Create(container); + } +} diff --git a/HTML.Chromium/HTML.Chromium.csproj b/HTML.Chromium/HTML.Chromium.csproj new file mode 100644 index 000000000..4d8773d9b --- /dev/null +++ b/HTML.Chromium/HTML.Chromium.csproj @@ -0,0 +1,31 @@ + + + + net10.0 + enable + enable + Debug;Release;Debug (Dedicated);Release (Dedicated) + win-x64 + false + false + true + true + + + + + + + + + + + + + + + false + + + + diff --git a/HTML.Chromium/HtmlResourceHandler.cs b/HTML.Chromium/HtmlResourceHandler.cs new file mode 100644 index 000000000..e82255b45 --- /dev/null +++ b/HTML.Chromium/HtmlResourceHandler.cs @@ -0,0 +1,72 @@ +using CefSharp; +using CefSharp.Callback; + +using System.Collections.Specialized; + +namespace HTML.Chromium; + +public sealed class HtmlResourceHandlerFactory : ISchemeHandlerFactory +{ + public IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request) => new HtmlResourceHandler(); +} + +public sealed class HtmlResourceHandler : IResourceHandler +{ + byte[] Html = []; + int Current; + + public bool Open(IRequest request, out bool handleRequest, ICallback callback) { + handleRequest = true; + Current = 0; + + if (!Uri.TryCreate(request.Url, UriKind.Absolute, out Uri? url)) + return false; + + string encodedHtml = url.Query.StartsWith('?') ? url.Query[1..] : url.Query; + byte[] data = new byte[encodedHtml.Length]; + if (Convert.TryFromBase64String(encodedHtml, data, out int written)) + Html = data[..written]; + + return true; + } + + public bool ProcessRequest(IRequest request, ICallback callback) => false; + + public void GetResponseHeaders(IResponse response, out long responseLength, out string redirectUrl) { + redirectUrl = null!; + + response.StatusCode = 200; + response.Headers = new NameValueCollection { { "X-XSS-Protection", "0" } }; + response.MimeType = "text/html"; + responseLength = Html.Length; + } + + public bool Skip(long bytesToSkip, out long bytesSkipped, IResourceSkipCallback callback) { + bytesSkipped = -2; + return false; + } + + public bool Read(Stream dataOut, out int bytesRead, IResourceReadCallback callback) { + bytesRead = 0; + if (Html.Length <= 0) + return false; + + int bytesToRead = (int)Math.Min(dataOut.Length, Html.Length - Current); + bytesToRead = Math.Max(bytesToRead, 0); + + dataOut.Write(Html, Current, bytesToRead); + bytesRead = bytesToRead; + Current += bytesToRead; + + return bytesToRead > 0; + } + + public bool ReadResponse(Stream dataOut, out int bytesRead, ICallback callback) { + bytesRead = 0; + return false; + } + + public void Cancel() { } + + public void Dispose() { } +} diff --git a/HTML.Chromium/ImageData.cs b/HTML.Chromium/ImageData.cs new file mode 100644 index 000000000..aedb07203 --- /dev/null +++ b/HTML.Chromium/ImageData.cs @@ -0,0 +1,59 @@ +using System.Runtime.InteropServices; + +namespace HTML.Chromium; + +public class ImageData +{ + readonly Lock Mutex = new(); + bool Dirty; + int Wide; + int Tall; + byte[]? Data; + + public void Lock() => Mutex.Enter(); + public void Unlock() => Mutex.Exit(); + + public void SetData(nint data, int wide, int tall) { + int bufSize = wide * tall * 4; + + if (Wide != wide || Tall != tall || Data == null) + Data = new byte[bufSize]; + + Marshal.Copy(data, Data, 0, bufSize); + Wide = wide; + Tall = tall; + Dirty = true; + } + + public void CopyImage(byte[]? data, int x, int y, int w, int h) { + if (w < 0 || h < 0 || data == null || Data == null) + return; + + int dstX = Math.Max(0, x); + int dstY = Math.Max(0, y); + int srcX = Math.Max(0, -x); + int srcY = Math.Max(0, -y); + + int copyW = Math.Min(w - srcX, Wide - dstX); + int copyH = Math.Min(h - srcY, Tall - dstY); + + if (copyW > 0 && copyH > 0) { + for (int row = 0; row < copyH; ++row) { + int dstOffset = ((dstY + row) * Wide + dstX) * 4; + int srcOffset = ((srcY + row) * w + srcX) * 4; + Buffer.BlockCopy(data, srcOffset, Data, dstOffset, copyW * 4); + } + + Dirty = true; + } + } + + public ReadOnlySpan GetData(out int wide, out int tall) { + wide = Wide; + tall = Tall; + return Data; + } + + public bool IsDirty() => Dirty; + public void SetDirty(bool dirty) => Dirty = dirty; +} diff --git a/HTML.Chromium/JSObjects.cs b/HTML.Chromium/JSObjects.cs new file mode 100644 index 000000000..d6a1904b6 --- /dev/null +++ b/HTML.Chromium/JSObjects.cs @@ -0,0 +1,57 @@ +using Source.Common.GarrysMod; + +namespace HTML.Chromium; + +public sealed class JSArray : JSValue.IArray +{ + readonly JSValue[] Data; + + JSArray(JSValue[] data) => Data = data; + + public ReadOnlySpan GetData() => Data; + public JSValue[] GetInternalData() => Data; + + public static JSValue Create(JSValue[] data) => new(new JSArray(data)); +} + +public sealed class JSString : JSValue.IString +{ + readonly string Data; + + JSString(string data) => Data = data; + + public ReadOnlySpan GetData() => Data; + public string GetInternalData() => Data; + + public static JSValue Create(string data) => new(new JSString(data)); +} + +public sealed class JSHashMap : JSValue.IHashMap +{ + readonly Dictionary Data; + Dictionary.Enumerator Iterator; + + JSHashMap(Dictionary data) => Data = data; + + public bool Begin(out ReadOnlySpan key, out JSValue value) { + Iterator = Data.GetEnumerator(); + return Next(out key, out value); + } + + public bool Next(out ReadOnlySpan key, out JSValue value) { + if (!Iterator.MoveNext()) { + key = default; + value = default; + return false; + } + + key = Iterator.Current.Key; + value = Iterator.Current.Value; + return true; + } + + public int Size() => Data.Count; + public Dictionary GetInternalData() => Data; + + public static JSValue Create(Dictionary data) => new(new JSHashMap(data)); +} diff --git a/HTML.Chromium/MessageQueue.cs b/HTML.Chromium/MessageQueue.cs new file mode 100644 index 000000000..c8297e595 --- /dev/null +++ b/HTML.Chromium/MessageQueue.cs @@ -0,0 +1,39 @@ +using Source.Common.GarrysMod; + +namespace HTML.Chromium; + +public class MessageQueue +{ + public enum Type + { + OnAddressChange, + OnConsoleMessage, + OnTitleChange, + OnCursorChange, + OnLoadStart, + OnLoadEnd, + OnCreateChildView, + OnJavaScriptCall + } + + public struct Message + { + public Type Type; + public int Integer; + public int Integer2; + public long FrameId; + public string Nonce; + public string String1; + public string String2; + public JSValue JSParams; + } + + readonly Lock Mutex = new(); + readonly Queue Messages = new(); + + public void Lock() => Mutex.Enter(); + public void Unlock() => Mutex.Exit(); + public void Push(in Message message) => Messages.Enqueue(message); + public bool Empty() => Messages.Count == 0; + public Message Pop() => Messages.Dequeue(); +} diff --git a/HTML.Chromium/ModuleResolver.cs b/HTML.Chromium/ModuleResolver.cs new file mode 100644 index 000000000..5b146585b --- /dev/null +++ b/HTML.Chromium/ModuleResolver.cs @@ -0,0 +1,15 @@ +using System.Runtime.Loader; + +namespace HTML.Chromium; + +static class ModuleResolver +{ + public static bool Install() { + string moduleDir = Path.GetDirectoryName(typeof(ModuleResolver).Assembly.Location)!; + AssemblyLoadContext.Default.Resolving += (context, name) => { + string path = Path.Combine(moduleDir, $"{name.Name}.dll"); + return File.Exists(path) ? context.LoadFromAssemblyPath(path) : null; + }; + return true; + } +} diff --git a/HTML.Chromium/ResourceHandler.cs b/HTML.Chromium/ResourceHandler.cs new file mode 100644 index 000000000..41c86ae80 --- /dev/null +++ b/HTML.Chromium/ResourceHandler.cs @@ -0,0 +1,145 @@ +using CefSharp; +using CefSharp.Callback; + +using Source.Common.GarrysMod; + +using System.Text; + +namespace HTML.Chromium; + +public sealed class ResourceHandlerFactory : ISchemeHandlerFactory +{ + public IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request) => new ResourceHandler(); +} + +public sealed class ResourceHandler : IResourceHandler +{ + public static IHtmlResourceHandler? g_pHtmlResourceHandler; + + string Host = ""; + string Path = ""; + ICallback? ResponseCallback; + + byte[]? Buffer; + int BufferPtr; + + public void Handle() { + HtmlResource? resource = g_pHtmlResourceHandler!.OpenResource(Host, Path); + + if (resource != null) { + long size = g_pHtmlResourceHandler.GetLength(resource); + Buffer = new byte[size]; + BufferPtr = 0; + + g_pHtmlResourceHandler.ReadData(resource, Buffer); + g_pHtmlResourceHandler.CloseResource(resource); + } + + if (ResponseCallback != null && !ResponseCallback.IsDisposed) + ResponseCallback.Continue(); + } + + public bool Open(IRequest request, out bool handleRequest, ICallback callback) { + handleRequest = true; + + if (!Uri.TryCreate(request.Url, UriKind.Absolute, out Uri? url)) + return false; + + Host = url.Host; + Path = URIDecode(url.AbsolutePath); + + handleRequest = false; + ResponseCallback = callback; + ChromiumSystem.g_ChromiumSystem.QueueRequest(this); + + return true; + } + + public bool ProcessRequest(IRequest request, ICallback callback) => false; + + static string GetFileExtension(string path) { + int i = path.LastIndexOf('.'); + if (i == -1) + return ""; + return path[(i + 1)..]; + } + + public void GetResponseHeaders(IResponse response, out long responseLength, out string redirectUrl) { + redirectUrl = null!; + + if (Buffer == null) { + responseLength = 0; + response.ErrorCode = CefErrorCode.FileNotFound; + return; + } + + string mimeType = "text/html"; + + string ext = GetFileExtension(Path); + if (ext == "png" || Host == "mapimage") mimeType = "image/png"; + else if (ext == "jpg") mimeType = "image/jpg"; + else if (ext == "jpeg") mimeType = "image/jpg"; + else if (ext == "css") mimeType = "text/css"; + else if (ext == "js") mimeType = "text/javascript"; + else if (ext == "svg") mimeType = "image/svg+xml"; + else if (ext == "gif") mimeType = "image/gif"; + else if (ext == "webm") mimeType = "video/webm"; + else if (ext == "mp4") mimeType = "video/mp4"; + + response.StatusCode = 200; + response.MimeType = mimeType; + responseLength = Buffer.Length; + } + + public bool Skip(long bytesToSkip, out long bytesSkipped, IResourceSkipCallback callback) { + bytesSkipped = -2; + return false; + } + + public bool Read(Stream dataOut, out int bytesRead, IResourceReadCallback callback) { + int bytesToRead = (int)Math.Min(dataOut.Length, (Buffer?.Length ?? 0) - BufferPtr); + bytesToRead = Math.Max(bytesToRead, 0); + + if (bytesToRead > 0) { + dataOut.Write(Buffer!, BufferPtr, bytesToRead); + BufferPtr += bytesToRead; + } + bytesRead = bytesToRead; + + if (bytesToRead == 0) + Buffer = null; + + return bytesToRead > 0; + } + + public bool ReadResponse(Stream dataOut, out int bytesRead, ICallback callback) { + bytesRead = 0; + return false; + } + + public void Cancel() { } + + public void Dispose() { } + + static string URIDecode(string encoded) { + byte[] source = Encoding.UTF8.GetBytes(encoded); + List bytes = new(source.Length); + for (int i = 0; i < source.Length; i++) { + byte c = source[i]; + if (c == '%' && i + 2 < source.Length && IsHex(source[i + 1]) && IsHex(source[i + 2])) { + int value = (HexValue(source[i + 1]) << 4) | HexValue(source[i + 2]); + if (value >= 0x20 && value != 0x7F && value != '/' && value != '\\') { + bytes.Add((byte)value); + i += 2; + continue; + } + } + + bytes.Add(c); + } + return Encoding.UTF8.GetString(bytes.ToArray()); + } + + static bool IsHex(byte c) => c is (>= (byte)'0' and <= (byte)'9') or (>= (byte)'a' and <= (byte)'f') or (>= (byte)'A' and <= (byte)'F'); + static int HexValue(byte c) => c <= '9' ? c - '0' : (c | 0x20) - 'a' + 10; +} diff --git a/Source.Launcher/Program.cs b/Source.Launcher/Program.cs index f55d8b7dc..b5f8ea3d0 100644 --- a/Source.Launcher/Program.cs +++ b/Source.Launcher/Program.cs @@ -87,6 +87,9 @@ public void Boot() { #if GMOD_DLL .WithComponent() .WithComponent() + #if WIN32 + .WithKeyedComponent("html_chromium", HTML.Chromium.ChromiumSystem.g_pHtmlSystem) + #endif .WithKeyedComponent("html_stub", HTML.Stub.StubSystem.g_pHtmlSystem) #endif .WithComponent() diff --git a/Source.Launcher/Source.Launcher.csproj b/Source.Launcher/Source.Launcher.csproj index 54bb183ea..be510d3b7 100644 --- a/Source.Launcher/Source.Launcher.csproj +++ b/Source.Launcher/Source.Launcher.csproj @@ -40,6 +40,7 @@ + diff --git a/Source.NET.slnx b/Source.NET.slnx index 9b8bac89e..559d2b387 100644 --- a/Source.NET.slnx +++ b/Source.NET.slnx @@ -113,6 +113,12 @@ + + + + + + From be73d2859f6e1bef395b470c7fc53baaba024a3f Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Thu, 15 Oct 2026 15:06:03 -0700 Subject: [PATCH 27/38] SetDynamicImage --- Source.Common/GarrysMod/IResources.cs | 2 +- Source.Engine/GarrysMod/Resources.cs | 14 +++++++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/Source.Common/GarrysMod/IResources.cs b/Source.Common/GarrysMod/IResources.cs index d1da81a42..9a6312226 100644 --- a/Source.Common/GarrysMod/IResources.cs +++ b/Source.Common/GarrysMod/IResources.cs @@ -54,5 +54,5 @@ public interface IResources void AudioSamples(Span unk1, uint unk2 /* probably size of unk1*/, byte unk3, byte unk4); void SavePNGToBuffer(int unk1, int unk2, Span unk3, Stream unk4, int unk5, int unk6); void SaveJPGToBuffer(int unk1, int unk2, Span unk3, Stream unk4, int unk5, int unk6, int unk7); - void SetImage(ITexture unk1, ReadOnlySpan unk2); + void SetImage(ITexture texture, ReadOnlySpan name); } diff --git a/Source.Engine/GarrysMod/Resources.cs b/Source.Engine/GarrysMod/Resources.cs index fb5cabd64..d6fadb389 100644 --- a/Source.Engine/GarrysMod/Resources.cs +++ b/Source.Engine/GarrysMod/Resources.cs @@ -281,7 +281,19 @@ public void SavePNG(int width, int height, Span pixels, ReadOnlySpan public void AudioSamples(Span unk1, uint unk2, byte unk3, byte unk4) => throw new NotImplementedException(); public void SavePNGToBuffer(int unk1, int unk2, Span unk3, Stream unk4, int unk5, int unk6) => throw new NotImplementedException(); public void SaveJPGToBuffer(int unk1, int unk2, Span unk3, Stream unk4, int unk5, int unk6, int unk7) => throw new NotImplementedException(); - public void SetImage(ITexture unk1, ReadOnlySpan unk2) => throw new NotImplementedException(); + public void SetImage(ITexture texture, ReadOnlySpan name) { + foreach (Image image in Image.DynamicImages) { + if (image.Texture != texture) + continue; + + if (!image.Bitmap.IsNull) { + FreeImage.Unload(image.Bitmap); + image.Bitmap = FIBITMAP.Zero; + } + image.Name = new(name); + return; + } + } public IMaterial? FindMaterial(ReadOnlySpan name, ReadOnlySpan flags, bool create, bool anyExtension, bool dynamic) { Span extension = stackalloc char[6]; From 1889f77f115c6ccb72c2582ce501e046156f0c04 Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Thu, 15 Oct 2026 15:18:33 -0700 Subject: [PATCH 28/38] New Chromium --- .gitmodules | 3 + .vscode/launch.json | 14 +- ChromiumProcess/ChromiumProcess.csproj | 1 + Dependencies/CEF | 1 + HTML.CEF/CefApplication.cs | 28 + HTML.CEF/CefBrowserClient.cs | 780 ++++++++++++++++++ HTML.CEF/CefHtmlClient.cs | 150 ++++ HTML.CEF/CefSystem.cs | 184 +++++ HTML.CEF/HTML.CEF.csproj | 20 + HTML.CEF/HtmlResourceHandler.cs | 61 ++ HTML.CEF/ImageData.cs | 59 ++ HTML.CEF/JSObjects.cs | 57 ++ HTML.CEF/MessageQueue.cs | 38 + HTML.CEF/ResourceHandler.cs | 138 ++++ HTML.Chromium/HTML.Chromium.csproj | 1 + Source.Launcher.Native/App.cpp | 379 +++++++++ Source.Launcher.Native/App.h | 49 ++ Source.Launcher.Native/CMakeLists.txt | 43 + Source.Launcher.Native/MainLinux.cpp | 15 + Source.Launcher.Native/MainWin.cpp | 126 +++ .../Source.Launcher.Native.targets | 61 ++ Source.Launcher/Program.cs | 4 +- Source.Launcher/Source.Launcher.csproj | 16 +- Source.NET.slnx | 3 + 24 files changed, 2225 insertions(+), 6 deletions(-) create mode 160000 Dependencies/CEF create mode 100644 HTML.CEF/CefApplication.cs create mode 100644 HTML.CEF/CefBrowserClient.cs create mode 100644 HTML.CEF/CefHtmlClient.cs create mode 100644 HTML.CEF/CefSystem.cs create mode 100644 HTML.CEF/HTML.CEF.csproj create mode 100644 HTML.CEF/HtmlResourceHandler.cs create mode 100644 HTML.CEF/ImageData.cs create mode 100644 HTML.CEF/JSObjects.cs create mode 100644 HTML.CEF/MessageQueue.cs create mode 100644 HTML.CEF/ResourceHandler.cs create mode 100644 Source.Launcher.Native/App.cpp create mode 100644 Source.Launcher.Native/App.h create mode 100644 Source.Launcher.Native/CMakeLists.txt create mode 100644 Source.Launcher.Native/MainLinux.cpp create mode 100644 Source.Launcher.Native/MainWin.cpp create mode 100644 Source.Launcher.Native/Source.Launcher.Native.targets diff --git a/.gitmodules b/.gitmodules index 547993f96..6c6fd7236 100644 --- a/.gitmodules +++ b/.gitmodules @@ -6,3 +6,6 @@ path = Dependencies/Steamworks.NET url = https://github.com/marchc1/Steamworks.NET branch = 1-64 +[submodule "Dependencies/CEF"] + path = Dependencies/CEF + url = https://github.com/SourceDotNet/CEF-SDK.git diff --git a/.vscode/launch.json b/.vscode/launch.json index 932170ee1..5cfc2b72d 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -6,7 +6,7 @@ "type": "coreclr", "request": "launch", "preLaunchTask": "build Source.Launcher", - "program": "${workspaceFolder}/Build/Debug/Source.Launcher.dll", + "program": "${workspaceFolder}/Build/Debug/Source.Launcher.exe", "cwd": "${workspaceFolder}/Build/Debug", "stopAtEntry": false }, @@ -15,11 +15,21 @@ "type": "coreclr", "request": "launch", "preLaunchTask": "build Source.Launcher", - "program": "${workspaceFolder}/Build/Debug/Source.Launcher.dll", + "program": "${workspaceFolder}/Build/Debug/Source.Launcher.exe", "cwd": "${workspaceFolder}/Build/Debug", "stopAtEntry": false, "console": "externalTerminal" }, + { + "name": "Source.LauncherMain (no sandbox)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build Source.Launcher", + "program": "${workspaceFolder}/Build/Debug/Source.LauncherMain.dll", + "cwd": "${workspaceFolder}/Build/Debug", + "args": ["-nochromiumsandbox"], + "stopAtEntry": false + }, { "name": "Source.Dedicated", "type": "coreclr", diff --git a/ChromiumProcess/ChromiumProcess.csproj b/ChromiumProcess/ChromiumProcess.csproj index f27c5b25d..08805427b 100644 --- a/ChromiumProcess/ChromiumProcess.csproj +++ b/ChromiumProcess/ChromiumProcess.csproj @@ -9,6 +9,7 @@ win-x64 false false + $(MSBuildThisFileDirectory)..\Build\$(Configuration)\cefsharp\ app.manifest diff --git a/Dependencies/CEF b/Dependencies/CEF new file mode 160000 index 000000000..c82a98d46 --- /dev/null +++ b/Dependencies/CEF @@ -0,0 +1 @@ +Subproject commit c82a98d46de8301ccdbb69d9e58fb8ac279c7395 diff --git a/HTML.CEF/CefApplication.cs b/HTML.CEF/CefApplication.cs new file mode 100644 index 000000000..b58c190f8 --- /dev/null +++ b/HTML.CEF/CefApplication.cs @@ -0,0 +1,28 @@ +using Xilium.CefGlue; + +namespace HTML.CEF; + +sealed class CefApplication : CefApp +{ + protected override void OnBeforeCommandLineProcessing(string processType, CefCommandLine commandLine) { + if (!string.IsNullOrEmpty(processType)) + return; + + commandLine.AppendSwitch("disable-gpu"); + commandLine.AppendSwitch("disable-gpu-compositing"); + commandLine.AppendSwitch("disable-smooth-scrolling"); + if (OperatingSystem.IsWindows()) + commandLine.AppendSwitch("enable-begin-frame-scheduling"); + commandLine.AppendSwitch("enable-system-flash"); + commandLine.AppendSwitch("disable-in-process-stack-traces"); + + commandLine.AppendSwitch("disable-features", "TouchpadAndWheelScrollLatching,AsyncWheelEvents"); + commandLine.AppendSwitch("autoplay-policy", "no-user-gesture-required"); + commandLine.AppendSwitch("enable-blink-features", "HTMLImports"); + commandLine.AppendSwitch("disable-site-isolation-trials"); + } + + protected override void OnRegisterCustomSchemes(CefSchemeRegistrar registrar) { + registrar.AddCustomScheme("asset", CefSchemeOptions.Standard | CefSchemeOptions.CspBypassing); + } +} diff --git a/HTML.CEF/CefBrowserClient.cs b/HTML.CEF/CefBrowserClient.cs new file mode 100644 index 000000000..2958db785 --- /dev/null +++ b/HTML.CEF/CefBrowserClient.cs @@ -0,0 +1,780 @@ +using Source.Common.GarrysMod; + +using System.Diagnostics; +using System.Text; + +using Xilium.CefGlue; + +namespace HTML.CEF; + +public sealed class CefBrowserClient : CefClient +{ + static readonly string[] BlockedJavaScriptHosts = [ + "steampowered", + "steamcommunity", + "valvesoftware", + "steamgames", + "discord.", + "discordapp", + "watchanimeattheoffice", + "bigbeans.solutions", + "dis.gd", + "10.", + "172.16.", + "192.168.", + "127.", + "localhost", + ]; + + static bool CefValueToJSValue(out JSValue outValue, ICefListValue list, int index, int depth = 0) { + outValue = default; + + if (depth > 16) + return false; + + switch (list.GetValueType(index)) { + case CefValueType.Bool: + outValue = new JSValue(list.GetBool(index)); + break; + case CefValueType.Int: + outValue = new JSValue(list.GetInt(index)); + break; + case CefValueType.Double: + outValue = new JSValue(list.GetDouble(index)); + break; + case CefValueType.String: + outValue = JSString.Create(list.GetString(index) ?? ""); + break; + case CefValueType.List: { + using ICefListValue inner = list.GetList(index); + if (!CefListToJSValues(out JSValue[] values, inner, depth + 1)) + return false; + outValue = JSArray.Create(values); + break; + } + case CefValueType.Dictionary: { + using ICefDictionaryValue inner = list.GetDictionary(index); + if (!CefDictionaryToJSValue(out outValue, inner, depth + 1)) + return false; + break; + } + } + + return true; + } + + static bool CefDictionaryToJSValue(out JSValue outValue, ICefDictionaryValue dict, int depth) { + outValue = default; + + if (depth > 16) + return false; + + string[] keys = dict.GetKeys(); + Dictionary map = new(keys.Length); + foreach (string key in keys) { + using CefListValue wrapper = CefListValue.Create(); + using (CefValue? value = dict.GetValue(key)) { + if (value == null) + continue; + wrapper.SetValue(0, value); + } + + if (!CefValueToJSValue(out JSValue entry, wrapper, 0, depth + 1)) + return false; + + map.TryAdd(key, entry); + } + + outValue = JSHashMap.Create(map); + return true; + } + + static bool CefListToJSValues(out JSValue[] outList, ICefListValue inList, int depth = 0) { + outList = new JSValue[inList.Count]; + + for (int i = 0; i < outList.Length; i++) + if (!CefValueToJSValue(out outList[i], inList, i, depth)) + return false; + + return true; + } + + static bool JSValueToCefList(CefListValue outList, int index, in JSValue inValue, int depth = 0) { + if (depth > 16) + return false; + + switch (inValue.GetJSType()) { + case JSValue.Type.Bool: + outList.SetBool(index, inValue.GetBool()); + break; + case JSValue.Type.Number: + outList.SetDouble(index, inValue.GetNumber()); + break; + case JSValue.Type.String: + outList.SetString(index, new string(inValue.GetString())); + break; + case JSValue.Type.Array: { + using CefListValue list = CefListValue.Create(); + ReadOnlySpan values = inValue.GetArray(); + for (int i = 0; i < values.Length; i++) + if (!JSValueToCefList(list, i, values[i], depth + 1)) + return false; + outList.SetList(index, list); + break; + } + case JSValue.Type.HashMap: { + using CefDictionaryValue dict = CefDictionaryValue.Create(); + if (inValue.HashMap_Begin(out ReadOnlySpan key, out JSValue value)) { + do { + using CefListValue wrapper = CefListValue.Create(); + if (!JSValueToCefList(wrapper, 0, value, depth + 1)) + return false; + using CefValue? entry = wrapper.GetValue(0); + if (entry != null) + dict.SetValue(new string(key), entry); + } + while (inValue.HashMap_Next(out key, out value)); + } + outList.SetDictionary(index, dict); + break; + } + default: + outList.SetNull(index); + break; + } + + return true; + } + + static CefEventFlags GetModifiers(IHtmlClient.EventModifiers modifiers) { + CefEventFlags flags = CefEventFlags.None; + + if ((modifiers & IHtmlClient.EventModifiers.Shift) != 0) + flags |= CefEventFlags.ShiftDown | CefEventFlags.IsLeft; + + if ((modifiers & IHtmlClient.EventModifiers.ShiftR) != 0) + flags |= CefEventFlags.ShiftDown | CefEventFlags.IsRight; + + if ((modifiers & IHtmlClient.EventModifiers.Control) != 0) + flags |= CefEventFlags.ControlDown | CefEventFlags.IsLeft; + + if ((modifiers & IHtmlClient.EventModifiers.ControlR) != 0) + flags |= CefEventFlags.ControlDown | CefEventFlags.IsRight; + + if ((modifiers & IHtmlClient.EventModifiers.Alt) != 0) + flags |= CefEventFlags.AltDown | CefEventFlags.IsLeft; + + if ((modifiers & IHtmlClient.EventModifiers.AltGr) != 0) + flags |= CefEventFlags.AltDown | CefEventFlags.IsRight; + + if ((modifiers & IHtmlClient.EventModifiers.LeftMouse) != 0) + flags |= CefEventFlags.LeftMouseButton; + + if ((modifiers & IHtmlClient.EventModifiers.MiddleMouse) != 0) + flags |= CefEventFlags.MiddleMouseButton; + + if ((modifiers & IHtmlClient.EventModifiers.RightMouse) != 0) + flags |= CefEventFlags.RightMouseButton; + + if ((modifiers & IHtmlClient.EventModifiers.Numpad) != 0) + flags |= CefEventFlags.IsKeyPad; + + return flags; + } + + static bool TryParseScheme(string url, out string scheme) { + if (Uri.TryCreate(url, UriKind.Absolute, out Uri? uri)) { + scheme = uri.Scheme; + return true; + } + + scheme = ""; + return false; + } + + int Wide = 512; + int Tall = 512; + + int PopupX; + int PopupY; + int PopupWide; + int PopupTall; + byte[]? PopupData; + + readonly MessageQueue MessageQueue = new(); + readonly ImageData ImageData = new(); + + CefBrowserSettings? Settings; + CefBrowser? Browser; + CefBrowserHost? BrowserHost; + bool Created; + bool Closing; + + bool OpenLinksExternally; + + readonly List<(string Obj, string Func)> RegisteredFunctions = []; + readonly List PendingTasks = []; + + readonly LifeSpanHandler LifeSpan; + readonly LoadHandler Load; + readonly DisplayHandler Display; + readonly RequestHandler Request; + readonly ContextMenuHandler ContextMenu = new(); + readonly DialogHandler Dialog = new(); + readonly JSDialogHandler JSDialog = new(); + readonly RenderHandler Render; + + public CefBrowserClient() { + LifeSpan = new LifeSpanHandler(this); + Load = new LoadHandler(this); + Display = new DisplayHandler(this); + Request = new RequestHandler(this); + Render = new RenderHandler(this); + } + + public void CreateBrowser(CefBrowserSettings browserSettings) => Settings = browserSettings; + + bool CreateBrowserWithUrl(string url) { + if (Created || Closing || Settings == null) + return false; + + Created = true; + + using CefListValue functions = CefListValue.Create(); + for (int i = 0; i < RegisteredFunctions.Count; i++) { + using CefListValue pair = CefListValue.Create(); + pair.SetString(0, RegisteredFunctions[i].Obj); + pair.SetString(1, RegisteredFunctions[i].Func); + functions.SetList(i, pair); + } + + using CefDictionaryValue extraInfo = CefDictionaryValue.Create(); + extraInfo.SetList("functions", functions); + + CefWindowInfo windowInfo = CefWindowInfo.Create(); + windowInfo.SetAsWindowless(IntPtr.Zero, false); + CefBrowserHost.CreateBrowser(windowInfo, this, Settings, url, extraInfo); + return true; + } + + public ImageData GetImageData() => ImageData; + + public MessageQueue GetMessageQueue() => MessageQueue; + + void QueueMessage(in MessageQueue.Message message) { + MessageQueue.Lock(); + MessageQueue.Push(message); + MessageQueue.Unlock(); + } + + void RunOrDefer(Action task) { + if (Closing) + return; + + if (Browser == null) { + PendingTasks.Add(task); + return; + } + + task(); + } + + public void Close() { + PendingTasks.Clear(); + Closing = true; + BrowserHost?.CloseBrowser(true); + } + + public void SetSize(int wide, int tall) { + Wide = wide; + Tall = tall; + RunOrDefer(() => BrowserHost!.WasResized()); + } + + public void SetFocused(bool hasFocus) => RunOrDefer(() => BrowserHost!.SetFocus(hasFocus)); + + public void SendKeyEvent(IHtmlClient.KeyEvent keyEvent) { + CefKeyEvent cefKeyEvent = new() { + Modifiers = GetModifiers(keyEvent.Modifiers), + WindowsKeyCode = keyEvent.WindowsKeyCode, + NativeKeyCode = keyEvent.NativeKeyCode, + EventType = keyEvent.EventType switch { + IHtmlClient.KeyEvent.Type.KeyChar => CefKeyEventType.Char, + IHtmlClient.KeyEvent.Type.KeyUp => CefKeyEventType.KeyUp, + _ => CefKeyEventType.KeyDown, + } + }; + + if (keyEvent.EventType == IHtmlClient.KeyEvent.Type.KeyChar) { + cefKeyEvent.Character = (char)keyEvent.KeyChar; + cefKeyEvent.UnmodifiedCharacter = (char)keyEvent.KeyChar; + } + + RunOrDefer(() => BrowserHost!.SendKeyEvent(cefKeyEvent)); + } + + public void SendMouseMoveEvent(IHtmlClient.MouseEvent mouseEvent, bool mouseLeave) { + CefMouseEvent cefMouseEvent = new(mouseEvent.X, mouseEvent.Y, GetModifiers(mouseEvent.Modifiers)); + RunOrDefer(() => BrowserHost!.SendMouseMoveEvent(cefMouseEvent, mouseLeave)); + } + + public void SendMouseWheelEvent(IHtmlClient.MouseEvent mouseEvent, int deltaX, int deltaY) { + CefMouseEvent cefMouseEvent = new(mouseEvent.X, mouseEvent.Y, GetModifiers(mouseEvent.Modifiers)); + RunOrDefer(() => BrowserHost!.SendMouseWheelEvent(cefMouseEvent, deltaX, deltaY)); + } + + public void SendMouseClickEvent(IHtmlClient.MouseEvent mouseEvent, IHtmlClient.MouseButton mouseButton, bool mouseUp, int clickCount) { + CefMouseEvent cefMouseEvent = new(mouseEvent.X, mouseEvent.Y, GetModifiers(mouseEvent.Modifiers)); + + CefMouseButtonType buttonType = mouseButton switch { + IHtmlClient.MouseButton.Middle => CefMouseButtonType.Middle, + IHtmlClient.MouseButton.Right => CefMouseButtonType.Right, + _ => CefMouseButtonType.Left, + }; + + RunOrDefer(() => BrowserHost!.SendMouseClickEvent(cefMouseEvent, buttonType, mouseUp, clickCount)); + } + + public void LoadUrl(string url) { + if (CreateBrowserWithUrl(url)) + return; + + RunOrDefer(() => Browser!.GetMainFrame()?.LoadUrl(url)); + } + + public void SetHtml(string html) => LoadUrl($"asset://html/?{Convert.ToBase64String(Encoding.UTF8.GetBytes(html))}"); + + public void Refresh() => RunOrDefer(() => Browser!.Reload()); + + public void Stop() => RunOrDefer(() => Browser!.StopLoad()); + + public void GoBack() => RunOrDefer(() => Browser!.GoBack()); + + public void GoForward() => RunOrDefer(() => Browser!.GoForward()); + + public void RunJavaScript(string code) { + RunOrDefer(() => { + CefFrame? mainFrame = Browser!.GetMainFrame(); + if (mainFrame == null) + return; + + string url = mainFrame.Url ?? ""; + + int slash = url.Length >= 9 ? url.IndexOf('/', 8) : -1; + string host = slash == -1 ? url : url[..slash]; + + foreach (string blocked in BlockedJavaScriptHosts) + if (host.Contains(blocked, StringComparison.Ordinal)) + return; + + mainFrame.ExecuteJavaScript(code, "Lua File", 1); + }); + } + + public void RegisterJavaScriptFunction(string objName, string funcName) { + if (Closing || RegisteredFunctions.Contains((objName, funcName))) + return; + + RegisteredFunctions.Add((objName, funcName)); + + if (Browser == null) + return; + + foreach (string frameId in Browser.GetFrameIdentifiers()) { + CefFrame? frame = Browser.GetFrameByIdentifier(frameId); + if (frame != null && frame.IsValid) + SendRegisterFunction(frame, objName, funcName); + } + } + + static void SendRegisterFunction(CefFrame frame, string objName, string funcName) { + using CefProcessMessage message = CefProcessMessage.Create("RegisterFunction"); + message.Arguments!.SetString(0, objName); + message.Arguments!.SetString(1, funcName); + frame.SendProcessMessage(CefProcessId.Renderer, message); + } + + public void SetOpenLinksExternally(bool openLinksExternally) => OpenLinksExternally = openLinksExternally; + + public void ExecuteCallback(int callbackId, string frameId, JSValue paramsArray) { + if (Browser == null) + return; + + CefFrame? frame = Browser.GetFrameByIdentifier(frameId); + if (frame == null || !frame.IsValid) + return; + + using CefProcessMessage message = CefProcessMessage.Create("ExecuteCallback"); + using CefListValue args = CefListValue.Create(); + + ReadOnlySpan values = paramsArray.GetJSType() == JSValue.Type.Array ? paramsArray.GetArray() : default; + for (int i = 0; i < values.Length; i++) { + if (!JSValueToCefList(args, i, values[i])) { + ForgetCallback(frame, callbackId); + return; + } + } + + message.Arguments!.SetInt(0, callbackId); + message.Arguments!.SetList(1, args); + frame.SendProcessMessage(CefProcessId.Renderer, message); + } + + static void ForgetCallback(CefFrame frame, int callbackId) { + using CefProcessMessage message = CefProcessMessage.Create("ForgetCallback"); + message.Arguments!.SetInt(0, callbackId); + frame.SendProcessMessage(CefProcessId.Renderer, message); + } + + protected override bool OnProcessMessageReceived(CefBrowser browser, CefFrame frame, CefProcessId sourceProcess, CefProcessMessage message) { + if (sourceProcess != CefProcessId.Renderer) + return false; + + switch (message.Name) { + case "SyncFunctions": + foreach ((string obj, string func) in RegisteredFunctions) + SendRegisterFunction(frame, obj, func); + return true; + + case "ExecuteFunction": + if (message.Arguments is { } arguments) + OnExecuteFunction(frame, arguments); + return true; + } + + return false; + } + + void OnExecuteFunction(CefFrame frame, ICefListValue args) { + if (args.Count != 4 || args.GetValueType(0) != CefValueType.String || args.GetValueType(1) != CefValueType.String + || args.GetValueType(2) != CefValueType.Int || args.GetValueType(3) != CefValueType.List) + return; + + string objName = args.GetString(0) ?? ""; + string funcName = args.GetString(1) ?? ""; + if (!RegisteredFunctions.Contains((objName, funcName))) + return; + + int callbackId = args.GetInt(2); + if (callbackId < -1 || callbackId >= 16384) + return; + + using ICefListValue list = args.GetList(3); + if (!CefListToJSValues(out JSValue[] values, list)) { + if (callbackId != -1) + ForgetCallback(frame, callbackId); + return; + } + + QueueMessage(new MessageQueue.Message { + Type = MessageQueue.Type.OnJavaScriptCall, + String1 = objName, + String2 = funcName, + Integer = callbackId, + FrameId = frame.Identifier, + JSParams = JSArray.Create(values) + }); + } + + void OnAfterCreated(CefBrowser browser) { + Browser = browser; + BrowserHost = browser.GetHost(); + + if (Closing) { + BrowserHost.CloseBrowser(true); + return; + } + + Action[] pending = [.. PendingTasks]; + PendingTasks.Clear(); + foreach (Action task in pending) + task(); + } + + void OnBeforeClose() { + Browser = null; + BrowserHost = null; + } + + void QueueChildView(string sourceUrl, string targetUrl, bool isPopup) { + QueueMessage(new MessageQueue.Message { + Type = MessageQueue.Type.OnCreateChildView, + String1 = sourceUrl, + String2 = targetUrl, + Integer = isPopup ? 1 : 0 + }); + } + + void OnMainFrameLoaded(CefFrame frame) { + QueueMessage(new MessageQueue.Message { + Type = MessageQueue.Type.OnLoadEnd, + String1 = frame.Url + }); + + frame.ExecuteJavaScript("WebSocket = undefined;", "haha", 0); + } + + void OnPopupShow(bool show) { + if (BrowserHost == null || show) + return; + + PopupX = 0; + PopupY = 0; + PopupWide = 0; + PopupTall = 0; + PopupData = null; + + BrowserHost.Invalidate(CefPaintElementType.View); + } + + void OnPopupSize(CefRectangle rect) { + PopupX = rect.X; + PopupY = rect.Y; + } + + void OnPaint(CefPaintElementType type, nint buffer, int width, int height) { + if (width <= 0 || height <= 0) + return; + + switch (type) { + case CefPaintElementType.Popup: + PopupData = new byte[width * height * 4]; + System.Runtime.InteropServices.Marshal.Copy(buffer, PopupData, 0, PopupData.Length); + PopupWide = width; + PopupTall = height; + + BrowserHost?.Invalidate(CefPaintElementType.View); + return; + + case CefPaintElementType.View: + ImageData.Lock(); + ImageData.SetData(buffer, width, height); + + if (PopupWide > 0 && PopupTall > 0 && + PopupX < width && PopupY < height && + (PopupX + PopupWide) > 0 && (PopupY + PopupTall) > 0) { + ImageData.CopyImage(PopupData, PopupX, PopupY, PopupWide, PopupTall); + } + + ImageData.SetDirty(true); + ImageData.Unlock(); + return; + } + } + + bool ShouldBlockNavigation(string url) { + if (!TryParseScheme(url, out string scheme)) + return true; + + if (url == "chrome://credits/") + return false; + + if (scheme != "http" && scheme != "https" && scheme != "asset") + return true; + + if (OpenLinksExternally) { + try { + Process.Start(new ProcessStartInfo(url) { UseShellExecute = true }); + } + catch (Exception) { } + return true; + } + + return false; + } + + protected override CefLifeSpanHandler GetLifeSpanHandler() => LifeSpan; + protected override CefLoadHandler GetLoadHandler() => Load; + protected override CefDisplayHandler GetDisplayHandler() => Display; + protected override CefRequestHandler GetRequestHandler() => Request; + protected override CefContextMenuHandler GetContextMenuHandler() => ContextMenu; + protected override CefDialogHandler GetDialogHandler() => Dialog; + protected override CefJSDialogHandler GetJSDialogHandler() => JSDialog; + protected override CefRenderHandler GetRenderHandler() => Render; + + sealed class LifeSpanHandler(CefBrowserClient owner) : CefLifeSpanHandler + { + protected override bool OnBeforePopup(CefBrowser browser, CefFrame frame, int popupId, string targetUrl, string targetFrameName, CefWindowOpenDisposition targetDisposition, bool userGesture, CefPopupFeatures popupFeatures, CefWindowInfo windowInfo, ref CefClient client, CefBrowserSettings settings, ref CefDictionaryValue extraInfo, ref bool noJavascriptAccess) { + owner.QueueChildView(frame.Url, targetUrl, targetDisposition == CefWindowOpenDisposition.NewPopup); + return true; + } + + protected override void OnAfterCreated(CefBrowser browser) => owner.OnAfterCreated(browser); + + protected override bool DoClose(CefBrowser browser) => false; + + protected override void OnBeforeClose(CefBrowser browser) => owner.OnBeforeClose(); + } + + sealed class LoadHandler(CefBrowserClient owner) : CefLoadHandler + { + protected override void OnLoadStart(CefBrowser browser, CefFrame frame, CefTransitionType transitionType) { + if (!frame.IsMain) + return; + + owner.QueueMessage(new MessageQueue.Message { + Type = MessageQueue.Type.OnLoadStart, + String1 = frame.Url + }); + } + + protected override void OnLoadEnd(CefBrowser browser, CefFrame frame, int httpStatusCode) { + if (frame.IsMain) + owner.OnMainFrameLoaded(frame); + } + + protected override void OnLoadError(CefBrowser browser, CefFrame frame, CefErrorCode errorCode, string errorText, string failedUrl) { + if (frame.IsMain) + owner.OnMainFrameLoaded(frame); + } + } + + sealed class DisplayHandler(CefBrowserClient owner) : CefDisplayHandler + { + protected override void OnAddressChange(CefBrowser browser, CefFrame frame, string url) { + if (!frame.IsMain) + return; + + owner.QueueMessage(new MessageQueue.Message { + Type = MessageQueue.Type.OnAddressChange, + String1 = url + }); + } + + protected override void OnTitleChange(CefBrowser browser, string title) { + owner.QueueMessage(new MessageQueue.Message { + Type = MessageQueue.Type.OnTitleChange, + String1 = title + }); + } + + protected override bool OnConsoleMessage(CefBrowser browser, CefLogSeverity level, string message, string source, int line) { + owner.QueueMessage(new MessageQueue.Message { + Type = MessageQueue.Type.OnConsoleMessage, + String1 = message, + String2 = source, + Integer = line, + Integer2 = (int)level + }); + return false; + } + + protected override bool OnCursorChange(CefBrowser browser, nint cursorHandle, CefCursorType type, CefCursorInfo customCursorInfo) { + IHtmlClientListener.CursorType cursor = type switch { + CefCursorType.Pointer => IHtmlClientListener.CursorType.Default, + CefCursorType.Cross => IHtmlClientListener.CursorType.Crosshair, + CefCursorType.Hand => IHtmlClientListener.CursorType.Hand, + CefCursorType.IBeam => IHtmlClientListener.CursorType.IBeam, + CefCursorType.Wait => IHtmlClientListener.CursorType.Hourglass, + CefCursorType.Move => IHtmlClientListener.CursorType.SizeAll, + CefCursorType.EastResize or CefCursorType.WestResize or CefCursorType.EastWestResize or CefCursorType.ColumnResize => IHtmlClientListener.CursorType.SizeEW, + CefCursorType.NorthResize or CefCursorType.SouthResize or CefCursorType.NorthSouthResize or CefCursorType.RowResize => IHtmlClientListener.CursorType.SizeNS, + CefCursorType.NorthEastResize or CefCursorType.SouthWestResize or CefCursorType.NorthEastSouthWestResize => IHtmlClientListener.CursorType.SizeNESW, + CefCursorType.NorthWestResize or CefCursorType.SouthEastResize or CefCursorType.NorthWestSouthEastResize => IHtmlClientListener.CursorType.SizeNWSE, + CefCursorType.NotAllowed => IHtmlClientListener.CursorType.No, + CefCursorType.None => IHtmlClientListener.CursorType.None, + CefCursorType.MiddlePanning or CefCursorType.EastPanning or CefCursorType.NorthPanning or CefCursorType.NorthEastPanning or CefCursorType.NorthWestPanning + or CefCursorType.SouthPanning or CefCursorType.SouthEastPanning or CefCursorType.SouthWestPanning or CefCursorType.WestPanning => IHtmlClientListener.CursorType.SizeAll, + _ => IHtmlClientListener.CursorType.Default + }; + + owner.QueueMessage(new MessageQueue.Message { + Type = MessageQueue.Type.OnCursorChange, + Integer = (int)cursor + }); + return true; + } + } + + sealed class RequestHandler(CefBrowserClient owner) : CefRequestHandler + { + readonly ResourceRequestHandler ResourceRequest = new(); + + protected override bool OnBeforeBrowse(CefBrowser browser, CefFrame frame, CefRequest request, bool userGesture, bool isRedirect) => owner.ShouldBlockNavigation(request.Url); + + protected override bool OnOpenUrlFromTab(CefBrowser browser, CefFrame frame, string targetUrl, CefWindowOpenDisposition targetDisposition, bool userGesture) { + if (targetDisposition == CefWindowOpenDisposition.NewPopup || targetDisposition == CefWindowOpenDisposition.NewForegroundTab || targetDisposition == CefWindowOpenDisposition.NewBackgroundTab) { + owner.QueueChildView(frame.Url, targetUrl, targetDisposition == CefWindowOpenDisposition.NewPopup); + return true; + } + + return false; + } + + protected override CefResourceRequestHandler GetResourceRequestHandler(CefBrowser browser, CefFrame frame, CefRequest request, bool isNavigation, bool isDownload, string requestInitiator, ref bool disableDefaultHandling) => ResourceRequest; + } + + sealed class ResourceRequestHandler : CefResourceRequestHandler + { + protected override CefCookieAccessFilter GetCookieAccessFilter(CefBrowser browser, CefFrame frame, CefRequest request) => null!; + + protected override CefReturnValue OnBeforeResourceLoad(CefBrowser browser, CefFrame frame, CefRequest request, CefCallback callback) { + string sourceUrl = request.Url; + + if (!TryParseScheme(sourceUrl, out string scheme)) + return CefReturnValue.Cancel; + + if (sourceUrl == "chrome://credits/" || + sourceUrl == "chrome://resources/js/cr.js" || + sourceUrl == "chrome://credits/credits.js") { + return CefReturnValue.Continue; + } + + if (scheme != "http" && scheme != "https" && scheme != "asset") + return CefReturnValue.Cancel; + + return CefReturnValue.Continue; + } + } + + sealed class ContextMenuHandler : CefContextMenuHandler + { + protected override void OnBeforeContextMenu(CefBrowser browser, CefFrame frame, CefContextMenuParams state, CefMenuModel model) => model.Clear(); + } + + sealed class DialogHandler : CefDialogHandler + { + protected override bool OnFileDialog(CefBrowser browser, CefFileDialogMode mode, string title, string defaultFilePath, string[] acceptFilters, string[] acceptExtensions, string[] acceptDescriptions, CefFileDialogCallback callback) { + callback.Cancel(); + return true; + } + } + + sealed class JSDialogHandler : CefJSDialogHandler + { + protected override bool OnJSDialog(CefBrowser browser, string originUrl, CefJSDialogType dialogType, string message_text, string default_prompt_text, CefJSDialogCallback callback, out bool suppress_message) { + suppress_message = true; + return false; + } + + protected override bool OnBeforeUnloadDialog(CefBrowser browser, string messageText, bool isReload, CefJSDialogCallback callback) { + callback.Continue(true, ""); + return true; + } + + protected override void OnResetDialogState(CefBrowser browser) { } + + protected override void OnDialogClosed(CefBrowser browser) { } + } + + sealed class RenderHandler(CefBrowserClient owner) : CefRenderHandler + { + protected override CefAccessibilityHandler GetAccessibilityHandler() => null!; + + protected override void GetViewRect(CefBrowser browser, out CefRectangle rect) => rect = new CefRectangle(0, 0, Math.Max(owner.Wide, 1), Math.Max(owner.Tall, 1)); + + protected override bool GetScreenInfo(CefBrowser browser, CefScreenInfo screenInfo) => false; + + protected override void OnPopupShow(CefBrowser browser, bool show) => owner.OnPopupShow(show); + + protected override void OnPopupSize(CefBrowser browser, CefRectangle rect) => owner.OnPopupSize(rect); + + protected override void OnPaint(CefBrowser browser, CefPaintElementType type, CefRectangle[] dirtyRects, nint buffer, int width, int height) => owner.OnPaint(type, buffer, width, height); + + protected override void OnAcceleratedPaint(CefBrowser browser, CefPaintElementType type, CefRectangle[] dirtyRects, CefAcceleratedPaintInfo info) { } + + protected override void OnScrollOffsetChanged(CefBrowser browser, double x, double y) { } + + protected override void OnImeCompositionRangeChanged(CefBrowser browser, CefRange selectedRange, CefRectangle[] characterBounds) { } + } +} diff --git a/HTML.CEF/CefHtmlClient.cs b/HTML.CEF/CefHtmlClient.cs new file mode 100644 index 000000000..411fca19d --- /dev/null +++ b/HTML.CEF/CefHtmlClient.cs @@ -0,0 +1,150 @@ +using Source.Common.GarrysMod; + +using Xilium.CefGlue; + +namespace HTML.CEF; + +sealed class ActionTask(Action action) : CefTask +{ + protected override void Execute() => action(); +} + +public class CefHtmlClient : IHtmlClient +{ + readonly CefBrowserClient Browser; + readonly IHtmlClientListener Listener; + bool Closed; + + public CefHtmlClient(CefBrowserClient browser, IHtmlClientListener listener) { + Browser = browser; + Listener = listener; + CefSystem.g_CefSystem.OnClientOpen(this); + } + + static void PostTask(Action task) => CefRuntime.PostTask(CefThreadId.UI, new ActionTask(task)); + + public void Update() { + MessageQueue messageQueue = Browser.GetMessageQueue(); + + messageQueue.Lock(); + try { + while (!Closed && !messageQueue.Empty()) { + MessageQueue.Message msg = messageQueue.Pop(); + + switch (msg.Type) { + case MessageQueue.Type.OnAddressChange: + Listener.OnAddressChange(msg.String1); + break; + case MessageQueue.Type.OnConsoleMessage: + Listener.OnConsoleMessage(msg.String1, msg.String2, msg.Integer, msg.Integer2); + break; + case MessageQueue.Type.OnTitleChange: + Listener.OnTitleChange(msg.String1); + break; + case MessageQueue.Type.OnCursorChange: + Listener.OnCursorChange((IHtmlClientListener.CursorType)msg.Integer); + break; + case MessageQueue.Type.OnLoadStart: + Listener.OnLoadStart(msg.String1); + break; + case MessageQueue.Type.OnLoadEnd: + Listener.OnDocumentReady(msg.String1); + Listener.OnLoadEnd(msg.String1); + break; + case MessageQueue.Type.OnCreateChildView: + Listener.OnCreateChildView(msg.String1, msg.String2, msg.Integer != 0); + break; + case MessageQueue.Type.OnJavaScriptCall: + HandleJavaScriptCall(msg.String1, msg.String2, msg.JSParams, msg.Integer, msg.FrameId); + break; + } + } + } + finally { + messageQueue.Unlock(); + } + } + + void HandleJavaScriptCall(string objName, string funcName, in JSValue paramArray, int callbackId, string frameId) { + JSValue retArray = Listener.OnJavaScriptCall(objName, funcName, paramArray); + + if (callbackId == -1) + return; + + PostTask(() => Browser.ExecuteCallback(callbackId, frameId, retArray)); + } + + public void Close() { + PostTask(Browser.Close); + + CefSystem.g_CefSystem.OnClientClose(this); + Closed = true; + } + + public void SetSize(int wide, int tall) => PostTask(() => Browser.SetSize(wide, tall)); + + public void SetFocused(bool hasFocus) => PostTask(() => Browser.SetFocused(hasFocus)); + + public void SendKeyEvent(IHtmlClient.KeyEvent keyEvent) => PostTask(() => Browser.SendKeyEvent(keyEvent)); + + public void SendMouseMoveEvent(IHtmlClient.MouseEvent mouseEvent, bool mouseLeave) => PostTask(() => Browser.SendMouseMoveEvent(mouseEvent, mouseLeave)); + + public void SendMouseWheelEvent(IHtmlClient.MouseEvent mouseEvent, int deltaX, int deltaY) => PostTask(() => Browser.SendMouseWheelEvent(mouseEvent, deltaX, deltaY)); + + public void SendMouseClickEvent(IHtmlClient.MouseEvent mouseEvent, IHtmlClient.MouseButton mouseButton, bool mouseUp, int clickCount) => PostTask(() => Browser.SendMouseClickEvent(mouseEvent, mouseButton, mouseUp, clickCount)); + + public void LoadUrl(ReadOnlySpan url) { + string str = new(url); + PostTask(() => Browser.LoadUrl(str)); + } + + public void SetHtml(ReadOnlySpan html) { + string str = new(html); + PostTask(() => Browser.SetHtml(str)); + } + + public void Refresh() => PostTask(Browser.Refresh); + + public void Stop() => PostTask(Browser.Stop); + + public void GoBack() => PostTask(Browser.GoBack); + + public void GoForward() => PostTask(Browser.GoForward); + + public void RunJavaScript(ReadOnlySpan code) { + string str = new(code); + PostTask(() => Browser.RunJavaScript(str)); + } + + public void RegisterJavaScriptFunction(ReadOnlySpan objName, ReadOnlySpan funcName) { + string obj = new(objName); + string func = new(funcName); + PostTask(() => Browser.RegisterJavaScriptFunction(obj, func)); + } + + public void SetOpenLinksExternally(bool openLinksExternally) => PostTask(() => Browser.SetOpenLinksExternally(openLinksExternally)); + + public bool LockImageData() { + ImageData imageData = Browser.GetImageData(); + + imageData.Lock(); + + if (!imageData.IsDirty()) { + imageData.Unlock(); + return false; + } + + return true; + } + + public void UnlockImageData() { + ImageData imageData = Browser.GetImageData(); + imageData.SetDirty(false); + imageData.Unlock(); + } + + public ReadOnlySpan GetImageData(out int imageWide, out int imageTall) { + ImageData imageData = Browser.GetImageData(); + return imageData.GetData(out imageWide, out imageTall); + } +} diff --git a/HTML.CEF/CefSystem.cs b/HTML.CEF/CefSystem.cs new file mode 100644 index 000000000..5bd372884 --- /dev/null +++ b/HTML.CEF/CefSystem.cs @@ -0,0 +1,184 @@ +using Source.Common.GarrysMod; + +using System.Globalization; + +using Xilium.CefGlue; + +namespace HTML.CEF; + +public class CefSystem : IHtmlSystem +{ + public static readonly CefSystem g_CefSystem = new(); + public static readonly IHtmlSystem g_pHtmlSystem = g_CefSystem; + + const string SandboxInfoProperty = "SN_CEF_SANDBOX_INFO"; + const string NoSandboxParm = "-nochromiumsandbox"; + + readonly IHtmlSystem Fallback = HTML.Stub.StubSystem.g_pHtmlSystem; + bool Initialized; + + readonly List ActiveClients = []; + + readonly Lock RequestsLock = new(); + List Requests = []; + + static bool HasParm(string parm) { + foreach (string arg in Environment.GetCommandLineArgs()) + if (string.Equals(arg, parm, StringComparison.OrdinalIgnoreCase)) + return true; + return false; + } + + static nint GetSandboxInfo() { + if (AppContext.GetData(SandboxInfoProperty) is not string hex) + return 0; + return long.TryParse(hex, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out long value) ? (nint)value : 0; + } + + public bool Init(ReadOnlySpan pBaseDir, IHtmlResourceHandler resourceHandler) { + ResourceHandler.g_pHtmlResourceHandler = resourceHandler; + + string baseDir = new(pBaseDir); + string chromiumDir = AppContext.BaseDirectory; + + nint sandboxInfo = 0; + bool noSandbox = false; + if (OperatingSystem.IsWindows()) { + sandboxInfo = GetSandboxInfo(); + if (sandboxInfo == 0) { + if (!HasParm(NoSandboxParm)) { + resourceHandler.Message("Chromium: not started through Source.Launcher.exe, so there is no sandbox. Refusing to start Chromium unsandboxed (use -nochromiumsandbox to override for debugging).\n"); + return false; + } + + resourceHandler.Message("Chromium: WARNING - running WITHOUT the Chromium sandbox (-nochromiumsandbox). Web content runs with full user privileges!\n"); + noSandbox = true; + } + } + + try { + if (OperatingSystem.IsWindows()) + CefRuntime.Load(chromiumDir); + else + CefRuntime.Load(); + } + catch (Exception e) { + resourceHandler.Message($"Chromium failed to load: {e.Message}\n"); + return false; + } + + CefSettings settings = new() { + WindowlessRenderingEnabled = true, + NoSandbox = noSandbox, + MultiThreadedMessageLoop = OperatingSystem.IsWindows(), + ExternalMessagePump = false, + CommandLineArgsDisabled = true, + RemoteDebuggingPort = 0, + LogSeverity = CefLogSeverity.Default, + LogFile = Path.Combine(baseDir, "chromium.log"), + RootCachePath = Path.Combine(baseDir, "cache", "chromium"), + UserAgent = "Mozilla/5.0 (Windows NT; Valve Source Client) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36 GMod/13", + ResourcesDirPath = chromiumDir, + LocalesDirPath = Path.Combine(chromiumDir, "locales"), + }; + + if (!OperatingSystem.IsWindows()) + settings.BrowserSubprocessPath = Path.Combine(chromiumDir, "Source.Launcher.CEF"); + else if (noSandbox) + settings.BrowserSubprocessPath = Path.Combine(chromiumDir, "Source.Launcher.exe"); + + try { + CefRuntime.Initialize(new CefMainArgs([]), settings, new CefApplication(), sandboxInfo); + } + catch (Exception e) { + resourceHandler.Message($"Chromium failed to initialize: {e.Message}\n"); + return false; + } + + RegisterScheme("garrysmod", new ResourceHandlerFactory()); + RegisterScheme("mapimage", new ResourceHandlerFactory()); + RegisterScheme("html", new HtmlResourceHandlerFactory()); + + resourceHandler.Message($"Chromium {CefRuntime.ChromeVersion} initialized ({(noSandbox ? "UNSANDBOXED" : "sandboxed")}).\n"); + Initialized = true; + return true; + } + + static void RegisterScheme(string host, CefSchemeHandlerFactory factory) { + CefRuntime.RegisterSchemeHandlerFactory("asset", host, factory); + CefRuntime.AddCrossOriginWhitelistEntry($"asset://{host}", "http", "", true); + CefRuntime.AddCrossOriginWhitelistEntry($"asset://{host}", "https", "", true); + CefRuntime.AddCrossOriginWhitelistEntry($"asset://{host}", "asset", "", true); + } + + public void Shutdown() { + if (!Initialized) { + Fallback.Shutdown(); + return; + } + + CefRuntime.Shutdown(); + Initialized = false; + } + + public IHtmlClient CreateClient(IHtmlClientListener listener) { + if (!Initialized) + return Fallback.CreateClient(listener); + + CefBrowserSettings browserSettings = new() { + DefaultEncoding = "UTF-8", + WindowlessFrameRate = 60, + JavaScriptAccessClipboard = CefState.Disabled, + JavaScriptCloseWindows = CefState.Disabled, + WebGL = CefState.Disabled + }; + + CefBrowserClient browser = new(); + CefRuntime.PostTask(CefThreadId.UI, new ActionTask(() => browser.CreateBrowser(browserSettings))); + + return new CefHtmlClient(browser, listener); + } + + public void Update() { + if (!Initialized) { + Fallback.Update(); + return; + } + + if (!OperatingSystem.IsWindows()) + CefRuntime.DoMessageLoopWork(); + + List requests; + lock (RequestsLock) { + requests = Requests; + Requests = []; + } + + foreach (ResourceHandler request in requests) + request.Handle(); + + foreach (CefHtmlClient client in ActiveClients.ToArray()) + client.Update(); + } + + public void OnClientOpen(CefHtmlClient client) => ActiveClients.Add(client); + public void OnClientClose(CefHtmlClient client) => ActiveClients.Remove(client); + + public void QueueRequest(ResourceHandler resourceHandler) { + lock (RequestsLock) + Requests.Add(resourceHandler); + } + + public JSValue CreateArray(ReadOnlySpan values) => JSArray.Create(values.ToArray()); + + public JSValue CreateString(ReadOnlySpan value) => JSString.Create(new string(value)); + + public JSValue CreateHashMap(ReadOnlySpan keys, ReadOnlySpan values) { + Dictionary container = new(keys.Length); + + for (int i = 0; i < keys.Length; i++) + container[keys[i]] = values[i]; + + return JSHashMap.Create(container); + } +} diff --git a/HTML.CEF/HTML.CEF.csproj b/HTML.CEF/HTML.CEF.csproj new file mode 100644 index 000000000..e8c887cbd --- /dev/null +++ b/HTML.CEF/HTML.CEF.csproj @@ -0,0 +1,20 @@ + + + + net10.0 + enable + enable + Debug;Release;Debug (Dedicated);Release (Dedicated) + true + + + + + + + + + + + + diff --git a/HTML.CEF/HtmlResourceHandler.cs b/HTML.CEF/HtmlResourceHandler.cs new file mode 100644 index 000000000..d8ca1bfd1 --- /dev/null +++ b/HTML.CEF/HtmlResourceHandler.cs @@ -0,0 +1,61 @@ +using System.Collections.Specialized; + +using Xilium.CefGlue; + +namespace HTML.CEF; + +public sealed class HtmlResourceHandlerFactory : CefSchemeHandlerFactory +{ + protected override CefResourceHandler Create(CefBrowser browser, CefFrame frame, string schemeName, CefRequest request) => new HtmlResourceHandler(); +} + +public sealed class HtmlResourceHandler : CefResourceHandler +{ + byte[] Html = []; + int Current; + + protected override bool Open(CefRequest request, out bool handleRequest, CefCallback callback) { + handleRequest = true; + Current = 0; + + if (!Uri.TryCreate(request.Url, UriKind.Absolute, out Uri? url)) + return false; + + string encodedHtml = url.Query.StartsWith('?') ? url.Query[1..] : url.Query; + byte[] data = new byte[encodedHtml.Length]; + if (Convert.TryFromBase64String(encodedHtml, data, out int written)) + Html = data[..written]; + + return true; + } + + protected override void GetResponseHeaders(CefResponse response, out long responseLength, out string redirectUrl) { + redirectUrl = null!; + + response.Status = 200; + response.SetHeaderMap(new NameValueCollection { { "X-XSS-Protection", "0" } }); + response.MimeType = "text/html"; + responseLength = Html.Length; + } + + protected override bool Skip(long bytesToSkip, out long bytesSkipped, CefResourceSkipCallback callback) { + bytesSkipped = -2; + return false; + } + + protected override bool Read(Stream response, int bytesToRead, out int bytesRead, CefResourceReadCallback callback) { + bytesRead = 0; + if (Html.Length <= 0) + return false; + + int count = Math.Max(Math.Min(bytesToRead, Html.Length - Current), 0); + + response.Write(Html, Current, count); + bytesRead = count; + Current += count; + + return count > 0; + } + + protected override void Cancel() { } +} diff --git a/HTML.CEF/ImageData.cs b/HTML.CEF/ImageData.cs new file mode 100644 index 000000000..9ff80d332 --- /dev/null +++ b/HTML.CEF/ImageData.cs @@ -0,0 +1,59 @@ +using System.Runtime.InteropServices; + +namespace HTML.CEF; + +public class ImageData +{ + readonly Lock Mutex = new(); + bool Dirty; + int Wide; + int Tall; + byte[]? Data; + + public void Lock() => Mutex.Enter(); + public void Unlock() => Mutex.Exit(); + + public void SetData(nint data, int wide, int tall) { + int bufSize = wide * tall * 4; + + if (Wide != wide || Tall != tall || Data == null) + Data = new byte[bufSize]; + + Marshal.Copy(data, Data, 0, bufSize); + Wide = wide; + Tall = tall; + Dirty = true; + } + + public void CopyImage(byte[]? data, int x, int y, int w, int h) { + if (w < 0 || h < 0 || data == null || Data == null) + return; + + int dstX = Math.Max(0, x); + int dstY = Math.Max(0, y); + int srcX = Math.Max(0, -x); + int srcY = Math.Max(0, -y); + + int copyW = Math.Min(w - srcX, Wide - dstX); + int copyH = Math.Min(h - srcY, Tall - dstY); + + if (copyW > 0 && copyH > 0) { + for (int row = 0; row < copyH; ++row) { + int dstOffset = ((dstY + row) * Wide + dstX) * 4; + int srcOffset = ((srcY + row) * w + srcX) * 4; + Buffer.BlockCopy(data, srcOffset, Data, dstOffset, copyW * 4); + } + + Dirty = true; + } + } + + public ReadOnlySpan GetData(out int wide, out int tall) { + wide = Wide; + tall = Tall; + return Data; + } + + public bool IsDirty() => Dirty; + public void SetDirty(bool dirty) => Dirty = dirty; +} diff --git a/HTML.CEF/JSObjects.cs b/HTML.CEF/JSObjects.cs new file mode 100644 index 000000000..2a4797b43 --- /dev/null +++ b/HTML.CEF/JSObjects.cs @@ -0,0 +1,57 @@ +using Source.Common.GarrysMod; + +namespace HTML.CEF; + +public sealed class JSArray : JSValue.IArray +{ + readonly JSValue[] Data; + + JSArray(JSValue[] data) => Data = data; + + public ReadOnlySpan GetData() => Data; + public JSValue[] GetInternalData() => Data; + + public static JSValue Create(JSValue[] data) => new(new JSArray(data)); +} + +public sealed class JSString : JSValue.IString +{ + readonly string Data; + + JSString(string data) => Data = data; + + public ReadOnlySpan GetData() => Data; + public string GetInternalData() => Data; + + public static JSValue Create(string data) => new(new JSString(data)); +} + +public sealed class JSHashMap : JSValue.IHashMap +{ + readonly Dictionary Data; + Dictionary.Enumerator Iterator; + + JSHashMap(Dictionary data) => Data = data; + + public bool Begin(out ReadOnlySpan key, out JSValue value) { + Iterator = Data.GetEnumerator(); + return Next(out key, out value); + } + + public bool Next(out ReadOnlySpan key, out JSValue value) { + if (!Iterator.MoveNext()) { + key = default; + value = default; + return false; + } + + key = Iterator.Current.Key; + value = Iterator.Current.Value; + return true; + } + + public int Size() => Data.Count; + public Dictionary GetInternalData() => Data; + + public static JSValue Create(Dictionary data) => new(new JSHashMap(data)); +} diff --git a/HTML.CEF/MessageQueue.cs b/HTML.CEF/MessageQueue.cs new file mode 100644 index 000000000..0e16b8ad9 --- /dev/null +++ b/HTML.CEF/MessageQueue.cs @@ -0,0 +1,38 @@ +using Source.Common.GarrysMod; + +namespace HTML.CEF; + +public class MessageQueue +{ + public enum Type + { + OnAddressChange, + OnConsoleMessage, + OnTitleChange, + OnCursorChange, + OnLoadStart, + OnLoadEnd, + OnCreateChildView, + OnJavaScriptCall + } + + public struct Message + { + public Type Type; + public int Integer; + public int Integer2; + public string FrameId; + public string String1; + public string String2; + public JSValue JSParams; + } + + readonly Lock Mutex = new(); + readonly Queue Messages = new(); + + public void Lock() => Mutex.Enter(); + public void Unlock() => Mutex.Exit(); + public void Push(in Message message) => Messages.Enqueue(message); + public bool Empty() => Messages.Count == 0; + public Message Pop() => Messages.Dequeue(); +} diff --git a/HTML.CEF/ResourceHandler.cs b/HTML.CEF/ResourceHandler.cs new file mode 100644 index 000000000..1565f42a4 --- /dev/null +++ b/HTML.CEF/ResourceHandler.cs @@ -0,0 +1,138 @@ +using Source.Common.GarrysMod; + +using System.Text; + +using Xilium.CefGlue; + +namespace HTML.CEF; + +public sealed class ResourceHandlerFactory : CefSchemeHandlerFactory +{ + protected override CefResourceHandler Create(CefBrowser browser, CefFrame frame, string schemeName, CefRequest request) => new ResourceHandler(); +} + +public sealed class ResourceHandler : CefResourceHandler +{ + public static IHtmlResourceHandler? g_pHtmlResourceHandler; + + string Host = ""; + string Path = ""; + CefCallback? ResponseCallback; + + byte[]? Buffer; + int BufferPtr; + + public void Handle() { + HtmlResource? resource = g_pHtmlResourceHandler!.OpenResource(Host, Path); + + if (resource != null) { + long size = g_pHtmlResourceHandler.GetLength(resource); + Buffer = new byte[size]; + BufferPtr = 0; + + g_pHtmlResourceHandler.ReadData(resource, Buffer); + g_pHtmlResourceHandler.CloseResource(resource); + } + + CefCallback? callback = ResponseCallback; + ResponseCallback = null; + callback?.Continue(); + } + + protected override bool Open(CefRequest request, out bool handleRequest, CefCallback callback) { + handleRequest = true; + + if (!Uri.TryCreate(request.Url, UriKind.Absolute, out Uri? url)) + return false; + + Host = url.Host; + Path = URIDecode(url.AbsolutePath); + + handleRequest = false; + ResponseCallback = callback; + CefSystem.g_CefSystem.QueueRequest(this); + + return true; + } + + static string GetFileExtension(string path) { + int i = path.LastIndexOf('.'); + if (i == -1) + return ""; + return path[(i + 1)..]; + } + + protected override void GetResponseHeaders(CefResponse response, out long responseLength, out string redirectUrl) { + redirectUrl = null!; + + if (Buffer == null) { + responseLength = 0; + response.Error = CefErrorCode.FileNotFound; + return; + } + + string mimeType = "text/html"; + + string ext = GetFileExtension(Path); + if (ext == "png" || Host == "mapimage") mimeType = "image/png"; + else if (ext == "jpg") mimeType = "image/jpg"; + else if (ext == "jpeg") mimeType = "image/jpg"; + else if (ext == "css") mimeType = "text/css"; + else if (ext == "js") mimeType = "text/javascript"; + else if (ext == "svg") mimeType = "image/svg+xml"; + else if (ext == "gif") mimeType = "image/gif"; + else if (ext == "webm") mimeType = "video/webm"; + else if (ext == "mp4") mimeType = "video/mp4"; + + response.Status = 200; + response.MimeType = mimeType; + responseLength = Buffer.Length; + } + + protected override bool Skip(long bytesToSkip, out long bytesSkipped, CefResourceSkipCallback callback) { + bytesSkipped = -2; + return false; + } + + protected override bool Read(Stream response, int bytesToRead, out int bytesRead, CefResourceReadCallback callback) { + int count = Math.Min(bytesToRead, (Buffer?.Length ?? 0) - BufferPtr); + count = Math.Max(count, 0); + + if (count > 0) { + response.Write(Buffer!, BufferPtr, count); + BufferPtr += count; + } + bytesRead = count; + + if (count == 0) + Buffer = null; + + return count > 0; + } + + protected override void Cancel() { + ResponseCallback = null; + } + + static string URIDecode(string encoded) { + byte[] source = Encoding.UTF8.GetBytes(encoded); + List bytes = new(source.Length); + for (int i = 0; i < source.Length; i++) { + byte c = source[i]; + if (c == '%' && i + 2 < source.Length && IsHex(source[i + 1]) && IsHex(source[i + 2])) { + int value = (HexValue(source[i + 1]) << 4) | HexValue(source[i + 2]); + if (value >= 0x20 && value != 0x7F && value != '/' && value != '\\') { + bytes.Add((byte)value); + i += 2; + continue; + } + } + + bytes.Add(c); + } + return Encoding.UTF8.GetString(bytes.ToArray()); + } + + static bool IsHex(byte c) => c is (>= (byte)'0' and <= (byte)'9') or (>= (byte)'a' and <= (byte)'f') or (>= (byte)'A' and <= (byte)'F'); + static int HexValue(byte c) => c <= '9' ? c - '0' : (c | 0x20) - 'a' + 10; +} diff --git a/HTML.Chromium/HTML.Chromium.csproj b/HTML.Chromium/HTML.Chromium.csproj index 4d8773d9b..de31af24d 100644 --- a/HTML.Chromium/HTML.Chromium.csproj +++ b/HTML.Chromium/HTML.Chromium.csproj @@ -8,6 +8,7 @@ win-x64 false false + $(MSBuildThisFileDirectory)..\Build\$(Configuration)\cefsharp\ true true diff --git a/Source.Launcher.Native/App.cpp b/Source.Launcher.Native/App.cpp new file mode 100644 index 000000000..5fefe01b0 --- /dev/null +++ b/Source.Launcher.Native/App.cpp @@ -0,0 +1,379 @@ +#include "App.h" + +#include "include/cef_process_message.h" +#include "include/cef_values.h" + +static bool V8ValueToCefValue(CefRefPtr outValue, const CefRefPtr& inValue, int depth = 0) +{ + if (depth > 16) + return false; + + if (!inValue || inValue->IsNull() || inValue->IsUndefined()) { + outValue->SetNull(); + } + else if (inValue->IsBool()) { + outValue->SetBool(inValue->GetBoolValue()); + } + else if (inValue->IsInt() || inValue->IsUInt() || inValue->IsDouble()) { + outValue->SetDouble(inValue->GetDoubleValue()); + } + else if (inValue->IsString()) { + outValue->SetString(inValue->GetStringValue()); + } + else if (inValue->IsArray()) { + int arrayLen = inValue->GetArrayLength(); + CefRefPtr newList = CefListValue::Create(); + newList->SetSize(arrayLen); + + for (int i = 0; i < arrayLen; i++) { + CefRefPtr newValue = CefValue::Create(); + if (!V8ValueToCefValue(newValue, inValue->GetValue(i), depth + 1)) + return false; + newList->SetValue(i, newValue); + } + + outValue->SetList(newList); + } + else if (inValue->IsObject()) { + CefRefPtr newMap = CefDictionaryValue::Create(); + std::vector keys; + inValue->GetKeys(keys); + + for (const CefString& key : keys) { + CefRefPtr newValue = CefValue::Create(); + if (!V8ValueToCefValue(newValue, inValue->GetValue(key), depth + 1)) + return false; + newMap->SetValue(key, newValue); + } + + outValue->SetDictionary(newMap); + } + else { + outValue->SetNull(); + } + + return true; +} + +static bool V8ValuesToCefList(CefRefPtr& outList, const CefV8ValueList& inList) +{ + outList->SetSize(inList.size()); + + size_t index = 0; + for (const CefRefPtr& x : inList) { + CefRefPtr newValue = CefValue::Create(); + if (!V8ValueToCefValue(newValue, x)) + return false; + outList->SetValue(index, newValue); + index++; + } + + return true; +} + +static bool CefValueToV8Value(CefRefPtr& outValue, const CefRefPtr& inValue, int depth = 0) +{ + if (depth > 16) + return false; + + switch (inValue->GetType()) { + case VTYPE_BOOL: + outValue = CefV8Value::CreateBool(inValue->GetBool()); + break; + case VTYPE_INT: + outValue = CefV8Value::CreateInt(inValue->GetInt()); + break; + case VTYPE_DOUBLE: + outValue = CefV8Value::CreateDouble(inValue->GetDouble()); + break; + case VTYPE_STRING: + outValue = CefV8Value::CreateString(inValue->GetString()); + break; + case VTYPE_LIST: { + CefRefPtr inList = inValue->GetList(); + outValue = CefV8Value::CreateArray(static_cast(inList->GetSize())); + + for (size_t i = 0; i < inList->GetSize(); i++) { + CefRefPtr entry; + if (!CefValueToV8Value(entry, inList->GetValue(i), depth + 1)) + return false; + outValue->SetValue(static_cast(i), entry); + } + break; + } + case VTYPE_DICTIONARY: { + CefRefPtr inMap = inValue->GetDictionary(); + outValue = CefV8Value::CreateObject(nullptr, nullptr); + + CefDictionaryValue::KeyList keys; + inMap->GetKeys(keys); + + for (const CefString& key : keys) { + CefRefPtr value; + if (!CefValueToV8Value(value, inMap->GetValue(key), depth + 1)) + return false; + outValue->SetValue(key, value, V8_PROPERTY_ATTRIBUTE_NONE); + } + break; + } + default: + outValue = CefV8Value::CreateUndefined(); + break; + } + + return true; +} + +static bool CefListToV8Values(CefV8ValueList& outList, const CefRefPtr& inList) +{ + outList.reserve(inList->GetSize()); + + for (size_t i = 0; i < inList->GetSize(); i++) { + CefRefPtr entry; + if (!CefValueToV8Value(entry, inList->GetValue(i))) + return false; + outList.emplace_back(entry); + } + + return true; +} + +void SourceApp::OnRegisterCustomSchemes(CefRawPtr registrar) +{ + registrar->AddCustomScheme("asset", CEF_SCHEME_OPTION_STANDARD | CEF_SCHEME_OPTION_CSP_BYPASSING); +} + +CefRefPtr SourceApp::GetRenderProcessHandler() +{ + return this; +} + +void SourceApp::OnBrowserCreated(CefRefPtr browser, CefRefPtr extra_info) +{ + FunctionList& functions = m_Functions[browser->GetIdentifier()]; + + if (extra_info && extra_info->GetType("functions") == VTYPE_LIST) { + CefRefPtr list = extra_info->GetList("functions"); + for (size_t i = 0; i < list->GetSize(); i++) { + if (list->GetType(i) != VTYPE_LIST) + continue; + + CefRefPtr pair = list->GetList(i); + if (pair->GetSize() == 2 && pair->GetType(0) == VTYPE_STRING && pair->GetType(1) == VTYPE_STRING) + functions.emplace_back(pair->GetString(0), pair->GetString(1)); + } + } + + RequestFunctions(browser); +} + +void SourceApp::OnBrowserDestroyed(CefRefPtr browser) +{ + int browserId = browser->GetIdentifier(); + m_Functions.erase(browserId); + m_Synced.erase(browserId); + + for (auto it = m_Callbacks.begin(); it != m_Callbacks.end();) { + if (it->second.BrowserId == browserId) + it = m_Callbacks.erase(it); + else + ++it; + } +} + +void SourceApp::RequestFunctions(CefRefPtr browser) +{ + int browserId = browser->GetIdentifier(); + if (m_Synced[browserId]) + return; + + CefRefPtr mainFrame = browser->GetMainFrame(); + if (!mainFrame) + return; + + mainFrame->SendProcessMessage(PID_BROWSER, CefProcessMessage::Create("SyncFunctions")); + m_Synced[browserId] = true; +} + +void SourceApp::OnContextCreated(CefRefPtr browser, CefRefPtr frame, CefRefPtr context) +{ + context->Enter(); + { + context->GetGlobal()->DeleteValue("print"); + context->GetGlobal()->DeleteValue("openDatabase"); + } + context->Exit(); + + if (!browser) + return; + + RequestFunctions(browser); + + auto it = m_Functions.find(browser->GetIdentifier()); + if (it == m_Functions.end()) + return; + + for (const auto& pair : it->second) + RegisterFunctionInFrame(frame, pair.first, pair.second); +} + +bool SourceApp::OnProcessMessageReceived(CefRefPtr browser, CefRefPtr frame, CefProcessId source_process, CefRefPtr message) +{ + if (source_process != PID_BROWSER) + return false; + + CefString name = message->GetName(); + CefRefPtr args = message->GetArgumentList(); + + if (name == "RegisterFunction") { + RegisterFunction(browser, args); + return true; + } + + if (name == "ExecuteCallback") { + ExecuteCallback(args); + return true; + } + + if (name == "ForgetCallback") { + ForgetCallback(args); + return true; + } + + return false; +} + +bool SourceApp::Execute(const CefString& name, CefRefPtr object, const CefV8ValueList& arguments, CefRefPtr& retval, CefString& exception) +{ + CefRefPtr context = CefV8Context::GetCurrentContext(); + CefRefPtr browser = context->GetBrowser(); + CefRefPtr frame = context->GetFrame(); + + if (!browser || !frame) { + exception = "CefV8Context::GetBrowser == nullptr"; + return true; + } + + std::string fullName = name.ToString(); + size_t delimPos = fullName.find('#'); + if (delimPos == std::string::npos) { + exception = "SourceApp::Execute couldn't parse this function's name"; + return true; + } + + std::string objName = fullName.substr(0, delimPos); + std::string funcName = fullName.substr(delimPos + 1); + + CefRefPtr argsList = CefListValue::Create(); + if (!V8ValuesToCefList(argsList, arguments)) { + exception = "failed to serialize parameters (did you return a deeply nested structure?)"; + return true; + } + + CefRefPtr message = CefProcessMessage::Create("ExecuteFunction"); + CefRefPtr args = message->GetArgumentList(); + + args->SetString(0, objName); + args->SetString(1, funcName); + + if (arguments.empty() || !arguments.back()->IsFunction()) { + args->SetInt(2, -1); + } + else { + args->SetInt(2, CreateCallback(browser->GetIdentifier(), context, arguments.back())); + argsList->Remove(argsList->GetSize() - 1); + } + + args->SetList(3, argsList); + + frame->SendProcessMessage(PID_BROWSER, message); + return true; +} + +int SourceApp::CreateCallback(int browserId, CefRefPtr context, CefRefPtr func) +{ + if (m_Callbacks.find(m_NextCallbackId) != m_Callbacks.end()) + return -1; + + int callbackId = m_NextCallbackId; + m_Callbacks.emplace(callbackId, Callback{ browserId, context, func }); + + m_NextCallbackId++; + if (m_NextCallbackId >= 16384) + m_NextCallbackId = 0; + + return callbackId; +} + +void SourceApp::RegisterFunctionInFrame(CefRefPtr frame, const CefString& objName, const CefString& funcName) +{ + if (!frame) + return; + + CefRefPtr context = frame->GetV8Context(); + if (!context || !context->IsValid()) + return; + + CefString fullName(objName.ToString() + "#" + funcName.ToString()); + + context->Enter(); + { + CefRefPtr window = context->GetGlobal(); + CefRefPtr obj = window->GetValue(objName); + + if (!obj || !obj->IsObject()) { + obj = CefV8Value::CreateObject(nullptr, nullptr); + window->SetValue(objName, obj, V8_PROPERTY_ATTRIBUTE_NONE); + } + + obj->SetValue(funcName, CefV8Value::CreateFunction(fullName, this), V8_PROPERTY_ATTRIBUTE_NONE); + } + context->Exit(); +} + +void SourceApp::RegisterFunction(CefRefPtr browser, CefRefPtr args) +{ + CefString objName = args->GetString(0); + CefString funcName = args->GetString(1); + + FunctionList& functions = m_Functions[browser->GetIdentifier()]; + for (const auto& pair : functions) { + if (pair.first == objName && pair.second == funcName) + return; + } + functions.emplace_back(objName, funcName); + + std::vector frameIds; + browser->GetFrameIdentifiers(frameIds); + for (const CefString& frameId : frameIds) + RegisterFunctionInFrame(browser->GetFrameByIdentifier(frameId), objName, funcName); +} + +void SourceApp::ExecuteCallback(CefRefPtr args) +{ + auto it = m_Callbacks.find(args->GetInt(0)); + if (it == m_Callbacks.end()) + return; + + CefRefPtr context = it->second.Context; + CefRefPtr func = it->second.Function; + m_Callbacks.erase(it); + + if (!context->IsValid()) + return; + + CefRefPtr argList = args->GetList(1); + + context->Enter(); + { + CefV8ValueList arguments; + if (CefListToV8Values(arguments, argList)) + func->ExecuteFunction(nullptr, arguments); + } + context->Exit(); +} + +void SourceApp::ForgetCallback(CefRefPtr args) +{ + m_Callbacks.erase(args->GetInt(0)); +} diff --git a/Source.Launcher.Native/App.h b/Source.Launcher.Native/App.h new file mode 100644 index 000000000..3c78731b3 --- /dev/null +++ b/Source.Launcher.Native/App.h @@ -0,0 +1,49 @@ +#pragma once + +#include "include/cef_app.h" + +#include +#include +#include + +class SourceApp + : public CefApp + , public CefRenderProcessHandler + , public CefV8Handler +{ +public: + void OnRegisterCustomSchemes(CefRawPtr registrar) override; + CefRefPtr GetRenderProcessHandler() override; + + void OnBrowserCreated(CefRefPtr browser, CefRefPtr extra_info) override; + void OnBrowserDestroyed(CefRefPtr browser) override; + void OnContextCreated(CefRefPtr browser, CefRefPtr frame, CefRefPtr context) override; + bool OnProcessMessageReceived(CefRefPtr browser, CefRefPtr frame, CefProcessId source_process, CefRefPtr message) override; + + bool Execute(const CefString& name, CefRefPtr object, const CefV8ValueList& arguments, CefRefPtr& retval, CefString& exception) override; + +private: + using FunctionList = std::vector>; + + struct Callback + { + int BrowserId; + CefRefPtr Context; + CefRefPtr Function; + }; + + int CreateCallback(int browserId, CefRefPtr context, CefRefPtr func); + void RegisterFunctionInFrame(CefRefPtr frame, const CefString& objName, const CefString& funcName); + void RequestFunctions(CefRefPtr browser); + + void RegisterFunction(CefRefPtr browser, CefRefPtr args); + void ExecuteCallback(CefRefPtr args); + void ForgetCallback(CefRefPtr args); + + std::unordered_map m_Functions; + std::unordered_map m_Synced; + std::unordered_map m_Callbacks; + int m_NextCallbackId = 0; + + IMPLEMENT_REFCOUNTING(SourceApp); +}; diff --git a/Source.Launcher.Native/CMakeLists.txt b/Source.Launcher.Native/CMakeLists.txt new file mode 100644 index 000000000..54f802aa3 --- /dev/null +++ b/Source.Launcher.Native/CMakeLists.txt @@ -0,0 +1,43 @@ +cmake_minimum_required(VERSION 3.21) + +project(SourceLauncherNative CXX) + +set(CEF_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../Dependencies/CEF/154.0.34" CACHE PATH "CEF binary distribution root") +list(APPEND CMAKE_MODULE_PATH "${CEF_ROOT}/cmake") + +find_package(CEF REQUIRED) + +add_subdirectory(${CEF_LIBCEF_DLL_WRAPPER_PATH} libcef_dll_wrapper) + +set(SN_SOURCES App.cpp App.h) + +if(OS_WINDOWS) + set(NETHOST_DIR "" CACHE PATH "Directory containing nethost.h, hostfxr.h and nethost.lib") + if(NOT EXISTS "${NETHOST_DIR}/nethost.h") + message(FATAL_ERROR "NETHOST_DIR must point at the .NET apphost pack native directory (got '${NETHOST_DIR}')") + endif() + + add_library(Source.Launcher SHARED ${SN_SOURCES} MainWin.cpp) + SET_LIBRARY_TARGET_PROPERTIES(Source.Launcher) + add_dependencies(Source.Launcher libcef_dll_wrapper) + + ADD_LOGICAL_TARGET("libcef_lib" "${CEF_LIB_RELEASE}" "${CEF_LIB_RELEASE}") + target_include_directories(Source.Launcher PRIVATE "${NETHOST_DIR}") + target_link_libraries(Source.Launcher libcef_lib libcef_dll_wrapper ${CEF_STANDARD_LIBS} "${NETHOST_DIR}/nethost.lib" delayimp.lib) + target_link_options(Source.Launcher PRIVATE "/DELAYLOAD:libcef.dll") +elseif(OS_LINUX) + set(CEF_LIBCEF_SO "" CACHE FILEPATH "Path to libcef.so to link against") + if(NOT EXISTS "${CEF_LIBCEF_SO}") + message(FATAL_ERROR "CEF_LIBCEF_SO must point at libcef.so (got '${CEF_LIBCEF_SO}')") + endif() + + add_executable(Source.Launcher.CEF ${SN_SOURCES} MainLinux.cpp) + SET_EXECUTABLE_TARGET_PROPERTIES(Source.Launcher.CEF) + add_dependencies(Source.Launcher.CEF libcef_dll_wrapper) + + ADD_LOGICAL_TARGET("libcef_lib" "${CEF_LIBCEF_SO}" "${CEF_LIBCEF_SO}") + target_link_libraries(Source.Launcher.CEF libcef_lib libcef_dll_wrapper ${CEF_STANDARD_LIBS}) + set_target_properties(Source.Launcher.CEF PROPERTIES BUILD_RPATH "\$ORIGIN" INSTALL_RPATH "\$ORIGIN") +else() + message(FATAL_ERROR "Source.Launcher.Native supports Windows and Linux only") +endif() diff --git a/Source.Launcher.Native/MainLinux.cpp b/Source.Launcher.Native/MainLinux.cpp new file mode 100644 index 000000000..5e2cfec47 --- /dev/null +++ b/Source.Launcher.Native/MainLinux.cpp @@ -0,0 +1,15 @@ +#include +#include + +#include "include/cef_app.h" + +#include "App.h" + +int main(int argc, char* argv[]) +{ + prctl(PR_SET_PDEATHSIG, SIGKILL); + + CefMainArgs mainArgs(argc, argv); + CefRefPtr app(new SourceApp); + return CefExecuteProcess(mainArgs, app, nullptr); +} diff --git a/Source.Launcher.Native/MainWin.cpp b/Source.Launcher.Native/MainWin.cpp new file mode 100644 index 000000000..aa425bad4 --- /dev/null +++ b/Source.Launcher.Native/MainWin.cpp @@ -0,0 +1,126 @@ +#include +#include + +#include +#include +#include + +#include "include/cef_app.h" +#include "include/cef_sandbox_win.h" + +#include +#include + +#include "App.h" + +static const wchar_t* const ManagedAssembly = L"Source.LauncherMain.dll"; + +static std::wstring GetExeDirectory() +{ + std::wstring path(MAX_PATH, L'\0'); + for (;;) { + DWORD length = GetModuleFileNameW(nullptr, path.data(), static_cast(path.size())); + if (length == 0) + return L""; + if (length < path.size()) { + path.resize(length); + break; + } + path.resize(path.size() * 2); + } + + size_t slash = path.find_last_of(L"\\/"); + return slash == std::wstring::npos ? L"" : path.substr(0, slash + 1); +} + +static bool IsSubprocess() +{ + return wcsstr(GetCommandLineW(), L"--type=") != nullptr; +} + +static void Fail(const wchar_t* message) +{ + fwprintf(stderr, L"%s\n", message); + MessageBoxW(nullptr, message, L"Source.NET", MB_OK | MB_ICONERROR); +} + +static int RunSubprocess(void* sandboxInfo) +{ + CefMainArgs mainArgs(GetModuleHandleW(nullptr)); + CefRefPtr app(new SourceApp); + return CefExecuteProcess(mainArgs, app, sandboxInfo); +} + +static int RunManaged(void* sandboxInfo) +{ + std::wstring exeDir = GetExeDirectory(); + std::wstring assemblyPath = exeDir + ManagedAssembly; + + get_hostfxr_parameters params{ sizeof(get_hostfxr_parameters), assemblyPath.c_str(), nullptr }; + wchar_t hostfxrPath[MAX_PATH]; + size_t hostfxrPathSize = MAX_PATH; + if (get_hostfxr_path(hostfxrPath, &hostfxrPathSize, ¶ms) != 0) { + Fail(L"Could not locate the .NET runtime (hostfxr). Is the .NET 10 runtime installed?"); + return 1; + } + + HMODULE hostfxr = LoadLibraryW(hostfxrPath); + if (!hostfxr) { + Fail(L"Could not load hostfxr."); + return 1; + } + + auto initialize = reinterpret_cast(GetProcAddress(hostfxr, "hostfxr_initialize_for_dotnet_command_line")); + auto setProperty = reinterpret_cast(GetProcAddress(hostfxr, "hostfxr_set_runtime_property_value")); + auto runApp = reinterpret_cast(GetProcAddress(hostfxr, "hostfxr_run_app")); + auto close = reinterpret_cast(GetProcAddress(hostfxr, "hostfxr_close")); + if (!initialize || !setProperty || !runApp || !close) { + Fail(L"hostfxr is missing required exports."); + return 1; + } + + int argc = 0; + wchar_t** argv = CommandLineToArgvW(GetCommandLineW(), &argc); + std::vector managedArgv; + managedArgv.push_back(assemblyPath.c_str()); + for (int i = 1; i < argc; i++) + managedArgv.push_back(argv[i]); + + hostfxr_handle handle = nullptr; + int rc = initialize(static_cast(managedArgv.size()), managedArgv.data(), nullptr, &handle); + if (rc != 0 || !handle) { + LocalFree(argv); + wchar_t message[256]; + swprintf(message, 256, L"Failed to initialize the .NET runtime for %s (0x%08X).", ManagedAssembly, static_cast(rc)); + Fail(message); + if (handle) + close(handle); + return 1; + } + + wchar_t sandboxHex[32]; + swprintf(sandboxHex, 32, L"%llX", static_cast(reinterpret_cast(sandboxInfo))); + setProperty(handle, L"SN_CEF_SANDBOX_INFO", sandboxHex); + + rc = runApp(handle); + close(handle); + LocalFree(argv); + return rc; +} + +static int Run(void* sandboxInfo) +{ + if (IsSubprocess()) + return RunSubprocess(sandboxInfo); + return RunManaged(sandboxInfo); +} + +CEF_BOOTSTRAP_EXPORT int RunWinMain(HINSTANCE hInstance, LPWSTR lpCmdLine, int nCmdShow, void* sandbox_info, cef_version_info_t* version_info) +{ + return Run(sandbox_info); +} + +CEF_BOOTSTRAP_EXPORT int RunConsoleMain(int argc, char* argv[], void* sandbox_info, cef_version_info_t* version_info) +{ + return Run(sandbox_info); +} diff --git a/Source.Launcher.Native/Source.Launcher.Native.targets b/Source.Launcher.Native/Source.Launcher.Native.targets new file mode 100644 index 000000000..0f8365bb9 --- /dev/null +++ b/Source.Launcher.Native/Source.Launcher.Native.targets @@ -0,0 +1,61 @@ + + + + 154.0.34 + $(MSBuildThisFileDirectory) + $(MSBuildProjectDirectory)\obj\native\ + $(MSBuildThisFileDirectory)..\Dependencies\CEF\$(SNCefVersion)\ + $(NetCoreTargetingPackRoot)\Microsoft.NETCore.App.Host.win-x64\$(BundledNETCoreAppPackageVersion)\runtimes\win-x64\native\ + $(NuGetPackageRoot)cef.runtime.linux-x64\$(SNCefVersion)\CEF\linux-x64\ + + + + + + + + + <_SNVsWhere>$(MSBuildProgramFiles32)\Microsoft Visual Studio\Installer\vswhere.exe + + + + + + <_SNVsCMake>$(_SNVsInstall)\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe + $(_SNVsCMake) + cmake + + + + + + + + + + + + + + + + + + + + + + + + + <_SNCefLinuxRuntime Include="$(SNCefLinuxRuntimeDir)*" /> + <_SNCefLinuxResources Include="$(SNCefLinuxRuntimeDir)Resources\**\*" /> + + + + + + + diff --git a/Source.Launcher/Program.cs b/Source.Launcher/Program.cs index b5f8ea3d0..e06fadd00 100644 --- a/Source.Launcher/Program.cs +++ b/Source.Launcher/Program.cs @@ -87,9 +87,7 @@ public void Boot() { #if GMOD_DLL .WithComponent() .WithComponent() - #if WIN32 - .WithKeyedComponent("html_chromium", HTML.Chromium.ChromiumSystem.g_pHtmlSystem) - #endif + .WithKeyedComponent("html_chromium", HTML.CEF.CefSystem.g_pHtmlSystem) .WithKeyedComponent("html_stub", HTML.Stub.StubSystem.g_pHtmlSystem) #endif .WithComponent() diff --git a/Source.Launcher/Source.Launcher.csproj b/Source.Launcher/Source.Launcher.csproj index be510d3b7..2f881eb16 100644 --- a/Source.Launcher/Source.Launcher.csproj +++ b/Source.Launcher/Source.Launcher.csproj @@ -7,6 +7,13 @@ Debug;Release;Debug (Dedicated);Release (Dedicated) SourceDotNET.ico + + true + + + Source.LauncherMain + false + $(DefineConstants);DBGFLAG_ASSERT @@ -40,10 +47,17 @@ - + + + + + + + + diff --git a/Source.NET.slnx b/Source.NET.slnx index 559d2b387..93a2a6307 100644 --- a/Source.NET.slnx +++ b/Source.NET.slnx @@ -116,6 +116,9 @@ + + + From f274d90750a48c186cb0330f37d2e75b38e88e13 Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Thu, 15 Oct 2026 15:22:56 -0700 Subject: [PATCH 29/38] Remove the old Chromium system --- ChromiumProcess/ChromiumApp.cs | 27 - ChromiumProcess/ChromiumProcess.csproj | 26 - ChromiumProcess/HtmlBridge.cs | 310 --------- ChromiumProcess/Program.cs | 12 - ChromiumProcess/app.manifest | 26 - HTML.Chromium/ChromiumBrowser.cs | 854 ------------------------- HTML.Chromium/ChromiumClient.cs | 145 ----- HTML.Chromium/ChromiumSystem.cs | 258 -------- HTML.Chromium/HTML.Chromium.csproj | 32 - HTML.Chromium/HtmlResourceHandler.cs | 72 --- HTML.Chromium/ImageData.cs | 59 -- HTML.Chromium/JSObjects.cs | 57 -- HTML.Chromium/MessageQueue.cs | 39 -- HTML.Chromium/ModuleResolver.cs | 15 - HTML.Chromium/ResourceHandler.cs | 145 ----- Source.NET.slnx | 6 - 16 files changed, 2083 deletions(-) delete mode 100644 ChromiumProcess/ChromiumApp.cs delete mode 100644 ChromiumProcess/ChromiumProcess.csproj delete mode 100644 ChromiumProcess/HtmlBridge.cs delete mode 100644 ChromiumProcess/Program.cs delete mode 100644 ChromiumProcess/app.manifest delete mode 100644 HTML.Chromium/ChromiumBrowser.cs delete mode 100644 HTML.Chromium/ChromiumClient.cs delete mode 100644 HTML.Chromium/ChromiumSystem.cs delete mode 100644 HTML.Chromium/HTML.Chromium.csproj delete mode 100644 HTML.Chromium/HtmlResourceHandler.cs delete mode 100644 HTML.Chromium/ImageData.cs delete mode 100644 HTML.Chromium/JSObjects.cs delete mode 100644 HTML.Chromium/MessageQueue.cs delete mode 100644 HTML.Chromium/ModuleResolver.cs delete mode 100644 HTML.Chromium/ResourceHandler.cs diff --git a/ChromiumProcess/ChromiumApp.cs b/ChromiumProcess/ChromiumApp.cs deleted file mode 100644 index e4f7775e7..000000000 --- a/ChromiumProcess/ChromiumApp.cs +++ /dev/null @@ -1,27 +0,0 @@ -using CefSharp; -using CefSharp.RenderProcess; - -using System.Security.Cryptography; - -namespace ChromiumProcess; - -class ChromiumApp : IRenderProcessHandler -{ - readonly string? Secret = Environment.GetEnvironmentVariable(HtmlBridge.SecretVariable); - HtmlBridge.RegistryReader? Registry; - - public void OnContextCreated(IBrowser browser, IFrame frame, IV8Context context) { - context.Execute("delete this.print;delete this.openDatabase;", "", 0, out _); - - if (browser == null || string.IsNullOrEmpty(Secret)) - return; - - Registry ??= new HtmlBridge.RegistryReader(Secret); - string nonce = Convert.ToHexString(RandomNumberGenerator.GetBytes(16)); - context.Execute(HtmlBridge.BootstrapScript(Secret, Registry.Read(browser.Identifier), frame.Identifier, nonce), "", 0, out _); - } - - public void OnContextReleased(IBrowser browser, IFrame frame, IV8Context context) { } - - public void OnWebKitInitialized() { } -} diff --git a/ChromiumProcess/ChromiumProcess.csproj b/ChromiumProcess/ChromiumProcess.csproj deleted file mode 100644 index 08805427b..000000000 --- a/ChromiumProcess/ChromiumProcess.csproj +++ /dev/null @@ -1,26 +0,0 @@ - - - - WinExe - net10.0 - enable - enable - Debug;Release;Debug (Dedicated);Release (Dedicated) - win-x64 - false - false - $(MSBuildThisFileDirectory)..\Build\$(Configuration)\cefsharp\ - app.manifest - - - - - - - - - $(PkgCefSharp_Common_NETCore)\runtimes\win-x64\native\CefSharp.BrowserSubprocess.Core.dll - - - - diff --git a/ChromiumProcess/HtmlBridge.cs b/ChromiumProcess/HtmlBridge.cs deleted file mode 100644 index 62a21f49e..000000000 --- a/ChromiumProcess/HtmlBridge.cs +++ /dev/null @@ -1,310 +0,0 @@ -using System.IO.MemoryMappedFiles; -using System.Text; -using System.Text.Json; - -namespace ChromiumProcess; - -public static class HtmlBridge -{ - public const string SecretVariable = "SOURCENET_HTML_BRIDGE"; - const int RegistryCapacity = 4 * 1024 * 1024; - - public static string ApiName(string secret) => $"__SN{secret}"; - public static string BridgeName(string secret) => $"__SN{secret}_b"; - static string RegistryName(string secret) => $"Local\\SourceNET_HTML_{secret}"; - static string RegistryLockName(string secret) => $"Local\\SourceNET_HTML_{secret}_lock"; - - public static string Quote(string value) => JsonSerializer.Serialize(value); - - public static string BootstrapScript(string secret, IReadOnlyList<(string Obj, string Func)> registered, long frameId, string nonce) { - StringBuilder list = new("["); - for (int i = 0; i < registered.Count; i++) { - if (i > 0) - list.Append(','); - list.Append('[').Append(Quote(registered[i].Obj)).Append(',').Append(Quote(registered[i].Func)).Append(']'); - } - list.Append(']'); - - return $"({Bootstrap})(this,{Quote(ApiName(secret))},{Quote(BridgeName(secret))},{list},{Quote(frameId.ToString())},{Quote(nonce)});"; - } - - public static string RegisterScript(string secret, string objName, string funcName) - => $"(function(b){{if(b)b.r({Quote(objName)},{Quote(funcName)});}})(window[{Quote(BridgeName(secret))}]);"; - - public static string CallbackScript(string secret, int callbackId, string nonce, string encodedArgs) - => $"(function(b){{if(b)b.c({callbackId},{Quote(nonce)},{encodedArgs});}})(window[{Quote(BridgeName(secret))}]);"; - - const string Bootstrap = """ - function (G, apiName, bridgeName, registered, frameId, nonce) { - var defineProperty = Object.defineProperty; - var keys = Object.keys; - var isArray = Array.isArray; - var apply = Reflect.apply; - var stringify = JSON.stringify; - var toNumber = Number; - var toString = String; - var callbacks = Object.create(null); - var nextCallbackId = 0; - var FAIL = {}; - - function serialize(value, depth) { - if (depth > 16) - throw FAIL; - if (value === null || value === undefined) - return 0; - var type = typeof value; - if (type === 'boolean') - return [1, value]; - if (type === 'number') - return [2, (value === value && value !== Infinity && value !== -Infinity) ? value : toString(value)]; - if (type === 'string') - return [3, value]; - if (isArray(value)) { - var length = value.length, list = []; - for (var i = 0; i < length; i++) - list[i] = serialize(value[i], depth + 1); - return [4, list]; - } - if (type === 'object' || type === 'function') { - var names = keys(value), map = []; - for (var j = 0; j < names.length; j++) { - var entry; - try { - entry = value[names[j]]; - } - catch (e) { - entry = null; - } - map[j] = [names[j], serialize(entry, depth + 1)]; - } - return [5, map]; - } - return 0; - } - - function deserialize(value, depth) { - if (depth > 16) - throw FAIL; - if (value === 0) - return undefined; - switch (value[0]) { - case 1: - case 3: - return value[1]; - case 2: - return typeof value[1] === 'string' ? toNumber(value[1]) : value[1]; - case 4: { - var list = []; - for (var i = 0; i < value[1].length; i++) - list[i] = deserialize(value[1][i], depth + 1); - return list; - } - case 5: { - var object = {}; - for (var j = 0; j < value[1].length; j++) - defineProperty(object, value[1][j][0], { value: deserialize(value[1][j][1], depth + 1), writable: true, enumerable: true, configurable: true }); - return object; - } - } - return undefined; - } - - function createCallback(func) { - if (callbacks[nextCallbackId] !== undefined) - return -1; - var callbackId = nextCallbackId; - callbacks[callbackId] = func; - nextCallbackId++; - if (nextCallbackId >= 16384) - nextCallbackId = 0; - return callbackId; - } - - function execute(objName, funcName, args) { - var count = args.length, list = []; - try { - for (var i = 0; i < count; i++) - list[i] = serialize(args[i], 0); - } - catch (e) { - if (e === FAIL) - throw new Error('failed to serialize parameters (did you return a deeply nested structure?)'); - throw e; - } - - var callbackId = -1; - if (count > 0 && typeof args[count - 1] === 'function') { - callbackId = createCallback(args[count - 1]); - list.length = count - 1; - } - - var api = G[apiName]; - if (api && typeof api.PostMessage === 'function') - api.PostMessage(stringify(['ExecuteFunction', objName, funcName, callbackId, list, frameId, nonce])); - } - - function registerFunction(objName, funcName) { - try { - var obj = G[objName]; - if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { - obj = {}; - defineProperty(G, objName, { value: obj, writable: true, enumerable: true, configurable: true }); - } - var func = function () { return execute(objName, funcName, arguments); }; - defineProperty(func, 'name', { value: objName + '#' + funcName }); - defineProperty(obj, funcName, { value: func, writable: true, enumerable: true, configurable: true }); - } - catch (e) { } - } - - function executeCallback(callbackId, callbackNonce, encodedArgs) { - if (callbackNonce !== nonce) - return; - var func = callbacks[callbackId]; - if (func === undefined) - return; - delete callbacks[callbackId]; - - var args = []; - try { - for (var i = 0; i < encodedArgs.length; i++) - args[i] = deserialize(encodedArgs[i], 0); - } - catch (e) { - return; - } - apply(func, G, args); - } - - var bridge = Object.create(null); - bridge.c = executeCallback; - bridge.r = registerFunction; - try { - defineProperty(G, bridgeName, { value: bridge }); - } - catch (e) { } - - for (var k = 0; k < registered.length; k++) - registerFunction(registered[k][0], registered[k][1]); - } - """; - - public sealed class RegistryWriter : IDisposable - { - readonly MemoryMappedFile File; - readonly MemoryMappedViewAccessor View; - readonly Mutex Lock; - readonly Dictionary> Registrations = []; - - public RegistryWriter(string secret) { - File = MemoryMappedFile.CreateNew(RegistryName(secret), RegistryCapacity); - View = File.CreateViewAccessor(); - Lock = new Mutex(false, RegistryLockName(secret)); - Flush(); - } - - public void Add(int browserId, string objName, string funcName) { - lock (Registrations) { - if (!Registrations.TryGetValue(browserId, out List<(string, string)>? list)) - Registrations[browserId] = list = []; - list.Add((objName, funcName)); - Flush(); - } - } - - public void Remove(int browserId) { - lock (Registrations) { - if (Registrations.Remove(browserId)) - Flush(); - } - } - - void Flush() { - using MemoryStream stream = new(); - using (Utf8JsonWriter writer = new(stream)) { - writer.WriteStartObject(); - foreach (KeyValuePair> pair in Registrations) { - writer.WriteStartArray(pair.Key.ToString()); - foreach ((string obj, string func) in pair.Value) { - writer.WriteStartArray(); - writer.WriteStringValue(obj); - writer.WriteStringValue(func); - writer.WriteEndArray(); - } - writer.WriteEndArray(); - } - writer.WriteEndObject(); - } - - ReadOnlySpan data = stream.GetBuffer().AsSpan(0, (int)stream.Length); - if (data.Length + sizeof(int) > RegistryCapacity) - return; - - try { - Lock.WaitOne(); - } - catch (AbandonedMutexException) { } - try { - View.WriteArray(sizeof(int), stream.GetBuffer(), 0, data.Length); - View.Write(0, data.Length); - } - finally { - Lock.ReleaseMutex(); - } - } - - public void Dispose() { - View.Dispose(); - File.Dispose(); - Lock.Dispose(); - } - } - - public sealed class RegistryReader(string secret) - { - MemoryMappedFile? File; - MemoryMappedViewAccessor? View; - Mutex? Lock; - - public IReadOnlyList<(string Obj, string Func)> Read(int browserId) { - try { - File ??= MemoryMappedFile.OpenExisting(RegistryName(secret), MemoryMappedFileRights.Read); - View ??= File.CreateViewAccessor(0, 0, MemoryMappedFileAccess.Read); - Lock ??= Mutex.OpenExisting(RegistryLockName(secret)); - } - catch (Exception) { - return []; - } - - bool acquired; - try { - acquired = Lock.WaitOne(1000); - } - catch (AbandonedMutexException) { - acquired = true; - } - if (!acquired) - return []; - - byte[] data; - try { - int length = View.ReadInt32(0); - if (length <= 0 || length + sizeof(int) > RegistryCapacity) - return []; - data = new byte[length]; - View.ReadArray(sizeof(int), data, 0, length); - } - finally { - Lock.ReleaseMutex(); - } - - List<(string, string)> result = []; - using JsonDocument document = JsonDocument.Parse(data); - if (!document.RootElement.TryGetProperty(browserId.ToString(), out JsonElement list)) - return result; - foreach (JsonElement entry in list.EnumerateArray()) - result.Add((entry[0].GetString() ?? "", entry[1].GetString() ?? "")); - return result; - } - } -} diff --git a/ChromiumProcess/Program.cs b/ChromiumProcess/Program.cs deleted file mode 100644 index 15f229f0a..000000000 --- a/ChromiumProcess/Program.cs +++ /dev/null @@ -1,12 +0,0 @@ -using CefSharp.BrowserSubprocess; - -namespace ChromiumProcess; - -static class Program -{ - static int Main(string[] args) { - SubProcess.EnableHighDPISupport(); - BrowserSubprocessExecutable executable = new(); - return executable.Main(args, new ChromiumApp()); - } -} diff --git a/ChromiumProcess/app.manifest b/ChromiumProcess/app.manifest deleted file mode 100644 index 239090107..000000000 --- a/ChromiumProcess/app.manifest +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - true/PM - PerMonitorV2,PerMonitor - - - diff --git a/HTML.Chromium/ChromiumBrowser.cs b/HTML.Chromium/ChromiumBrowser.cs deleted file mode 100644 index d2961ca92..000000000 --- a/HTML.Chromium/ChromiumBrowser.cs +++ /dev/null @@ -1,854 +0,0 @@ -using CefSharp; -using CefSharp.Enums; -using CefSharp.OffScreen; -using CefSharp.Structs; - -using ChromiumProcess; - -using Source.Common.GarrysMod; - -using System.Diagnostics; -using System.Globalization; -using System.Security.Cryptography.X509Certificates; -using System.Text; -using System.Text.Json; - -using Range = CefSharp.Structs.Range; -using Size = CefSharp.Structs.Size; - -namespace HTML.Chromium; - -public class ChromiumBrowser : ILifeSpanHandler, ILoadHandler, IDisplayHandler, IRequestHandler, IContextMenuHandler, IDialogHandler, IJsDialogHandler -{ - static readonly JsonDocumentOptions MessageOptions = new() { MaxDepth = 256 }; - - static readonly string[] BlockedJavaScriptHosts = [ - "steampowered", - "steamcommunity", - "valvesoftware", - "steamgames", - "discord.", - "discordapp", - "watchanimeattheoffice", - "bigbeans.solutions", - "dis.gd", - "10.", - "172.16.", - "192.168.", - "127.", - "localhost", - ]; - - static bool CefValueToJSValue(out JSValue outValue, JsonElement inValue, int depth = 0) { - outValue = default; - - if (depth > 16) - return false; - - if (inValue.ValueKind != JsonValueKind.Array || inValue.GetArrayLength() < 2) - return true; - - JsonElement value = inValue[1]; - switch (inValue[0].GetInt32()) { - case 1: - outValue = new JSValue(value.GetBoolean()); - break; - case 2: - if (value.ValueKind == JsonValueKind.String) { - outValue = new JSValue(value.GetString() switch { - "Infinity" => double.PositiveInfinity, - "-Infinity" => double.NegativeInfinity, - _ => double.NaN - }); - } - else - outValue = new JSValue(value.GetDouble()); - break; - case 3: - outValue = JSString.Create(value.GetString() ?? ""); - break; - case 4: { - JSValue[] outList = new JSValue[value.GetArrayLength()]; - int i = 0; - foreach (JsonElement entry in value.EnumerateArray()) { - if (!CefValueToJSValue(out outList[i], entry, depth + 1)) - return false; - i++; - } - outValue = JSArray.Create(outList); - break; - } - case 5: { - Dictionary outMap = new(value.GetArrayLength()); - foreach (JsonElement entry in value.EnumerateArray()) { - if (!CefValueToJSValue(out JSValue mapValue, entry[1], depth + 1)) - return false; - outMap.TryAdd(entry[0].GetString() ?? "", mapValue); - } - outValue = JSHashMap.Create(outMap); - break; - } - } - - return true; - } - - static bool CefListToJSValues(out JSValue[] outList, JsonElement inList) { - outList = new JSValue[inList.GetArrayLength()]; - - int i = 0; - foreach (JsonElement entry in inList.EnumerateArray()) { - if (!CefValueToJSValue(out outList[i], entry)) - return false; - i++; - } - - return true; - } - - static bool JSValueToCefValue(Utf8JsonWriter outValue, in JSValue inValue, int depth = 0) { - if (depth > 16) - return false; - - switch (inValue.GetJSType()) { - case JSValue.Type.Undefined: - outValue.WriteNumberValue(0); - break; - case JSValue.Type.Bool: - outValue.WriteStartArray(); - outValue.WriteNumberValue(1); - outValue.WriteBooleanValue(inValue.GetBool()); - outValue.WriteEndArray(); - break; - case JSValue.Type.Number: { - double number = inValue.GetNumber(); - outValue.WriteStartArray(); - outValue.WriteNumberValue(2); - if (double.IsFinite(number)) - outValue.WriteNumberValue(number); - else - outValue.WriteStringValue(double.IsNaN(number) ? "NaN" : number > 0 ? "Infinity" : "-Infinity"); - outValue.WriteEndArray(); - break; - } - case JSValue.Type.String: - outValue.WriteStartArray(); - outValue.WriteNumberValue(3); - outValue.WriteStringValue(inValue.GetString()); - outValue.WriteEndArray(); - break; - case JSValue.Type.Array: - outValue.WriteStartArray(); - outValue.WriteNumberValue(4); - outValue.WriteStartArray(); - foreach (JSValue x in inValue.GetArray()) - if (!JSValueToCefValue(outValue, x, depth + 1)) - return false; - outValue.WriteEndArray(); - outValue.WriteEndArray(); - break; - case JSValue.Type.HashMap: { - outValue.WriteStartArray(); - outValue.WriteNumberValue(5); - outValue.WriteStartArray(); - if (inValue.HashMap_Begin(out ReadOnlySpan key, out JSValue value)) { - do { - outValue.WriteStartArray(); - outValue.WriteStringValue(key); - if (!JSValueToCefValue(outValue, value, depth + 1)) - return false; - outValue.WriteEndArray(); - } - while (inValue.HashMap_Next(out key, out value)); - } - outValue.WriteEndArray(); - outValue.WriteEndArray(); - break; - } - default: - outValue.WriteNumberValue(0); - break; - } - - return true; - } - - static bool JSValuesToCefList(out string outList, ReadOnlySpan inList) { - outList = ""; - - using MemoryStream stream = new(); - try { - using Utf8JsonWriter writer = new(stream); - writer.WriteStartArray(); - foreach (JSValue x in inList) - if (!JSValueToCefValue(writer, x)) - return false; - writer.WriteEndArray(); - } - catch (ArgumentException) { - return false; - } - catch (InvalidOperationException) { - return false; - } - - outList = Encoding.UTF8.GetString(stream.GetBuffer(), 0, (int)stream.Length); - return true; - } - - static CefEventFlags GetModifiers(IHtmlClient.EventModifiers modifiers) { - CefEventFlags chromiumModifiers = 0; - - if ((modifiers & IHtmlClient.EventModifiers.Shift) != 0) - chromiumModifiers |= CefEventFlags.ShiftDown | CefEventFlags.IsLeft; - - if ((modifiers & IHtmlClient.EventModifiers.ShiftR) != 0) - chromiumModifiers |= CefEventFlags.ShiftDown | CefEventFlags.IsRight; - - if ((modifiers & IHtmlClient.EventModifiers.Control) != 0) - chromiumModifiers |= CefEventFlags.ControlDown | CefEventFlags.IsLeft; - - if ((modifiers & IHtmlClient.EventModifiers.ControlR) != 0) - chromiumModifiers |= CefEventFlags.ControlDown | CefEventFlags.IsRight; - - if ((modifiers & IHtmlClient.EventModifiers.Alt) != 0) - chromiumModifiers |= CefEventFlags.AltDown | CefEventFlags.IsLeft; - - if ((modifiers & IHtmlClient.EventModifiers.AltGr) != 0) - chromiumModifiers |= CefEventFlags.AltDown | CefEventFlags.IsRight; - - if ((modifiers & IHtmlClient.EventModifiers.LeftMouse) != 0) - chromiumModifiers |= CefEventFlags.LeftMouseButton; - - if ((modifiers & IHtmlClient.EventModifiers.MiddleMouse) != 0) - chromiumModifiers |= CefEventFlags.MiddleMouseButton; - - if ((modifiers & IHtmlClient.EventModifiers.RightMouse) != 0) - chromiumModifiers |= CefEventFlags.RightMouseButton; - - if ((modifiers & IHtmlClient.EventModifiers.Numpad) != 0) - chromiumModifiers |= CefEventFlags.IsKeyPad; - - return chromiumModifiers; - } - - static bool TryParseScheme(string url, out string scheme) { - if (Uri.TryCreate(url, UriKind.Absolute, out Uri? uri)) { - scheme = uri.Scheme; - return true; - } - - scheme = ""; - return false; - } - - int Wide = 512; - int Tall = 512; - - int PopupX; - int PopupY; - int PopupWide; - int PopupTall; - byte[]? PopupData; - - readonly MessageQueue MessageQueue = new(); - - readonly ImageData ImageData = new(); - - ChromiumWebBrowser? WebBrowser; - IBrowser? Browser; - IBrowserHost? BrowserHost; - - bool OpenLinksExternally; - - readonly string BridgeSecret; - readonly HtmlBridge.RegistryWriter? Registry; - readonly HashSet<(string Obj, string Func)> RegisteredFunctions = []; - readonly List PendingTasks = []; - readonly ResourceRequestHandler ResourceRequest; - readonly RenderHandler Render; - - public ChromiumBrowser(string bridgeSecret, HtmlBridge.RegistryWriter? registry) { - BridgeSecret = bridgeSecret; - Registry = registry; - ResourceRequest = new ResourceRequestHandler(); - Render = new RenderHandler(this); - } - - public void CreateBrowser(IBrowserSettings browserSettings) { - WebBrowser = new ChromiumWebBrowser("", null, null, false); - - WebBrowser.RenderHandler?.Dispose(); - WebBrowser.RenderHandler = Render; - WebBrowser.LifeSpanHandler = this; - WebBrowser.LoadHandler = this; - WebBrowser.DisplayHandler = this; - WebBrowser.RequestHandler = this; - WebBrowser.MenuHandler = this; - WebBrowser.DialogHandler = this; - WebBrowser.JsDialogHandler = this; - WebBrowser.JavascriptObjectRepository.Settings.JavascriptBindingApiGlobalObjectName = HtmlBridge.ApiName(BridgeSecret); - WebBrowser.JavascriptMessageReceived += OnJavascriptMessageReceived; - - WindowInfo windowInfo = new(); - windowInfo.SetAsWindowless(0); - - WebBrowser.CreateBrowser(windowInfo, browserSettings); - } - - public ImageData GetImageData() => ImageData; - - public MessageQueue GetMessageQueue() => MessageQueue; - - public void QueueMessage(in MessageQueue.Message message) { - MessageQueue.Lock(); - MessageQueue.Push(message); - MessageQueue.Unlock(); - } - - void RunOrDefer(Action task) { - if (Browser == null) { - PendingTasks.Add(task); - return; - } - - task(); - } - - public void Close() { - PendingTasks.Clear(); - - if (Browser != null) - Registry?.Remove(Browser.Identifier); - - BrowserHost?.CloseBrowser(true); - WebBrowser?.Dispose(); - WebBrowser = null; - } - - public void SetSize(int wide, int tall) { - Wide = wide; - Tall = tall; - RunOrDefer(() => BrowserHost!.WasResized()); - } - - public void SetFocused(bool hasFocus) => RunOrDefer(() => BrowserHost!.SendFocusEvent(hasFocus)); - - public void SendKeyEvent(IHtmlClient.KeyEvent keyEvent) { - KeyEvent chromiumKeyEvent = new() { - Modifiers = GetModifiers(keyEvent.Modifiers) - }; - - switch (keyEvent.EventType) { - case IHtmlClient.KeyEvent.Type.KeyChar: - chromiumKeyEvent.Type = KeyEventType.Char; - chromiumKeyEvent.WindowsKeyCode = keyEvent.WindowsKeyCode; - chromiumKeyEvent.NativeKeyCode = keyEvent.NativeKeyCode; - break; - case IHtmlClient.KeyEvent.Type.KeyDown: - chromiumKeyEvent.Type = KeyEventType.KeyDown; - chromiumKeyEvent.WindowsKeyCode = keyEvent.WindowsKeyCode; - chromiumKeyEvent.NativeKeyCode = keyEvent.NativeKeyCode; - break; - case IHtmlClient.KeyEvent.Type.KeyUp: - chromiumKeyEvent.Type = KeyEventType.KeyUp; - chromiumKeyEvent.WindowsKeyCode = keyEvent.WindowsKeyCode; - chromiumKeyEvent.NativeKeyCode = keyEvent.NativeKeyCode; - break; - } - - RunOrDefer(() => BrowserHost!.SendKeyEvent(chromiumKeyEvent)); - } - - public void SendMouseMoveEvent(IHtmlClient.MouseEvent gmodMouseEvent, bool mouseLeave) { - MouseEvent mouseEvent = new(gmodMouseEvent.X, gmodMouseEvent.Y, GetModifiers(gmodMouseEvent.Modifiers)); - RunOrDefer(() => BrowserHost!.SendMouseMoveEvent(mouseEvent, mouseLeave)); - } - - public void SendMouseWheelEvent(IHtmlClient.MouseEvent gmodMouseEvent, int deltaX, int deltaY) { - MouseEvent mouseEvent = new(gmodMouseEvent.X, gmodMouseEvent.Y, GetModifiers(gmodMouseEvent.Modifiers)); - RunOrDefer(() => BrowserHost!.SendMouseWheelEvent(mouseEvent, deltaX, deltaY)); - } - - public void SendMouseClickEvent(IHtmlClient.MouseEvent gmodMouseEvent, IHtmlClient.MouseButton gmodButtonType, bool mouseUp, int clickCount) { - MouseEvent mouseEvent = new(gmodMouseEvent.X, gmodMouseEvent.Y, GetModifiers(gmodMouseEvent.Modifiers)); - - MouseButtonType buttonType = gmodButtonType switch { - IHtmlClient.MouseButton.Middle => MouseButtonType.Middle, - IHtmlClient.MouseButton.Right => MouseButtonType.Right, - _ => MouseButtonType.Left, - }; - - RunOrDefer(() => BrowserHost!.SendMouseClickEvent(mouseEvent, buttonType, mouseUp, clickCount)); - } - - public void LoadUrl(string url) => RunOrDefer(() => Browser!.MainFrame.LoadUrl(url)); - - public void SetHtml(string html) { - string url = $"asset://html/?{Convert.ToBase64String(Encoding.UTF8.GetBytes(html))}"; - RunOrDefer(() => Browser!.MainFrame.LoadUrl(url)); - } - - public void Refresh() => RunOrDefer(() => Browser!.Reload()); - - public void Stop() => RunOrDefer(() => Browser!.StopLoad()); - - public void GoBack() => RunOrDefer(() => Browser!.GoBack()); - - public void GoForward() => RunOrDefer(() => Browser!.GoForward()); - - public void RunJavaScript(string code) { - RunOrDefer(() => { - IFrame mainFrame = Browser!.MainFrame; - string url = mainFrame.Url ?? ""; - - int slash = url.Length >= 9 ? url.IndexOf('/', 8) : -1; - string host = slash == -1 ? url : url[..slash]; - - foreach (string blocked in BlockedJavaScriptHosts) - if (host.Contains(blocked, StringComparison.Ordinal)) - return; - - mainFrame.ExecuteJavaScriptAsync(code, "Lua File", 1); - }); - } - - public void RegisterJavaScriptFunction(string objName, string funcName) { - RunOrDefer(() => { - lock (RegisteredFunctions) - RegisteredFunctions.Add((objName, funcName)); - Registry?.Add(Browser!.Identifier, objName, funcName); - - string script = HtmlBridge.RegisterScript(BridgeSecret, objName, funcName); - foreach (long frameId in Browser!.GetFrameIdentifiers()) { - IFrame? frame = Browser.GetFrame(frameId); - if (frame != null && frame.IsValid) - frame.ExecuteJavaScriptAsync(script); - } - }); - } - - public void SetOpenLinksExternally(bool openLinksExternally) => OpenLinksExternally = openLinksExternally; - - public void ExecuteCallback(int callbackId, long frameId, string nonce, JSValue paramsArray) { - if (Browser == null) - return; - - ReadOnlySpan paramsVector = paramsArray.GetJSType() == JSValue.Type.Array ? paramsArray.GetArray() : default; - if (!JSValuesToCefList(out string cefArgs, paramsVector)) - return; - - IFrame? frame = Browser.GetFrame(frameId); - if (frame == null || !frame.IsValid) - return; - - frame.ExecuteJavaScriptAsync(HtmlBridge.CallbackScript(BridgeSecret, callbackId, nonce, cefArgs)); - } - - void OnJavascriptMessageReceived(object? sender, JavascriptMessageReceivedEventArgs e) { - if (e.Message is not string message) - return; - - JsonDocument document; - try { - document = JsonDocument.Parse(message, MessageOptions); - } - catch (JsonException) { - return; - } - - using (document) { - JsonElement args = document.RootElement; - if (args.ValueKind != JsonValueKind.Array || args.GetArrayLength() != 7) - return; - - if (args[0].ValueKind != JsonValueKind.String || args[0].GetString() != "ExecuteFunction") - return; - - if (args[1].ValueKind != JsonValueKind.String || args[2].ValueKind != JsonValueKind.String || args[3].ValueKind != JsonValueKind.Number || args[4].ValueKind != JsonValueKind.Array - || args[5].ValueKind != JsonValueKind.String || args[6].ValueKind != JsonValueKind.String) - return; - - string objName = args[1].GetString()!; - string funcName = args[2].GetString()!; - lock (RegisteredFunctions) { - if (!RegisteredFunctions.Contains((objName, funcName))) - return; - } - - if (!args[3].TryGetInt32(out int callbackId) || callbackId < -1 || callbackId >= 16384) - return; - - if (!long.TryParse(args[5].GetString(), NumberStyles.Integer, CultureInfo.InvariantCulture, out long frameId)) - return; - - if (!CefListToJSValues(out JSValue[] values, args[4])) - return; - - MessageQueue.Message msg = new() { - Type = MessageQueue.Type.OnJavaScriptCall, - String1 = objName, - String2 = funcName, - Integer = callbackId, - FrameId = frameId, - Nonce = args[6].GetString()!, - JSParams = JSArray.Create(values) - }; - - QueueMessage(msg); - } - } - - public void OnAfterCreated(IWebBrowser chromiumWebBrowser, IBrowser browser) { - Browser = browser; - BrowserHost = browser.GetHost(); - - Action[] pending = [.. PendingTasks]; - PendingTasks.Clear(); - foreach (Action task in pending) - task(); - } - - public bool DoClose(IWebBrowser chromiumWebBrowser, IBrowser browser) => false; - - public void OnBeforeClose(IWebBrowser chromiumWebBrowser, IBrowser browser) { - Browser = null; - BrowserHost = null; - } - - public bool OnBeforePopup(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, string targetUrl, string targetFrameName, WindowOpenDisposition targetDisposition, bool userGesture, IPopupFeatures popupFeatures, IWindowInfo windowInfo, IBrowserSettings browserSettings, ref bool noJavascriptAccess, out IWebBrowser newBrowser) { - string sourceUrl = frame.Url; - - MessageQueue.Message msg = new() { - Type = MessageQueue.Type.OnCreateChildView, - String1 = sourceUrl, - String2 = targetUrl, - Integer = targetDisposition == WindowOpenDisposition.NewPopup ? 1 : 0 - }; - QueueMessage(msg); - - newBrowser = null!; - return true; - } - - public void OnLoadingStateChange(IWebBrowser chromiumWebBrowser, LoadingStateChangedEventArgs loadingStateChangedArgs) { } - - public void OnFrameLoadStart(IWebBrowser chromiumWebBrowser, FrameLoadStartEventArgs frameLoadStartArgs) { - IFrame frame = frameLoadStartArgs.Frame; - if (!frame.IsMain) - return; - - MessageQueue.Message msg = new() { - Type = MessageQueue.Type.OnLoadStart, - String1 = frame.Url - }; - QueueMessage(msg); - } - - public void OnFrameLoadEnd(IWebBrowser chromiumWebBrowser, FrameLoadEndEventArgs frameLoadEndArgs) { - IFrame frame = frameLoadEndArgs.Frame; - if (!frame.IsMain) - return; - - MessageQueue.Message msg = new() { - Type = MessageQueue.Type.OnLoadEnd, - String1 = frame.Url - }; - QueueMessage(msg); - - frame.ExecuteJavaScriptAsync("WebSocket = undefined;", "haha", 0); - } - - public void OnLoadError(IWebBrowser chromiumWebBrowser, LoadErrorEventArgs loadErrorArgs) { - IFrame frame = loadErrorArgs.Frame; - if (!frame.IsMain) - return; - - MessageQueue.Message msg = new() { - Type = MessageQueue.Type.OnLoadEnd, - String1 = frame.Url - }; - QueueMessage(msg); - - frame.ExecuteJavaScriptAsync("WebSocket = undefined;", "haha", 0); - } - - public void OnAddressChanged(IWebBrowser chromiumWebBrowser, AddressChangedEventArgs addressChangedArgs) { - IFrame? mainFrame = addressChangedArgs.Browser?.MainFrame; - if (mainFrame != null && mainFrame.Url != addressChangedArgs.Address) - return; - - MessageQueue.Message msg = new() { - Type = MessageQueue.Type.OnAddressChange, - String1 = addressChangedArgs.Address - }; - QueueMessage(msg); - } - - public bool OnAutoResize(IWebBrowser chromiumWebBrowser, IBrowser browser, Size newSize) => false; - - public bool OnCursorChange(IWebBrowser chromiumWebBrowser, IBrowser browser, nint cursor, CursorType type, CursorInfo customCursorInfo) { - IHtmlClientListener.CursorType gmodCursor = type switch { - CursorType.Pointer => IHtmlClientListener.CursorType.Default, - CursorType.Cross => IHtmlClientListener.CursorType.Crosshair, - CursorType.Hand => IHtmlClientListener.CursorType.Hand, - CursorType.IBeam => IHtmlClientListener.CursorType.IBeam, - CursorType.Wait => IHtmlClientListener.CursorType.Hourglass, - CursorType.Move => IHtmlClientListener.CursorType.SizeAll, - CursorType.EastResize or CursorType.WestResize or CursorType.EastWestResize => IHtmlClientListener.CursorType.SizeEW, - CursorType.NorthResize or CursorType.SouthResize or CursorType.NorthSouthResize => IHtmlClientListener.CursorType.SizeNS, - CursorType.NortheastResize or CursorType.SouthwestResize or CursorType.NortheastSouthwestResize => IHtmlClientListener.CursorType.SizeNESW, - CursorType.NorthwestResize or CursorType.SoutheastResize or CursorType.NorthwestSoutheastResize => IHtmlClientListener.CursorType.SizeNWSE, - CursorType.ColumnResize => IHtmlClientListener.CursorType.SizeEW, - CursorType.RowResize => IHtmlClientListener.CursorType.SizeNS, - CursorType.NotAllowed => IHtmlClientListener.CursorType.No, - CursorType.None => IHtmlClientListener.CursorType.None, - CursorType.MiddlePanning or CursorType.EastPanning or CursorType.NorthPanning or CursorType.NortheastPanning or CursorType.NorthwestPanning - or CursorType.SouthPanning or CursorType.SoutheastPanning or CursorType.SouthwestPanning or CursorType.WestPanning => IHtmlClientListener.CursorType.SizeAll, - _ => IHtmlClientListener.CursorType.Default - }; - - MessageQueue.Message msg = new() { - Type = MessageQueue.Type.OnCursorChange, - Integer = (int)gmodCursor - }; - QueueMessage(msg); - return true; - } - - public void OnTitleChanged(IWebBrowser chromiumWebBrowser, TitleChangedEventArgs titleChangedArgs) { - MessageQueue.Message msg = new() { - Type = MessageQueue.Type.OnTitleChange, - String1 = titleChangedArgs.Title - }; - QueueMessage(msg); - } - - public void OnFaviconUrlChange(IWebBrowser chromiumWebBrowser, IBrowser browser, IList urls) { } - - public void OnFullscreenModeChange(IWebBrowser chromiumWebBrowser, IBrowser browser, bool fullscreen) { } - - public void OnLoadingProgressChange(IWebBrowser chromiumWebBrowser, IBrowser browser, double progress) { } - - public bool OnTooltipChanged(IWebBrowser chromiumWebBrowser, ref string text) => false; - - public void OnStatusMessage(IWebBrowser chromiumWebBrowser, StatusMessageEventArgs statusMessageArgs) { } - - public bool OnConsoleMessage(IWebBrowser chromiumWebBrowser, ConsoleMessageEventArgs consoleMessageArgs) { - MessageQueue.Message msg = new() { - Type = MessageQueue.Type.OnConsoleMessage, - String1 = consoleMessageArgs.Message, - String2 = consoleMessageArgs.Source, - Integer = consoleMessageArgs.Line, - Integer2 = (int)consoleMessageArgs.Level - }; - QueueMessage(msg); - - return false; - } - - void OnPopupShow(bool show) { - if (BrowserHost == null) - return; - - if (!show) { - PopupX = 0; - PopupY = 0; - PopupWide = 0; - PopupTall = 0; - PopupData = null; - - BrowserHost.Invalidate(PaintElementType.View); - } - } - - void OnPopupSize(Rect rect) { - PopupX = rect.X; - PopupY = rect.Y; - } - - void OnPaint(PaintElementType type, nint buffer, int width, int height) { - if (width <= 0 || height <= 0) - return; - - switch (type) { - case PaintElementType.Popup: - PopupData = new byte[width * height * 4]; - System.Runtime.InteropServices.Marshal.Copy(buffer, PopupData, 0, PopupData.Length); - PopupWide = width; - PopupTall = height; - - BrowserHost?.Invalidate(PaintElementType.View); - return; - - case PaintElementType.View: - ImageData.Lock(); - ImageData.SetData(buffer, width, height); - - if (PopupWide > 0 && PopupTall > 0 && - PopupX < width && PopupY < height && - (PopupX + PopupWide) > 0 && (PopupY + PopupTall) > 0) { - ImageData.CopyImage(PopupData, PopupX, PopupY, PopupWide, PopupTall); - } - - ImageData.SetDirty(true); - ImageData.Unlock(); - return; - } - } - - public bool OnOpenUrlFromTab(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, string targetUrl, WindowOpenDisposition targetDisposition, bool userGesture) { - if (targetDisposition == WindowOpenDisposition.NewPopup || targetDisposition == WindowOpenDisposition.NewForegroundTab || targetDisposition == WindowOpenDisposition.NewBackgroundTab) { - string sourceUrl = frame.Url; - - MessageQueue.Message msg = new() { - Type = MessageQueue.Type.OnCreateChildView, - String1 = sourceUrl, - String2 = targetUrl, - Integer = targetDisposition == WindowOpenDisposition.NewPopup ? 1 : 0 - }; - QueueMessage(msg); - - return true; - } - - return false; - } - - public bool OnBeforeBrowse(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, bool userGesture, bool isRedirect) { - string url = request.Url; - if (!TryParseScheme(url, out string strScheme)) - return true; - - if (url == "chrome://credits/") - return false; - - if (strScheme != "http" && strScheme != "https" && strScheme != "asset") - return true; - - if (OpenLinksExternally) { - try { - Process.Start(new ProcessStartInfo(url) { UseShellExecute = true }); - } - catch (Exception) { } - return true; - } - - return false; - } - - public void OnDocumentAvailableInMainFrame(IWebBrowser chromiumWebBrowser, IBrowser browser) { } - - public IResourceRequestHandler GetResourceRequestHandler(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, bool isNavigation, bool isDownload, string requestInitiator, ref bool disableDefaultHandling) => ResourceRequest; - - public bool GetAuthCredentials(IWebBrowser chromiumWebBrowser, IBrowser browser, string originUrl, bool isProxy, string host, int port, string realm, string scheme, IAuthCallback callback) => false; - - public bool OnQuotaRequest(IWebBrowser chromiumWebBrowser, IBrowser browser, string originUrl, long newSize, IRequestCallback callback) => false; - - public bool OnCertificateError(IWebBrowser chromiumWebBrowser, IBrowser browser, CefErrorCode errorCode, string requestUrl, ISslInfo sslInfo, IRequestCallback callback) => false; - - public bool OnSelectClientCertificate(IWebBrowser chromiumWebBrowser, IBrowser browser, bool isProxy, string host, int port, X509Certificate2Collection certificates, ISelectClientCertificateCallback callback) => false; - - public void OnPluginCrashed(IWebBrowser chromiumWebBrowser, IBrowser browser, string pluginPath) { } - - public void OnRenderViewReady(IWebBrowser chromiumWebBrowser, IBrowser browser) { } - - public void OnRenderProcessTerminated(IWebBrowser chromiumWebBrowser, IBrowser browser, CefTerminationStatus status) { } - - public void OnBeforeContextMenu(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model) => model.Clear(); - - public bool OnContextMenuCommand(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags) => false; - - public void OnContextMenuDismissed(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame) { } - - public bool RunContextMenu(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model, IRunContextMenuCallback callback) => false; - - public bool OnFileDialog(IWebBrowser chromiumWebBrowser, IBrowser browser, CefFileDialogMode mode, CefFileDialogFlags flags, string title, string defaultFilePath, List acceptFilters, int selectedAcceptFilter, IFileDialogCallback callback) { - callback.Cancel(); - return true; - } - - public bool OnJSDialog(IWebBrowser chromiumWebBrowser, IBrowser browser, string originUrl, CefJsDialogType dialogType, string messageText, string defaultPromptText, IJsDialogCallback callback, ref bool suppressMessage) { - suppressMessage = true; - return false; - } - - public bool OnBeforeUnloadDialog(IWebBrowser chromiumWebBrowser, IBrowser browser, string messageText, bool isReload, IJsDialogCallback callback) { - callback.Continue(true, ""); - return true; - } - - public void OnResetDialogState(IWebBrowser chromiumWebBrowser, IBrowser browser) { } - - public void OnDialogClosed(IWebBrowser chromiumWebBrowser, IBrowser browser) { } - - sealed class ResourceRequestHandler : IResourceRequestHandler - { - public ICookieAccessFilter GetCookieAccessFilter(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request) => null!; - - public CefReturnValue OnBeforeResourceLoad(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback) { - string sourceUrl = request.Url; - - if (!TryParseScheme(sourceUrl, out string strScheme)) - return CefReturnValue.Cancel; - - if (sourceUrl == "chrome://credits/" || - sourceUrl == "chrome://resources/js/cr.js" || - sourceUrl == "chrome://credits/credits.js") { - return CefReturnValue.Continue; - } - - if (strScheme != "http" && strScheme != "https" && strScheme != "asset") - return CefReturnValue.Cancel; - - return CefReturnValue.Continue; - } - - public IResourceHandler GetResourceHandler(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request) => null!; - - public void OnResourceRedirect(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IResponse response, ref string newUrl) { } - - public bool OnResourceResponse(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IResponse response) => false; - - public IResponseFilter GetResourceResponseFilter(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IResponse response) => null!; - - public void OnResourceLoadComplete(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IResponse response, UrlRequestStatus status, long receivedContentLength) { } - - public bool OnProtocolExecution(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request) => false; - - public void Dispose() { } - } - - sealed class RenderHandler(ChromiumBrowser owner) : IRenderHandler - { - public ScreenInfo? GetScreenInfo() => null; - - public Rect GetViewRect() => new(0, 0, owner.Wide, owner.Tall); - - public bool GetScreenPoint(int viewX, int viewY, out int screenX, out int screenY) { - screenX = viewX; - screenY = viewY; - return false; - } - - public void OnAcceleratedPaint(PaintElementType type, Rect dirtyRect, nint sharedHandle) { } - - public void OnPaint(PaintElementType type, Rect dirtyRect, nint buffer, int width, int height) => owner.OnPaint(type, buffer, width, height); - - public void OnCursorChange(nint cursor, CursorType type, CursorInfo customCursorInfo) { } - - public bool StartDragging(IDragData dragData, DragOperationsMask mask, int x, int y) => false; - - public void UpdateDragCursor(DragOperationsMask operation) { } - - public void OnPopupShow(bool show) => owner.OnPopupShow(show); - - public void OnPopupSize(Rect rect) => owner.OnPopupSize(rect); - - public void OnImeCompositionRangeChanged(Range selectedRange, Rect[] characterBounds) { } - - public void OnVirtualKeyboardRequested(IBrowser browser, TextInputMode inputMode) { } - - public void Dispose() { } - } -} diff --git a/HTML.Chromium/ChromiumClient.cs b/HTML.Chromium/ChromiumClient.cs deleted file mode 100644 index b82ecb76b..000000000 --- a/HTML.Chromium/ChromiumClient.cs +++ /dev/null @@ -1,145 +0,0 @@ -using CefSharp; - -using Source.Common.GarrysMod; - -namespace HTML.Chromium; - -public class ChromiumClient : IHtmlClient -{ - readonly ChromiumBrowser Browser; - readonly IHtmlClientListener Listener; - bool Closed; - - public ChromiumClient(ChromiumBrowser browser, IHtmlClientListener listener) { - Browser = browser; - Listener = listener; - ChromiumSystem.g_ChromiumSystem.OnClientOpen(this); - } - - static void PostTask(Action task) => Cef.UIThreadTaskFactory.StartNew(task); - - public void Update() { - MessageQueue messageQueue = Browser.GetMessageQueue(); - - messageQueue.Lock(); - try { - while (!Closed && !messageQueue.Empty()) { - MessageQueue.Message msg = messageQueue.Pop(); - - switch (msg.Type) { - case MessageQueue.Type.OnAddressChange: - Listener.OnAddressChange(msg.String1); - break; - case MessageQueue.Type.OnConsoleMessage: - Listener.OnConsoleMessage(msg.String1, msg.String2, msg.Integer, msg.Integer2); - break; - case MessageQueue.Type.OnTitleChange: - Listener.OnTitleChange(msg.String1); - break; - case MessageQueue.Type.OnCursorChange: - Listener.OnCursorChange((IHtmlClientListener.CursorType)msg.Integer); - break; - case MessageQueue.Type.OnLoadStart: - Listener.OnLoadStart(msg.String1); - break; - case MessageQueue.Type.OnLoadEnd: - Listener.OnDocumentReady(msg.String1); - Listener.OnLoadEnd(msg.String1); - break; - case MessageQueue.Type.OnCreateChildView: - Listener.OnCreateChildView(msg.String1, msg.String2, msg.Integer != 0); - break; - case MessageQueue.Type.OnJavaScriptCall: - HandleJavaScriptCall(msg.String1, msg.String2, msg.JSParams, msg.Integer, msg.FrameId, msg.Nonce); - break; - } - } - } - finally { - messageQueue.Unlock(); - } - } - - void HandleJavaScriptCall(string objName, string funcName, in JSValue paramArray, int callbackId, long frameId, string nonce) { - JSValue retArray = Listener.OnJavaScriptCall(objName, funcName, paramArray); - - if (callbackId == -1) - return; - - PostTask(() => Browser.ExecuteCallback(callbackId, frameId, nonce, retArray)); - } - - public void Close() { - PostTask(Browser.Close); - - ChromiumSystem.g_ChromiumSystem.OnClientClose(this); - Closed = true; - } - - public void SetSize(int wide, int tall) => PostTask(() => Browser.SetSize(wide, tall)); - - public void SetFocused(bool hasFocus) => PostTask(() => Browser.SetFocused(hasFocus)); - - public void SendKeyEvent(IHtmlClient.KeyEvent keyEvent) => PostTask(() => Browser.SendKeyEvent(keyEvent)); - - public void SendMouseMoveEvent(IHtmlClient.MouseEvent mouseEvent, bool mouseLeave) => PostTask(() => Browser.SendMouseMoveEvent(mouseEvent, mouseLeave)); - - public void SendMouseWheelEvent(IHtmlClient.MouseEvent mouseEvent, int deltaX, int deltaY) => PostTask(() => Browser.SendMouseWheelEvent(mouseEvent, deltaX, deltaY)); - - public void SendMouseClickEvent(IHtmlClient.MouseEvent mouseEvent, IHtmlClient.MouseButton mouseButton, bool mouseUp, int clickCount) => PostTask(() => Browser.SendMouseClickEvent(mouseEvent, mouseButton, mouseUp, clickCount)); - - public void LoadUrl(ReadOnlySpan url) { - string str = new(url); - PostTask(() => Browser.LoadUrl(str)); - } - - public void SetHtml(ReadOnlySpan html) { - string str = new(html); - PostTask(() => Browser.SetHtml(str)); - } - - public void Refresh() => PostTask(Browser.Refresh); - - public void Stop() => PostTask(Browser.Stop); - - public void GoBack() => PostTask(Browser.GoBack); - - public void GoForward() => PostTask(Browser.GoForward); - - public void RunJavaScript(ReadOnlySpan code) { - string str = new(code); - PostTask(() => Browser.RunJavaScript(str)); - } - - public void RegisterJavaScriptFunction(ReadOnlySpan objName, ReadOnlySpan funcName) { - string obj = new(objName); - string func = new(funcName); - PostTask(() => Browser.RegisterJavaScriptFunction(obj, func)); - } - - public void SetOpenLinksExternally(bool openLinksExternally) => PostTask(() => Browser.SetOpenLinksExternally(openLinksExternally)); - - public bool LockImageData() { - ImageData imageData = Browser.GetImageData(); - - imageData.Lock(); - - if (!imageData.IsDirty()) { - imageData.Unlock(); - return false; - } - - return true; - } - - public void UnlockImageData() { - ImageData imageData = Browser.GetImageData(); - imageData.SetDirty(false); - imageData.Unlock(); - } - - public ReadOnlySpan GetImageData(out int imageWide, out int imageTall) { - ImageData imageData = Browser.GetImageData(); - return imageData.GetData(out imageWide, out imageTall); - } -} diff --git a/HTML.Chromium/ChromiumSystem.cs b/HTML.Chromium/ChromiumSystem.cs deleted file mode 100644 index a12f0128e..000000000 --- a/HTML.Chromium/ChromiumSystem.cs +++ /dev/null @@ -1,258 +0,0 @@ -using CefSharp; -using CefSharp.Enums; -using CefSharp.OffScreen; - -using ChromiumProcess; - -using Microsoft.Win32.SafeHandles; - -using Source.Common.GarrysMod; - -using System.Runtime.InteropServices; -using System.Security.Cryptography; - -namespace HTML.Chromium; - -public partial class ChromiumSystem : IHtmlSystem -{ - static readonly bool ResolverInstalled = ModuleResolver.Install(); - public static readonly ChromiumSystem g_ChromiumSystem = new(); - public static readonly IHtmlSystem g_pHtmlSystem = g_ChromiumSystem; - - readonly List ActiveClients = []; - - readonly Lock RequestsLock = new(); - List Requests = []; - - public string BridgeSecret { get; private set; } = ""; - public HtmlBridge.RegistryWriter? Registry { get; private set; } - - static void OnBeforeCommandLineProcessing(CefSettings settings) { - settings.CefCommandLineArgs.Add("disable-gpu"); - settings.CefCommandLineArgs.Add("disable-gpu-compositing"); - settings.CefCommandLineArgs.Add("disable-smooth-scrolling"); - settings.CefCommandLineArgs.Add("enable-begin-frame-scheduling"); - settings.CefCommandLineArgs.Add("enable-system-flash"); - - settings.CefCommandLineArgs["disable-features"] = "TouchpadAndWheelScrollLatching,AsyncWheelEvents"; - - settings.CefCommandLineArgs["autoplay-policy"] = "no-user-gesture-required"; - - settings.CefCommandLineArgs["enable-blink-features"] = "HTMLImports"; - - settings.CefCommandLineArgs["disable-site-isolation-trials"] = ""; - } - - static void OnRegisterCustomSchemes(CefSettings settings) { - settings.RegisterScheme(new CefCustomScheme("asset", SchemeOptions.Standard | SchemeOptions.CspBypassing)); - } - - [LibraryImport("kernel32.dll", EntryPoint = "GetFinalPathNameByHandleW", StringMarshalling = StringMarshalling.Utf16)] - private static partial uint GetFinalPathNameByHandle(SafeFileHandle hFile, [Out] char[] lpszFilePath, uint cchFilePath, uint dwFlags); - - static string? GetFinalDirectoryPath(string path) { - try { - using SafeFileHandle handle = Win32CreateDirectoryHandle(path); - if (handle.IsInvalid) - return null; - char[] buffer = new char[260]; - uint length = GetFinalPathNameByHandle(handle, buffer, (uint)buffer.Length, 0); - if (length == 0 || length >= buffer.Length) - return null; - return new string(buffer, 0, (int)length); - } - catch (Exception) { - return null; - } - } - - [LibraryImport("kernel32.dll", EntryPoint = "CreateFileW", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)] - private static partial SafeFileHandle CreateFile(string lpFileName, uint dwDesiredAccess, uint dwShareMode, nint lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, nint hTemplateFile); - - static SafeFileHandle Win32CreateDirectoryHandle(string path) { - const uint GENERIC_READ = 0x80000000; - const uint FILE_SHARE_READ = 0x00000001; - const uint OPEN_EXISTING = 3; - const uint FILE_FLAG_BACKUP_SEMANTICS = 0x02000000; - return CreateFile(path, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0); - } - - public bool Init(ReadOnlySpan pBaseDir, IHtmlResourceHandler resourceHandler) { - ResourceHandler.g_pHtmlResourceHandler = resourceHandler; - - CefSettings settings = new(); - settings.EnableAudio(); - - string strBaseDir = new(pBaseDir); - string moduleDir = Path.GetDirectoryName(typeof(ChromiumSystem).Assembly.Location)!; - string strChromiumDir = moduleDir; - - settings.RemoteDebuggingPort = 0; - settings.WindowlessRenderingEnabled = true; - settings.CommandLineArgsDisabled = true; - settings.LogSeverity = LogSeverity.Default; - - bool useTempDir = false; - - string? finalBaseDir = GetFinalDirectoryPath(strBaseDir); - if (finalBaseDir != null) { - if (finalBaseDir.StartsWith(@"\\?\UNC", StringComparison.Ordinal)) - useTempDir = true; - else - strBaseDir = finalBaseDir[4..]; - } - - string? finalChromiumDir = GetFinalDirectoryPath(strChromiumDir); - if (finalChromiumDir != null) { - if (finalChromiumDir.StartsWith(@"\\?\UNC", StringComparison.Ordinal)) - useTempDir = true; - else - strChromiumDir = finalChromiumDir[4..]; - } - - string chromiumDir = strChromiumDir; - - if (useTempDir) { - resourceHandler.Message("Copying Chromium resources to temporary directory...\n"); - - try { - string targetPath = Path.Combine(Path.GetTempPath(), "gmod-resources"); - Directory.CreateDirectory(targetPath); - - foreach (string file in Directory.EnumerateFiles(strChromiumDir, "*.pak")) - File.Copy(file, Path.Combine(targetPath, Path.GetFileName(file)), true); - - string locales = Path.Combine(strChromiumDir, "locales"); - string targetLocales = Path.Combine(targetPath, "locales"); - Directory.CreateDirectory(targetLocales); - foreach (string file in Directory.EnumerateFiles(locales)) - File.Copy(file, Path.Combine(targetLocales, Path.GetFileName(file)), true); - - chromiumDir = targetPath; - } - catch (Exception) { - return false; - } - } - - settings.UserAgent = "Mozilla/5.0 (Windows NT; Valve Source Client) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36 GMod/13"; - - settings.ResourcesDirPath = chromiumDir; - settings.LocalesDirPath = Path.Combine(chromiumDir, "locales"); - - settings.MultiThreadedMessageLoop = true; - - settings.LogFile = Path.Combine(strBaseDir, "chromium.log"); - - settings.BrowserSubprocessPath = Path.Combine(moduleDir, "ChromiumProcess.exe"); - - OnBeforeCommandLineProcessing(settings); - OnRegisterCustomSchemes(settings); - - BridgeSecret = Convert.ToHexString(RandomNumberGenerator.GetBytes(8)); - Environment.SetEnvironmentVariable(HtmlBridge.SecretVariable, BridgeSecret); - try { - Registry = new HtmlBridge.RegistryWriter(BridgeSecret); - } - catch (Exception) { - return false; - } - - CefSharpSettings.ShutdownOnExit = false; - - try { - if (!Cef.Initialize(settings, performDependencyCheck: false, browserProcessHandler: null)) - return false; - } - catch (Exception e) { - resourceHandler.Message($"Chromium failed to initialize: {e.Message}\n"); - return false; - } - - { - ResourceHandlerFactory factory = new(); - IRequestContext context = Cef.GetGlobalRequestContext(); - - context.RegisterSchemeHandlerFactory("asset", "garrysmod", factory); - Cef.AddCrossOriginWhitelistEntry("asset://garrysmod", "http", "", true); - Cef.AddCrossOriginWhitelistEntry("asset://garrysmod", "https", "", true); - Cef.AddCrossOriginWhitelistEntry("asset://garrysmod", "asset", "", true); - - context.RegisterSchemeHandlerFactory("asset", "mapimage", factory); - Cef.AddCrossOriginWhitelistEntry("asset://mapimage", "http", "", true); - Cef.AddCrossOriginWhitelistEntry("asset://mapimage", "https", "", true); - Cef.AddCrossOriginWhitelistEntry("asset://mapimage", "asset", "", true); - } - - { - HtmlResourceHandlerFactory factory = new(); - IRequestContext context = Cef.GetGlobalRequestContext(); - - context.RegisterSchemeHandlerFactory("asset", "html", factory); - Cef.AddCrossOriginWhitelistEntry("asset://html", "http", "", true); - Cef.AddCrossOriginWhitelistEntry("asset://html", "https", "", true); - Cef.AddCrossOriginWhitelistEntry("asset://html", "asset", "", true); - } - - return true; - } - - public void Shutdown() { - Cef.Shutdown(); - Registry?.Dispose(); - Registry = null; - } - - public IHtmlClient CreateClient(IHtmlClientListener listener) { - BrowserSettings browserSettings = new() { - DefaultEncoding = "UTF-8", - WindowlessFrameRate = 60, - JavascriptAccessClipboard = CefState.Disabled, - JavascriptCloseWindows = CefState.Disabled, - UniversalAccessFromFileUrls = CefState.Disabled, - FileAccessFromFileUrls = CefState.Disabled, - WebGl = CefState.Disabled - }; - - ChromiumBrowser cefClient = new(BridgeSecret, Registry); - - cefClient.CreateBrowser(browserSettings); - - return new ChromiumClient(cefClient, listener); - } - - public void Update() { - List requests; - lock (RequestsLock) { - requests = Requests; - Requests = []; - } - - foreach (ResourceHandler request in requests) - request.Handle(); - - foreach (ChromiumClient client in ActiveClients.ToArray()) - client.Update(); - } - - public void OnClientOpen(ChromiumClient client) => ActiveClients.Add(client); - public void OnClientClose(ChromiumClient client) => ActiveClients.Remove(client); - - public void QueueRequest(ResourceHandler resourceHandler) { - lock (RequestsLock) - Requests.Add(resourceHandler); - } - - public JSValue CreateArray(ReadOnlySpan values) => JSArray.Create(values.ToArray()); - - public JSValue CreateString(ReadOnlySpan value) => JSString.Create(new string(value)); - - public JSValue CreateHashMap(ReadOnlySpan keys, ReadOnlySpan values) { - Dictionary container = new(keys.Length); - - for (int i = 0; i < keys.Length; i++) - container[keys[i]] = values[i]; - - return JSHashMap.Create(container); - } -} diff --git a/HTML.Chromium/HTML.Chromium.csproj b/HTML.Chromium/HTML.Chromium.csproj deleted file mode 100644 index de31af24d..000000000 --- a/HTML.Chromium/HTML.Chromium.csproj +++ /dev/null @@ -1,32 +0,0 @@ - - - - net10.0 - enable - enable - Debug;Release;Debug (Dedicated);Release (Dedicated) - win-x64 - false - false - $(MSBuildThisFileDirectory)..\Build\$(Configuration)\cefsharp\ - true - true - - - - - - - - - - - - - - - false - - - - diff --git a/HTML.Chromium/HtmlResourceHandler.cs b/HTML.Chromium/HtmlResourceHandler.cs deleted file mode 100644 index e82255b45..000000000 --- a/HTML.Chromium/HtmlResourceHandler.cs +++ /dev/null @@ -1,72 +0,0 @@ -using CefSharp; -using CefSharp.Callback; - -using System.Collections.Specialized; - -namespace HTML.Chromium; - -public sealed class HtmlResourceHandlerFactory : ISchemeHandlerFactory -{ - public IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request) => new HtmlResourceHandler(); -} - -public sealed class HtmlResourceHandler : IResourceHandler -{ - byte[] Html = []; - int Current; - - public bool Open(IRequest request, out bool handleRequest, ICallback callback) { - handleRequest = true; - Current = 0; - - if (!Uri.TryCreate(request.Url, UriKind.Absolute, out Uri? url)) - return false; - - string encodedHtml = url.Query.StartsWith('?') ? url.Query[1..] : url.Query; - byte[] data = new byte[encodedHtml.Length]; - if (Convert.TryFromBase64String(encodedHtml, data, out int written)) - Html = data[..written]; - - return true; - } - - public bool ProcessRequest(IRequest request, ICallback callback) => false; - - public void GetResponseHeaders(IResponse response, out long responseLength, out string redirectUrl) { - redirectUrl = null!; - - response.StatusCode = 200; - response.Headers = new NameValueCollection { { "X-XSS-Protection", "0" } }; - response.MimeType = "text/html"; - responseLength = Html.Length; - } - - public bool Skip(long bytesToSkip, out long bytesSkipped, IResourceSkipCallback callback) { - bytesSkipped = -2; - return false; - } - - public bool Read(Stream dataOut, out int bytesRead, IResourceReadCallback callback) { - bytesRead = 0; - if (Html.Length <= 0) - return false; - - int bytesToRead = (int)Math.Min(dataOut.Length, Html.Length - Current); - bytesToRead = Math.Max(bytesToRead, 0); - - dataOut.Write(Html, Current, bytesToRead); - bytesRead = bytesToRead; - Current += bytesToRead; - - return bytesToRead > 0; - } - - public bool ReadResponse(Stream dataOut, out int bytesRead, ICallback callback) { - bytesRead = 0; - return false; - } - - public void Cancel() { } - - public void Dispose() { } -} diff --git a/HTML.Chromium/ImageData.cs b/HTML.Chromium/ImageData.cs deleted file mode 100644 index aedb07203..000000000 --- a/HTML.Chromium/ImageData.cs +++ /dev/null @@ -1,59 +0,0 @@ -using System.Runtime.InteropServices; - -namespace HTML.Chromium; - -public class ImageData -{ - readonly Lock Mutex = new(); - bool Dirty; - int Wide; - int Tall; - byte[]? Data; - - public void Lock() => Mutex.Enter(); - public void Unlock() => Mutex.Exit(); - - public void SetData(nint data, int wide, int tall) { - int bufSize = wide * tall * 4; - - if (Wide != wide || Tall != tall || Data == null) - Data = new byte[bufSize]; - - Marshal.Copy(data, Data, 0, bufSize); - Wide = wide; - Tall = tall; - Dirty = true; - } - - public void CopyImage(byte[]? data, int x, int y, int w, int h) { - if (w < 0 || h < 0 || data == null || Data == null) - return; - - int dstX = Math.Max(0, x); - int dstY = Math.Max(0, y); - int srcX = Math.Max(0, -x); - int srcY = Math.Max(0, -y); - - int copyW = Math.Min(w - srcX, Wide - dstX); - int copyH = Math.Min(h - srcY, Tall - dstY); - - if (copyW > 0 && copyH > 0) { - for (int row = 0; row < copyH; ++row) { - int dstOffset = ((dstY + row) * Wide + dstX) * 4; - int srcOffset = ((srcY + row) * w + srcX) * 4; - Buffer.BlockCopy(data, srcOffset, Data, dstOffset, copyW * 4); - } - - Dirty = true; - } - } - - public ReadOnlySpan GetData(out int wide, out int tall) { - wide = Wide; - tall = Tall; - return Data; - } - - public bool IsDirty() => Dirty; - public void SetDirty(bool dirty) => Dirty = dirty; -} diff --git a/HTML.Chromium/JSObjects.cs b/HTML.Chromium/JSObjects.cs deleted file mode 100644 index d6a1904b6..000000000 --- a/HTML.Chromium/JSObjects.cs +++ /dev/null @@ -1,57 +0,0 @@ -using Source.Common.GarrysMod; - -namespace HTML.Chromium; - -public sealed class JSArray : JSValue.IArray -{ - readonly JSValue[] Data; - - JSArray(JSValue[] data) => Data = data; - - public ReadOnlySpan GetData() => Data; - public JSValue[] GetInternalData() => Data; - - public static JSValue Create(JSValue[] data) => new(new JSArray(data)); -} - -public sealed class JSString : JSValue.IString -{ - readonly string Data; - - JSString(string data) => Data = data; - - public ReadOnlySpan GetData() => Data; - public string GetInternalData() => Data; - - public static JSValue Create(string data) => new(new JSString(data)); -} - -public sealed class JSHashMap : JSValue.IHashMap -{ - readonly Dictionary Data; - Dictionary.Enumerator Iterator; - - JSHashMap(Dictionary data) => Data = data; - - public bool Begin(out ReadOnlySpan key, out JSValue value) { - Iterator = Data.GetEnumerator(); - return Next(out key, out value); - } - - public bool Next(out ReadOnlySpan key, out JSValue value) { - if (!Iterator.MoveNext()) { - key = default; - value = default; - return false; - } - - key = Iterator.Current.Key; - value = Iterator.Current.Value; - return true; - } - - public int Size() => Data.Count; - public Dictionary GetInternalData() => Data; - - public static JSValue Create(Dictionary data) => new(new JSHashMap(data)); -} diff --git a/HTML.Chromium/MessageQueue.cs b/HTML.Chromium/MessageQueue.cs deleted file mode 100644 index c8297e595..000000000 --- a/HTML.Chromium/MessageQueue.cs +++ /dev/null @@ -1,39 +0,0 @@ -using Source.Common.GarrysMod; - -namespace HTML.Chromium; - -public class MessageQueue -{ - public enum Type - { - OnAddressChange, - OnConsoleMessage, - OnTitleChange, - OnCursorChange, - OnLoadStart, - OnLoadEnd, - OnCreateChildView, - OnJavaScriptCall - } - - public struct Message - { - public Type Type; - public int Integer; - public int Integer2; - public long FrameId; - public string Nonce; - public string String1; - public string String2; - public JSValue JSParams; - } - - readonly Lock Mutex = new(); - readonly Queue Messages = new(); - - public void Lock() => Mutex.Enter(); - public void Unlock() => Mutex.Exit(); - public void Push(in Message message) => Messages.Enqueue(message); - public bool Empty() => Messages.Count == 0; - public Message Pop() => Messages.Dequeue(); -} diff --git a/HTML.Chromium/ModuleResolver.cs b/HTML.Chromium/ModuleResolver.cs deleted file mode 100644 index 5b146585b..000000000 --- a/HTML.Chromium/ModuleResolver.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Runtime.Loader; - -namespace HTML.Chromium; - -static class ModuleResolver -{ - public static bool Install() { - string moduleDir = Path.GetDirectoryName(typeof(ModuleResolver).Assembly.Location)!; - AssemblyLoadContext.Default.Resolving += (context, name) => { - string path = Path.Combine(moduleDir, $"{name.Name}.dll"); - return File.Exists(path) ? context.LoadFromAssemblyPath(path) : null; - }; - return true; - } -} diff --git a/HTML.Chromium/ResourceHandler.cs b/HTML.Chromium/ResourceHandler.cs deleted file mode 100644 index 41c86ae80..000000000 --- a/HTML.Chromium/ResourceHandler.cs +++ /dev/null @@ -1,145 +0,0 @@ -using CefSharp; -using CefSharp.Callback; - -using Source.Common.GarrysMod; - -using System.Text; - -namespace HTML.Chromium; - -public sealed class ResourceHandlerFactory : ISchemeHandlerFactory -{ - public IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request) => new ResourceHandler(); -} - -public sealed class ResourceHandler : IResourceHandler -{ - public static IHtmlResourceHandler? g_pHtmlResourceHandler; - - string Host = ""; - string Path = ""; - ICallback? ResponseCallback; - - byte[]? Buffer; - int BufferPtr; - - public void Handle() { - HtmlResource? resource = g_pHtmlResourceHandler!.OpenResource(Host, Path); - - if (resource != null) { - long size = g_pHtmlResourceHandler.GetLength(resource); - Buffer = new byte[size]; - BufferPtr = 0; - - g_pHtmlResourceHandler.ReadData(resource, Buffer); - g_pHtmlResourceHandler.CloseResource(resource); - } - - if (ResponseCallback != null && !ResponseCallback.IsDisposed) - ResponseCallback.Continue(); - } - - public bool Open(IRequest request, out bool handleRequest, ICallback callback) { - handleRequest = true; - - if (!Uri.TryCreate(request.Url, UriKind.Absolute, out Uri? url)) - return false; - - Host = url.Host; - Path = URIDecode(url.AbsolutePath); - - handleRequest = false; - ResponseCallback = callback; - ChromiumSystem.g_ChromiumSystem.QueueRequest(this); - - return true; - } - - public bool ProcessRequest(IRequest request, ICallback callback) => false; - - static string GetFileExtension(string path) { - int i = path.LastIndexOf('.'); - if (i == -1) - return ""; - return path[(i + 1)..]; - } - - public void GetResponseHeaders(IResponse response, out long responseLength, out string redirectUrl) { - redirectUrl = null!; - - if (Buffer == null) { - responseLength = 0; - response.ErrorCode = CefErrorCode.FileNotFound; - return; - } - - string mimeType = "text/html"; - - string ext = GetFileExtension(Path); - if (ext == "png" || Host == "mapimage") mimeType = "image/png"; - else if (ext == "jpg") mimeType = "image/jpg"; - else if (ext == "jpeg") mimeType = "image/jpg"; - else if (ext == "css") mimeType = "text/css"; - else if (ext == "js") mimeType = "text/javascript"; - else if (ext == "svg") mimeType = "image/svg+xml"; - else if (ext == "gif") mimeType = "image/gif"; - else if (ext == "webm") mimeType = "video/webm"; - else if (ext == "mp4") mimeType = "video/mp4"; - - response.StatusCode = 200; - response.MimeType = mimeType; - responseLength = Buffer.Length; - } - - public bool Skip(long bytesToSkip, out long bytesSkipped, IResourceSkipCallback callback) { - bytesSkipped = -2; - return false; - } - - public bool Read(Stream dataOut, out int bytesRead, IResourceReadCallback callback) { - int bytesToRead = (int)Math.Min(dataOut.Length, (Buffer?.Length ?? 0) - BufferPtr); - bytesToRead = Math.Max(bytesToRead, 0); - - if (bytesToRead > 0) { - dataOut.Write(Buffer!, BufferPtr, bytesToRead); - BufferPtr += bytesToRead; - } - bytesRead = bytesToRead; - - if (bytesToRead == 0) - Buffer = null; - - return bytesToRead > 0; - } - - public bool ReadResponse(Stream dataOut, out int bytesRead, ICallback callback) { - bytesRead = 0; - return false; - } - - public void Cancel() { } - - public void Dispose() { } - - static string URIDecode(string encoded) { - byte[] source = Encoding.UTF8.GetBytes(encoded); - List bytes = new(source.Length); - for (int i = 0; i < source.Length; i++) { - byte c = source[i]; - if (c == '%' && i + 2 < source.Length && IsHex(source[i + 1]) && IsHex(source[i + 2])) { - int value = (HexValue(source[i + 1]) << 4) | HexValue(source[i + 2]); - if (value >= 0x20 && value != 0x7F && value != '/' && value != '\\') { - bytes.Add((byte)value); - i += 2; - continue; - } - } - - bytes.Add(c); - } - return Encoding.UTF8.GetString(bytes.ToArray()); - } - - static bool IsHex(byte c) => c is (>= (byte)'0' and <= (byte)'9') or (>= (byte)'a' and <= (byte)'f') or (>= (byte)'A' and <= (byte)'F'); - static int HexValue(byte c) => c <= '9' ? c - '0' : (c | 0x20) - 'a' + 10; -} diff --git a/Source.NET.slnx b/Source.NET.slnx index 93a2a6307..3b030d3ed 100644 --- a/Source.NET.slnx +++ b/Source.NET.slnx @@ -113,15 +113,9 @@ - - - - - - From 98c20bad0334c69520671df3b4b30507d91fd872 Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Thu, 15 Oct 2026 15:27:55 -0700 Subject: [PATCH 30/38] Separate native launcher for win/linux --- Dependencies/CEF | 2 +- Source.Launcher.Native/CMakeLists.txt | 7 ++++++- Source.Launcher.Native/Source.Launcher.Native.targets | 3 ++- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/Dependencies/CEF b/Dependencies/CEF index c82a98d46..c1194733f 160000 --- a/Dependencies/CEF +++ b/Dependencies/CEF @@ -1 +1 @@ -Subproject commit c82a98d46de8301ccdbb69d9e58fb8ac279c7395 +Subproject commit c1194733f6f36d52e3b4ee3152fe2db74cd85a2b diff --git a/Source.Launcher.Native/CMakeLists.txt b/Source.Launcher.Native/CMakeLists.txt index 54f802aa3..f9f04fb88 100644 --- a/Source.Launcher.Native/CMakeLists.txt +++ b/Source.Launcher.Native/CMakeLists.txt @@ -2,7 +2,12 @@ cmake_minimum_required(VERSION 3.21) project(SourceLauncherNative CXX) -set(CEF_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../Dependencies/CEF/154.0.34" CACHE PATH "CEF binary distribution root") +if(WIN32) + set(SN_CEF_PLATFORM windows64) +else() + set(SN_CEF_PLATFORM linux64) +endif() +set(CEF_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../Dependencies/CEF/154.0.34/${SN_CEF_PLATFORM}" CACHE PATH "CEF binary distribution root") list(APPEND CMAKE_MODULE_PATH "${CEF_ROOT}/cmake") find_package(CEF REQUIRED) diff --git a/Source.Launcher.Native/Source.Launcher.Native.targets b/Source.Launcher.Native/Source.Launcher.Native.targets index 0f8365bb9..6d5d9ea6b 100644 --- a/Source.Launcher.Native/Source.Launcher.Native.targets +++ b/Source.Launcher.Native/Source.Launcher.Native.targets @@ -4,7 +4,8 @@ 154.0.34 $(MSBuildThisFileDirectory) $(MSBuildProjectDirectory)\obj\native\ - $(MSBuildThisFileDirectory)..\Dependencies\CEF\$(SNCefVersion)\ + $(MSBuildThisFileDirectory)..\Dependencies\CEF\$(SNCefVersion)\windows64\ + $(MSBuildThisFileDirectory)../Dependencies/CEF/$(SNCefVersion)/linux64/ $(NetCoreTargetingPackRoot)\Microsoft.NETCore.App.Host.win-x64\$(BundledNETCoreAppPackageVersion)\runtimes\win-x64\native\ $(NuGetPackageRoot)cef.runtime.linux-x64\$(SNCefVersion)\CEF\linux-x64\ From 14a59aeb7f26bd1196c49eba9a510305541a3de5 Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Thu, 15 Oct 2026 15:33:45 -0700 Subject: [PATCH 31/38] IsEntity should not be menu-only --- Game.Shared/GarrysMod/LuaGlobalFunctions.cs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/Game.Shared/GarrysMod/LuaGlobalFunctions.cs b/Game.Shared/GarrysMod/LuaGlobalFunctions.cs index 8ce16405e..a6a250904 100644 --- a/Game.Shared/GarrysMod/LuaGlobalFunctions.cs +++ b/Game.Shared/GarrysMod/LuaGlobalFunctions.cs @@ -663,10 +663,7 @@ static int IsType(LuaType type) { [LuaGlobal] static int isstring(ILuaInterface lua) => IsType(LuaType.String); [LuaGlobal] static int istable(ILuaInterface lua) => IsType(LuaType.Table); [LuaGlobal] static int isfunction(ILuaInterface lua) => IsType(LuaType.Function); -#if MENU_DLL - [LuaGlobal("IsEntity")] -#endif - [LuaGlobal] static int isentity(ILuaInterface lua) => IsType(LuaType.Entity); + [LuaGlobal("IsEntity")][LuaGlobal] static int isentity(ILuaInterface lua) => IsType(LuaType.Entity); [LuaGlobal] static int isvector(ILuaInterface lua) => IsType(LuaType.Vector); [LuaGlobal] static int isangle(ILuaInterface lua) => IsType(LuaType.Angle); [LuaGlobal] static int ispanel(ILuaInterface lua) => IsType(LuaType.Panel); From bf564e71b91ac72eaa6d05fd6e7c691ad4c4e1bb Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Thu, 15 Oct 2026 16:25:37 -0700 Subject: [PATCH 32/38] attempt to fix linux cmake --- Source.Launcher.Native/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source.Launcher.Native/CMakeLists.txt b/Source.Launcher.Native/CMakeLists.txt index f9f04fb88..ca007fecc 100644 --- a/Source.Launcher.Native/CMakeLists.txt +++ b/Source.Launcher.Native/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required(VERSION 3.21) -project(SourceLauncherNative CXX) +project(SourceLauncherNative C CXX) if(WIN32) set(SN_CEF_PLATFORM windows64) From fb7cfd729d7599f245a829e5d27f8548bd910991 Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Thu, 15 Oct 2026 16:34:26 -0700 Subject: [PATCH 33/38] Fix Loading... not showing up --- Source.Engine/SysModes.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Source.Engine/SysModes.cs b/Source.Engine/SysModes.cs index 5d7b028f7..4441937ad 100644 --- a/Source.Engine/SysModes.cs +++ b/Source.Engine/SysModes.cs @@ -226,6 +226,12 @@ public void DrawStartupGraphic() { // I guess it just sets it to 1, 1, 1 but still, need to review how we'd even replicate tone mapping float depth = 0.5f; +#if !SWDS + renderUtils.DrawScreenSpaceRectangle(material, 0, 0, w, h, 0, 0, tw - 1, th - 1, tw, th, null, 1, 1, depth); + renderUtils.DrawScreenSpaceRectangle(loadingMaterial, w - lw, h - lh, lw, lh, 0, 0, lw - 1, lh - 1, lw, lh, null, 1, 1, depth); + Singleton().WaitForPendingCompiles(null); +#endif + for (int i = 0; i < 2; i++) { renderContext.ClearColor3ub(0, 0, 0); renderContext.ClearBuffers(true, true, true); From 4c0e0055931bc978ed12f3bde9005385523b8183 Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Thu, 15 Oct 2026 17:06:32 -0700 Subject: [PATCH 34/38] fc-match fixes, hopefully --- Source.SDLSystem/SDL3_System.cs | 58 +++++++++++++++++++++------------ 1 file changed, 38 insertions(+), 20 deletions(-) diff --git a/Source.SDLSystem/SDL3_System.cs b/Source.SDLSystem/SDL3_System.cs index 9031ad1ef..181217d2b 100644 --- a/Source.SDLSystem/SDL3_System.cs +++ b/Source.SDLSystem/SDL3_System.cs @@ -225,30 +225,48 @@ public ReadOnlySpan GetSystemFontPath(ReadOnlySpan fontName, int wei } #pragma warning restore CA1416 // Validate platform compatibility #elif LINUX + const string FontConfig = "libfontconfig.so.1"; + const int FcMatchPattern = 0; + const int FcResultMatch = 0; + + [DllImport(FontConfig)] static extern nint FcNameParse(byte* name); + [DllImport(FontConfig)] static extern int FcConfigSubstitute(nint config, nint pattern, int kind); + [DllImport(FontConfig)] static extern void FcDefaultSubstitute(nint pattern); + [DllImport(FontConfig)] static extern nint FcFontMatch(nint config, nint pattern, out int result); + [DllImport(FontConfig)] static extern int FcPatternGetString(nint pattern, byte* obj, int n, out byte* value); + [DllImport(FontConfig)] static extern void FcPatternDestroy(nint pattern); + public ReadOnlySpan GetSystemFontPath(ReadOnlySpan fontName, int weight = 0, bool italic = false) { try { - var processStartInfo = new System.Diagnostics.ProcessStartInfo { - FileName = "fc-match", - RedirectStandardOutput = true, - UseShellExecute = false, - CreateNoWindow = true - }; - - // Use ArgumentList to escape fontName - processStartInfo.ArgumentList.Add("--format=%{file}"); - processStartInfo.ArgumentList.Add("--"); // Ensure user can't inject options - processStartInfo.ArgumentList.Add(new string(fontName)); - - using var process = System.Diagnostics.Process.Start(processStartInfo); - if (process != null) { - string output = process.StandardOutput.ReadToEnd(); - process.WaitForExit(); - - if (process.ExitCode == 0 && !string.IsNullOrWhiteSpace(output)) { - return output.Trim(); + byte[] name = Encoding.UTF8.GetBytes(new string(fontName) + '\0'); + nint pattern; + fixed (byte* pName = name) + pattern = FcNameParse(pName); + if (pattern == 0) + return null; + + try { + FcConfigSubstitute(0, pattern, FcMatchPattern); + FcDefaultSubstitute(pattern); + + nint match = FcFontMatch(0, pattern, out int result); + if (match == 0) + return null; + + try { + fixed (byte* pFile = "file"u8) + if (result == FcResultMatch && FcPatternGetString(match, pFile, 0, out byte* file) == FcResultMatch && file != null) + return Marshal.PtrToStringUTF8((nint)file); + } + finally { + FcPatternDestroy(match); } } - } catch(Exception ex) { + finally { + FcPatternDestroy(pattern); + } + } + catch (Exception ex) { Assert($"GetSystemFontPath: {ex.Message}"); } From fac7347996fb8da39ceac3a2c2fd80fe28615a65 Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Thu, 15 Oct 2026 17:06:46 -0700 Subject: [PATCH 35/38] Better linux handling for Get (previously using \) --- Source.Engine/GarrysMod/Get.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Source.Engine/GarrysMod/Get.cs b/Source.Engine/GarrysMod/Get.cs index 5f9578b95..309797065 100644 --- a/Source.Engine/GarrysMod/Get.cs +++ b/Source.Engine/GarrysMod/Get.cs @@ -40,7 +40,7 @@ public class Get(IServiceProvider appSystemFactory, EngineParms host_parms) : IG public void OnLoadFailed(ReadOnlySpan module) { strcpy(gameDir, host_parms.BaseDir); - FixSlashes(gameDir, '\\'); + FixSlashes(gameDir, Path.DirectorySeparatorChar); if (!IsDedicatedServer() && HasSteamClient()) SteamApps.MarkContentCorrupt(false); @@ -50,7 +50,7 @@ public void OnLoadFailed(ReadOnlySpan module) { return; } - string path = $"{GameDir()}\\{module}".Replace('/', '\\'); + string path = Path.Combine(new string(GameDir()), new string(module)); string reason = "unknown"; try { NativeLibrary.Load(path); @@ -163,9 +163,9 @@ public void Initialize(IFileSystem fileSystem) { } strcpy(gameDir, Common.Gamedir); - FixSlashes(gameDir, '\\'); + FixSlashes(gameDir, Path.DirectorySeparatorChar); strcpy(gameDirParent, Common.Gamedir); - FixSlashes(gameDirParent, '\\'); + FixSlashes(gameDirParent, Path.DirectorySeparatorChar); StripLastDir(gameDirParent); } From 03ebf4e69f08cafb60080b400976982f313282f4 Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Thu, 15 Oct 2026 17:07:05 -0700 Subject: [PATCH 36/38] Preload SQLite on linux --- Game.Shared/GarrysMod/LuaSql.cs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Game.Shared/GarrysMod/LuaSql.cs b/Game.Shared/GarrysMod/LuaSql.cs index ae3483345..76a3250ca 100644 --- a/Game.Shared/GarrysMod/LuaSql.cs +++ b/Game.Shared/GarrysMod/LuaSql.cs @@ -3,6 +3,8 @@ using SQLitePCL; +using System.Runtime.InteropServices; + #if CLIENT_DLL namespace Game.Client.GarrysMod; #elif MENU_DLL @@ -31,7 +33,26 @@ static int DBCallback(object user_data, string[] values, string[] names) { return 0; } + const int RTLD_NOW = 0x2; + const int RTLD_DEEPBIND = 0x8; + + [LibraryImport("libc", EntryPoint = "dlopen", StringMarshalling = StringMarshalling.Utf8)] + private static partial nint dlopen(string fileName, int flags); + + // libcef dlopens GTK into the global scope, which drags in the system libsqlite3. e_sqlite3 calls its own exported + // API through the PLT, so without deep binding those calls resolve to the system copy, e_sqlite3 never initializes + // and its first allocation jumps to a null function pointer. Load it ourselves first so .NET reuses this handle. + static void PreloadSQLite() { + if (!OperatingSystem.IsLinux()) + return; + + string path = Path.Combine(AppContext.BaseDirectory, "runtimes", $"linux-{RuntimeInformation.ProcessArchitecture.ToString().ToLowerInvariant()}", "native", "libe_sqlite3.so"); + if (File.Exists(path)) + dlopen(path, RTLD_NOW | RTLD_DEEPBIND); + } + static void CreateDatabase() { + PreloadSQLite(); Batteries_V2.Init(); #if CLIENT_DLL From 6019c26a348acd7f45f1aad12a9d74e67f16fce3 Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Thu, 15 Oct 2026 17:18:53 -0700 Subject: [PATCH 37/38] lock native parallel count --- Source.Launcher.Native/Source.Launcher.Native.targets | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source.Launcher.Native/Source.Launcher.Native.targets b/Source.Launcher.Native/Source.Launcher.Native.targets index 6d5d9ea6b..c839e1d79 100644 --- a/Source.Launcher.Native/Source.Launcher.Native.targets +++ b/Source.Launcher.Native/Source.Launcher.Native.targets @@ -46,7 +46,7 @@ Inputs="@(SNNativeInput)" Outputs="$(SNNativeBuildDir)Source.Launcher.CEF"> - + From cb99621c5b0263849101387d624781e7552de9ea Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Thu, 15 Oct 2026 18:03:21 -0700 Subject: [PATCH 38/38] Try fixing the CI... again... --- Source.Launcher.Native/CMakeLists.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Source.Launcher.Native/CMakeLists.txt b/Source.Launcher.Native/CMakeLists.txt index ca007fecc..e14057ce2 100644 --- a/Source.Launcher.Native/CMakeLists.txt +++ b/Source.Launcher.Native/CMakeLists.txt @@ -41,7 +41,8 @@ elseif(OS_LINUX) add_dependencies(Source.Launcher.CEF libcef_dll_wrapper) ADD_LOGICAL_TARGET("libcef_lib" "${CEF_LIBCEF_SO}" "${CEF_LIBCEF_SO}") - target_link_libraries(Source.Launcher.CEF libcef_lib libcef_dll_wrapper ${CEF_STANDARD_LIBS}) + # CEF_STANDARD_LIBS is just X11 on Linux, which only CEF's sample apps use. Skipping it avoids needing libx11-dev to build. + target_link_libraries(Source.Launcher.CEF libcef_lib libcef_dll_wrapper) set_target_properties(Source.Launcher.CEF PROPERTIES BUILD_RPATH "\$ORIGIN" INSTALL_RPATH "\$ORIGIN") else() message(FATAL_ERROR "Source.Launcher.Native supports Windows and Linux only")