Files
RAGECOOP-V/RageCoop.Client/Scripting/ResourceDomain.cs

219 lines
8.4 KiB
C#
Raw Normal View History

2022-10-09 22:07:52 +08:00
using RageCoop.Core;
using Console = GTA.Console;
using SHVDN;
2022-10-08 23:49:48 +08:00
using System;
2022-10-08 12:43:24 +08:00
using System.IO;
using System.Reflection;
using System.Windows.Forms;
2022-10-09 22:07:52 +08:00
using System.Collections.Generic;
using System.Linq;
using System.Collections.Concurrent;
2022-10-09 23:35:30 +08:00
using static System.Net.WebRequestMethods;
2022-10-08 12:43:24 +08:00
namespace RageCoop.Client.Scripting
{
2022-10-08 23:49:48 +08:00
internal class ResourceDomain : MarshalByRefObject, IDisposable
2022-10-08 12:43:24 +08:00
{
2022-10-09 22:07:52 +08:00
public static ConcurrentDictionary<string, ResourceDomain> LoadedDomains => new ConcurrentDictionary<string, ResourceDomain>(_loadedDomains);
static readonly ConcurrentDictionary<string, ResourceDomain> _loadedDomains = new ConcurrentDictionary<string, ResourceDomain>();
2022-10-08 23:49:48 +08:00
public static ScriptDomain PrimaryDomain;
2022-10-09 22:07:52 +08:00
public string BaseDirectory => AppDomain.CurrentDomain.BaseDirectory;
2022-10-08 23:49:48 +08:00
private ScriptDomain CurrentDomain => ScriptDomain.CurrentDomain;
2022-10-10 16:45:58 +08:00
private static ConcurrentDictionary<string, Action<object>> _callBacks = new ConcurrentDictionary<string, Action<object>>();
API API => API.GetInstance();
2022-10-09 22:07:52 +08:00
private ResourceDomain(ScriptDomain primary, string[] apiPaths)
2022-10-08 12:43:24 +08:00
{
2022-10-10 16:45:58 +08:00
AppDomain.CurrentDomain.SetData("Primary", primary);
2022-10-09 22:07:52 +08:00
foreach (var apiPath in apiPaths)
{
try
{
Assembly.LoadFrom(apiPath);
}
catch
{
}
}
2022-10-08 23:49:48 +08:00
PrimaryDomain = primary;
primary.Tick += Tick;
2022-10-10 16:45:58 +08:00
primary.KeyEvent += KeyEvent;
2022-10-09 23:35:30 +08:00
CurrentDomain.Start();
SetupScripts();
2022-10-10 16:45:58 +08:00
Console.WriteLine($"Loaded domain: {AppDomain.CurrentDomain.FriendlyName}, {AppDomain.CurrentDomain.BaseDirectory}");
2022-10-08 12:43:24 +08:00
}
2022-10-09 22:07:52 +08:00
public static bool IsLoaded(string dir)
2022-10-08 12:43:24 +08:00
{
2022-10-09 22:07:52 +08:00
return _loadedDomains.ContainsKey(Path.GetFullPath(dir).ToLower());
}
public void SetupScripts()
{
2022-10-09 23:35:30 +08:00
foreach (var s in GetClientScripts())
2022-10-08 23:49:48 +08:00
{
2022-10-09 23:35:30 +08:00
try
{
2022-10-10 16:45:58 +08:00
API.Logger.Debug("Starting script: " + s.GetType().FullName);
2022-10-09 23:35:30 +08:00
var script = (ClientScript)s;
2022-10-10 16:45:58 +08:00
var res = API.GetResource(Path.GetFileName(Directory.GetParent(script.Filename).FullName));
if (res == null) { API.Logger.Warning("Failed to locate resource for script: " + script.Filename); continue; }
2022-10-09 23:35:30 +08:00
script.CurrentResource = res;
2022-10-10 16:45:58 +08:00
script.CurrentFile = res.Files.Values.Where(x => x.Name.ToLower() == script.Filename.Substring(res.ScriptsDirectory.Length + 1).Replace('\\', '/')).FirstOrDefault();
2022-10-09 23:35:30 +08:00
res.Scripts.Add(script);
2022-10-10 16:45:58 +08:00
s.GetType().Assembly.GetReferencedAssemblies().ForEach(x => Assembly.Load(x.FullName));
2022-10-09 23:35:30 +08:00
script.OnStart();
}
catch (Exception ex)
{
2022-10-10 16:45:58 +08:00
API.Logger.Error($"Failed to start {s.GetType().FullName}", ex);
2022-10-09 23:35:30 +08:00
}
2022-10-08 23:49:48 +08:00
}
2022-10-09 22:07:52 +08:00
}
2022-10-09 23:35:30 +08:00
public object[] GetClientScripts()
{
2022-10-10 16:45:58 +08:00
Console.WriteLine("Running scripts: " + ScriptDomain.CurrentDomain.RunningScripts.Select(x => x.ScriptInstance.GetType().FullName).Dump());
2022-10-09 23:35:30 +08:00
return ScriptDomain.CurrentDomain.RunningScripts.Where(x =>
2022-10-10 16:45:58 +08:00
x.ScriptInstance.GetType().IsSubclassOf(typeof(ClientScript)) &&
2022-10-09 23:35:30 +08:00
!x.ScriptInstance.GetType().IsAbstract).Select(x => x.ScriptInstance).ToArray();
}
2022-10-10 16:45:58 +08:00
public static void RegisterCallBackForCurrentDomain(string name, Action<object> callback)
{
if (!_callBacks.TryAdd(name, callback))
{
throw new Exception("Failed to add callback");
}
}
public void DoCallback(string name,object data)
{
if(_callBacks.TryGetValue(name, out var callBack))
{
callBack(data);
}
}
public static void DoCallBack(string name,object data)
{
foreach(var d in _loadedDomains)
{
d.Value.DoCallback(name, data);
}
}
2022-10-09 22:07:52 +08:00
public static ResourceDomain Load(string dir = @"RageCoop\Scripts\Debug")
{
lock (_loadedDomains)
2022-10-08 12:43:24 +08:00
{
2022-10-09 22:07:52 +08:00
dir = Path.GetFullPath(dir).ToLower();
if (!Util.IsPrimaryDomain)
2022-10-08 12:43:24 +08:00
{
2022-10-09 22:07:52 +08:00
throw new InvalidOperationException("Cannot load in another domain");
2022-10-08 12:43:24 +08:00
}
2022-10-09 22:07:52 +08:00
if (IsLoaded(dir))
{
throw new Exception("Already loaded");
}
2022-10-09 23:35:30 +08:00
ScriptDomain sDomain = null;
2022-10-09 22:07:52 +08:00
try
{
dir = Path.GetFullPath(dir);
Directory.CreateDirectory(dir);
// Copy test script
// File.Copy(@"M:\SandBox-Shared\repos\RAGECOOP\RAGECOOP-V\bin\Debug\TestScript.dll", Path.Combine(dir, Path.GetFileName("TestScript.dll")), true);
// Load domain in main thread
Main.QueueToMainThread(() =>
{
var api = new List<string>();
api.Add(typeof(ResourceDomain).Assembly.Location);
api.AddRange(typeof(ResourceDomain).Assembly.GetReferencedAssemblies()
.Select(x => Assembly.Load(x.FullName).Location)
.Where(x => !string.IsNullOrEmpty(x)));
2022-10-09 23:35:30 +08:00
sDomain = ScriptDomain.Load(Directory.GetParent(typeof(ScriptDomain).Assembly.Location).FullName, dir);
sDomain.AppDomain.SetData("Console", ScriptDomain.CurrentDomain.AppDomain.GetData("Console"));
sDomain.AppDomain.SetData("RageCoop.Client.API", API.GetInstance());
_loadedDomains.TryAdd(dir, (ResourceDomain)sDomain.AppDomain.CreateInstanceFromAndUnwrap(typeof(ResourceDomain).Assembly.Location, typeof(ResourceDomain).FullName, false, BindingFlags.NonPublic | BindingFlags.Instance, null, new object[] { ScriptDomain.CurrentDomain, api.ToArray() }, null, null));
2022-10-09 22:07:52 +08:00
});
2022-10-08 12:43:24 +08:00
2022-10-09 22:07:52 +08:00
// Wait till next tick
GTA.Script.Yield();
return _loadedDomains[dir];
}
catch (Exception ex)
2022-10-08 12:43:24 +08:00
{
2022-10-09 22:07:52 +08:00
GTA.UI.Notification.Show(ex.ToString());
Main.Logger.Error(ex);
2022-10-09 23:35:30 +08:00
if (sDomain != null)
2022-10-08 12:43:24 +08:00
{
2022-10-09 23:35:30 +08:00
ScriptDomain.Unload(sDomain);
2022-10-08 12:43:24 +08:00
}
2022-10-09 22:07:52 +08:00
throw;
2022-10-08 12:43:24 +08:00
}
2022-10-09 22:07:52 +08:00
}
}
2022-10-08 12:43:24 +08:00
2022-10-09 22:07:52 +08:00
public static void Unload(ResourceDomain domain)
{
lock (_loadedDomains)
{
2022-10-10 16:45:58 +08:00
Exception ex = null;
2022-10-08 12:43:24 +08:00
Main.QueueToMainThread(() =>
{
2022-10-09 23:35:30 +08:00
try
{
domain.Dispose();
ScriptDomain.Unload(domain.CurrentDomain);
_loadedDomains.TryRemove(domain.BaseDirectory, out _);
}
2022-10-10 16:45:58 +08:00
catch (Exception e) { ex = e; }
2022-10-08 12:43:24 +08:00
});
GTA.Script.Yield();
2022-10-10 16:45:58 +08:00
if (ex != null) { throw ex; }
2022-10-08 12:43:24 +08:00
}
}
2022-10-09 22:07:52 +08:00
public static void Unload(string dir)
2022-10-08 12:43:24 +08:00
{
2022-10-09 22:07:52 +08:00
Unload(_loadedDomains[Path.GetFullPath(dir).ToLower()]);
}
public static void UnloadAll()
{
lock (_loadedDomains)
2022-10-08 12:43:24 +08:00
{
2022-10-09 22:07:52 +08:00
foreach (var d in _loadedDomains.Values.ToArray())
{
Unload(d);
}
2022-10-08 12:43:24 +08:00
}
}
2022-10-08 23:49:48 +08:00
private void Tick(object sender, EventArgs args)
2022-10-08 12:43:24 +08:00
{
CurrentDomain.DoTick();
}
2022-10-08 23:49:48 +08:00
private void KeyEvent(Keys keys, bool status)
2022-10-08 12:43:24 +08:00
{
CurrentDomain.DoKeyEvent(keys, status);
}
public void Dispose()
{
2022-10-10 16:45:58 +08:00
PrimaryDomain.Tick -= Tick;
PrimaryDomain.KeyEvent -= KeyEvent;
foreach (var s in GetClientScripts())
2022-10-09 23:35:30 +08:00
{
try
{
2022-10-10 16:45:58 +08:00
API.Logger.Debug("Stopping script: " + s.GetType().FullName);
2022-10-09 23:35:30 +08:00
((ClientScript)s).OnStop();
}
2022-10-10 16:45:58 +08:00
catch (Exception ex)
2022-10-09 23:35:30 +08:00
{
2022-10-10 16:45:58 +08:00
API.Logger.Error($"Failed to stop {s.GetType().FullName}", ex);
2022-10-09 23:35:30 +08:00
}
}
2022-10-08 12:43:24 +08:00
}
}
}