1
0
mirror of https://github.com/Artemis-RGB/Artemis synced 2025-12-13 05:48:35 +00:00

LUA memory improvements

This commit is contained in:
SpoinkyNL 2016-11-01 16:28:57 +01:00
parent e5608907e4
commit 03c8da54c3
7 changed files with 119 additions and 129 deletions

View File

@ -41,10 +41,7 @@ namespace Artemis.Models
public virtual void Dispose() public virtual void Dispose()
{ {
if (Profile?.LuaWrapper == null) Profile?.Deactivate();
return;
Profile.LuaWrapper.Dispose();
Profile.LuaWrapper = null;
} }
// Called on creation // Called on creation
@ -70,8 +67,8 @@ namespace Artemis.Models
var renderLayers = GetRenderLayers(keyboardOnly); var renderLayers = GetRenderLayers(keyboardOnly);
// If the profile has no active LUA wrapper, create one // If the profile has no active LUA wrapper, create one
if (Profile.LuaWrapper == null && !string.IsNullOrEmpty(Profile.LuaScript)) if (!string.IsNullOrEmpty(Profile.LuaScript))
Profile.LuaWrapper = new LuaWrapper(Profile, MainManager.DeviceManager.ActiveKeyboard); Profile.Activate(MainManager.DeviceManager.ActiveKeyboard);
// Render the keyboard layer-by-layer // Render the keyboard layer-by-layer
var keyboardRect = MainManager.DeviceManager.ActiveKeyboard.KeyboardRectangle(KeyboardScale); var keyboardRect = MainManager.DeviceManager.ActiveKeyboard.KeyboardRectangle(KeyboardScale);

View File

@ -54,8 +54,8 @@ namespace Artemis.Modules.Effects.ProfilePreview
var renderLayers = GetRenderLayers(keyboardOnly); var renderLayers = GetRenderLayers(keyboardOnly);
// If the profile has no active LUA wrapper, create one // If the profile has no active LUA wrapper, create one
if (Profile.LuaWrapper == null && !string.IsNullOrEmpty(Profile.LuaScript)) if (!string.IsNullOrEmpty(Profile.LuaScript))
Profile.LuaWrapper = new LuaWrapper(Profile, MainManager.DeviceManager.ActiveKeyboard); Profile.Activate(MainManager.DeviceManager.ActiveKeyboard);
// Render the keyboard layer-by-layer // Render the keyboard layer-by-layer
var keyboardRect = MainManager.DeviceManager.ActiveKeyboard.KeyboardRectangle(KeyboardScale); var keyboardRect = MainManager.DeviceManager.ActiveKeyboard.KeyboardRectangle(KeyboardScale);

View File

