CrabUI
Loading...
Searching...
No Matches
CUILuaRegistrar.cs
1#define USELUA
2
3using System;
4using System.Collections.Generic;
5using System.Linq;
6using System.Reflection;
7using System.Diagnostics;
8using System.Runtime.CompilerServices;
9using System.IO;
10
11using Barotrauma;
12using Microsoft.Xna.Framework;
13using Microsoft.Xna.Framework.Input;
14using Microsoft.Xna.Framework.Graphics;
15using HarmonyLib;
16using MoonSharp.Interpreter;
17
18namespace CrabUI
19{
20 public class CUIInternalAttribute : System.Attribute { }
21 [CUIInternal]
22 public class CUILuaRegistrar
23 {
24 public static string CUITypesFile => Path.Combine(CUI.LuaFolder, "CUITypes.lua");
25
26 public static bool IsRealCUIType(Type T)
27 {
28 if (T.DeclaringType != null) return false; // nested type
29 if (T.Name == "<>c") return false; // guh
30 if (T.IsGenericType) return false; // in lua?
31 if (T.IsInterface) return false;
32 if (T.IsSubclassOf(typeof(Attribute))) return false;
33 if (Attribute.IsDefined(T, typeof(CUIInternalAttribute))) return false;
34 if (typeof(CUILuaRegistrar).Namespace != T.Namespace) return false;
35 return true;
36 }
37
38
39
40#if !USELUA
41 [Conditional("DONT")]
42#endif
43 public void Register()
44 {
45 if (CUI.LuaFolder == null) return;
46 if (!Directory.Exists(CUI.LuaFolder) || !CUI.UseLua) return;
47
48 Assembly thisAssembly = Assembly.GetAssembly(typeof(CUILuaRegistrar));
49
50 foreach (Type T in thisAssembly.GetTypes().Where(IsRealCUIType))
51 {
52 LuaUserData.RegisterType(T.FullName);
53 // This has to be done in lua
54 //GameMain.LuaCs.Lua.Globals[T.Name] = UserData.CreateStatic(T);
55 }
56
57 GameMain.LuaCs.RegisterAction<CUIInput>();
58 GameMain.LuaCs.RegisterAction<float, float>();
59 GameMain.LuaCs.RegisterAction<TextInputEventArgs>();
60 GameMain.LuaCs.RegisterAction<string>();
61 GameMain.LuaCs.RegisterAction<CUIComponent>();
62 GameMain.LuaCs.RegisterAction<bool>();
63 GameMain.LuaCs.RegisterAction<CUIComponent, int>();
64
65
66 LuaUserData.RegisterType(typeof(CUI).FullName);
67 GameMain.LuaCs.Lua.Globals[nameof(CUI)] = UserData.CreateStatic(typeof(CUI));
68
69 ConstructLuaStaticsFile();
70 }
71
72#if !USELUA
73 [Conditional("DONT")]
74#endif
75 public void Deregister()
76 {
77 try
78 {
79 GameMain.LuaCs.Lua.Globals[nameof(CUI)] = null;
80 }
81 catch (Exception e)
82 {
83 CUI.Error(e);
84 }
85 }
86
87 public void ConstructLuaStaticsFile()
88 {
89 if (!Directory.Exists(CUI.LuaFolder)) return;
90
91 Assembly thisAssembly = Assembly.GetAssembly(typeof(CUILuaRegistrar));
92
93 string content = "-- This file is autogenerated\n";
94
95 foreach (Type T in thisAssembly.GetTypes().Where(IsRealCUIType))
96 {
97 content += $"{T.Name} = LuaUserData.CreateStatic('{T.FullName}', true)\n";
98 }
99
100 using (StreamWriter writer = new StreamWriter(CUITypesFile, false))
101 {
102 writer.Write(content);
103 }
104 }
105 }
106}