@ -11,6 +11,7 @@ namespace Artemis.Profiles.Lua.Events
public class LuaEventsWrapper public class LuaEventsWrapper
{ {
private readonly Logger _logger = LogManager.GetCurrentClassLogger(); private readonly Logger _logger = LogManager.GetCurrentClassLogger();
private readonly string _invokeLock = string.Empty;
public event EventHandler<LuaProfileUpdatingEventArgs> ProfileUpdating; public event EventHandler<LuaProfileUpdatingEventArgs> ProfileUpdating;
public event EventHandler<LuaProfileDrawingEventArgs> ProfileDrawing; public event EventHandler<LuaProfileDrawingEventArgs> ProfileDrawing;
public event EventHandler<LuaKeyPressEventArgs> KeyboardKeyPressed; public event EventHandler<LuaKeyPressEventArgs> KeyboardKeyPressed;
@ -19,8 +20,8 @@ namespace Artemis.Profiles.Lua.Events
{ {
try try
{ {
OnProfileUpdating(new LuaProfileWrapper(profileModel), LuaInvoke(profileModel, () => OnProfileUpdating(new LuaProfileWrapper(profileModel),
new LuaProfileUpdatingEventArgs(dataModel, preview)); new LuaProfileUpdatingEventArgs(dataModel, preview)));
} }
catch (Exception) catch (Exception)
{ {
@ -32,8 +33,8 @@ namespace Artemis.Profiles.Lua.Events
{ {
try try
{ {
OnProfileDrawing(new LuaProfileWrapper(profileModel), LuaInvoke(profileModel, () => OnProfileDrawing(new LuaProfileWrapper(profileModel),
new LuaProfileDrawingEventArgs(dataModel, preview, new LuaDrawWrapper(c))); new LuaProfileDrawingEventArgs(dataModel, preview, new LuaDrawWrapper(c))));
} }
catch (Exception) catch (Exception)
{ {
@ -45,7 +46,8 @@ namespace Artemis.Profiles.Lua.Events
{ {
try try
{ {
OnKeyboardKeyPressed(new LuaProfileWrapper(profileModel), keyboard, new LuaKeyPressEventArgs(key, x, y)); LuaInvoke(profileModel, () => OnKeyboardKeyPressed(new LuaProfileWrapper(profileModel),
keyboard, new LuaKeyPressEventArgs(key, x, y)));
} }
catch (Exception) catch (Exception)
{ {
@ -53,65 +55,43 @@ namespace Artemis.Profiles.Lua.Events
} }
} }
private void LuaInvoke(ProfileModel profileModel, Action action)
{
lock (_invokeLock)
{
try
{
action.Invoke();
}
catch (InternalErrorException ex)
{
_logger.Error(ex, "[{0}-LUA]: Error: {1}", profileModel.Name, ex.DecoratedMessage);
}
catch (SyntaxErrorException ex)
{
_logger.Error(ex, "[{0}-LUA]: Error: {1}", profileModel.Name, ex.DecoratedMessage);
}
catch (ScriptRuntimeException ex)
{
_logger.Error(ex, "[{0}-LUA]: Error: {1}", profileModel.Name, ex.DecoratedMessage);
}
}
}
protected virtual void OnProfileUpdating(LuaProfileWrapper profileModel, LuaProfileUpdatingEventArgs e) protected virtual void OnProfileUpdating(LuaProfileWrapper profileModel, LuaProfileUpdatingEventArgs e)
{ {
try ProfileUpdating?.Invoke(profileModel, e);
{
ProfileUpdating?.Invoke(profileModel, e);
}
catch (InternalErrorException ex)
{
_logger.Error(ex, "[{0}-LUA]: Error: {1}", profileModel.Name, ex.DecoratedMessage);
}
catch (SyntaxErrorException ex)
{
_logger.Error(ex, "[{0}-LUA]: Error: {1}", profileModel.Name, ex.DecoratedMessage);
}
catch (ScriptRuntimeException ex)
{
_logger.Error(ex, "[{0}-LUA]: Error: {1}", profileModel.Name, ex.DecoratedMessage);
}
} }
protected virtual void OnProfileDrawing(LuaProfileWrapper profileModel, LuaProfileDrawingEventArgs e) protected virtual void OnProfileDrawing(LuaProfileWrapper profileModel, LuaProfileDrawingEventArgs e)
{ {
try ProfileDrawing?.Invoke(profileModel, e);
{
ProfileDrawing?.Invoke(profileModel, e);
}
catch (InternalErrorException ex)
{
_logger.Error(ex, "[{0}-LUA]: Error: {1}", profileModel.Name, ex.DecoratedMessage);
}
catch (SyntaxErrorException ex)
{
_logger.Error(ex, "[{0}-LUA]: Error: {1}", profileModel.Name, ex.DecoratedMessage);
}
catch (ScriptRuntimeException ex)
{
_logger.Error(ex, "[{0}-LUA]: Error: {1}", profileModel.Name, ex.DecoratedMessage);
}
} }
protected virtual void OnKeyboardKeyPressed(LuaProfileWrapper profileModel, LuaKeyboardWrapper keyboard, protected virtual void OnKeyboardKeyPressed(LuaProfileWrapper profileModel, LuaKeyboardWrapper keyboard,
LuaKeyPressEventArgs e) LuaKeyPressEventArgs e)
{ {
try KeyboardKeyPressed?.Invoke(profileModel, e);
{
KeyboardKeyPressed?.Invoke(profileModel, e);
}
catch (InternalErrorException ex)
{
_logger.Error(ex, "[{0}-LUA]: Error: {1}", profileModel.Name, ex.DecoratedMessage);
}
catch (SyntaxErrorException ex)
{
_logger.Error(ex, "[{0}-LUA]: Error: {1}", profileModel.Name, ex.DecoratedMessage);
}
catch (ScriptRuntimeException ex)
{
_logger.Error(ex, "[{0}-LUA]: Error: {1}", profileModel.Name, ex.DecoratedMessage);
}
} }
} }
} }

View File

@ -11,11 +11,9 @@ namespace Artemis.Profiles.Lua
public class LuaKeyboardWrapper : IDisposable public class LuaKeyboardWrapper : IDisposable
{ {
private readonly KeyboardProvider _keyboardProvider; private readonly KeyboardProvider _keyboardProvider;
private readonly LuaWrapper _luaWrapper;
public LuaKeyboardWrapper(LuaWrapper luaWrapper, KeyboardProvider keyboardProvider) public LuaKeyboardWrapper(KeyboardProvider keyboardProvider)
{ {
_luaWrapper = luaWrapper;
_keyboardProvider = keyboardProvider; _keyboardProvider = keyboardProvider;
KeyboardHook.KeyDownCallback += KeyboardHookOnKeyDownCallback; KeyboardHook.KeyDownCallback += KeyboardHookOnKeyDownCallback;
@ -36,8 +34,8 @@ namespace Artemis.Profiles.Lua
{ {
var keyMatch = _keyboardProvider.GetKeyPosition(e.KeyCode); var keyMatch = _keyboardProvider.GetKeyPosition(e.KeyCode);
if (keyMatch != null) if (keyMatch != null)
_luaWrapper.LuaEventsWrapper.InvokeKeyPressed(_luaWrapper.ProfileModel, this, LuaWrapper.LuaEventsWrapper.InvokeKeyPressed(LuaWrapper.ProfileModel, this, keyMatch.Value.KeyCode,
keyMatch.Value.KeyCode, keyMatch.Value.X, keyMatch.Value.Y); keyMatch.Value.X, keyMatch.Value.Y);
} }
public void SendKeys(string keys) public void SendKeys(string keys)

View File

@ -12,30 +12,33 @@ using NLog;
namespace Artemis.Profiles.Lua namespace Artemis.Profiles.Lua
{ {
public class LuaWrapper : IDisposable public static class LuaWrapper
{ {
private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private static readonly Script LuaScript = new Script(CoreModules.Preset_SoftSandbox);
private static KeyboardProvider _keyboardProvider;
private static FileSystemWatcher _watcher;
public LuaWrapper(ProfileModel profileModel, KeyboardProvider keyboardProvider) public static ProfileModel ProfileModel { get; private set; }
public static LuaProfileWrapper LuaProfileWrapper { get; private set; }
public static LuaBrushWrapper LuaBrushWrapper { get; private set; }
public static LuaKeyboardWrapper LuaKeyboardWrapper { get; private set; }
public static LuaEventsWrapper LuaEventsWrapper { get; private set; }
public static void SetupLua(ProfileModel profileModel, KeyboardProvider keyboardProvider)
{ {
Clear();
if (profileModel == null || keyboardProvider == null)
return;
// Setup a new environment
_keyboardProvider = keyboardProvider;
ProfileModel = profileModel; ProfileModel = profileModel;
LuaProfileWrapper = new LuaProfileWrapper(ProfileModel); LuaProfileWrapper = new LuaProfileWrapper(ProfileModel);
LuaBrushWrapper = new LuaBrushWrapper(); LuaBrushWrapper = new LuaBrushWrapper();
LuaKeyboardWrapper = new LuaKeyboardWrapper(this, keyboardProvider); LuaKeyboardWrapper = new LuaKeyboardWrapper(keyboardProvider);
SetupLuaScript();
}
public ProfileModel ProfileModel { get; set; }
public LuaProfileWrapper LuaProfileWrapper { get; set; }
public LuaBrushWrapper LuaBrushWrapper { get; set; }
public LuaKeyboardWrapper LuaKeyboardWrapper { get; set; }
public LuaEventsWrapper LuaEventsWrapper { get; set; }
public Script LuaScript { get; set; }
private void SetupLuaScript()
{
LuaEventsWrapper = new LuaEventsWrapper(); LuaEventsWrapper = new LuaEventsWrapper();
LuaScript = new Script(CoreModules.Preset_SoftSandbox);
LuaScript.Options.DebugPrint = LuaPrint; LuaScript.Options.DebugPrint = LuaPrint;
LuaScript.Globals["Profile"] = LuaProfileWrapper; LuaScript.Globals["Profile"] = LuaProfileWrapper;
@ -66,7 +69,7 @@ namespace Artemis.Profiles.Lua
#region Private lua functions #region Private lua functions
private void LuaPrint(string s) private static void LuaPrint(string s)
{ {
Logger.Debug("[{0}-LUA]: {1}", ProfileModel.Name, s); Logger.Debug("[{0}-LUA]: {1}", ProfileModel.Name, s);
} }
@ -75,8 +78,11 @@ namespace Artemis.Profiles.Lua
#region Editor #region Editor
public void OpenEditor() public static void OpenEditor()
{ {
if (ProfileModel == null)
return;
// Create a temp file // Create a temp file
var fileName = Guid.NewGuid() + ".lua"; var fileName = Guid.NewGuid() + ".lua";
var file = File.Create(Path.GetTempPath() + fileName); var file = File.Create(Path.GetTempPath() + fileName);
@ -88,21 +94,31 @@ namespace Artemis.Profiles.Lua
File.WriteAllText(Path.GetTempPath() + fileName, ProfileModel.LuaScript); File.WriteAllText(Path.GetTempPath() + fileName, ProfileModel.LuaScript);
// Watch the file for changes // Watch the file for changes
var watcher = new FileSystemWatcher(Path.GetTempPath(), fileName); SetupWatcher(Path.GetTempPath(), fileName);
watcher.Changed += LuaFileChanged;
watcher.EnableRaisingEvents = true;
// Open the temp file with the default editor // Open the temp file with the default editor
System.Diagnostics.Process.Start(Path.GetTempPath() + fileName); System.Diagnostics.Process.Start(Path.GetTempPath() + fileName);
} }
private void LuaFileChanged(object sender, FileSystemEventArgs fileSystemEventArgs) private static void SetupWatcher(string path, string fileName)
{ {
if (fileSystemEventArgs.ChangeType != WatcherChangeTypes.Changed) if (_watcher == null)
{
_watcher = new FileSystemWatcher(Path.GetTempPath(), fileName);
_watcher.Changed += LuaFileChanged;
_watcher.EnableRaisingEvents = true;
}
_watcher.Path = path;
_watcher.Filter = fileName;
}
private static void LuaFileChanged(object sender, FileSystemEventArgs args)
{
if (args.ChangeType != WatcherChangeTypes.Changed)
return; return;
using (var fs = new FileStream(fileSystemEventArgs.FullPath, using (var fs = new FileStream(args.FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{ {
using (var sr = new StreamReader(fs)) using (var sr = new StreamReader(fs))
{ {
@ -111,29 +127,27 @@ namespace Artemis.Profiles.Lua
} }
ProfileProvider.AddOrUpdate(ProfileModel); ProfileProvider.AddOrUpdate(ProfileModel);
SetupLuaScript();
if (_keyboardProvider != null)
SetupLua(ProfileModel, _keyboardProvider);
} }
#endregion #endregion
#region Event triggers public static void Clear()
public void TriggerUpdate()
{ {
} // Clear old fields/properties
_keyboardProvider = null;
ProfileModel = null;
LuaKeyboardWrapper?.Dispose();
LuaKeyboardWrapper = null;
public void TriggerDraw()
{
}
#endregion
public void Dispose()
{
LuaKeyboardWrapper.Dispose();
LuaScript.Globals.Clear(); LuaScript.Globals.Clear();
LuaScript.Registry.Clear(); LuaScript.Registry.Clear();
LuaScript = null; LuaScript.Registry.RegisterConstants();
LuaScript.Registry.RegisterCoreModules(CoreModules.Preset_SoftSandbox);
LuaScript.Globals.RegisterConstants();
LuaScript.Globals.RegisterCoreModules(CoreModules.Preset_SoftSandbox);
} }
} }
} }

View File

@ -40,9 +40,6 @@ namespace Artemis.Profiles
public int Height { get; set; } public int Height { get; set; }
public string LuaScript { get; set; } public string LuaScript { get; set; }
[JsonIgnore]
public LuaWrapper LuaWrapper { get; set; }
public void FixOrder() public void FixOrder()
{ {
Layers.Sort(l => l.Order); Layers.Sort(l => l.Order);
@ -118,14 +115,14 @@ namespace Artemis.Profiles
layerModel.Update(dataModel, preview, updateAnimations); layerModel.Update(dataModel, preview, updateAnimations);
if (triggerLua) if (triggerLua)
LuaWrapper?.LuaEventsWrapper?.InvokeProfileUpdate(this, dataModel, preview); LuaWrapper.LuaEventsWrapper?.InvokeProfileUpdate(this, dataModel, preview);
// Draw the layers // Draw the layers
foreach (var layerModel in layerModels) foreach (var layerModel in layerModels)
layerModel.Draw(dataModel, c, preview, updateAnimations); layerModel.Draw(dataModel, c, preview, updateAnimations);
if (triggerLua) if (triggerLua)
LuaWrapper?.LuaEventsWrapper?.InvokeProfileDraw(this, dataModel, preview, c); LuaWrapper.LuaEventsWrapper?.InvokeProfileDraw(this, dataModel, preview, c);
// Remove the clip // Remove the clip
c.Pop(); c.Pop();
@ -206,5 +203,21 @@ namespace Artemis.Profiles
} }
#endregion #endregion
public void Activate(KeyboardProvider keyboard)
{
if (!Equals(LuaWrapper.ProfileModel, this))
{
LuaWrapper.SetupLua(this, keyboard);
}
}
public void Deactivate()
{
if (Equals(LuaWrapper.ProfileModel, this))
{
LuaWrapper.Clear();
}
}
} }
} }

View File

@ -125,11 +125,7 @@ namespace Artemis.ViewModels.Profiles
set set
{ {
if (Equals(value, _selectedProfile)) return; if (Equals(value, _selectedProfile)) return;
if (_selectedProfile?.LuaWrapper != null) _selectedProfile?.Deactivate();
{
_selectedProfile.LuaWrapper.Dispose();
_selectedProfile.LuaWrapper = null;
}
_selectedProfile = value; _selectedProfile = value;
NotifyOfPropertyChange(() => SelectedProfile); NotifyOfPropertyChange(() => SelectedProfile);
} }
@ -237,12 +233,7 @@ namespace Artemis.ViewModels.Profiles
public void Deactivate() public void Deactivate()
{ {
ProfileViewModel.Deactivate(); ProfileViewModel.Deactivate();
if (SelectedProfile?.LuaWrapper != null) SelectedProfile?.Deactivate();
{
SelectedProfile.LuaWrapper.Dispose();
SelectedProfile.LuaWrapper = null;
}
_saveTimer.Stop();
} }
/// <summary> /// <summary>
@ -713,11 +704,8 @@ namespace Artemis.ViewModels.Profiles
return; return;
try try
{ {
if (SelectedProfile.LuaWrapper == null) SelectedProfile?.Activate(_mainManager.DeviceManager.ActiveKeyboard);
SelectedProfile.LuaWrapper = new LuaWrapper(SelectedProfile, LuaWrapper.OpenEditor();
_mainManager.DeviceManager.ActiveKeyboard);
SelectedProfile.LuaWrapper.OpenEditor();
} }
catch (Exception e) catch (Exception e)
{ {
@ -755,7 +743,7 @@ namespace Artemis.ViewModels.Profiles
private void ProfileSaveHandler(object sender, ElapsedEventArgs e) private void ProfileSaveHandler(object sender, ElapsedEventArgs e)
{ {
if (_saving || (SelectedProfile == null)) if (_saving || (SelectedProfile == null) || !IsActive)
return; return;
_saving = true; _saving = true;