diff --git a/BizHawk.Client.Common/Api/Classes/EmuApi.cs b/BizHawk.Client.Common/Api/Classes/EmuApi.cs index ea5524e1af..4e5dbf7029 100644 --- a/BizHawk.Client.Common/Api/Classes/EmuApi.cs +++ b/BizHawk.Client.Common/Api/Classes/EmuApi.cs @@ -377,22 +377,22 @@ namespace BizHawk.Client.Common s.DispBackground = luaParam[1]; nes.PutSettings(s); } - else if (Emulator is QuickNES quickNes) + else if (Emulator is QuickNES quicknes) { - var s = quickNes.GetSettings(); + var s = quicknes.GetSettings(); // this core doesn't support disabling BG - bool showsp = GetSetting(0, luaParam); - if (showsp && s.NumSprites == 0) + bool showSp = GetSetting(0, luaParam); + if (showSp && s.NumSprites == 0) { s.NumSprites = 8; } - else if (!showsp && s.NumSprites > 0) + else if (!showSp && s.NumSprites > 0) { s.NumSprites = 0; } - quickNes.PutSettings(s); + quicknes.PutSettings(s); } else if (Emulator is PCEngine pce) { @@ -426,12 +426,7 @@ namespace BizHawk.Client.Common private static bool GetSetting(int index, bool[] settings) { - if (index < settings.Length) - { - return settings[index]; - } - - return true; + return index >= settings.Length || settings[index]; } } } diff --git a/BizHawk.Client.Common/Api/Classes/GameInfoApi.cs b/BizHawk.Client.Common/Api/Classes/GameInfoApi.cs index f6bd4848df..52c8b017a5 100644 --- a/BizHawk.Client.Common/Api/Classes/GameInfoApi.cs +++ b/BizHawk.Client.Common/Api/Classes/GameInfoApi.cs @@ -12,22 +12,12 @@ namespace BizHawk.Client.Common public string GetRomName() { - if (Global.Game != null) - { - return Global.Game.Name ?? ""; - } - - return ""; + return Global.Game?.Name ?? ""; } public string GetRomHash() { - if (Global.Game != null) - { - return Global.Game.Hash ?? ""; - } - - return ""; + return Global.Game?.Hash ?? ""; } public bool InDatabase() @@ -42,22 +32,12 @@ namespace BizHawk.Client.Common public string GetStatus() { - if (Global.Game != null) - { - return Global.Game.Status.ToString(); - } - - return ""; + return Global.Game?.Status.ToString(); } public bool IsStatusBad() { - if (Global.Game != null) - { - return Global.Game.IsRomStatusBad(); - } - - return true; + return Global.Game?.IsRomStatusBad() ?? true; } public string GetBoardType() diff --git a/BizHawk.Client.Common/Api/Classes/MovieApi.cs b/BizHawk.Client.Common/Api/Classes/MovieApi.cs index 1463b0d498..a876ebca16 100644 --- a/BizHawk.Client.Common/Api/Classes/MovieApi.cs +++ b/BizHawk.Client.Common/Api/Classes/MovieApi.cs @@ -95,8 +95,8 @@ namespace BizHawk.Client.Common { var movie = Global.MovieSession.Movie; var system = movie.HeaderEntries[HeaderKeys.PLATFORM]; - var pal = movie.HeaderEntries.ContainsKey(HeaderKeys.PAL) && - movie.HeaderEntries[HeaderKeys.PAL] == "1"; + var pal = movie.HeaderEntries.ContainsKey(HeaderKeys.PAL) + && movie.HeaderEntries[HeaderKeys.PAL] == "1"; return new PlatformFrameRates()[system, pal]; } diff --git a/BizHawk.Client.Common/Api/Classes/SqlApi.cs b/BizHawk.Client.Common/Api/Classes/SqlApi.cs index 069c4dcf26..0df1e1f18b 100644 --- a/BizHawk.Client.Common/Api/Classes/SqlApi.cs +++ b/BizHawk.Client.Common/Api/Classes/SqlApi.cs @@ -29,7 +29,7 @@ namespace BizHawk.Client.Common { DataSource = name, Version = 3, - JournalMode = SQLiteJournalModeEnum.Wal, // Allows for reads and writes to happen at the same time + JournalMode = SQLiteJournalModeEnum.Wal, // Allows for reads and writes to happen at the same time DefaultIsolationLevel = System.Data.IsolationLevel.ReadCommitted, // This only helps make the database lock left. May be pointless now SyncMode = SynchronizationModes.Off // This shortens the delay for do synchronous calls. }; diff --git a/BizHawk.Client.Common/config/Config.cs b/BizHawk.Client.Common/config/Config.cs index e3b684b4a8..36be920135 100644 --- a/BizHawk.Client.Common/config/Config.cs +++ b/BizHawk.Client.Common/config/Config.cs @@ -399,7 +399,6 @@ namespace BizHawk.Client.Common public RecentFiles RecentLuaSession = new RecentFiles(8); public bool DisableLuaScriptsOnLoad = false; public bool ToggleAllIfNoneSelected = true; - public bool RemoveRegisteredFunctionsOnToggle = true; public bool LuaReloadOnScriptFileChange = false; public bool RunLuaDuringTurbo = true; diff --git a/BizHawk.Client.Common/lua/EmuLuaLibrary.Bit.cs b/BizHawk.Client.Common/lua/EmuLuaLibrary.Bit.cs index e5f8a0e37b..6f085fca19 100644 --- a/BizHawk.Client.Common/lua/EmuLuaLibrary.Bit.cs +++ b/BizHawk.Client.Common/lua/EmuLuaLibrary.Bit.cs @@ -3,6 +3,7 @@ using System.ComponentModel; using NLua; +// ReSharper disable UnusedMember.Global namespace BizHawk.Client.Common { [Description("A library for performing standard bitwise operations.")] diff --git a/BizHawk.Client.Common/lua/EmuLuaLibrary.Emu.cs b/BizHawk.Client.Common/lua/EmuLuaLibrary.Emu.cs index da767ebb4c..c723353e7e 100644 --- a/BizHawk.Client.Common/lua/EmuLuaLibrary.Emu.cs +++ b/BizHawk.Client.Common/lua/EmuLuaLibrary.Emu.cs @@ -11,6 +11,8 @@ using BizHawk.Emulation.Cores.Consoles.Nintendo.QuickNES; using NLua; +// ReSharper disable UnusedMember.Global +// ReSharper disable UnusedAutoPropertyAccessor.Local namespace BizHawk.Client.Common { [Description("A library for interacting with the currently loaded emulator core")] @@ -267,37 +269,34 @@ namespace BizHawk.Client.Common [LuaMethod("setrenderplanes", "Toggles the drawing of sprites and background planes. Set to false or nil to disable a pane, anything else will draw them")] public void SetRenderPlanes(params bool[] luaParam) { - if (Emulator is NES) + if (Emulator is NES nes) { // in the future, we could do something more arbitrary here. // but this isn't any worse than the old system - var nes = Emulator as NES; var s = nes.GetSettings(); s.DispSprites = luaParam[0]; s.DispBackground = luaParam[1]; nes.PutSettings(s); } - else if (Emulator is QuickNES) + else if (Emulator is QuickNES quicknes) { - var quicknes = Emulator as QuickNES; var s = quicknes.GetSettings(); // this core doesn't support disabling BG - bool showsp = GetSetting(0, luaParam); - if (showsp && s.NumSprites == 0) + bool showSp = GetSetting(0, luaParam); + if (showSp && s.NumSprites == 0) { s.NumSprites = 8; } - else if (!showsp && s.NumSprites > 0) + else if (!showSp && s.NumSprites > 0) { s.NumSprites = 0; } quicknes.PutSettings(s); } - else if (Emulator is PCEngine) + else if (Emulator is PCEngine pce) { - var pce = Emulator as PCEngine; var s = pce.GetSettings(); s.ShowOBJ1 = GetSetting(0, luaParam); s.ShowBG1 = GetSetting(1, luaParam); @@ -309,17 +308,15 @@ namespace BizHawk.Client.Common pce.PutSettings(s); } - else if (Emulator is SMS) + else if (Emulator is SMS sms) { - var sms = Emulator as SMS; var s = sms.GetSettings(); s.DispOBJ = GetSetting(0, luaParam); s.DispBG = GetSetting(1, luaParam); sms.PutSettings(s); } - else if (Emulator is WonderSwan) + else if (Emulator is WonderSwan ws) { - var ws = Emulator as WonderSwan; var s = ws.GetSettings(); s.EnableSprites = GetSetting(0, luaParam); s.EnableFG = GetSetting(1, luaParam); @@ -330,12 +327,7 @@ namespace BizHawk.Client.Common private static bool GetSetting(int index, bool[] settings) { - if (index < settings.Length) - { - return settings[index]; - } - - return true; + return index >= settings.Length || settings[index]; } [LuaMethodExample("emu.yield( );")] @@ -349,24 +341,18 @@ namespace BizHawk.Client.Common [LuaMethod("getdisplaytype", "returns the display type (PAL vs NTSC) that the emulator is currently running in")] public string GetDisplayType() { - if (RegionableCore != null) - { - return RegionableCore.Region.ToString(); - } - - return ""; + return RegionableCore != null + ? RegionableCore.Region.ToString() + : ""; } [LuaMethodExample("local stemuget = emu.getboardname();")] [LuaMethod("getboardname", "returns (if available) the board name of the loaded ROM")] public string GetBoardName() { - if (BoardInfo != null) - { - return BoardInfo.BoardName; - } - - return ""; + return BoardInfo != null + ? BoardInfo.BoardName + : ""; } [LuaMethod("getluacore", "returns the name of the Lua core currently in use")] diff --git a/BizHawk.Client.Common/lua/EmuLuaLibrary.Events.cs b/BizHawk.Client.Common/lua/EmuLuaLibrary.Events.cs index da03cbd7eb..3ef04e8708 100644 --- a/BizHawk.Client.Common/lua/EmuLuaLibrary.Events.cs +++ b/BizHawk.Client.Common/lua/EmuLuaLibrary.Events.cs @@ -6,8 +6,8 @@ using NLua; using BizHawk.Emulation.Common; using BizHawk.Emulation.Common.IEmulatorExtensions; -using BizHawk.Emulation.Cores.Nintendo.N64; - +// ReSharper disable UnusedMember.Global +// ReSharper disable UnusedAutoPropertyAccessor.Local namespace BizHawk.Client.Common { [Description("A library for registering lua functions to emulator events.\n All events support multiple registered methods.\nAll registered event methods can be named and return a Guid when registered")] @@ -25,8 +25,6 @@ namespace BizHawk.Client.Common [OptionalService] private IMemoryDomains Domains { get; set; } - private readonly LuaFunctionList _luaFunctions = new LuaFunctionList(); - public EventLuaLibrary(Lua lua) : base(lua) { } @@ -37,20 +35,23 @@ namespace BizHawk.Client.Common #region Events Library Helpers - public void CallExitEvent(Lua thread) + public void CallExitEvent(LuaFile luaFile) { - var exitCallbacks = _luaFunctions.Where(l => l.Lua == thread && l.Event == "OnExit"); + var exitCallbacks = RegisteredFunctions + .ForFile(luaFile) + .ForEvent("OnExit"); + foreach (var exitCallback in exitCallbacks) { exitCallback.Call(); } } - public LuaFunctionList RegisteredFunctions => _luaFunctions; + public LuaFunctionList RegisteredFunctions { get; } = new LuaFunctionList(); public void CallSaveStateEvent(string name) { - var lfs = _luaFunctions.Where(l => l.Event == "OnSavestateSave"); + var lfs = RegisteredFunctions.Where(l => l.Event == "OnSavestateSave"); try { foreach (var lf in lfs) @@ -66,7 +67,7 @@ namespace BizHawk.Client.Common public void CallLoadStateEvent(string name) { - var lfs = _luaFunctions.Where(l => l.Event == "OnSavestateLoad"); + var lfs = RegisteredFunctions.Where(l => l.Event == "OnSavestateLoad"); try { foreach (var lf in lfs) @@ -82,7 +83,7 @@ namespace BizHawk.Client.Common public void CallFrameBeforeEvent() { - var lfs = _luaFunctions.Where(l => l.Event == "OnFrameStart"); + var lfs = RegisteredFunctions.Where(l => l.Event == "OnFrameStart"); try { foreach (var lf in lfs) @@ -98,7 +99,7 @@ namespace BizHawk.Client.Common public void CallFrameAfterEvent() { - var lfs = _luaFunctions.Where(l => l.Event == "OnFrameEnd"); + var lfs = RegisteredFunctions.Where(l => l.Event == "OnFrameEnd"); try { foreach (var lf in lfs) @@ -112,17 +113,6 @@ namespace BizHawk.Client.Common } } - private bool N64CoreTypeDynarec() - { - //if ((Emulator as N64)?.GetSyncSettings().Core == N64SyncSettings.CoreType.Dynarec) - //{ - // Log("N64 Error: Memory callbacks are not implemented for Dynamic Recompiler core type\nUse Interpreter or Pure Interpreter\n"); - // return true; - //} - - return false; - } - private void LogMemoryCallbacksNotImplemented() { Log($"{Emulator.Attributes().CoreName} does not implement memory callbacks"); @@ -140,8 +130,8 @@ namespace BizHawk.Client.Common [LuaMethod("onframeend", "Calls the given lua function at the end of each frame, after all emulation and drawing has completed. Note: this is the default behavior of lua scripts")] public string OnFrameEnd(LuaFunction luaf, string name = null) { - var nlf = new NamedLuaFunction(luaf, "OnFrameEnd", LogOutputCallback, CurrentThread, name); - _luaFunctions.Add(nlf); + var nlf = new NamedLuaFunction(luaf, "OnFrameEnd", LogOutputCallback, CurrentFile, name); + RegisteredFunctions.Add(nlf); return nlf.Guid.ToString(); } @@ -149,8 +139,8 @@ namespace BizHawk.Client.Common [LuaMethod("onframestart", "Calls the given lua function at the beginning of each frame before any emulation and drawing occurs")] public string OnFrameStart(LuaFunction luaf, string name = null) { - var nlf = new NamedLuaFunction(luaf, "OnFrameStart", LogOutputCallback, CurrentThread, name); - _luaFunctions.Add(nlf); + var nlf = new NamedLuaFunction(luaf, "OnFrameStart", LogOutputCallback, CurrentFile, name); + RegisteredFunctions.Add(nlf); return nlf.Guid.ToString(); } @@ -158,8 +148,8 @@ namespace BizHawk.Client.Common [LuaMethod("oninputpoll", "Calls the given lua function after each time the emulator core polls for input")] public string OnInputPoll(LuaFunction luaf, string name = null) { - var nlf = new NamedLuaFunction(luaf, "OnInputPoll", LogOutputCallback, CurrentThread, name); - _luaFunctions.Add(nlf); + var nlf = new NamedLuaFunction(luaf, "OnInputPoll", LogOutputCallback, CurrentFile, name); + RegisteredFunctions.Add(nlf); if (InputPollableCore != null) { @@ -188,8 +178,8 @@ namespace BizHawk.Client.Common [LuaMethod("onloadstate", "Fires after a state is loaded. Receives a lua function name, and registers it to the event immediately following a successful savestate event")] public string OnLoadState(LuaFunction luaf, string name = null) { - var nlf = new NamedLuaFunction(luaf, "OnSavestateLoad", LogOutputCallback, CurrentThread, name); - _luaFunctions.Add(nlf); + var nlf = new NamedLuaFunction(luaf, "OnSavestateLoad", LogOutputCallback, CurrentFile, name); + RegisteredFunctions.Add(nlf); return nlf.Guid.ToString(); } @@ -202,13 +192,8 @@ namespace BizHawk.Client.Common if (DebuggableCore != null && DebuggableCore.MemoryCallbacksAvailable() && DebuggableCore.MemoryCallbacks.ExecuteCallbacksAvailable) { - if (N64CoreTypeDynarec()) - { - return Guid.Empty.ToString(); - } - - var nlf = new NamedLuaFunction(luaf, "OnMemoryExecute", LogOutputCallback, CurrentThread, name); - _luaFunctions.Add(nlf); + var nlf = new NamedLuaFunction(luaf, "OnMemoryExecute", LogOutputCallback, CurrentFile, name); + RegisteredFunctions.Add(nlf); if (string.IsNullOrWhiteSpace(domain)) { @@ -241,13 +226,8 @@ namespace BizHawk.Client.Common { if (DebuggableCore != null && DebuggableCore.MemoryCallbacksAvailable()) { - if (N64CoreTypeDynarec()) - { - return Guid.Empty.ToString(); - } - - var nlf = new NamedLuaFunction(luaf, "OnMemoryRead", LogOutputCallback, CurrentThread, name); - _luaFunctions.Add(nlf); + var nlf = new NamedLuaFunction(luaf, "OnMemoryRead", LogOutputCallback, CurrentFile, name); + RegisteredFunctions.Add(nlf); if (string.IsNullOrWhiteSpace(domain)) { @@ -280,13 +260,8 @@ namespace BizHawk.Client.Common { if (DebuggableCore != null && DebuggableCore.MemoryCallbacksAvailable()) { - if (N64CoreTypeDynarec()) - { - return Guid.Empty.ToString(); - } - - var nlf = new NamedLuaFunction(luaf, "OnMemoryWrite", LogOutputCallback, CurrentThread, name); - _luaFunctions.Add(nlf); + var nlf = new NamedLuaFunction(luaf, "OnMemoryWrite", LogOutputCallback, CurrentFile, name); + RegisteredFunctions.Add(nlf); if (string.IsNullOrWhiteSpace(domain)) { @@ -315,8 +290,8 @@ namespace BizHawk.Client.Common [LuaMethod("onsavestate", "Fires after a state is saved")] public string OnSaveState(LuaFunction luaf, string name = null) { - var nlf = new NamedLuaFunction(luaf, "OnSavestateSave", LogOutputCallback, CurrentThread, name); - _luaFunctions.Add(nlf); + var nlf = new NamedLuaFunction(luaf, "OnSavestateSave", LogOutputCallback, CurrentFile, name); + RegisteredFunctions.Add(nlf); return nlf.Guid.ToString(); } @@ -324,8 +299,8 @@ namespace BizHawk.Client.Common [LuaMethod("onexit", "Fires after the calling script has stopped")] public string OnExit(LuaFunction luaf, string name = null) { - var nlf = new NamedLuaFunction(luaf, "OnExit", LogOutputCallback, CurrentThread, name); - _luaFunctions.Add(nlf); + var nlf = new NamedLuaFunction(luaf, "OnExit", LogOutputCallback, CurrentFile, name); + RegisteredFunctions.Add(nlf); return nlf.Guid.ToString(); } @@ -333,9 +308,9 @@ namespace BizHawk.Client.Common [LuaMethod("unregisterbyid", "Removes the registered function that matches the guid. If a function is found and remove the function will return true. If unable to find a match, the function will return false.")] public bool UnregisterById(string guid) { - foreach (var nlf in _luaFunctions.Where(nlf => nlf.Guid.ToString() == guid.ToString())) + foreach (var nlf in RegisteredFunctions.Where(nlf => nlf.Guid.ToString() == guid)) { - _luaFunctions.Remove(nlf); + RegisteredFunctions.Remove(nlf); return true; } @@ -346,9 +321,9 @@ namespace BizHawk.Client.Common [LuaMethod("unregisterbyname", "Removes the first registered function that matches Name. If a function is found and remove the function will return true. If unable to find a match, the function will return false.")] public bool UnregisterByName(string name) { - foreach (var nlf in _luaFunctions.Where(nlf => nlf.Name == name)) + foreach (var nlf in RegisteredFunctions.Where(nlf => nlf.Name == name)) { - _luaFunctions.Remove(nlf); + RegisteredFunctions.Remove(nlf); return true; } diff --git a/BizHawk.Client.Common/lua/EmuLuaLibrary.GameInfo.cs b/BizHawk.Client.Common/lua/EmuLuaLibrary.GameInfo.cs index 61d2d4afb0..5c846844ed 100644 --- a/BizHawk.Client.Common/lua/EmuLuaLibrary.GameInfo.cs +++ b/BizHawk.Client.Common/lua/EmuLuaLibrary.GameInfo.cs @@ -3,6 +3,8 @@ using NLua; using BizHawk.Emulation.Common; +// ReSharper disable UnusedMember.Global +// ReSharper disable UnusedAutoPropertyAccessor.Local namespace BizHawk.Client.Common { public sealed class GameInfoLuaLibrary : LuaLibraryBase @@ -22,24 +24,14 @@ namespace BizHawk.Client.Common [LuaMethod("getromname", "returns the name of the currently loaded rom, if a rom is loaded")] public string GetRomName() { - if (Global.Game != null) - { - return Global.Game.Name ?? ""; - } - - return ""; + return Global.Game?.Name ?? ""; } [LuaMethodExample("local stgamget = gameinfo.getromhash( );")] [LuaMethod("getromhash", "returns the hash of the currently loaded rom, if a rom is loaded")] public string GetRomHash() { - if (Global.Game != null) - { - return Global.Game.Hash ?? ""; - } - - return ""; + return Global.Game?.Hash ?? ""; } [LuaMethodExample("if ( gameinfo.indatabase( ) ) then\r\n\tconsole.log( \"returns whether or not the currently loaded rom is in the game database\" );\r\nend;")] @@ -58,24 +50,14 @@ namespace BizHawk.Client.Common [LuaMethod("getstatus", "returns the game database status of the currently loaded rom. Statuses are for example: GoodDump, BadDump, Hack, Unknown, NotInDatabase")] public string GetStatus() { - if (Global.Game != null) - { - return Global.Game.Status.ToString(); - } - - return ""; + return Global.Game?.Status.ToString(); } [LuaMethodExample("if ( gameinfo.isstatusbad( ) ) then\r\n\tconsole.log( \"returns the currently loaded rom's game database status is considered 'bad'\" );\r\nend;")] [LuaMethod("isstatusbad", "returns the currently loaded rom's game database status is considered 'bad'")] public bool IsStatusBad() { - if (Global.Game != null) - { - return Global.Game.IsRomStatusBad(); - } - - return true; + return Global.Game?.IsRomStatusBad() ?? true; } [LuaMethodExample("local stgamget = gameinfo.getboardtype( );")] diff --git a/BizHawk.Client.Common/lua/EmuLuaLibrary.Genesis.cs b/BizHawk.Client.Common/lua/EmuLuaLibrary.Genesis.cs index de469a25d7..5f51bc827b 100644 --- a/BizHawk.Client.Common/lua/EmuLuaLibrary.Genesis.cs +++ b/BizHawk.Client.Common/lua/EmuLuaLibrary.Genesis.cs @@ -6,6 +6,8 @@ using NLua; using BizHawk.Emulation.Common; using BizHawk.Emulation.Cores.Consoles.Sega.gpgx; +// ReSharper disable UnusedMember.Global +// ReSharper disable UnusedAutoPropertyAccessor.Local namespace BizHawk.Client.Common { [Description("Functions specific to GenesisHawk (functions may not run when an Genesis game is not loaded)")] @@ -24,12 +26,9 @@ namespace BizHawk.Client.Common private GPGX.GPGXSettings GetSettings() { - if (Genesis != null) - { - return Genesis.GetSettings(); - } - - return new GPGX.GPGXSettings(); + return Genesis != null + ? Genesis.GetSettings() + : new GPGX.GPGXSettings(); } private void PutSettings(GPGX.GPGXSettings settings) diff --git a/BizHawk.Client.Common/lua/EmuLuaLibrary.Joypad.cs b/BizHawk.Client.Common/lua/EmuLuaLibrary.Joypad.cs index 6c8ebe32be..3588c8fff8 100644 --- a/BizHawk.Client.Common/lua/EmuLuaLibrary.Joypad.cs +++ b/BizHawk.Client.Common/lua/EmuLuaLibrary.Joypad.cs @@ -1,6 +1,7 @@ using System; using NLua; +// ReSharper disable UnusedMember.Global namespace BizHawk.Client.Common { public sealed class JoypadLuaLibrary : LuaLibraryBase diff --git a/BizHawk.Client.Common/lua/EmuLuaLibrary.MainMemory.cs b/BizHawk.Client.Common/lua/EmuLuaLibrary.MainMemory.cs index 1d41611cde..32516ad061 100644 --- a/BizHawk.Client.Common/lua/EmuLuaLibrary.MainMemory.cs +++ b/BizHawk.Client.Common/lua/EmuLuaLibrary.MainMemory.cs @@ -5,6 +5,7 @@ using NLua; using BizHawk.Emulation.Common; using BizHawk.Emulation.Common.IEmulatorExtensions; +// ReSharper disable UnusedMember.Global namespace BizHawk.Client.Common { [Description("Main memory library reads and writes from the Main memory domain (the default memory domain set by any given core)")] diff --git a/BizHawk.Client.Common/lua/EmuLuaLibrary.Memory.cs b/BizHawk.Client.Common/lua/EmuLuaLibrary.Memory.cs index 168920035d..2de8448082 100644 --- a/BizHawk.Client.Common/lua/EmuLuaLibrary.Memory.cs +++ b/BizHawk.Client.Common/lua/EmuLuaLibrary.Memory.cs @@ -6,6 +6,7 @@ using BizHawk.Emulation.Common; using BizHawk.Emulation.Common.IEmulatorExtensions; using BizHawk.Common.BufferExtensions; +// ReSharper disable UnusedMember.Global namespace BizHawk.Client.Common { [Description("These functions behavior identically to the mainmemory functions but the user can set the memory domain to read and write from. The default domain is main memory. Use getcurrentmemorydomain(), and usememorydomain() to control which domain is used. Each core has its own set of valid memory domains. Use getmemorydomainlist() to get a list of memory domains for the current core loaded.")] diff --git a/BizHawk.Client.Common/lua/EmuLuaLibrary.MemorySavestate.cs b/BizHawk.Client.Common/lua/EmuLuaLibrary.MemorySavestate.cs index 8ebb3f5875..acd08d9a4c 100644 --- a/BizHawk.Client.Common/lua/EmuLuaLibrary.MemorySavestate.cs +++ b/BizHawk.Client.Common/lua/EmuLuaLibrary.MemorySavestate.cs @@ -6,6 +6,8 @@ using NLua; using BizHawk.Emulation.Common; +// ReSharper disable UnusedMember.Global +// ReSharper disable UnusedAutoPropertyAccessor.Local namespace BizHawk.Client.Common { public sealed class MemorySavestateEmuLuaLibrary : LuaLibraryBase diff --git a/BizHawk.Client.Common/lua/EmuLuaLibrary.Movie.cs b/BizHawk.Client.Common/lua/EmuLuaLibrary.Movie.cs index 74e15136fb..9b0e1b43f5 100644 --- a/BizHawk.Client.Common/lua/EmuLuaLibrary.Movie.cs +++ b/BizHawk.Client.Common/lua/EmuLuaLibrary.Movie.cs @@ -2,6 +2,7 @@ using System.IO; using NLua; +// ReSharper disable UnusedMember.Global namespace BizHawk.Client.Common { public sealed class MovieLuaLibrary : LuaLibraryBase @@ -176,9 +177,9 @@ namespace BizHawk.Client.Common { // Lua numbers are always double, integer precision holds up // to 53 bits, so throw an error if it's bigger than that. - const double PrecisionLimit = 9007199254740992d; + const double precisionLimit = 9007199254740992d; - if (count > PrecisionLimit) + if (count > precisionLimit) { throw new Exception("Rerecord count exceeds Lua integer precision."); } @@ -208,8 +209,8 @@ namespace BizHawk.Client.Common { var movie = Global.MovieSession.Movie; var system = movie.HeaderEntries[HeaderKeys.PLATFORM]; - var pal = movie.HeaderEntries.ContainsKey(HeaderKeys.PAL) && - movie.HeaderEntries[HeaderKeys.PAL] == "1"; + var pal = movie.HeaderEntries.ContainsKey(HeaderKeys.PAL) + && movie.HeaderEntries[HeaderKeys.PAL] == "1"; return new PlatformFrameRates()[system, pal]; } diff --git a/BizHawk.Client.Common/lua/EmuLuaLibrary.NES.cs b/BizHawk.Client.Common/lua/EmuLuaLibrary.NES.cs index d1e4ea11b1..8cf9c7ad13 100644 --- a/BizHawk.Client.Common/lua/EmuLuaLibrary.NES.cs +++ b/BizHawk.Client.Common/lua/EmuLuaLibrary.NES.cs @@ -8,6 +8,8 @@ using BizHawk.Emulation.Common; using BizHawk.Emulation.Cores.Nintendo.NES; using BizHawk.Emulation.Cores.Consoles.Nintendo.QuickNES; +// ReSharper disable UnusedMember.Global +// ReSharper disable UnusedAutoPropertyAccessor.Local namespace BizHawk.Client.Common { [Description("Functions related specifically to Nes Cores")] @@ -31,7 +33,7 @@ namespace BizHawk.Client.Common private bool NESAvailable => Neshawk != null || Quicknes != null; - private bool HasMemoryDOmains => MemoryDomains != null; + private bool HasMemoryDomains => MemoryDomains != null; public NesLuaLibrary(Lua lua, Action logOutputCallback) : base(lua, logOutputCallback) { } @@ -42,7 +44,7 @@ namespace BizHawk.Client.Common [LuaMethod("addgamegenie", "Adds the specified game genie code. If an NES game is not currently loaded or the code is not a valid game genie code, this will have no effect")] public void AddGameGenie(string code) { - if (NESAvailable && HasMemoryDOmains) + if (NESAvailable && HasMemoryDomains) { var decoder = new NESGameGenieDecoder(code); var watch = Watch.GenerateWatch( diff --git a/BizHawk.Client.Common/lua/EmuLuaLibrary.SNES.cs b/BizHawk.Client.Common/lua/EmuLuaLibrary.SNES.cs index 3a5bbdc617..2d5cdcd6ac 100644 --- a/BizHawk.Client.Common/lua/EmuLuaLibrary.SNES.cs +++ b/BizHawk.Client.Common/lua/EmuLuaLibrary.SNES.cs @@ -4,6 +4,8 @@ using BizHawk.Emulation.Common; using NLua; using BizHawk.Emulation.Cores.Nintendo.SNES; +// ReSharper disable UnusedMember.Global +// ReSharper disable UnusedAutoPropertyAccessor.Local namespace BizHawk.Client.Common { [Description("Functions specific to SNESHawk (functions may not run when an SNES game is not loaded)")] @@ -22,12 +24,9 @@ namespace BizHawk.Client.Common private LibsnesCore.SnesSettings GetSettings() { - if (Snes != null) - { - return Snes.GetSettings(); - } - - return new LibsnesCore.SnesSettings(); + return Snes != null + ? Snes.GetSettings() + : new LibsnesCore.SnesSettings(); } private void PutSettings(LibsnesCore.SnesSettings settings) diff --git a/BizHawk.Client.Common/lua/EmuLuaLibrary.SQL.cs b/BizHawk.Client.Common/lua/EmuLuaLibrary.SQL.cs index 00bcfb92c1..0969c2502f 100644 --- a/BizHawk.Client.Common/lua/EmuLuaLibrary.SQL.cs +++ b/BizHawk.Client.Common/lua/EmuLuaLibrary.SQL.cs @@ -4,21 +4,21 @@ using System.ComponentModel; using System.Data.SQLite; using NLua; +// ReSharper disable UnusedMember.Global namespace BizHawk.Client.Common { [Description("A library for performing SQLite operations.")] - public sealed class SQLLuaLibrary : LuaLibraryBase + public sealed class SqlLuaLibrary : LuaLibraryBase { - public SQLLuaLibrary(Lua lua) + public SqlLuaLibrary(Lua lua) : base(lua) { } - public SQLLuaLibrary(Lua lua, Action logOutputCallback) + public SqlLuaLibrary(Lua lua, Action logOutputCallback) : base(lua, logOutputCallback) { } public override string Name => "SQL"; - SQLiteConnection m_dbConnection; - string connectionString; + SQLiteConnection _mDBConnection; [LuaMethodExample("local stSQLcre = SQL.createdatabase( \"eg_db\" );")] [LuaMethod("createdatabase", "Creates a SQLite Database. Name should end with .db")] @@ -29,11 +29,10 @@ namespace BizHawk.Client.Common SQLiteConnection.CreateFile(name); return "Database Created Successfully"; } - catch (SQLiteException sqlEX) + catch (SQLiteException sqlEx) { - return sqlEX.Message; + return sqlEx.Message; } - } @@ -43,21 +42,23 @@ namespace BizHawk.Client.Common { try { - SQLiteConnectionStringBuilder connBuilder = new SQLiteConnectionStringBuilder(); - connBuilder.DataSource = name; - connBuilder.Version = 3; //SQLite version - connBuilder.JournalMode = SQLiteJournalModeEnum.Wal; //Allows for reads and writes to happen at the same time - connBuilder.DefaultIsolationLevel = System.Data.IsolationLevel.ReadCommitted; //This only helps make the database lock left. May be pointless now - connBuilder.SyncMode = SynchronizationModes.Off; //This shortens the delay for do synchronous calls. - m_dbConnection = new SQLiteConnection(connBuilder.ToString()); - connectionString = connBuilder.ToString(); - m_dbConnection.Open(); - m_dbConnection.Close(); + var connBuilder = new SQLiteConnectionStringBuilder + { + DataSource = name, + Version = 3, + JournalMode = SQLiteJournalModeEnum.Wal, // Allows for reads and writes to happen at the same time + DefaultIsolationLevel = System.Data.IsolationLevel.ReadCommitted, // This only helps make the database lock left. May be pointless now + SyncMode = SynchronizationModes.Off, // This shortens the delay for do synchronous calls. + }; + + _mDBConnection = new SQLiteConnection(connBuilder.ToString()); + _mDBConnection.Open(); + _mDBConnection.Close(); return "Database Opened Successfully"; } - catch (SQLiteException sqlEX) + catch (SQLiteException sqlEx) { - return sqlEX.Message; + return sqlEx.Message; } } @@ -72,11 +73,11 @@ namespace BizHawk.Client.Common } try { - m_dbConnection.Open(); + _mDBConnection.Open(); string sql = query; - SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection); + SQLiteCommand command = new SQLiteCommand(sql, _mDBConnection); command.ExecuteNonQuery(); - m_dbConnection.Close(); + _mDBConnection.Close(); return "Command ran successfully"; @@ -87,7 +88,7 @@ namespace BizHawk.Client.Common } catch (SQLiteException sqlEx) { - m_dbConnection.Close(); + _mDBConnection.Close(); return sqlEx.Message; } } @@ -104,9 +105,9 @@ namespace BizHawk.Client.Common try { var table = Lua.NewTable(); - m_dbConnection.Open(); + _mDBConnection.Open(); string sql = $"PRAGMA read_uncommitted =1;{query}"; - SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection); + using var command = new SQLiteCommand(sql, _mDBConnection); SQLiteDataReader reader = command.ExecuteReader(); bool rows = reader.HasRows; long rowCount = 0; @@ -124,7 +125,7 @@ namespace BizHawk.Client.Common rowCount += 1; } reader.Close(); - m_dbConnection.Close(); + _mDBConnection.Close(); if (rows == false) { return "No rows found"; @@ -137,12 +138,11 @@ namespace BizHawk.Client.Common { return "Database not opened."; } - catch (SQLiteException sqlEX) + catch (SQLiteException sqlEx) { - m_dbConnection.Close(); - return sqlEX.Message; + _mDBConnection.Close(); + return sqlEx.Message; } } - } } diff --git a/BizHawk.Client.Common/lua/EmuLuaLibrary.String.cs b/BizHawk.Client.Common/lua/EmuLuaLibrary.String.cs index ba1afd211e..51ed286115 100644 --- a/BizHawk.Client.Common/lua/EmuLuaLibrary.String.cs +++ b/BizHawk.Client.Common/lua/EmuLuaLibrary.String.cs @@ -4,6 +4,7 @@ using System.Linq; using NLua; +// ReSharper disable UnusedMember.Global namespace BizHawk.Client.Common { [Description("A library exposing standard .NET string methods")] @@ -68,96 +69,66 @@ namespace BizHawk.Client.Common [LuaMethod("replace", "Returns a string that replaces all occurances of str2 in str1 with the value of replace")] public static string Replace(string str, string str2, string replace) { - if (string.IsNullOrEmpty(str)) - { - return null; - } - - return str.Replace(str2, replace); + return string.IsNullOrEmpty(str) + ? null + : str.Replace(str2, replace); } [LuaMethodExample("local stbiztou = bizstring.toupper( \"Some string\" );")] [LuaMethod("toupper", "Returns an uppercase version of the given string")] public static string ToUpper(string str) { - if (string.IsNullOrEmpty(str)) - { - return null; - } - - return str.ToUpper(); + return string.IsNullOrEmpty(str) + ? null + : str.ToUpper(); } [LuaMethodExample("local stbiztol = bizstring.tolower( \"Some string\" );")] [LuaMethod("tolower", "Returns an lowercase version of the given string")] public static string ToLower(string str) { - if (string.IsNullOrEmpty(str)) - { - return null; - } - - return str.ToLower(); + return string.IsNullOrEmpty(str) + ? null + : str.ToLower(); } [LuaMethodExample("local stbizsub = bizstring.substring( \"Some string\", 6, 3 );")] [LuaMethod("substring", "Returns a string that represents a substring of str starting at position for the specified length")] public static string SubString(string str, int position, int length) { - if (string.IsNullOrEmpty(str)) - { - return null; - } - - return str.Substring(position, length); + return string.IsNullOrEmpty(str) + ? null + : str.Substring(position, length); } [LuaMethodExample("local stbizrem = bizstring.remove( \"Some string\", 4, 5 );")] [LuaMethod("remove", "Returns a string that represents str with the given position and count removed")] public static string Remove(string str, int position, int count) { - if (string.IsNullOrEmpty(str)) - { - return null; - } - - return str.Remove(position, count); + return string.IsNullOrEmpty(str) + ? null + : str.Remove(position, count); } [LuaMethodExample("if ( bizstring.contains( \"Some string\", \"Some\") ) then\r\n\tconsole.log( \"Returns whether or not str contains str2\" );\r\nend;")] [LuaMethod("contains", "Returns whether or not str contains str2")] public static bool Contains(string str, string str2) { - if (string.IsNullOrEmpty(str)) - { - return false; - } - - return str.Contains(str2); + return !string.IsNullOrEmpty(str) && str.Contains(str2); } [LuaMethodExample("if ( bizstring.startswith( \"Some string\", \"Some\") ) then\r\n\tconsole.log( \"Returns whether str starts with str2\" );\r\nend;")] [LuaMethod("startswith", "Returns whether str starts with str2")] public static bool StartsWith(string str, string str2) { - if (string.IsNullOrEmpty(str)) - { - return false; - } - - return str.StartsWith(str2); + return !string.IsNullOrEmpty(str) && str.StartsWith(str2); } [LuaMethodExample("if ( bizstring.endswith( \"Some string\", \"string\") ) then\r\n\tconsole.log( \"Returns whether str ends wth str2\" );\r\nend;")] [LuaMethod("endswith", "Returns whether str ends wth str2")] public static bool EndsWith(string str, string str2) { - if (string.IsNullOrEmpty(str)) - { - return false; - } - - return str.EndsWith(str2); + return !string.IsNullOrEmpty(str) && str.EndsWith(str2); } [LuaMethodExample("local nlbizspl = bizstring.split( \"Some, string\", \", \" );")] diff --git a/BizHawk.Client.Common/lua/EmuLuaLibrary.UserData.cs b/BizHawk.Client.Common/lua/EmuLuaLibrary.UserData.cs index 088a19de8e..14eaf17707 100644 --- a/BizHawk.Client.Common/lua/EmuLuaLibrary.UserData.cs +++ b/BizHawk.Client.Common/lua/EmuLuaLibrary.UserData.cs @@ -1,10 +1,9 @@ using System; using System.ComponentModel; - using NLua; - using BizHawk.Client.Common; +// ReSharper disable UnusedMember.Global namespace BizHawk.Client.EmuHawk { [Description("A library for setting and retrieving dynamic data that will be saved and loaded with savestates")] diff --git a/BizHawk.Client.Common/lua/LuaAttributes.cs b/BizHawk.Client.Common/lua/LuaAttributes.cs index 398046f01a..5c012988bd 100644 --- a/BizHawk.Client.Common/lua/LuaAttributes.cs +++ b/BizHawk.Client.Common/lua/LuaAttributes.cs @@ -23,7 +23,6 @@ namespace BizHawk.Client.Common Example = example; } - public string Name { get; } public string Example { get; } } diff --git a/BizHawk.Client.Common/lua/LuaDocumentation.cs b/BizHawk.Client.Common/lua/LuaDocumentation.cs index 8b6b40737e..bf29edf54e 100644 --- a/BizHawk.Client.Common/lua/LuaDocumentation.cs +++ b/BizHawk.Client.Common/lua/LuaDocumentation.cs @@ -186,13 +186,13 @@ __Types and notation__ public string Example => _luaExampleAttribute?.Example; - private string _paramterList = null; + private string _parameterList; public string ParameterList { get { - if (_paramterList == null) + if (_parameterList == null) { var parameters = _method.GetParameters(); @@ -218,10 +218,10 @@ __Types and notation__ } list.Append(')'); - _paramterList = list.ToString(); + _parameterList = list.ToString(); } - return _paramterList; + return _parameterList; } } diff --git a/BizHawk.Client.Common/lua/LuaFileList.cs b/BizHawk.Client.Common/lua/LuaFileList.cs index a8148df357..7ca4c9253e 100644 --- a/BizHawk.Client.Common/lua/LuaFileList.cs +++ b/BizHawk.Client.Common/lua/LuaFileList.cs @@ -15,11 +15,7 @@ namespace BizHawk.Client.Common public bool Changes { - get - { - return _changes; - } - + get => _changes; set { _changes = value; @@ -32,15 +28,8 @@ namespace BizHawk.Client.Common public string Filename { - get - { - return _filename; - } - - set - { - _filename = value ?? ""; - } + get => _filename; + set => _filename = value ?? ""; } public void StopAllScripts() @@ -100,7 +89,7 @@ namespace BizHawk.Client.Common if (!Path.IsPathRooted(scriptPath)) { var directory = Path.GetDirectoryName(path); - scriptPath = Path.GetFullPath(Path.Combine(directory, scriptPath)); + scriptPath = Path.GetFullPath(Path.Combine(directory ?? "", scriptPath)); } Add(new LuaFile(scriptPath) diff --git a/BizHawk.Client.Common/lua/LuaFunctionList.cs b/BizHawk.Client.Common/lua/LuaFunctionList.cs index 87d36e9d3b..7d93144f9d 100644 --- a/BizHawk.Client.Common/lua/LuaFunctionList.cs +++ b/BizHawk.Client.Common/lua/LuaFunctionList.cs @@ -7,13 +7,8 @@ namespace BizHawk.Client.Common { public class LuaFunctionList : List { - public NamedLuaFunction this[string guid] - { - get - { - return this.FirstOrDefault(nlf => nlf.Guid.ToString() == guid); - } - } + public NamedLuaFunction this[string guid] => + this.FirstOrDefault(nlf => nlf.Guid.ToString() == guid); public new bool Remove(NamedLuaFunction function) { @@ -30,6 +25,18 @@ namespace BizHawk.Client.Common return base.Remove(function); } + public void RemoveForFile(LuaFile file) + { + var functionsToRemove = this + .ForFile(file) + .ToList(); + + foreach (var function in functionsToRemove) + { + Remove(function); + } + } + public void ClearAll() { if (Global.Emulator.InputCallbacksAvailable()) @@ -46,4 +53,19 @@ namespace BizHawk.Client.Common Clear(); } } + + public static class LuaFunctionListExtensions + { + public static IEnumerable ForFile(this IEnumerable list, LuaFile luaFile) + { + return list + .Where(l => l.LuaFile.Path == luaFile.Path + || l.LuaFile.Thread == luaFile.Thread); + } + + public static IEnumerable ForEvent(this IEnumerable list, string eventName) + { + return list.Where(l => l.Event == eventName); + } + } } diff --git a/BizHawk.Client.Common/lua/LuaLibraryBase.cs b/BizHawk.Client.Common/lua/LuaLibraryBase.cs index 797be96ebc..bc044f5652 100644 --- a/BizHawk.Client.Common/lua/LuaLibraryBase.cs +++ b/BizHawk.Client.Common/lua/LuaLibraryBase.cs @@ -21,7 +21,7 @@ namespace BizHawk.Client.Common LogOutputCallback = logOutputCallback; } - protected static Lua CurrentThread { get; private set; } + protected static LuaFile CurrentFile { get; private set; } private static Thread CurrentHostThread; private static readonly object ThreadMutex = new object(); @@ -35,11 +35,11 @@ namespace BizHawk.Client.Common lock (ThreadMutex) { CurrentHostThread = null; - CurrentThread = null; + CurrentFile = null; } } - public static void SetCurrentThread(Lua luaThread) + public static void SetCurrentThread(LuaFile luaFile) { lock (ThreadMutex) { @@ -49,7 +49,7 @@ namespace BizHawk.Client.Common } CurrentHostThread = Thread.CurrentThread; - CurrentThread = luaThread; + CurrentFile = luaFile; } } @@ -58,11 +58,6 @@ namespace BizHawk.Client.Common return (int)(double)luaArg; } - protected static uint LuaUInt(object luaArg) - { - return (uint)(double)luaArg; - } - protected static Color? ToColor(object o) { if (o == null) @@ -70,14 +65,14 @@ namespace BizHawk.Client.Common return null; } - if (o.GetType() == typeof(double)) + if (o is double d) { - return Color.FromArgb((int)(long)(double)o); + return Color.FromArgb((int)(long)d); } - if (o.GetType() == typeof(string)) + if (o is string s) { - return Color.FromName(o.ToString()); + return Color.FromName(s); } return null; diff --git a/BizHawk.Client.Common/lua/LuaSandbox.cs b/BizHawk.Client.Common/lua/LuaSandbox.cs index 80fa7ec918..9559949d10 100644 --- a/BizHawk.Client.Common/lua/LuaSandbox.cs +++ b/BizHawk.Client.Common/lua/LuaSandbox.cs @@ -30,7 +30,7 @@ namespace BizHawk.Client.Common { string target = $"{_currentDirectory}\\"; - // first we'll bypass it with a general hack: dont do any setting if the value's already there (even at the OS level, setting the directory can be slow) + // first we'll bypass it with a general hack: don't do any setting if the value's already there (even at the OS level, setting the directory can be slow) // yeah I know, not the smoothest move to compare strings here, in case path normalization is happening at some point // but you got any better ideas? if (currDirSpeedHack == null) @@ -117,8 +117,7 @@ namespace BizHawk.Client.Common lock (SandboxForThread) { - LuaSandbox sandbox; - if (SandboxForThread.TryGetValue(thread, out sandbox)) + if (SandboxForThread.TryGetValue(thread, out var sandbox)) { return sandbox; } diff --git a/BizHawk.Client.Common/lua/NamedLuaFunction.cs b/BizHawk.Client.Common/lua/NamedLuaFunction.cs index bb602e8f62..adaf443a48 100644 --- a/BizHawk.Client.Common/lua/NamedLuaFunction.cs +++ b/BizHawk.Client.Common/lua/NamedLuaFunction.cs @@ -9,12 +9,12 @@ namespace BizHawk.Client.Common { private readonly LuaFunction _function; - public NamedLuaFunction(LuaFunction function, string theevent, Action logCallback, Lua lua, string name = null) + public NamedLuaFunction(LuaFunction function, string theEvent, Action logCallback, LuaFile luaFile, string name = null) { _function = function; Name = name ?? "Anonymous"; - Event = theevent; - Lua = lua; + Event = theEvent; + LuaFile = luaFile; Guid = Guid.NewGuid(); Callback = delegate @@ -35,11 +35,11 @@ namespace BizHawk.Client.Common }; } - public Guid Guid { get; private set; } + public Guid Guid { get; } public string Name { get; } - public Lua Lua { get; } + public LuaFile LuaFile { get; } public string Event { get; } @@ -49,7 +49,7 @@ namespace BizHawk.Client.Common public void Call(string name = null) { - LuaSandbox.Sandbox(Lua, () => + LuaSandbox.Sandbox(LuaFile.Thread, () => { _function.Call(name); }); diff --git a/BizHawk.Client.Common/tools/Watch/WatchList/WatchList.cs b/BizHawk.Client.Common/tools/Watch/WatchList/WatchList.cs index 0c8b93793c..f37f9ecd1e 100644 --- a/BizHawk.Client.Common/tools/Watch/WatchList/WatchList.cs +++ b/BizHawk.Client.Common/tools/Watch/WatchList/WatchList.cs @@ -334,13 +334,7 @@ namespace BizHawk.Client.Common /// /// Gets the number of that are not /// - public int WatchCount - { - get - { - return _watchList.Count(watch => !watch.IsSeparator); - } - } + public int WatchCount => _watchList.Count(watch => !watch.IsSeparator); #endregion diff --git a/BizHawk.Client.EmuHawk/BizHawk.Client.EmuHawk.csproj b/BizHawk.Client.EmuHawk/BizHawk.Client.EmuHawk.csproj index b34dec2252..fa953e5c93 100644 --- a/BizHawk.Client.EmuHawk/BizHawk.Client.EmuHawk.csproj +++ b/BizHawk.Client.EmuHawk/BizHawk.Client.EmuHawk.csproj @@ -972,9 +972,6 @@ LuaWinform.cs - - Component - Form diff --git a/BizHawk.Client.EmuHawk/CustomControls/InputRoll/InputRoll.cs b/BizHawk.Client.EmuHawk/CustomControls/InputRoll/InputRoll.cs index 0b50843a31..82972a4d98 100644 --- a/BizHawk.Client.EmuHawk/CustomControls/InputRoll/InputRoll.cs +++ b/BizHawk.Client.EmuHawk/CustomControls/InputRoll/InputRoll.cs @@ -182,7 +182,7 @@ namespace BizHawk.Client.EmuHawk /// [Category("Appearance")] [DefaultValue(true)] - public bool GridLines { get; set; } + public bool GridLines { get; set; } = true; /// /// Gets or sets a value indicating whether the control is horizontal or vertical @@ -245,9 +245,9 @@ namespace BizHawk.Client.EmuHawk { if (_rowCount != value) { - RecalculateScrollBars(); _rowCount = value; _selectedItems.RemoveWhere(i => i.RowIndex >= _rowCount); + RecalculateScrollBars(); } // Similarly to ListView in virtual mode, we want to always refresh @@ -490,6 +490,8 @@ namespace BizHawk.Client.EmuHawk #region Api + private int? _lastSelectedRow; + public void SelectRow(int index, bool val) { if (_columns.VisibleColumns.Any()) @@ -501,11 +503,13 @@ namespace BizHawk.Client.EmuHawk RowIndex = index, Column = _columns[0] }); + _lastSelectedRow = index; } else { IEnumerable items = _selectedItems.Where(cell => cell.RowIndex == index); _selectedItems.RemoveWhere(items.Contains); + _lastSelectedRow = _selectedItems.LastOrDefault()?.RowIndex; } } } @@ -520,16 +524,19 @@ namespace BizHawk.Client.EmuHawk } FullRowSelect = oldFullRowVal; + _lastSelectedRow = RowCount; } public void DeselectAll() { + _lastSelectedRow = null; _selectedItems.Clear(); } public void TruncateSelection(int index) { _selectedItems.RemoveWhere(cell => cell.RowIndex > index); + _lastSelectedRow = _selectedItems.LastOrDefault()?.RowIndex; } [Browsable(false)] @@ -900,11 +907,6 @@ namespace BizHawk.Client.EmuHawk public bool AnyRowsSelected => _selectedItems.Any(cell => cell.RowIndex.HasValue); - public void ClearSelectedRows() - { - _selectedItems.Clear(); - } - public IEnumerable GenerateContextMenuItems() { yield return new ToolStripSeparator(); @@ -1173,9 +1175,15 @@ namespace BizHawk.Client.EmuHawk _currentY = e.Y; Cell newCell = CalculatePointedCell(_currentX.Value, _currentY.Value); newCell.RowIndex += FirstVisibleRow; - _selectedItems.Clear(); + + // If this cell is not currently selected, clear and select + if (!_selectedItems.Contains(newCell)) + { + _selectedItems.Clear(); + SelectCell(CurrentCell); + } + CellChanged(newCell); - SelectCell(CurrentCell); } } @@ -1378,7 +1386,46 @@ namespace BizHawk.Client.EmuHawk } } } - // Selection courser + else if (!e.Control && e.Shift && !e.Alt && e.KeyCode == Keys.Up) // Shift+Up + { + if (MultiSelect && _lastSelectedRow > 0) + { + if (_selectedItems.Any(i => i.RowIndex == _lastSelectedRow.Value) + && _selectedItems.Any(i => i.RowIndex == _lastSelectedRow - 1)) // Unhighlight if already highlighted + { + SelectRow(_lastSelectedRow.Value, false); + } + else + { + SelectRow(_lastSelectedRow.Value - 1, true); + } + + Refresh(); + } + } + else if (!e.Control && e.Shift && !e.Alt && e.KeyCode == Keys.Down) // Shift+Down + { + if (MultiSelect && _lastSelectedRow < RowCount - 1) + { + if (_selectedItems.Any(i => i.RowIndex == _lastSelectedRow.Value) + && _selectedItems.Any(i => i.RowIndex == _lastSelectedRow + 1)) // Unhighlight if already highlighted + { + var origIndex = _lastSelectedRow.Value; + SelectRow(origIndex, false); + + // SelectRow assumed the max row should be selected, but in this edge case it isn't + _lastSelectedRow = _selectedItems.FirstOrDefault()?.RowIndex; + } + else + { + SelectRow(_lastSelectedRow.Value + 1, true); + + } + + Refresh(); + } + } + // Selection cursor else if (e.Control && !e.Shift && !e.Alt && e.KeyCode == Keys.Up) // Ctrl + Up { if (SelectedRows.Any() && LetKeysModifySelection && SelectedRows.First() > 0) @@ -1672,6 +1719,7 @@ namespace BizHawk.Client.EmuHawk if (!MultiSelect) { _selectedItems.Clear(); + _lastSelectedRow = null; } if (FullRowSelect) @@ -1679,6 +1727,7 @@ namespace BizHawk.Client.EmuHawk if (toggle && _selectedItems.Any(x => x.RowIndex.HasValue && x.RowIndex == cell.RowIndex)) { _selectedItems.RemoveWhere(x => x.RowIndex.HasValue && x.RowIndex == cell.RowIndex); + _lastSelectedRow = _selectedItems.LastOrDefault()?.RowIndex; } else { @@ -1689,11 +1738,13 @@ namespace BizHawk.Client.EmuHawk RowIndex = cell.RowIndex, Column = column }); + _lastSelectedRow = cell.RowIndex; } } } else { + _lastSelectedRow = null; // TODO: tracking this by cell is a lot more work if (toggle && _selectedItems.Any(x => x.RowIndex.HasValue && x.RowIndex == cell.RowIndex)) { var item = _selectedItems diff --git a/BizHawk.Client.EmuHawk/DisplayManager/Filters/Retro.cs b/BizHawk.Client.EmuHawk/DisplayManager/Filters/Retro.cs index 72e20b9c7f..ca756988c6 100644 --- a/BizHawk.Client.EmuHawk/DisplayManager/Filters/Retro.cs +++ b/BizHawk.Client.EmuHawk/DisplayManager/Filters/Retro.cs @@ -45,36 +45,39 @@ namespace BizHawk.Client.EmuHawk.Filters Owner = owner; this.Preset = preset; Passes = preset.Passes.ToArray(); - - bool ok = true; Errors = ""; //load up the shaders Shaders = new RetroShader[preset.Passes.Count]; - for (int i = 0; i < preset.Passes.Count; i++) + for (var i = 0; i < preset.Passes.Count; i++) { - RetroShaderPreset.ShaderPass pass = preset.Passes[i]; - //acquire content - string path = Path.Combine(baseDirectory, pass.ShaderPath); - if (!File.Exists(path)) + var path = Path.Combine(baseDirectory, preset.Passes[i].ShaderPath); + string content; + try { - ok = false; - break; + content = ResolveIncludes(File.ReadAllText(path), Path.GetDirectoryName(path)); + } + catch (DirectoryNotFoundException e) + { + Errors += $"caught {nameof(DirectoryNotFoundException)}: {e.Message}\n"; + return; + } + catch (FileNotFoundException e) + { + Errors += $"could not read file {e.FileName}\n"; + return; } - string content = ResolveIncludes(File.ReadAllText(path), Path.GetDirectoryName(path)); - - var shader = new RetroShader(Owner, content, debug); - Shaders[i] = shader; + var shader = Shaders[i] = new RetroShader(Owner, content, debug); if (!shader.Available) { - Errors += $"===================\r\nPass {i}:\r\n{shader.Errors}"; - ok = false; + Errors += $"===================\r\nPass {i}:\r\n{shader.Errors}\n"; + return; } } - Available = ok; + Available = true; } public void Dispose() @@ -85,12 +88,9 @@ namespace BizHawk.Client.EmuHawk.Filters _isDisposed = true; } - /// - /// Whether this shader chain is available (it wont be available if some resources failed to load or compile) - /// - public bool Available { get; private set; } - public string Errors { get; private set; } - + /// Whether this shader chain is available (it wont be available if some resources failed to load or compile) + public readonly bool Available; + public readonly string Errors; public readonly IGL Owner; public readonly RetroShaderPreset Preset; public readonly RetroShader[] Shaders; diff --git a/BizHawk.Client.EmuHawk/Extensions/ControlExtensions.cs b/BizHawk.Client.EmuHawk/Extensions/ControlExtensions.cs index 1f960f340f..43a2f92af1 100644 --- a/BizHawk.Client.EmuHawk/Extensions/ControlExtensions.cs +++ b/BizHawk.Client.EmuHawk/Extensions/ControlExtensions.cs @@ -131,7 +131,7 @@ namespace BizHawk.Client.EmuHawk.WinFormExtensions public static DialogResult ShowHawkDialog(this CommonDialog form) { GlobalWin.Sound.StopSound(); - using var tempForm = new Form() { TopMost = true }; + using var tempForm = new Form { TopMost = true }; var result = form.ShowDialog(tempForm); GlobalWin.Sound.StartSound(); return result; diff --git a/BizHawk.Client.EmuHawk/Extensions/ToolExtensions.cs b/BizHawk.Client.EmuHawk/Extensions/ToolExtensions.cs index 3e71f5ff11..5a69c03c8c 100644 --- a/BizHawk.Client.EmuHawk/Extensions/ToolExtensions.cs +++ b/BizHawk.Client.EmuHawk/Extensions/ToolExtensions.cs @@ -14,7 +14,7 @@ namespace BizHawk.Client.EmuHawk.ToolExtensions { public static class ToolExtensions { - public static ToolStripItem[] RecentMenu(this RecentFiles recent, Action loadFileCallback, bool autoload = false, bool romloading = false) + public static ToolStripItem[] RecentMenu(this RecentFiles recent, Action loadFileCallback, bool autoload = false, bool romLoading = false) { var items = new List(); @@ -33,7 +33,7 @@ namespace BizHawk.Client.EmuHawk.ToolExtensions bool crazyStuff = true; //sentinel for newer format OpenAdvanced type code - if (romloading) + if (romLoading) { if (filename.StartsWith("*")) { @@ -41,15 +41,15 @@ namespace BizHawk.Client.EmuHawk.ToolExtensions caption = oa.DisplayName; crazyStuff = false; - if (oa is OpenAdvanced_OpenRom) + if (oa is OpenAdvanced_OpenRom openRom) { crazyStuff = true; - physicalPath = ((oa as OpenAdvanced_OpenRom).Path); + physicalPath = openRom.Path; } } } - //TODO - do TSMI and TSDD need disposing? yuck + // TODO - do TSMI and TSDD need disposing? yuck var item = new ToolStripMenuItem { Text = caption.Replace("&", "&&") }; items.Add(item); @@ -65,9 +65,7 @@ namespace BizHawk.Client.EmuHawk.ToolExtensions //TODO - use standard methods to split filename (hawkfile acquire?) var hf = new HawkFile(); hf.Parse(physicalPath); - bool canExplore = true; - if (!File.Exists(hf.FullPathWithoutMember)) - canExplore = false; + bool canExplore = File.Exists(hf.FullPathWithoutMember); if (canExplore) { @@ -82,11 +80,11 @@ namespace BizHawk.Client.EmuHawk.ToolExtensions { //make a menuitem to let you copy the path var tsmiCopyCanonicalPath = new ToolStripMenuItem { Text = "&Copy Canonical Path" }; - tsmiCopyCanonicalPath.Click += (o, ev) => { System.Windows.Forms.Clipboard.SetText(physicalPath); }; + tsmiCopyCanonicalPath.Click += (o, ev) => { Clipboard.SetText(physicalPath); }; tsdd.Items.Add(tsmiCopyCanonicalPath); var tsmiCopyArchivePath = new ToolStripMenuItem { Text = "Copy Archive Path" }; - tsmiCopyArchivePath.Click += (o, ev) => { System.Windows.Forms.Clipboard.SetText(hf.FullPathWithoutMember); }; + tsmiCopyArchivePath.Click += (o, ev) => { Clipboard.SetText(hf.FullPathWithoutMember); }; tsdd.Items.Add(tsmiCopyArchivePath); var tsmiOpenArchive = new ToolStripMenuItem { Text = "Open &Archive" }; @@ -95,24 +93,27 @@ namespace BizHawk.Client.EmuHawk.ToolExtensions } else { - //make a menuitem to let you copy the path + // make a menuitem to let you copy the path var tsmiCopyPath = new ToolStripMenuItem { Text = "&Copy Path" }; - tsmiCopyPath.Click += (o, ev) => { System.Windows.Forms.Clipboard.SetText(physicalPath); }; + tsmiCopyPath.Click += (o, ev) => { Clipboard.SetText(physicalPath); }; tsdd.Items.Add(tsmiCopyPath); } tsdd.Items.Add(new ToolStripSeparator()); - //make a menuitem to let you explore to it + // make a menuitem to let you explore to it var tsmiExplore = new ToolStripMenuItem { Text = "&Explore" }; string explorePath = $"\"{hf.FullPathWithoutMember}\""; tsmiExplore.Click += (o, ev) => { System.Diagnostics.Process.Start("explorer.exe", $"/select, {explorePath}"); }; tsdd.Items.Add(tsmiExplore); var tsmiCopyFile = new ToolStripMenuItem { Text = "Copy &File" }; - var lame = new System.Collections.Specialized.StringCollection(); - lame.Add(hf.FullPathWithoutMember); - tsmiCopyFile.Click += (o, ev) => { System.Windows.Forms.Clipboard.SetFileDropList(lame); }; + var lame = new System.Collections.Specialized.StringCollection + { + hf.FullPathWithoutMember + }; + + tsmiCopyFile.Click += (o, ev) => { Clipboard.SetFileDropList(lame); }; tsdd.Items.Add(tsmiCopyFile); var tsmiTest = new ToolStripMenuItem { Text = "&Shell Context Menu" }; @@ -173,13 +174,13 @@ namespace BizHawk.Client.EmuHawk.ToolExtensions items.Add(new ToolStripSeparator()); - var clearitem = new ToolStripMenuItem { Text = "&Clear", Enabled = !recent.Frozen }; - clearitem.Click += (o, ev) => recent.Clear(); - items.Add(clearitem); + var clearItem = new ToolStripMenuItem { Text = "&Clear", Enabled = !recent.Frozen }; + clearItem.Click += (o, ev) => recent.Clear(); + items.Add(clearItem); - var freezeitem = new ToolStripMenuItem { Text = recent.Frozen ? "&Unfreeze" : "&Freeze" }; - freezeitem.Click += (o, ev) => recent.Frozen ^= true; - items.Add(freezeitem); + var freezeItem = new ToolStripMenuItem { Text = recent.Frozen ? "&Unfreeze" : "&Freeze" }; + freezeItem.Click += (o, ev) => recent.Frozen ^= true; + items.Add(freezeItem); if (autoload) { @@ -188,26 +189,24 @@ namespace BizHawk.Client.EmuHawk.ToolExtensions items.Add(auto); } - var settingsitem = new ToolStripMenuItem { Text = "&Recent Settings..." }; - settingsitem.Click += (o, ev) => + var settingsItem = new ToolStripMenuItem { Text = "&Recent Settings..." }; + settingsItem.Click += (o, ev) => { - using (var prompt = new InputPrompt + using var prompt = new InputPrompt { TextInputType = InputPrompt.InputType.Unsigned, Message = "Number of recent files to track", InitialValue = recent.MAX_RECENT_FILES.ToString() - }) + }; + var result = prompt.ShowDialog(); + if (result == DialogResult.OK) { - var result = prompt.ShowDialog(); - if (result == DialogResult.OK) - { - int val = int.Parse(prompt.PromptText); - if (val > 0) - recent.MAX_RECENT_FILES = val; - } + int val = int.Parse(prompt.PromptText); + if (val > 0) + recent.MAX_RECENT_FILES = val; } }; - items.Add(settingsitem); + items.Add(settingsItem); return items.ToArray(); } @@ -217,18 +216,15 @@ namespace BizHawk.Client.EmuHawk.ToolExtensions GlobalWin.Sound.StopSound(); if (recent.Frozen) { - var result = MessageBox.Show($"Could not open {path}", "File not found", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Could not open {path}", "File not found", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { // ensure topmost, not to have to minimize everything to see and use our modal window, if it somehow got covered - var result = MessageBox.Show(new Form(){TopMost = true}, $"Could not open {path}\nRemove from list?", "File not found", MessageBoxButtons.YesNo, MessageBoxIcon.Error); + var result = MessageBox.Show(new Form { TopMost = true }, $"Could not open {path}\nRemove from list?", "File not found", MessageBoxButtons.YesNo, MessageBoxIcon.Error); if (result == DialogResult.Yes) { - if (encodedPath != null) - recent.Remove(encodedPath); - else - recent.Remove(path); + recent.Remove(encodedPath ?? path); } } diff --git a/BizHawk.Client.EmuHawk/MainForm.Designer.cs b/BizHawk.Client.EmuHawk/MainForm.Designer.cs index 2999c02b63..cf88006485 100644 --- a/BizHawk.Client.EmuHawk/MainForm.Designer.cs +++ b/BizHawk.Client.EmuHawk/MainForm.Designer.cs @@ -360,6 +360,8 @@ this.GGLsettingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.VectrexSubMenu = new System.Windows.Forms.ToolStripMenuItem(); this.VectrexsettingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.O2HawkSubMenu = new System.Windows.Forms.ToolStripMenuItem(); + this.O2HawksettingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.GenesisSubMenu = new System.Windows.Forms.ToolStripMenuItem(); this.vDPViewerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.GenesisGameGenieECDC = new System.Windows.Forms.ToolStripMenuItem(); @@ -527,6 +529,7 @@ this.neoGeoPocketToolStripMenuItem, this.zXSpectrumToolStripMenuItem, this.VectrexSubMenu, + this.O2HawkSubMenu, this.HelpSubMenu, this.amstradCPCToolStripMenuItem}); this.MainformMenu.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.Flow; @@ -3256,6 +3259,21 @@ this.VectrexsettingsToolStripMenuItem.Text = "Settings..."; this.VectrexsettingsToolStripMenuItem.Click += new System.EventHandler(this.VectrexSettingsMenuItem_Click); // + // O2HawkSubMenu + // + this.O2HawkSubMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.O2HawksettingsToolStripMenuItem}); + this.O2HawkSubMenu.Name = "O2HawkSubMenu"; + this.O2HawkSubMenu.Size = new System.Drawing.Size(60, 19); + this.O2HawkSubMenu.Text = "&O2Hawk"; + // + // O2HawksettingsToolStripMenuItem + // + this.O2HawksettingsToolStripMenuItem.Name = "O2HawksettingsToolStripMenuItem"; + this.O2HawksettingsToolStripMenuItem.Size = new System.Drawing.Size(125, 22); + this.O2HawksettingsToolStripMenuItem.Text = "Settings..."; + this.O2HawksettingsToolStripMenuItem.Click += new System.EventHandler(this.O2HawkSettingsMenuItem_Click); + // // GenesisSubMenu // this.GenesisSubMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { @@ -4592,6 +4610,8 @@ private System.Windows.Forms.ToolStripMenuItem GGLsettingsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem VectrexSubMenu; private System.Windows.Forms.ToolStripMenuItem VectrexsettingsToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem O2HawkSubMenu; + private System.Windows.Forms.ToolStripMenuItem O2HawksettingsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem GenesisSubMenu; private System.Windows.Forms.ToolStripMenuItem GenesisSettingsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem AtariSettingsToolStripMenuItem; diff --git a/BizHawk.Client.EmuHawk/MainForm.Events.cs b/BizHawk.Client.EmuHawk/MainForm.Events.cs index fe6687df98..0f587323d7 100644 --- a/BizHawk.Client.EmuHawk/MainForm.Events.cs +++ b/BizHawk.Client.EmuHawk/MainForm.Events.cs @@ -2379,6 +2379,15 @@ namespace BizHawk.Client.EmuHawk #endregion + #region O2Hawk + + private void O2HawkSettingsMenuItem_Click(object sender, EventArgs e) + { + GenericCoreConfig.DoDialog(this, "Odyssey Settings"); + } + + #endregion + #region GEN private void GenVdpViewerMenuItem_Click(object sender, EventArgs e) diff --git a/BizHawk.Client.EmuHawk/MainForm.cs b/BizHawk.Client.EmuHawk/MainForm.cs index d8c5aa012b..9066688aac 100644 --- a/BizHawk.Client.EmuHawk/MainForm.cs +++ b/BizHawk.Client.EmuHawk/MainForm.cs @@ -1719,6 +1719,7 @@ namespace BizHawk.Client.EmuHawk zXSpectrumToolStripMenuItem.Visible = false; amstradCPCToolStripMenuItem.Visible = false; VectrexSubMenu.Visible = false; + O2HawkSubMenu.Visible = false; switch (system) { @@ -1837,6 +1838,9 @@ namespace BizHawk.Client.EmuHawk case "VEC": VectrexSubMenu.Visible = true; break; + case "O2": + O2HawkSubMenu.Visible = true; + break; case "GB3x": GB3xSubMenu.Visible = true; break; diff --git a/BizHawk.Client.EmuHawk/PresentationPanel.cs b/BizHawk.Client.EmuHawk/PresentationPanel.cs index b647f2ce01..ab04ffe991 100644 --- a/BizHawk.Client.EmuHawk/PresentationPanel.cs +++ b/BizHawk.Client.EmuHawk/PresentationPanel.cs @@ -1,17 +1,9 @@ -using System; -using System.Drawing; -using sd=System.Drawing; -using sysdrawingfont=System.Drawing.Font; -using sysdrawing2d=System.Drawing.Drawing2D; -using System.IO; -using System.Threading; +using System.Drawing; using System.Windows.Forms; using BizHawk.Client.Common; using BizHawk.Bizware.BizwareGL; -using OpenTK.Graphics.OpenGL; - namespace BizHawk.Client.EmuHawk { /// @@ -23,23 +15,25 @@ namespace BizHawk.Client.EmuHawk { GL = GlobalWin.GL; - GraphicsControl = new GraphicsControl(GL); - GraphicsControl.Dock = DockStyle.Fill; - GraphicsControl.BackColor = Color.Black; + GraphicsControl = new GraphicsControl(GL) + { + Dock = DockStyle.Fill, + BackColor = Color.Black + }; - //pass through these events to the form. we might need a more scalable solution for mousedown etc. for zapper and whatnot. - //http://stackoverflow.com/questions/547172/pass-through-mouse-events-to-parent-control (HTTRANSPARENT) - GraphicsControl.MouseDoubleClick += (o, e) => HandleFullscreenToggle(o, e); + // pass through these events to the form. we might need a more scalable solution for mousedown etc. for zapper and whatnot. + // http://stackoverflow.com/questions/547172/pass-through-mouse-events-to-parent-control (HTTRANSPARENT) + GraphicsControl.MouseDoubleClick += HandleFullscreenToggle; GraphicsControl.MouseClick += (o, e) => GlobalWin.MainForm.MainForm_MouseClick(o, e); GraphicsControl.MouseMove += (o, e) => GlobalWin.MainForm.MainForm_MouseMove(o, e); GraphicsControl.MouseWheel += (o, e) => GlobalWin.MainForm.MainForm_MouseWheel(o, e); } - bool IsDisposed = false; + private bool _isDisposed; public void Dispose() { - if (IsDisposed) return; - IsDisposed = true; + if (_isDisposed) return; + _isDisposed = true; GraphicsControl.Dispose(); } @@ -47,14 +41,14 @@ namespace BizHawk.Client.EmuHawk IGL GL; public GraphicsControl GraphicsControl; - public Control Control { get { return GraphicsControl; } } + public Control Control => GraphicsControl; public static implicit operator Control(PresentationPanel self) { return self.GraphicsControl; } private void HandleFullscreenToggle(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { - //allow suppression of the toggle.. but if shift is pressed, always do the toggle + // allow suppression of the toggle.. but if shift is pressed, always do the toggle bool allowSuppress = Control.ModifierKeys != Keys.Shift; if (Global.Config.DispChrome_AllowDoubleClickFullscreen || !allowSuppress) { @@ -65,11 +59,8 @@ namespace BizHawk.Client.EmuHawk public bool Resized { get; set; } - public Size NativeSize { get { return GraphicsControl.ClientSize; } } + public Size NativeSize => GraphicsControl.ClientSize; } - - public interface IBlitterFont { } - } diff --git a/BizHawk.Client.EmuHawk/movie/RecordMovie.Designer.cs b/BizHawk.Client.EmuHawk/movie/RecordMovie.Designer.cs index 9bad7a0962..582ddf2adf 100644 --- a/BizHawk.Client.EmuHawk/movie/RecordMovie.Designer.cs +++ b/BizHawk.Client.EmuHawk/movie/RecordMovie.Designer.cs @@ -47,7 +47,7 @@ // this.Cancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.Cancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; - this.Cancel.Location = new System.Drawing.Point(391, 139); + this.Cancel.Location = new System.Drawing.Point(391, 135); this.Cancel.Name = "Cancel"; this.Cancel.Size = new System.Drawing.Size(75, 23); this.Cancel.TabIndex = 1; @@ -58,7 +58,7 @@ // OK // this.OK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); - this.OK.Location = new System.Drawing.Point(310, 139); + this.OK.Location = new System.Drawing.Point(310, 135); this.OK.Name = "OK"; this.OK.Size = new System.Drawing.Size(75, 23); this.OK.TabIndex = 0; diff --git a/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.Forms.cs b/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.Forms.cs index 869843689a..f1a53542b8 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.Forms.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.Forms.cs @@ -302,9 +302,9 @@ namespace BizHawk.Client.EmuHawk { if (control.Handle == ptr) { - if (control is LuaCheckbox) + if (control is LuaCheckbox checkbox) { - return (control as LuaCheckbox).Checked; + return checkbox.Checked; } return false; @@ -360,7 +360,7 @@ namespace BizHawk.Client.EmuHawk "newform", "creates a new default dialog, if both width and height are specified it will create a dialog of the specified size. If title is specified it will be the caption of the dialog, else the dialog caption will be 'Lua Dialog'. The function will return an int representing the handle of the dialog created.")] public int NewForm(int? width = null, int? height = null, string title = null, LuaFunction onClose = null) { - var form = new LuaWinform(CurrentThread); + var form = new LuaWinform(CurrentFile); _luaForms.Add(form); if (width.HasValue && height.HasValue) { diff --git a/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.cs b/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.cs index 7b031f9214..f89149e2ae 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.cs @@ -64,7 +64,7 @@ namespace BizHawk.Client.EmuHawk var attributes = lib.GetCustomAttributes(typeof(LuaLibraryAttribute), false); if (attributes.Any()) { - addLibrary = VersionInfo.DeveloperBuild || (attributes.First() as LuaLibraryAttribute).Released; + addLibrary = VersionInfo.DeveloperBuild || ((LuaLibraryAttribute)attributes.First()).Released; } if (addLibrary) @@ -133,7 +133,6 @@ namespace BizHawk.Client.EmuHawk } } - public bool IsRunning { get; set; } public bool FrameAdvanceRequested { get; private set; } public override LuaFunctionList RegisteredFunctions => EventsLibrary.RegisteredFunctions; @@ -163,14 +162,9 @@ namespace BizHawk.Client.EmuHawk EventsLibrary.CallFrameAfterEvent(); } - public void CallExitEvent(Lua thread) - { - EventsLibrary.CallExitEvent(thread); - } - public override void CallExitEvent(LuaFile lf) { - CallExitEvent(lf.Thread); + EventsLibrary.CallExitEvent(lf); } public override void Close() @@ -209,20 +203,20 @@ namespace BizHawk.Client.EmuHawk _lua.Pop(); } - public ResumeResult ResumeScript(Lua script) + public override ResumeResult ResumeScript(LuaFile lf) { - _currThread = script; + _currThread = lf.Thread; try { - LuaLibraryBase.SetCurrentThread(_currThread); + LuaLibraryBase.SetCurrentThread(lf); - var execResult = script.Resume(0); + var execResult = _currThread.Resume(0); _lua.RunScheduledDisposes(); // not sure how this is going to work out, so do this too - script.RunScheduledDisposes(); + _currThread.RunScheduledDisposes(); _currThread = null; var result = new ResumeResult(); @@ -246,11 +240,6 @@ namespace BizHawk.Client.EmuHawk } } - public override ResumeResult ResumeScriptFromThreadOf(LuaFile lf) - { - return ResumeScript(lf.Thread); - } - public static void Print(params object[] outputs) { ConsoleLuaLibrary.Log(outputs); diff --git a/BizHawk.Client.EmuHawk/tools/Lua/Libraries/NotReallyLuaLibrary.cs b/BizHawk.Client.EmuHawk/tools/Lua/Libraries/NotReallyLuaLibrary.cs index 156a47cfe5..96f4ab85cd 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/Libraries/NotReallyLuaLibrary.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/Libraries/NotReallyLuaLibrary.cs @@ -40,7 +40,7 @@ namespace BizHawk.Client.EmuHawk { } private static readonly EmuLuaLibrary.ResumeResult EmptyResumeResult = new EmuLuaLibrary.ResumeResult(); - public override EmuLuaLibrary.ResumeResult ResumeScriptFromThreadOf(LuaFile lf) + public override EmuLuaLibrary.ResumeResult ResumeScript(LuaFile lf) { return EmptyResumeResult; } diff --git a/BizHawk.Client.EmuHawk/tools/Lua/Libraries/PlatformEmuLuaLibrary.cs b/BizHawk.Client.EmuHawk/tools/Lua/Libraries/PlatformEmuLuaLibrary.cs index d831bbd078..4e4bedc80b 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/Libraries/PlatformEmuLuaLibrary.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/Libraries/PlatformEmuLuaLibrary.cs @@ -29,7 +29,7 @@ namespace BizHawk.Client.EmuHawk public abstract void EndLuaDrawing(); public abstract void ExecuteString(string command); public abstract void Restart(IEmulatorServiceProvider newServiceProvider); - public abstract EmuLuaLibrary.ResumeResult ResumeScriptFromThreadOf(LuaFile lf); + public abstract EmuLuaLibrary.ResumeResult ResumeScript(LuaFile lf); public abstract void SpawnAndSetFileThread(string pathToLoad, LuaFile lf); public abstract void StartLuaDrawing(); public abstract void WindowClosed(IntPtr handle); diff --git a/BizHawk.Client.EmuHawk/tools/Lua/LuaButton.cs b/BizHawk.Client.EmuHawk/tools/Lua/LuaButton.cs index eab3a6accc..fd1f578b93 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/LuaButton.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/LuaButton.cs @@ -5,15 +5,9 @@ namespace BizHawk.Client.EmuHawk { internal class LuaButton : Button { - private void DoLuaClick(object sender, EventArgs e) - { - LuaWinform parent = Parent as LuaWinform; - parent?.DoLuaEvent(Handle); - } - protected override void OnClick(EventArgs e) { - DoLuaClick(this, e); + (Parent as LuaWinform)?.DoLuaEvent(Handle); base.OnClick(e); } } diff --git a/BizHawk.Client.EmuHawk/tools/Lua/LuaCanvas.cs b/BizHawk.Client.EmuHawk/tools/Lua/LuaCanvas.cs index b3d0f5f424..38c0e7c4cf 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/LuaCanvas.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/LuaCanvas.cs @@ -1,3 +1,4 @@ +using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; @@ -5,16 +6,13 @@ using System.IO; using BizHawk.Client.Common; using NLua; -using System; -using System.Collections.Generic; +// ReSharper disable UnusedMember.Global namespace BizHawk.Client.EmuHawk { [Description("Represents a canvas object returned by the gui.createcanvas() method")] public partial class LuaCanvas : Form { - //public List ControlEvents { get; } = new List(); - public LuaCanvas(int width, int height, int? x = null, int? y = null) { InitializeComponent(); @@ -24,7 +22,7 @@ namespace BizHawk.Client.EmuHawk if (x.HasValue) { - StartPosition = System.Windows.Forms.FormStartPosition.Manual; + StartPosition = FormStartPosition.Manual; Left = (int)x; if (y.HasValue) { @@ -50,9 +48,9 @@ namespace BizHawk.Client.EmuHawk "Sets the location of the canvas window")] public void SetLocation(int x, int y) { - StartPosition = System.Windows.Forms.FormStartPosition.Manual; - Left = (int)x; - Top = (int)y; + StartPosition = FormStartPosition.Manual; + Left = x; + Top = y; } [LuaMethodExample( @@ -99,7 +97,7 @@ namespace BizHawk.Client.EmuHawk "LuaCanvas.setDefaultTextBackground( 0x000000FF );")] [LuaMethod( "setDefaultTextBackground", - "Sets the default backgroiund color to use in text drawing methods, half-transparent black by default")] + "Sets the default background color to use in text drawing methods, half-transparent black by default")] public void SetDefaultTextBackground(Color color) { luaPictureBox.SetDefaultTextBackground(color); @@ -119,7 +117,6 @@ namespace BizHawk.Client.EmuHawk catch (Exception ex) { ConsoleLuaLibrary.Log(ex.Message); - return; } } @@ -137,7 +134,6 @@ namespace BizHawk.Client.EmuHawk catch (Exception ex) { ConsoleLuaLibrary.Log(ex.Message); - return; } } @@ -155,7 +151,6 @@ namespace BizHawk.Client.EmuHawk catch (Exception ex) { ConsoleLuaLibrary.Log(ex.Message); - return; } } @@ -173,7 +168,6 @@ namespace BizHawk.Client.EmuHawk catch (Exception ex) { ConsoleLuaLibrary.Log(ex.Message); - return; } } @@ -208,7 +202,7 @@ namespace BizHawk.Client.EmuHawk [LuaMethod( "drawImageRegion", "draws a given region of an image file from the given path at the given coordinate, and optionally with the given size")] - public void DrawImageRegion(string path, int source_x, int source_y, int source_width, int source_height, int dest_x, int dest_y, int? dest_width = null, int? dest_height = null) + public void DrawImageRegion(string path, int sourceX, int sourceY, int sourceWidth, int sourceHeight, int destX, int destY, int? destWidth = null, int? destHeight = null) { if (!File.Exists(path)) { @@ -216,7 +210,7 @@ namespace BizHawk.Client.EmuHawk return; } - luaPictureBox.DrawImageRegion(path, source_x, source_y, source_width, source_height, dest_x, dest_y, dest_width, dest_height); + luaPictureBox.DrawImageRegion(path, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight); } [LuaMethodExample( @@ -245,9 +239,9 @@ namespace BizHawk.Client.EmuHawk "drawArc", "draws a Arc shape at the given coordinates and the given width and height" )] - public void DrawArc(int x, int y, int width, int height, int startangle, int sweepangle, Color? line = null) + public void DrawArc(int x, int y, int width, int height, int startAngle, int sweepAngle, Color? line = null) { - luaPictureBox.DrawArc(x, y, width, height, startangle, sweepangle, line); + luaPictureBox.DrawArc(x, y, width, height, startAngle, sweepAngle, line); } [LuaMethodExample( @@ -260,12 +254,12 @@ namespace BizHawk.Client.EmuHawk int y, int width, int height, - int startangle, - int sweepangle, + int startAngle, + int sweepAngle, Color? line = null, Color? background = null) { - luaPictureBox.DrawPie(x, y, width, height, startangle, sweepangle, line, background); + luaPictureBox.DrawPie(x, y, width, height, startAngle, sweepAngle, line, background); } [LuaMethodExample( @@ -282,7 +276,6 @@ namespace BizHawk.Client.EmuHawk catch (Exception ex) { ConsoleLuaLibrary.Log(ex.Message); - return; } } @@ -300,7 +293,6 @@ namespace BizHawk.Client.EmuHawk catch (Exception ex) { ConsoleLuaLibrary.Log(ex.Message); - return; } } @@ -324,15 +316,15 @@ namespace BizHawk.Client.EmuHawk int x, int y, string message, - Color? forecolor = null, - Color? backcolor = null, - int? fontsize = null, - string fontfamily = null, - string fontstyle = null, - string horizalign = null, - string vertalign = null) + Color? foreColor = null, + Color? backColor = null, + int? fontSize = null, + string fontFamily = null, + string fontStyle = null, + string horizontalAlign = null, + string verticalAlign = null) { - luaPictureBox.DrawText(x, y, message, forecolor, backcolor, fontsize, fontfamily, fontstyle, horizalign, vertalign); + luaPictureBox.DrawText(x, y, message, foreColor, backColor, fontSize, fontFamily, fontStyle, horizontalAlign, verticalAlign); } [LuaMethodExample( @@ -344,15 +336,15 @@ namespace BizHawk.Client.EmuHawk int x, int y, string message, - Color? forecolor = null, - Color? backcolor = null, - int? fontsize = null, - string fontfamily = null, - string fontstyle = null, - string horizalign = null, - string vertalign = null) + Color? foreColor = null, + Color? backColor = null, + int? fontSize = null, + string fontFamily = null, + string fontStyle = null, + string horizontalAlign = null, + string verticalAlign = null) { - luaPictureBox.DrawText(x, y, message, forecolor, backcolor, fontsize, fontfamily, fontstyle, horizalign, vertalign); + luaPictureBox.DrawText(x, y, message, foreColor, backColor, fontSize, fontFamily, fontStyle, horizontalAlign, verticalAlign); } diff --git a/BizHawk.Client.EmuHawk/tools/Lua/LuaConsole.Designer.cs b/BizHawk.Client.EmuHawk/tools/Lua/LuaConsole.Designer.cs index 8eb55e3e65..91309eccf3 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/LuaConsole.Designer.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/LuaConsole.Designer.cs @@ -38,6 +38,7 @@ this.InsertSeperatorContextItem = new System.Windows.Forms.ToolStripMenuItem(); this.ScriptContextSeparator = new System.Windows.Forms.ToolStripSeparator(); this.StopAllScriptsContextItem = new System.Windows.Forms.ToolStripMenuItem(); + this.ClearRegisteredFunctionsContextItem = new System.Windows.Forms.ToolStripMenuItem(); this.menuStrip1 = new MenuStripEx(); this.FileSubMenu = new System.Windows.Forms.ToolStripMenuItem(); this.NewSessionMenuItem = new System.Windows.Forms.ToolStripMenuItem(); @@ -71,7 +72,6 @@ this.SettingsSubMenu = new System.Windows.Forms.ToolStripMenuItem(); this.DisableScriptsOnLoadMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.ReturnAllIfNoneSelectedMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.RemoveRegisteredFunctionsOnToggleMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.ReloadWhenScriptFileChangesMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator(); this.RegisterToTextEditorsSubMenu = new System.Windows.Forms.ToolStripMenuItem(); @@ -84,7 +84,10 @@ this.ConsoleContextMenu = new System.Windows.Forms.ContextMenuStrip(this.components); this.ClearConsoleContextItem = new System.Windows.Forms.ToolStripMenuItem(); this.SelectAllContextItem = new System.Windows.Forms.ToolStripMenuItem(); + this.CopyContextItem = new System.Windows.Forms.ToolStripMenuItem(); + this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator(); this.RegisteredFunctionsContextItem = new System.Windows.Forms.ToolStripMenuItem(); + this.ClearRegisteredFunctionsLogContextItem = new System.Windows.Forms.ToolStripMenuItem(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.InputBox = new System.Windows.Forms.TextBox(); this.NumberOfScripts = new System.Windows.Forms.Label(); @@ -104,9 +107,8 @@ this.InsertSeparatorToolbarItem = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator10 = new System.Windows.Forms.ToolStripSeparator(); this.EraseToolbarItem = new System.Windows.Forms.ToolStripButton(); - this.LuaListView = new InputRoll(); + this.LuaListView = new BizHawk.Client.EmuHawk.InputRoll(); this.splitContainer1 = new System.Windows.Forms.SplitContainer(); - this.CopyContextItem = new System.Windows.Forms.ToolStripMenuItem(); this.ScriptListContextMenu.SuspendLayout(); this.menuStrip1.SuspendLayout(); this.ConsoleContextMenu.SuspendLayout(); @@ -127,16 +129,17 @@ this.RemoveScriptContextItem, this.InsertSeperatorContextItem, this.ScriptContextSeparator, - this.StopAllScriptsContextItem}); + this.StopAllScriptsContextItem, + this.ClearRegisteredFunctionsContextItem}); this.ScriptListContextMenu.Name = "contextMenuStrip1"; - this.ScriptListContextMenu.Size = new System.Drawing.Size(158, 142); + this.ScriptListContextMenu.Size = new System.Drawing.Size(204, 164); this.ScriptListContextMenu.Opening += new System.ComponentModel.CancelEventHandler(this.ScriptListContextMenu_Opening); // // ToggleScriptContextItem // this.ToggleScriptContextItem.Image = global::BizHawk.Client.EmuHawk.Properties.Resources.Refresh1; this.ToggleScriptContextItem.Name = "ToggleScriptContextItem"; - this.ToggleScriptContextItem.Size = new System.Drawing.Size(157, 22); + this.ToggleScriptContextItem.Size = new System.Drawing.Size(203, 22); this.ToggleScriptContextItem.Text = "&Toggle"; this.ToggleScriptContextItem.Click += new System.EventHandler(this.ToggleScriptMenuItem_Click); // @@ -144,7 +147,7 @@ // this.PauseScriptContextItem.Image = global::BizHawk.Client.EmuHawk.Properties.Resources.Pause; this.PauseScriptContextItem.Name = "PauseScriptContextItem"; - this.PauseScriptContextItem.Size = new System.Drawing.Size(157, 22); + this.PauseScriptContextItem.Size = new System.Drawing.Size(203, 22); this.PauseScriptContextItem.Text = "Pause or Resume"; this.PauseScriptContextItem.Click += new System.EventHandler(this.PauseScriptMenuItem_Click); // @@ -152,7 +155,7 @@ // this.EditScriptContextItem.Image = global::BizHawk.Client.EmuHawk.Properties.Resources.CutHS; this.EditScriptContextItem.Name = "EditScriptContextItem"; - this.EditScriptContextItem.Size = new System.Drawing.Size(157, 22); + this.EditScriptContextItem.Size = new System.Drawing.Size(203, 22); this.EditScriptContextItem.Text = "&Edit"; this.EditScriptContextItem.Click += new System.EventHandler(this.EditScriptMenuItem_Click); // @@ -160,7 +163,7 @@ // this.RemoveScriptContextItem.Image = global::BizHawk.Client.EmuHawk.Properties.Resources.Close; this.RemoveScriptContextItem.Name = "RemoveScriptContextItem"; - this.RemoveScriptContextItem.Size = new System.Drawing.Size(157, 22); + this.RemoveScriptContextItem.Size = new System.Drawing.Size(203, 22); this.RemoveScriptContextItem.Text = "&Remove"; this.RemoveScriptContextItem.Click += new System.EventHandler(this.RemoveScriptMenuItem_Click); // @@ -168,23 +171,31 @@ // this.InsertSeperatorContextItem.Image = global::BizHawk.Client.EmuHawk.Properties.Resources.InsertSeparator; this.InsertSeperatorContextItem.Name = "InsertSeperatorContextItem"; - this.InsertSeperatorContextItem.Size = new System.Drawing.Size(157, 22); + this.InsertSeperatorContextItem.Size = new System.Drawing.Size(203, 22); this.InsertSeperatorContextItem.Text = "Insert Seperator"; this.InsertSeperatorContextItem.Click += new System.EventHandler(this.InsertSeparatorMenuItem_Click); // // ScriptContextSeparator // this.ScriptContextSeparator.Name = "ScriptContextSeparator"; - this.ScriptContextSeparator.Size = new System.Drawing.Size(154, 6); + this.ScriptContextSeparator.Size = new System.Drawing.Size(200, 6); // // StopAllScriptsContextItem // this.StopAllScriptsContextItem.Image = global::BizHawk.Client.EmuHawk.Properties.Resources.Stop; this.StopAllScriptsContextItem.Name = "StopAllScriptsContextItem"; - this.StopAllScriptsContextItem.Size = new System.Drawing.Size(157, 22); + this.StopAllScriptsContextItem.Size = new System.Drawing.Size(203, 22); this.StopAllScriptsContextItem.Text = "Stop All Scripts"; this.StopAllScriptsContextItem.Click += new System.EventHandler(this.StopAllScriptsMenuItem_Click); // + // ClearRegisteredFunctionsContextItem + // + this.ClearRegisteredFunctionsContextItem.Image = global::BizHawk.Client.EmuHawk.Properties.Resources.Delete; + this.ClearRegisteredFunctionsContextItem.Name = "ClearRegisteredFunctionsContextItem"; + this.ClearRegisteredFunctionsContextItem.Size = new System.Drawing.Size(203, 22); + this.ClearRegisteredFunctionsContextItem.Text = "Clear Registered Functions"; + this.ClearRegisteredFunctionsContextItem.Click += new System.EventHandler(this.ClearRegisteredFunctionsContextMenuItem_Click); + // // menuStrip1 // this.menuStrip1.ClickThrough = true; @@ -460,7 +471,6 @@ this.SettingsSubMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.DisableScriptsOnLoadMenuItem, this.ReturnAllIfNoneSelectedMenuItem, - this.RemoveRegisteredFunctionsOnToggleMenuItem, this.ReloadWhenScriptFileChangesMenuItem, this.toolStripSeparator4, this.RegisterToTextEditorsSubMenu}); @@ -472,35 +482,28 @@ // DisableScriptsOnLoadMenuItem // this.DisableScriptsOnLoadMenuItem.Name = "DisableScriptsOnLoadMenuItem"; - this.DisableScriptsOnLoadMenuItem.Size = new System.Drawing.Size(267, 22); + this.DisableScriptsOnLoadMenuItem.Size = new System.Drawing.Size(232, 22); this.DisableScriptsOnLoadMenuItem.Text = "Disable Scripts on Load"; this.DisableScriptsOnLoadMenuItem.Click += new System.EventHandler(this.DisableScriptsOnLoadMenuItem_Click); // // ReturnAllIfNoneSelectedMenuItem // this.ReturnAllIfNoneSelectedMenuItem.Name = "ReturnAllIfNoneSelectedMenuItem"; - this.ReturnAllIfNoneSelectedMenuItem.Size = new System.Drawing.Size(267, 22); + this.ReturnAllIfNoneSelectedMenuItem.Size = new System.Drawing.Size(232, 22); this.ReturnAllIfNoneSelectedMenuItem.Text = "Toggle All if None Selected"; this.ReturnAllIfNoneSelectedMenuItem.Click += new System.EventHandler(this.ToggleAllIfNoneSelectedMenuItem_Click); // - // RemoveRegisteredFunctionsOnToggleMenuItem - // - this.RemoveRegisteredFunctionsOnToggleMenuItem.Name = "RemoveRegisteredFunctionsOnToggleMenuItem"; - this.RemoveRegisteredFunctionsOnToggleMenuItem.Size = new System.Drawing.Size(267, 22); - this.RemoveRegisteredFunctionsOnToggleMenuItem.Text = "Remove Registered Functions on Toggle"; - this.RemoveRegisteredFunctionsOnToggleMenuItem.Click += new System.EventHandler(this.RemoveRegisteredFunctionsOnToggleMenuItem_Click); - // // ReloadWhenScriptFileChangesMenuItem // this.ReloadWhenScriptFileChangesMenuItem.Name = "ReloadWhenScriptFileChangesMenuItem"; - this.ReloadWhenScriptFileChangesMenuItem.Size = new System.Drawing.Size(267, 22); + this.ReloadWhenScriptFileChangesMenuItem.Size = new System.Drawing.Size(232, 22); this.ReloadWhenScriptFileChangesMenuItem.Text = "Reload When Script File Changes"; this.ReloadWhenScriptFileChangesMenuItem.Click += new System.EventHandler(this.ReloadWhenScriptFileChangesMenuItem_Click); // // toolStripSeparator4 // this.toolStripSeparator4.Name = "toolStripSeparator4"; - this.toolStripSeparator4.Size = new System.Drawing.Size(264, 6); + this.toolStripSeparator4.Size = new System.Drawing.Size(229, 6); // // RegisterToTextEditorsSubMenu // @@ -508,7 +511,7 @@ this.RegisterSublimeText2MenuItem, this.RegisterNotePadMenuItem}); this.RegisterToTextEditorsSubMenu.Name = "RegisterToTextEditorsSubMenu"; - this.RegisterToTextEditorsSubMenu.Size = new System.Drawing.Size(267, 22); + this.RegisterToTextEditorsSubMenu.Size = new System.Drawing.Size(232, 22); this.RegisterToTextEditorsSubMenu.Text = "Register To Text Editors"; this.RegisterToTextEditorsSubMenu.DropDownOpened += new System.EventHandler(this.RegisterToTextEditorsSubMenu_DropDownOpened); // @@ -570,35 +573,57 @@ // ConsoleContextMenu // this.ConsoleContextMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { - this.ClearConsoleContextItem, - this.SelectAllContextItem, - this.CopyContextItem, - this.RegisteredFunctionsContextItem}); + this.CopyContextItem, + this.SelectAllContextItem, + this.ClearConsoleContextItem, + this.toolStripSeparator5, + this.RegisteredFunctionsContextItem, + this.ClearRegisteredFunctionsLogContextItem}); this.ConsoleContextMenu.Name = "contextMenuStrip2"; - this.ConsoleContextMenu.Size = new System.Drawing.Size(181, 114); + this.ConsoleContextMenu.Size = new System.Drawing.Size(204, 142); this.ConsoleContextMenu.Opening += new System.ComponentModel.CancelEventHandler(this.ConsoleContextMenu_Opening); // // ClearConsoleContextItem // this.ClearConsoleContextItem.Name = "ClearConsoleContextItem"; - this.ClearConsoleContextItem.Size = new System.Drawing.Size(180, 22); + this.ClearConsoleContextItem.Size = new System.Drawing.Size(203, 22); this.ClearConsoleContextItem.Text = "&Clear"; this.ClearConsoleContextItem.Click += new System.EventHandler(this.ClearConsoleContextItem_Click); // // SelectAllContextItem // this.SelectAllContextItem.Name = "SelectAllContextItem"; - this.SelectAllContextItem.Size = new System.Drawing.Size(180, 22); + this.SelectAllContextItem.Size = new System.Drawing.Size(203, 22); this.SelectAllContextItem.Text = "Select &All"; this.SelectAllContextItem.Click += new System.EventHandler(this.SelectAllContextItem_Click); // + // CopyContextItem + // + this.CopyContextItem.Name = "CopyContextItem"; + this.CopyContextItem.Size = new System.Drawing.Size(203, 22); + this.CopyContextItem.Text = "Copy"; + this.CopyContextItem.Click += new System.EventHandler(this.CopyContextItem_Click); + // + // toolStripSeparator5 + // + this.toolStripSeparator5.Name = "toolStripSeparator5"; + this.toolStripSeparator5.Size = new System.Drawing.Size(200, 6); + // // RegisteredFunctionsContextItem // this.RegisteredFunctionsContextItem.Name = "RegisteredFunctionsContextItem"; - this.RegisteredFunctionsContextItem.Size = new System.Drawing.Size(180, 22); + this.RegisteredFunctionsContextItem.Size = new System.Drawing.Size(203, 22); this.RegisteredFunctionsContextItem.Text = "&Registered Functions"; this.RegisteredFunctionsContextItem.Click += new System.EventHandler(this.RegisteredFunctionsMenuItem_Click); // + // ClearRegisteredFunctionsLogContextItem + // + this.ClearRegisteredFunctionsLogContextItem.Image = global::BizHawk.Client.EmuHawk.Properties.Resources.Delete; + this.ClearRegisteredFunctionsLogContextItem.Name = "ClearRegisteredFunctionsLogContextItem"; + this.ClearRegisteredFunctionsLogContextItem.Size = new System.Drawing.Size(203, 22); + this.ClearRegisteredFunctionsLogContextItem.Text = "Clear Registered Functions"; + this.ClearRegisteredFunctionsLogContextItem.Click += new System.EventHandler(this.ClearRegisteredFunctionsContextMenuItem_Click); + // // groupBox1 // this.groupBox1.Controls.Add(this.InputBox); @@ -704,7 +729,7 @@ this.RefreshScriptToolbarItem.ImageTransparentColor = System.Drawing.Color.Magenta; this.RefreshScriptToolbarItem.Name = "RefreshScriptToolbarItem"; this.RefreshScriptToolbarItem.Size = new System.Drawing.Size(23, 22); - this.RefreshScriptToolbarItem.Text = "Reload Script"; + this.RefreshScriptToolbarItem.Text = "Refresh"; this.RefreshScriptToolbarItem.Click += new System.EventHandler(this.RefreshScriptMenuItem_Click); // // PauseToolbarItem @@ -799,23 +824,30 @@ // // LuaListView // + this.LuaListView.AllowColumnReorder = false; + this.LuaListView.AllowColumnResize = true; + this.LuaListView.AllowMassNavigationShortcuts = true; + this.LuaListView.AllowRightClickSelection = true; + this.LuaListView.AlwaysScroll = false; this.LuaListView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); - this.LuaListView.CellWidthPadding = 3; - this.LuaListView.AllowColumnResize = true; - this.LuaListView.AllowColumnReorder = false; + this.LuaListView.CellHeightPadding = 0; + this.LuaListView.CellWidthPadding = 0; this.LuaListView.ContextMenuStrip = this.ScriptListContextMenu; this.LuaListView.FullRowSelect = true; - this.LuaListView.GridLines = true; - this.LuaListView.RowCount = 0; + this.LuaListView.HorizontalOrientation = false; + this.LuaListView.LetKeysModifySelection = false; this.LuaListView.Location = new System.Drawing.Point(4, 21); this.LuaListView.Name = "LuaListView"; + this.LuaListView.RowCount = 0; + this.LuaListView.ScrollSpeed = 1; + this.LuaListView.SeekingCutoffInterval = 0; this.LuaListView.Size = new System.Drawing.Size(273, 271); this.LuaListView.TabIndex = 0; this.LuaListView.ColumnClick += new BizHawk.Client.EmuHawk.InputRoll.ColumnClickEventHandler(this.LuaListView_ColumnClick); - this.LuaListView.KeyDown += new System.Windows.Forms.KeyEventHandler(this.LuaListView_KeyDown); this.LuaListView.DoubleClick += new System.EventHandler(this.LuaListView_DoubleClick); + this.LuaListView.KeyDown += new System.Windows.Forms.KeyEventHandler(this.LuaListView_KeyDown); // // splitContainer1 // @@ -835,13 +867,6 @@ this.splitContainer1.SplitterDistance = 280; this.splitContainer1.TabIndex = 7; // - // CopyContextItem - // - this.CopyContextItem.Name = "CopyContextItem"; - this.CopyContextItem.Size = new System.Drawing.Size(180, 22); - this.CopyContextItem.Text = "Copy"; - this.CopyContextItem.Click += new System.EventHandler(this.CopyContextItem_Click); - // // LuaConsole // this.AllowDrop = true; @@ -948,9 +973,8 @@ private System.Windows.Forms.ToolStripButton DuplicateToolbarButton; private System.Windows.Forms.ToolStripMenuItem DuplicateScriptMenuItem; private System.Windows.Forms.TextBox InputBox; - private System.Windows.Forms.SplitContainer splitContainer1; - private System.Windows.Forms.ToolStripMenuItem ReturnAllIfNoneSelectedMenuItem; - private System.Windows.Forms.ToolStripMenuItem RemoveRegisteredFunctionsOnToggleMenuItem; + private System.Windows.Forms.SplitContainer splitContainer1; + private System.Windows.Forms.ToolStripMenuItem ReturnAllIfNoneSelectedMenuItem; private System.Windows.Forms.ToolStripMenuItem ReloadWhenScriptFileChangesMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator4; private System.Windows.Forms.ToolStripMenuItem RegisterToTextEditorsSubMenu; @@ -958,5 +982,8 @@ private System.Windows.Forms.ToolStripMenuItem RegisterNotePadMenuItem; private System.Windows.Forms.ToolStripMenuItem SelectAllContextItem; private System.Windows.Forms.ToolStripMenuItem CopyContextItem; + private System.Windows.Forms.ToolStripMenuItem ClearRegisteredFunctionsContextItem; + private System.Windows.Forms.ToolStripSeparator toolStripSeparator5; + private System.Windows.Forms.ToolStripMenuItem ClearRegisteredFunctionsLogContextItem; } } \ No newline at end of file diff --git a/BizHawk.Client.EmuHawk/tools/Lua/LuaConsole.cs b/BizHawk.Client.EmuHawk/tools/Lua/LuaConsole.cs index db2fa3069c..861df0181c 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/LuaConsole.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/LuaConsole.cs @@ -183,8 +183,7 @@ namespace BizHawk.Client.EmuHawk { LuaImp.CallExitEvent(file); - LuaImp.RegisteredFunctions.RemoveAll(lf => lf.Lua == file.Thread); - + LuaImp.RegisteredFunctions.RemoveForFile(file); UpdateRegisteredFunctionsDialog(); file.Stop(); @@ -432,24 +431,6 @@ namespace BizHawk.Client.EmuHawk return path; } - private static FileInfo GetFileFromUser(string filter) - { - var ofd = new OpenFileDialog - { - InitialDirectory = PathManager.GetLuaPath(), - Filter = filter, - RestoreDirectory = true - }; - - if (!Directory.Exists(ofd.InitialDirectory)) - { - Directory.CreateDirectory(ofd.InitialDirectory); - } - - var result = ofd.ShowHawkDialog(); - return result == DialogResult.OK ? new FileInfo(ofd.FileName) : null; - } - private void UpdateNumberOfScripts() { var message = ""; @@ -551,7 +532,7 @@ namespace BizHawk.Client.EmuHawk var prohibit = lf.FrameWaiting && !includeFrameWaiters; if (!prohibit) { - var result = LuaImp.ResumeScriptFromThreadOf(lf); + var result = LuaImp.ResumeScript(lf); if (result.Terminated) { LuaImp.CallExitEvent(lf); @@ -678,7 +659,7 @@ namespace BizHawk.Client.EmuHawk private static void UpdateRegisteredFunctionsDialog() { - foreach (var form in Application.OpenForms.OfType()) + foreach (var form in Application.OpenForms.OfType().ToList()) { form.UpdateValues(); } @@ -721,10 +702,23 @@ namespace BizHawk.Client.EmuHawk private void OpenSessionMenuItem_Click(object sender, EventArgs e) { - var file = GetFileFromUser("Lua Session Files (*.luases)|*.luases|All Files|*.*"); - if (file != null) + var ofd = new OpenFileDialog { - LuaImp.ScriptList.LoadLuaSession(file.FullName); + InitialDirectory = PathManager.GetLuaPath(), + Filter = "Lua Session Files (*.luases)|*.luases|All Files|*.*", + RestoreDirectory = true, + Multiselect = false + }; + + if (!Directory.Exists(ofd.InitialDirectory)) + { + Directory.CreateDirectory(ofd.InitialDirectory); + } + + var result = ofd.ShowHawkDialog(); + if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(ofd.FileName)) + { + LuaImp.ScriptList.LoadLuaSession(ofd.FileName); RunLuaScripts(); UpdateDialog(); LuaImp.ScriptList.Changes = false; @@ -814,10 +808,27 @@ namespace BizHawk.Client.EmuHawk private void OpenScriptMenuItem_Click(object sender, EventArgs e) { - var file = GetFileFromUser("Lua Scripts (*.lua)|*.lua|Text (*.text)|*.txt|All Files|*.*"); - if (file != null) + var ofd = new OpenFileDialog { - LoadLuaFile(file.FullName); + InitialDirectory = PathManager.GetLuaPath(), + Filter = "Lua Scripts (*.lua)|*.lua|Text (*.text)|*.txt|All Files|*.*", + RestoreDirectory = true, + Multiselect = true + }; + + if (!Directory.Exists(ofd.InitialDirectory)) + { + Directory.CreateDirectory(ofd.InitialDirectory); + } + + var result = ofd.ShowHawkDialog(); + if (result == DialogResult.OK && ofd.FileNames != null) + { + foreach (var file in ofd.FileNames) + { + LoadLuaFile(file); + } + UpdateDialog(); } } @@ -904,12 +915,10 @@ namespace BizHawk.Client.EmuHawk { foreach (var item in items) { - var temp = item; - LuaImp.RegisteredFunctions.RemoveAll(x => x.Lua == temp.Thread); - + LuaImp.RegisteredFunctions.RemoveForFile(item); LuaImp.ScriptList.Remove(item); } - + UpdateRegisteredFunctionsDialog(); UpdateDialog(); } @@ -1054,7 +1063,6 @@ namespace BizHawk.Client.EmuHawk { DisableScriptsOnLoadMenuItem.Checked = Global.Config.DisableLuaScriptsOnLoad; ReturnAllIfNoneSelectedMenuItem.Checked = Global.Config.ToggleAllIfNoneSelected; - RemoveRegisteredFunctionsOnToggleMenuItem.Checked = Global.Config.RemoveRegisteredFunctionsOnToggle; ReloadWhenScriptFileChangesMenuItem.Checked = Global.Config.LuaReloadOnScriptFileChange; } @@ -1068,11 +1076,6 @@ namespace BizHawk.Client.EmuHawk Global.Config.ToggleAllIfNoneSelected ^= true; } - private void RemoveRegisteredFunctionsOnToggleMenuItem_Click(object sender, EventArgs e) - { - Global.Config.RemoveRegisteredFunctionsOnToggle ^= true; - } - private void ReloadWhenScriptFileChangesMenuItem_Click(object sender, EventArgs e) { Global.Config.LuaReloadOnScriptFileChange ^= true; @@ -1175,6 +1178,9 @@ namespace BizHawk.Client.EmuHawk StopAllScriptsContextItem.Visible = ScriptContextSeparator.Visible = LuaImp.ScriptList.Any(file => file.Enabled); + + ClearRegisteredFunctionsContextItem.Enabled = + GlobalWin.Tools.LuaConsole.LuaImp.RegisteredFunctions.Any(); } private void ConsoleContextMenu_Opening(object sender, CancelEventArgs e) @@ -1184,6 +1190,9 @@ namespace BizHawk.Client.EmuHawk ClearConsoleContextItem.Enabled = SelectAllContextItem.Enabled = OutputBox.Text.Any(); + + ClearRegisteredFunctionsLogContextItem.Enabled = + GlobalWin.Tools.LuaConsole.LuaImp.RegisteredFunctions.Any(); } private void ClearConsoleContextItem_Click(object sender, EventArgs e) @@ -1219,6 +1228,11 @@ namespace BizHawk.Client.EmuHawk }); } + private void ClearRegisteredFunctionsContextMenuItem_Click(object sender, EventArgs e) + { + GlobalWin.Tools.LuaConsole.LuaImp.RegisteredFunctions.Clear(); + } + #endregion #region Dialog, Listview, OutputBox, InputBox @@ -1462,25 +1476,18 @@ namespace BizHawk.Client.EmuHawk if (file.Enabled && file.Thread == null) { + LuaImp.RegisteredFunctions.RemoveForFile(file); // First remove any existing registered functions for this file EnableLuaFile(file); + UpdateRegisteredFunctionsDialog(); } else if (!file.Enabled && file.Thread != null) { LuaImp.CallExitEvent(file); - - foreach (var selectedItem in SelectedItems) - { - var temp = selectedItem; - LuaImp.RegisteredFunctions.RemoveAll(lf => lf.Lua == temp.Thread); - UpdateRegisteredFunctionsDialog(); - } + LuaImp.RegisteredFunctions.RemoveForFile(file); + UpdateRegisteredFunctionsDialog(); LuaImp.CallExitEvent(file); file.Stop(); - if (Global.Config.RemoveRegisteredFunctionsOnToggle) - { - LuaImp.RegisteredFunctions.ClearAll(); - } } } diff --git a/BizHawk.Client.EmuHawk/tools/Lua/LuaConsole.resx b/BizHawk.Client.EmuHawk/tools/Lua/LuaConsole.resx index 4b0fdcdf07..866e9cdbd3 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/LuaConsole.resx +++ b/BizHawk.Client.EmuHawk/tools/Lua/LuaConsole.resx @@ -133,17 +133,17 @@ iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8 - YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAJHSURBVDhPxZBdSNNhFMb/F110ZZEVhVBgeeHNICiiuggp - olAUyyxI0oSaH1QYC3N+tKnp5ubm1JUua5uuqdNKMwr7kApFItTUkWZqVhSVYmao5Nevvy7UoYR3HXh4 - 4XCe33nOKyy3lAY7l9RWMo0O/raWXxEyo5spVYTNvOGyfIRPfW+ptOkXqaPl6T83hcRmExSdgzAz3NVm - YWyoYla/B+1M9JtxWLPpaH22JORIjI6gKAMB0jyEimIdo4OlbuaprwVMOOMovammpDADc34qppwUrmnl - 5Kni3aFlFg2j3y1z5mnRTJccnNIltQhwq0jFry+mOXNtpWZWDx1Z1NhV3C3JwGFOw25SYjVe5oYhiUKd - HKMmwQUrMWUw/CF3NnZvvYKqUh1TvUroS3fXe7HXkwidMngTS2t5KLbregSzMY2f3Wr4qKW6LJvGR1rX - 0MLor8OhKYTJBn/GHvvxrliCTBrsOqXIoOBHh5K+hmSq7FqmexTQHuUytkaKxuNMNgYyVneA4Qd7GKjc - hjLaRzxH7gIU6JIZaEvgtk1D8wsxSWecCDgNzWFMvwxm/PkhRmr3Mli1nW9lvjRdWc0Jf+/5jzRmyWmv - S+GOLQu6U6BFjPvqKOP1AYw88WOoZif9DgmfLVtxaj1RSLdwNvrkPCA3M54KqxrnvRia9MKcGrUrqFOt - 5H7qKsqT1mGO9+Lqhc2ELdw+U/r0i+gVZ8hMiCDx3DHORwZyKnQ/hw/uYt9uCTskPvh6e7Fp41rWr/Fg - g6eHO+A/lyD8ARfG3mk9fv1YAAAAAElFTkSuQmCC + YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAJQSURBVDhPlZNdSNNRGMb/F110ZZEVhVBgeeHNICiiuggp + olAUyyxI0oSaH1QYC3N+tKnp5ubm1JUua5uuqdPKMgr7kApFItTUkWZqVhSVYmao5Nev/xyoQ4k88Nyc + 8z6/93nP4QjCfy6lwc4ltZVso4P/tMyXRcmMHqZ0EeY6jZQVInzuf0e1Tb9Ina3P/tkpLD6XkNg8BJe5 + u93C+HDVrP4M2ZkcMOOw5tLZ9nxJyJE4HSExBoKkBQhVpTrGhso9zNPfiph0JlB+U01ZcRbmwnRMeWlc + 08opUCV6QissGsZ+WOY6z4hmuuXglC6pRYBbJSp+fzXNxnaZ66o1s3rkyKHWruJuWRYOcwZ2kxKr8TI3 + DCkU6+QYNUnuNGWmLEY+5uOK3degoKZcx3SfEvozPfVB3OtNhi4ZvI2nrTIc23U9gtmYwa8eNXzScq8i + l6bHWnfRwhHeREJzGFONgYw/CeB9qQSZNNR9FyUGBT87lfQ3plJj1zLTq4COGDegLVo0HmeqKZjx+gOM + PNzDYPU2lLF+4jhyN6BIl8pgexK3bRpaXopJuhJEwGloiWDmVSgTLw4xWreXoZrtfK/wp/nKak4E+s6/ + hDFHTkd9GndsOdCTBq1i3NdHmWgIYvRpAMO1OxlwSPhi2YpT641CuoWzsSfnAfnZiVRZ1Tjvx9GsF+bU + pF1BvWolD9JXUZmyDnOiD1cvbCZiYXfXCPrMi+gVZ8hOiiL53DHORwdzKnw/hw/uYt9uCTskfvj7+rBp + 41rWr/Fig7fX8j/Tsn/fcgx/ARfG3ml6M3rzAAAAAElFTkSuQmCC diff --git a/BizHawk.Client.EmuHawk/tools/Lua/LuaDropDown.cs b/BizHawk.Client.EmuHawk/tools/Lua/LuaDropDown.cs index d74f41429f..98e3ae72b8 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/LuaDropDown.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/LuaDropDown.cs @@ -6,14 +6,14 @@ namespace BizHawk.Client.EmuHawk { public class LuaDropDown : ComboBox { - public LuaDropDown(List items) + public LuaDropDown(ICollection items) { Items.AddRange(items.Cast().ToArray()); SelectedIndex = 0; DropDownStyle = ComboBoxStyle.DropDownList; } - public void SetItems(List items) + public void SetItems(ICollection items) { Items.Clear(); Items.AddRange(items.Cast().ToArray()); diff --git a/BizHawk.Client.EmuHawk/tools/Lua/LuaFunctionsForm.cs b/BizHawk.Client.EmuHawk/tools/Lua/LuaFunctionsForm.cs index a815c21846..c30ec46136 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/LuaFunctionsForm.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/LuaFunctionsForm.cs @@ -12,21 +12,20 @@ namespace BizHawk.Client.EmuHawk { private readonly Sorting _columnSort = new Sorting(); - private List FunctionList = new List(); - + private List _functionList = new List(); private List _filteredList = new List(); private void GenerateFilteredList() { if (!string.IsNullOrWhiteSpace(FilterBox.Text)) { - _filteredList = FunctionList + _filteredList = _functionList .Where(f => $"{f.Library}.{f.Name}".ToLowerInvariant().Contains(FilterBox.Text.ToLowerInvariant())) .ToList(); } else { - _filteredList = FunctionList.ToList(); + _filteredList = _functionList.ToList(); } } @@ -38,7 +37,7 @@ namespace BizHawk.Client.EmuHawk private void LuaFunctionList_Load(object sender, EventArgs e) { - FunctionList = GlobalWin.Tools.LuaConsole.LuaImp.Docs + _functionList = GlobalWin.Tools.LuaConsole.LuaImp.Docs .OrderBy(l => l.Library) .ThenBy(l => l.Name) .ToList(); @@ -66,19 +65,19 @@ namespace BizHawk.Client.EmuHawk switch (column) { case 0: // Return - FunctionList = FunctionList.OrderByDescending(x => x.ReturnType).ToList(); + _functionList = _functionList.OrderByDescending(x => x.ReturnType).ToList(); break; case 1: // Library - FunctionList = FunctionList.OrderByDescending(x => x.Library).ToList(); + _functionList = _functionList.OrderByDescending(x => x.Library).ToList(); break; case 2: // Name - FunctionList = FunctionList.OrderByDescending(x => x.Name).ToList(); + _functionList = _functionList.OrderByDescending(x => x.Name).ToList(); break; case 3: // Parameters - FunctionList = FunctionList.OrderByDescending(x => x.ParameterList).ToList(); + _functionList = _functionList.OrderByDescending(x => x.ParameterList).ToList(); break; case 4: // Description - FunctionList = FunctionList.OrderByDescending(x => x.Description).ToList(); + _functionList = _functionList.OrderByDescending(x => x.Description).ToList(); break; } } @@ -87,19 +86,19 @@ namespace BizHawk.Client.EmuHawk switch (column) { case 0: // Return - FunctionList = FunctionList.OrderBy(x => x.ReturnType).ToList(); + _functionList = _functionList.OrderBy(x => x.ReturnType).ToList(); break; case 1: // Library - FunctionList = FunctionList.OrderBy(x => x.Library).ToList(); + _functionList = _functionList.OrderBy(x => x.Library).ToList(); break; case 2: // Name - FunctionList = FunctionList.OrderBy(x => x.Name).ToList(); + _functionList = _functionList.OrderBy(x => x.Name).ToList(); break; case 3: // Parameters - FunctionList = FunctionList.OrderBy(x => x.ParameterList).ToList(); + _functionList = _functionList.OrderBy(x => x.ParameterList).ToList(); break; case 4: // Description - FunctionList = FunctionList.OrderBy(x => x.Description).ToList(); + _functionList = _functionList.OrderBy(x => x.Description).ToList(); break; } } diff --git a/BizHawk.Client.EmuHawk/tools/Lua/LuaPictureBox.cs b/BizHawk.Client.EmuHawk/tools/Lua/LuaPictureBox.cs index be641ceccb..fcb85b0fa9 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/LuaPictureBox.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/LuaPictureBox.cs @@ -17,8 +17,7 @@ namespace BizHawk.Client.EmuHawk private SolidBrush GetBrush(Color color) { - SolidBrush b; - if (!_solidBrushes.TryGetValue(color, out b)) + if (!_solidBrushes.TryGetValue(color, out var b)) { b = new SolidBrush(color); _solidBrushes[color] = b; @@ -29,8 +28,7 @@ namespace BizHawk.Client.EmuHawk private Pen GetPen(Color color) { - Pen p; - if (!_pens.TryGetValue(color, out p)) + if (!_pens.TryGetValue(color, out var p)) { p = new Pen(color); _pens[color] = p; @@ -190,7 +188,7 @@ namespace BizHawk.Client.EmuHawk _imageCache.Clear(); } - public void DrawImageRegion(string path, int source_x, int source_y, int source_width, int source_height, int dest_x, int dest_y, int? dest_width = null, int? dest_height = null) + public void DrawImageRegion(string path, int sourceX, int sourceY, int sourceWidth, int sourceHeight, int destX, int destY, int? destWidth = null, int? destHeight = null) { Image img; if (_imageCache.ContainsKey(path)) @@ -203,10 +201,10 @@ namespace BizHawk.Client.EmuHawk _imageCache.Add(path, img); } - var destRect = new Rectangle(dest_x, dest_y, dest_width ?? source_width, dest_height ?? source_height); + var destRect = new Rectangle(destX, destY, destWidth ?? sourceWidth, destHeight ?? sourceHeight); var boxBackground = Graphics.FromImage(Image); - boxBackground.DrawImage(img, destRect, source_x, source_y, source_width, source_height, GraphicsUnit.Pixel); + boxBackground.DrawImage(img, destRect, sourceX, sourceY, sourceWidth, sourceHeight, GraphicsUnit.Pixel); } public void DrawLine(int x1, int y1, int x2, int y2, Color? color = null) @@ -221,10 +219,10 @@ namespace BizHawk.Client.EmuHawk DrawLine(x, y + size, x, y - size, color); } - public void DrawArc(int x, int y, int width, int height, int startangle, int sweepangle, Color? line = null) + public void DrawArc(int x, int y, int width, int height, int startAngle, int sweepAngle, Color? line = null) { var boxBackground = Graphics.FromImage(Image); - boxBackground.DrawArc(GetPen(line ?? _defaultForeground), x, y, width, height, startangle, sweepangle); + boxBackground.DrawArc(GetPen(line ?? _defaultForeground), x, y, width, height, startAngle, sweepAngle); } public void DrawPie( @@ -232,8 +230,8 @@ namespace BizHawk.Client.EmuHawk int y, int width, int height, - int startangle, - int sweepangle, + int startAngle, + int sweepAngle, Color? line = null, Color? background = null) { @@ -242,11 +240,11 @@ namespace BizHawk.Client.EmuHawk if (bg.HasValue) { var brush = GetBrush(bg.Value); - boxBackground.FillPie(brush, x, y, width, height, startangle, sweepangle); + boxBackground.FillPie(brush, x, y, width, height, startAngle, sweepAngle); boxBackground = Graphics.FromImage(Image); } - boxBackground.DrawPie(GetPen(line ?? _defaultForeground), x + 1, y + 1, width - 1, height - 1, startangle, sweepangle); + boxBackground.DrawPie(GetPen(line ?? _defaultForeground), x + 1, y + 1, width - 1, height - 1, startAngle, sweepAngle); } public void DrawPixel(int x, int y, Color? color = null) @@ -292,52 +290,52 @@ namespace BizHawk.Client.EmuHawk int x, int y, string message, - Color? forecolor = null, - Color? backcolor = null, - int? fontsize = null, - string fontfamily = null, - string fontstyle = null, - string horizalign = null, - string vertalign = null) + Color? foreColor = null, + Color? backColor = null, + int? fontSize = null, + string fontFamily = null, + string fontStyle = null, + string horizAlign = null, + string vertAlign = null) { var family = FontFamily.GenericMonospace; - if (fontfamily != null) + if (fontFamily != null) { - family = new FontFamily(fontfamily); + family = new FontFamily(fontFamily); } - var fstyle = FontStyle.Regular; - if (fontstyle != null) + var fStyle = FontStyle.Regular; + if (fontStyle != null) { - switch (fontstyle.ToLower()) + switch (fontStyle.ToLower()) { default: case "regular": break; case "bold": - fstyle = FontStyle.Bold; + fStyle = FontStyle.Bold; break; case "italic": - fstyle = FontStyle.Italic; + fStyle = FontStyle.Italic; break; case "strikethrough": - fstyle = FontStyle.Strikeout; + fStyle = FontStyle.Strikeout; break; case "underline": - fstyle = FontStyle.Underline; + fStyle = FontStyle.Underline; break; } } var f = new StringFormat(StringFormat.GenericDefault); - var font = new Font(family, fontsize ?? 12, fstyle, GraphicsUnit.Pixel); + var font = new Font(family, fontSize ?? 12, fStyle, GraphicsUnit.Pixel); var boxBackground = Graphics.FromImage(Image); Size sizeOfText = boxBackground.MeasureString(message, font, 0, f).ToSize(); - if (horizalign != null) + if (horizAlign != null) { - switch (horizalign.ToLower()) + switch (horizAlign.ToLower()) { default: case "left": @@ -352,9 +350,9 @@ namespace BizHawk.Client.EmuHawk } } - if (vertalign != null) + if (vertAlign != null) { - switch (vertalign.ToLower()) + switch (vertAlign.ToLower()) { default: case "top": @@ -370,15 +368,15 @@ namespace BizHawk.Client.EmuHawk } Rectangle rect = new Rectangle(new Point(x, y), sizeOfText); boxBackground = Graphics.FromImage(Image); - boxBackground.FillRectangle(GetBrush(backcolor ?? _defaultTextBackground.Value), rect); + boxBackground.FillRectangle(GetBrush(backColor ?? _defaultTextBackground.Value), rect); boxBackground = Graphics.FromImage(Image); boxBackground.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit; - boxBackground.DrawString(message, font, new SolidBrush(forecolor ?? Color.Black), x, y); + boxBackground.DrawString(message, font, new SolidBrush(foreColor ?? Color.Black), x, y); } public Point GetMouse() { - var p = PointToClient(Control.MousePosition); + var p = PointToClient(MousePosition); return p; } diff --git a/BizHawk.Client.EmuHawk/tools/Lua/LuaRegisteredFunctionsList.cs b/BizHawk.Client.EmuHawk/tools/Lua/LuaRegisteredFunctionsList.cs index c42dc73fae..fee2f09f21 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/LuaRegisteredFunctionsList.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/LuaRegisteredFunctionsList.cs @@ -13,18 +13,9 @@ namespace BizHawk.Client.EmuHawk InitializeComponent(); } - public void NewUpdate(ToolFormUpdateType type) { } - public void UpdateValues() { - if (GlobalWin.Tools.LuaConsole.LuaImp.RegisteredFunctions.Any()) - { - PopulateListView(); - } - else - { - Close(); - } + PopulateListView(); } private void LuaRegisteredFunctionsList_Load(object sender, EventArgs e) @@ -46,8 +37,10 @@ namespace BizHawk.Client.EmuHawk { FunctionView.Items.Clear(); - var nlfs = GlobalWin.Tools.LuaConsole.LuaImp.RegisteredFunctions.OrderBy(x => x.Event).ThenBy(x => x.Name); - foreach (var nlf in nlfs) + var functions = GlobalWin.Tools.LuaConsole.LuaImp.RegisteredFunctions + .OrderBy(f => f.Event) + .ThenBy(f => f.Name); + foreach (var nlf in functions) { var item = new ListViewItem { Text = nlf.Event }; item.SubItems.Add(nlf.Name); diff --git a/BizHawk.Client.EmuHawk/tools/Lua/LuaWinform.cs b/BizHawk.Client.EmuHawk/tools/Lua/LuaWinform.cs index e2c4b21e85..e47325c0d3 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/LuaWinform.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/LuaWinform.cs @@ -13,12 +13,12 @@ namespace BizHawk.Client.EmuHawk public List ControlEvents { get; } = new List(); private readonly string _currentDirectory = Environment.CurrentDirectory; - private readonly Lua _ownerThread; + private readonly LuaFile _ownerFile; - public LuaWinform(Lua ownerThread) + public LuaWinform(LuaFile ownerFile) { InitializeComponent(); - _ownerThread = ownerThread; + _ownerFile = ownerFile; StartPosition = FormStartPosition.CenterParent; Closing += (o, e) => CloseThis(); } @@ -34,7 +34,7 @@ namespace BizHawk.Client.EmuHawk public void DoLuaEvent(IntPtr handle) { - LuaSandbox.Sandbox(_ownerThread, () => + LuaSandbox.Sandbox(_ownerFile.Thread, () => { Environment.CurrentDirectory = _currentDirectory; foreach (LuaEvent luaEvent in ControlEvents) @@ -49,9 +49,9 @@ namespace BizHawk.Client.EmuHawk public class LuaEvent { - public LuaEvent(IntPtr handle, LuaFunction lfunction) + public LuaEvent(IntPtr handle, LuaFunction luaFunction) { - Event = lfunction; + Event = luaFunction; Control = handle; } diff --git a/BizHawk.Client.EmuHawk/tools/Lua/SyncTextBox.cs b/BizHawk.Client.EmuHawk/tools/Lua/SyncTextBox.cs deleted file mode 100644 index 8359c1109c..0000000000 --- a/BizHawk.Client.EmuHawk/tools/Lua/SyncTextBox.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; -using System.Windows.Forms; -using System.Runtime.InteropServices; - -internal class SyncTextBox : RichTextBox -{ - public SyncTextBox() - { - this.Multiline = true; - this.ScrollBars = RichTextBoxScrollBars.Vertical; - } - - public Control Buddy { get; set; } - - private static bool scrolling; // In case buddy tries to scroll us - protected override void WndProc(ref Message m) - { - base.WndProc(ref m); - - // Trap WM_VSCROLL message and pass to buddy - if ((m.Msg == 0x115 || m.Msg == 0x20a) && !scrolling && Buddy != null && Buddy.IsHandleCreated) - { - scrolling = true; - SendMessage(Buddy.Handle, m.Msg, m.WParam, m.LParam); - scrolling = false; - } - } - - [DllImport("user32.dll", CharSet = CharSet.Auto)] - private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp); -} \ No newline at end of file diff --git a/BizHawk.Client.EmuHawk/tools/TAStudio/BookmarksBranchesBox.cs b/BizHawk.Client.EmuHawk/tools/TAStudio/BookmarksBranchesBox.cs index 08b8bc7360..fd44fc3715 100644 --- a/BizHawk.Client.EmuHawk/tools/TAStudio/BookmarksBranchesBox.cs +++ b/BizHawk.Client.EmuHawk/tools/TAStudio/BookmarksBranchesBox.cs @@ -337,7 +337,7 @@ namespace BizHawk.Client.EmuHawk if (index == Movie.Branches.Count) { - BranchView.ClearSelectedRows(); + BranchView.DeselectAll(); Select(Movie.Branches.Count - 1, true); } diff --git a/BizHawk.Client.EmuHawk/tools/ToolManager.cs b/BizHawk.Client.EmuHawk/tools/ToolManager.cs index cb454fbaf4..f729f19e5c 100644 --- a/BizHawk.Client.EmuHawk/tools/ToolManager.cs +++ b/BizHawk.Client.EmuHawk/tools/ToolManager.cs @@ -49,7 +49,7 @@ namespace BizHawk.Client.EmuHawk throw new ArgumentException($"Type {toolType.Name} does not implement {nameof(IToolForm)}."); } - // The type[] in parameter is used to avoid an ambigous name exception + // The type[] in parameter is used to avoid an ambiguous name exception MethodInfo method = GetType().GetMethod("Load", new Type[] { typeof(bool) }).MakeGenericMethod(toolType); return (IToolForm)method.Invoke(this, new object[] { focus }); } @@ -118,9 +118,9 @@ namespace BizHawk.Client.EmuHawk return null; } - if (newTool is Form) + if (newTool is Form form) { - (newTool as Form).Owner = GlobalWin.MainForm; + form.Owner = GlobalWin.MainForm; } if (isExternal) @@ -132,16 +132,15 @@ namespace BizHawk.Client.EmuHawk string toolType = typeof(T).ToString(); // auto settings - if (newTool is IToolFormAutoConfig) + if (newTool is IToolFormAutoConfig tool) { - ToolDialogSettings settings; - if (!Global.Config.CommonToolSettings.TryGetValue(toolType, out settings)) + if (!Global.Config.CommonToolSettings.TryGetValue(toolType, out var settings)) { settings = new ToolDialogSettings(); Global.Config.CommonToolSettings[toolType] = settings; } - AttachSettingHooks(newTool as IToolFormAutoConfig, settings); + AttachSettingHooks(tool, settings); } // custom settings @@ -347,7 +346,7 @@ namespace BizHawk.Client.EmuHawk object val; if (data.TryGetValue(prop.Name, out val)) { - if (val is string && prop.PropertyType != typeof(string)) + if (val is string str && prop.PropertyType != typeof(string)) { // if a type has a TypeConverter, and that converter can convert to string, // that will be used in place of object markup by JSON.NET @@ -356,7 +355,7 @@ namespace BizHawk.Client.EmuHawk // back on regular object serialization when needed. so try to undo a TypeConverter // operation here var converter = TypeDescriptor.GetConverter(prop.PropertyType); - val = converter.ConvertFromString(null, System.Globalization.CultureInfo.InvariantCulture, (string)val); + val = converter.ConvertFromString(null, System.Globalization.CultureInfo.InvariantCulture, str); } else if (!(val is bool) && prop.PropertyType.IsPrimitive) { @@ -820,11 +819,13 @@ namespace BizHawk.Client.EmuHawk public void LoadRamWatch(bool loadDialog) { - if (!IsLoaded()) + if (IsLoaded()) { - Load(); + return; } + Load(); + if (IsAvailable()) // Just because we attempted to load it, doesn't mean it was, the current core may not have the correct dependencies { if (Global.Config.RecentWatches.AutoLoad && !Global.Config.RecentWatches.Empty) diff --git a/BizHawk.Client.EmuHawk/tools/Watch/RamSearch.Designer.cs b/BizHawk.Client.EmuHawk/tools/Watch/RamSearch.Designer.cs index c4157747a6..17e8d0c2a3 100644 --- a/BizHawk.Client.EmuHawk/tools/Watch/RamSearch.Designer.cs +++ b/BizHawk.Client.EmuHawk/tools/Watch/RamSearch.Designer.cs @@ -256,7 +256,7 @@ // this.AddToRamWatchContextMenuItem.Image = global::BizHawk.Client.EmuHawk.Properties.Resources.FindHS; this.AddToRamWatchContextMenuItem.Name = "AddToRamWatchContextMenuItem"; - this.AddToRamWatchContextMenuItem.ShortcutKeyDisplayString = "Ctrl+R"; + this.AddToRamWatchContextMenuItem.ShortcutKeyDisplayString = "Ctrl+W"; this.AddToRamWatchContextMenuItem.Size = new System.Drawing.Size(217, 22); this.AddToRamWatchContextMenuItem.Text = "Add to RAM Watch"; this.AddToRamWatchContextMenuItem.Click += new System.EventHandler(this.AddToRamWatchMenuItem_Click); diff --git a/BizHawk.Client.EmuHawk/tools/Watch/RamSearch.cs b/BizHawk.Client.EmuHawk/tools/Watch/RamSearch.cs index 6d455a25a9..4f72408dd5 100644 --- a/BizHawk.Client.EmuHawk/tools/Watch/RamSearch.cs +++ b/BizHawk.Client.EmuHawk/tools/Watch/RamSearch.cs @@ -832,8 +832,8 @@ namespace BizHawk.Client.EmuHawk SetRemovedMessage(indices.Count); _searches.RemoveRange(indices); - UpdateList(); WatchListView.DeselectAll(); + UpdateList(); ToggleSearchDependentToolBarItems(); } } diff --git a/BizHawk.Emulation.Cores/BizHawk.Emulation.Cores.csproj b/BizHawk.Emulation.Cores/BizHawk.Emulation.Cores.csproj index b12cbd8090..164627f03a 100644 --- a/BizHawk.Emulation.Cores/BizHawk.Emulation.Cores.csproj +++ b/BizHawk.Emulation.Cores/BizHawk.Emulation.Cores.csproj @@ -709,7 +709,6 @@ - diff --git a/BizHawk.Emulation.Cores/CPUs/Intel8048/Execute.cs b/BizHawk.Emulation.Cores/CPUs/Intel8048/Execute.cs index 340c3c5a71..512addb1e1 100644 --- a/BizHawk.Emulation.Cores/CPUs/Intel8048/Execute.cs +++ b/BizHawk.Emulation.Cores/CPUs/Intel8048/Execute.cs @@ -159,9 +159,9 @@ namespace BizHawk.Emulation.Common.Components.I8048 case 0x85: OP_IMP(CL0); break; // CLR F0 case 0x86: JP_COND(!IRQPending, IDLE); break; // JP !IRQ case 0x87: ILLEGAL(); break; // ILLEGAL - case 0x88: OP_PB_DIR(OR8, BUS); break; // OR BUS,# - case 0x89: OP_PB_DIR(OR8, P1); break; // OR P1,# - case 0x8A: OP_PB_DIR(OR8, P2); break; // OR P2,# + case 0x88: OP_PB_DIR(OR8, 0); break; // OR BUS,# + case 0x89: OP_PB_DIR(OR8, 1); break; // OR P1,# + case 0x8A: OP_PB_DIR(OR8, 2); break; // OR P2,# case 0x8B: ILLEGAL(); break; // ILLEGAL case 0x8C: OP_EXP_A(OR8, P4); break; // OR P4,A case 0x8D: OP_EXP_A(OR8, P5); break; // OR P5,A @@ -175,9 +175,9 @@ namespace BizHawk.Emulation.Common.Components.I8048 case 0x95: OP_IMP(CM0); break; // COM F0 case 0x96: JP_COND(Regs[A] != 0, IDLE); break; // JP (A != 0) case 0x97: OP_IMP(CLC); break; // CLR C - case 0x98: OP_PB_DIR(AND8, BUS); break; // AND BUS,# - case 0x99: OP_PB_DIR(AND8, P1); break; // AND P1,# - case 0x9A: OP_PB_DIR(AND8, P2); break; // AND P2,# + case 0x98: OP_PB_DIR(AND8, 0); break; // AND BUS,# + case 0x99: OP_PB_DIR(AND8, 1); break; // AND P1,# + case 0x9A: OP_PB_DIR(AND8, 2); break; // AND P2,# case 0x9B: ILLEGAL(); break; // ILLEGAL case 0x9C: OP_EXP_A(AND8, P4); break; // AND P4,A case 0x9D: OP_EXP_A(AND8, P5); break; // AND P5,A diff --git a/BizHawk.Emulation.Cores/CPUs/Intel8048/I8048.cs b/BizHawk.Emulation.Cores/CPUs/Intel8048/I8048.cs index 61691764bb..6af3e975f3 100644 --- a/BizHawk.Emulation.Cores/CPUs/Intel8048/I8048.cs +++ b/BizHawk.Emulation.Cores/CPUs/Intel8048/I8048.cs @@ -418,10 +418,18 @@ namespace BizHawk.Emulation.Common.Components.I8048 EA = false; break; case RD_P: - EA = false; + reg_d_ad = cur_instr[instr_pntr++]; + reg_l_ad = cur_instr[instr_pntr++]; + + Regs[reg_d_ad] = ReadPort(reg_l_ad); + Regs[PX + reg_l_ad] = Regs[reg_d_ad]; break; case WR_P: - WritePort(cur_instr[instr_pntr++], (byte)Regs[cur_instr[instr_pntr++]]); + reg_d_ad = cur_instr[instr_pntr++]; + reg_l_ad = cur_instr[instr_pntr++]; + + WritePort(reg_d_ad, (byte)Regs[reg_l_ad]); + Regs[PX + reg_d_ad] = Regs[reg_l_ad]; break; } @@ -492,7 +500,7 @@ namespace BizHawk.Emulation.Common.Components.I8048 public string TraceHeader { - get { return "MC6809: PC, machine code, mnemonic, operands, registers (A, B, X, Y, US, SP, DP, CC), Cy, flags (EFHINZVC)"; } + get { return "MC6809: PC, machine code, mnemonic, operands, registers (A, B, X, Y, US, SP, DP, CC), Cy, flags (CAFBIFTTR)"; } } public TraceInfo State(bool disassemble = true) @@ -503,7 +511,7 @@ namespace BizHawk.Emulation.Common.Components.I8048 { Disassembly = $"{(disassemble ? Disassemble(Regs[PC], ReadMemory, out notused) : "---")} ".PadRight(50), RegisterInfo = string.Format( - "A:{0:X2} R0:{1:X2} R1:{2:X2} R2:{3:X2} R3:{4:X2} R4:{5:X2} R5:{6:X2} R6:{7:X2} R7:{8:X2} PSW:{9:X4} Cy:{10} {11}{12}{13}{14} {15}{16}{17}{18}{19}", + "A:{0:X2} R0:{1:X2} R1:{2:X2} R2:{3:X2} R3:{4:X2} R4:{5:X2} R5:{6:X2} R6:{7:X2} R7:{8:X2} PSW:{9:X4} Cy:{10} {11}{12}{13}{14}{15}{16}{17}{18}{19}{20}", Regs[A], Regs[(ushort)(R0 + RB)], Regs[(ushort)(R1 + RB)], @@ -520,6 +528,7 @@ namespace BizHawk.Emulation.Common.Components.I8048 FlagF0 ? "F" : "f", FlagBS ? "B" : "b", IntEn ? "I" : "i", + TimIntEn ? "N" : "n", F1 ? "F" : "f", T0 ? "T" : "t", T1 ? "T" : "t", diff --git a/BizHawk.Emulation.Cores/CPUs/Intel8048/Interrupts.cs b/BizHawk.Emulation.Cores/CPUs/Intel8048/Interrupts.cs index f346b0ccad..fe10cf9cea 100644 --- a/BizHawk.Emulation.Cores/CPUs/Intel8048/Interrupts.cs +++ b/BizHawk.Emulation.Cores/CPUs/Intel8048/Interrupts.cs @@ -26,7 +26,8 @@ namespace BizHawk.Emulation.Common.Components.I8048 private void ResetInterrupts() { - IntEn = true; + IntEn = false; + TimIntEn = false; } } } \ No newline at end of file diff --git a/BizHawk.Emulation.Cores/CPUs/Intel8048/OP_Tables.cs b/BizHawk.Emulation.Cores/CPUs/Intel8048/OP_Tables.cs index ce84b8efe8..d5fd15ed0f 100644 --- a/BizHawk.Emulation.Cores/CPUs/Intel8048/OP_Tables.cs +++ b/BizHawk.Emulation.Cores/CPUs/Intel8048/OP_Tables.cs @@ -212,13 +212,13 @@ namespace BizHawk.Emulation.Common.Components.I8048 { PopulateCURINSTR(IDLE, IDLE, + EEA, + WR_P, 0, (ushort)(reg + RB), + DEA, IDLE, IDLE, IDLE, - IDLE, - IDLE, - IDLE, - IDLE); + RD_P, A, 0); IRQS = 9; } @@ -268,18 +268,35 @@ namespace BizHawk.Emulation.Common.Components.I8048 IRQS = 9; } + // TODO: This should only write back to the port destination if directly wired, otherwise we should wait for a write pulse + // TODO: for O2, P1 is tied direct to CTRL outputs so this is ok, BUS and P2 should do something else though public void OP_PB_DIR(ushort oper, ushort reg) { - PopulateCURINSTR(IDLE, - IDLE, - IDLE, - RD, ALU, PC, - INC11, PC, - IDLE, - IDLE, - IDLE, - oper, reg, ALU); - + if (reg == 1) + { + PopulateCURINSTR(IDLE, + IDLE, + IDLE, + RD, ALU, PC, + INC11, PC, + oper, (ushort)(reg + PX), ALU, + IDLE, + IDLE, + WR_P, reg, (ushort)(reg + PX)); + } + else + { + PopulateCURINSTR(IDLE, + IDLE, + IDLE, + RD, ALU, PC, + INC11, PC, + oper, (ushort)(reg + PX), ALU, + IDLE, + IDLE, + IDLE); + } + IRQS = 9; } diff --git a/BizHawk.Emulation.Cores/CPUs/Intel8048/Registers.cs b/BizHawk.Emulation.Cores/CPUs/Intel8048/Registers.cs index fea2ad0fb9..a2038ba039 100644 --- a/BizHawk.Emulation.Cores/CPUs/Intel8048/Registers.cs +++ b/BizHawk.Emulation.Cores/CPUs/Intel8048/Registers.cs @@ -33,6 +33,9 @@ namespace BizHawk.Emulation.Common.Components.I8048 public const ushort R6 = 6; public const ushort R7 = 7; + // offset for port regs + public const ushort PX = 70; + // the location pointed to by the registers is controlled by the RAM bank public ushort RB = 0; public ushort RAM_ptr = 0; @@ -44,11 +47,11 @@ namespace BizHawk.Emulation.Common.Components.I8048 //RAM occupies registers 0-63 public const ushort PC = 64; public const ushort PSW = 65; - public const ushort BUS = 66; - public const ushort A = 67; - public const ushort ADDR = 68; // internal - public const ushort ALU = 69; // internal - public const ushort ALU2 = 70; // internal + public const ushort A = 66; + public const ushort ADDR = 67; // internal + public const ushort ALU = 68; // internal + public const ushort ALU2 = 69; // internal + public const ushort BUS = 70; public const ushort P1 = 71; public const ushort P2 = 72; public const ushort P4 = 73; diff --git a/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/Audio.cs b/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/Audio.cs deleted file mode 100644 index b2edc7104c..0000000000 --- a/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/Audio.cs +++ /dev/null @@ -1,180 +0,0 @@ -using System; - -using BizHawk.Common; -using BizHawk.Common.BufferExtensions; -using BizHawk.Emulation.Common; -using BizHawk.Common.NumberExtensions; - -namespace BizHawk.Emulation.Cores.Consoles.O2Hawk -{ - // Audio Emulation (a 24 bit shift register plus a control register) - public class Audio : ISoundProvider - { - public O2Hawk Core { get; set; } - - private BlipBuffer _blip_C = new BlipBuffer(15000); - - public byte sample; - - public byte shift_0, shift_1, shift_2, aud_ctrl; - - public uint master_audio_clock; - - public int tick_cnt, output_bit; - - public int latched_sample_C; - - public byte ReadReg(int addr) - { - byte ret = 0; - - switch (addr) - { - case 0xA7: ret = shift_0; break; - case 0xA8: ret = shift_1; break; - case 0xA9: ret = shift_2; break; - case 0xAA: ret = aud_ctrl; break; - } - - return ret; - } - - public void WriteReg(int addr, byte value) - { - switch (addr) - { - case 0xA7: shift_0 = value; break; - case 0xA8: shift_1 = value; break; - case 0xA9: shift_2 = value; break; - case 0xAA: aud_ctrl = value; break; - } - - } - - public void tick() - { - int C_final = 0; - - if (aud_ctrl.Bit(7)) - { - tick_cnt++; - if (tick_cnt > (aud_ctrl.Bit(5) ? 455 : 1820)) - { - tick_cnt = 0; - - output_bit = (shift_0 >> 1) & 1; - - shift_0 = (byte)((shift_0 >> 1) | ((shift_1 & 1) << 3)); - shift_1 = (byte)((shift_1 >> 1) | ((shift_2 & 1) << 3)); - - if (aud_ctrl.Bit(6)) - { - shift_2 = (byte)((shift_2 >> 1) | ((output_bit) << 3)); - } - else - { - shift_0 = (byte)(shift_2 >> 1); - } - } - - C_final = output_bit; - C_final *= ((aud_ctrl & 0xF) + 1) * 40; - } - - if (C_final != latched_sample_C) - { - _blip_C.AddDelta(master_audio_clock, C_final - latched_sample_C); - latched_sample_C = C_final; - } - - master_audio_clock++; - } - - public void power_off() - { - for (int i = 0; i < 0x16; i++) - { - WriteReg(0xFF10 + i, 0); - } - } - - public void Reset() - { - master_audio_clock = 0; - - sample = 0; - - _blip_C.SetRates(4194304, 44100); - } - - public void SyncState(Serializer ser) - { - ser.Sync(nameof(master_audio_clock), ref master_audio_clock); - - ser.Sync(nameof(sample), ref sample); - ser.Sync(nameof(latched_sample_C), ref latched_sample_C); - - ser.Sync(nameof(aud_ctrl), ref aud_ctrl); - ser.Sync(nameof(shift_0), ref shift_0); - ser.Sync(nameof(shift_1), ref shift_1); - ser.Sync(nameof(shift_2), ref shift_2); - ser.Sync(nameof(tick_cnt), ref tick_cnt); - ser.Sync(nameof(output_bit), ref output_bit); - } - - #region audio - - public bool CanProvideAsync => false; - - public void SetSyncMode(SyncSoundMode mode) - { - if (mode != SyncSoundMode.Sync) - { - throw new InvalidOperationException("Only Sync mode is supported_"); - } - } - - public SyncSoundMode SyncMode => SyncSoundMode.Sync; - - public void GetSamplesSync(out short[] samples, out int nsamp) - { - _blip_C.EndFrame(master_audio_clock); - - nsamp = _blip_C.SamplesAvailable(); - - samples = new short[nsamp * 2]; - - if (nsamp != 0) - { - _blip_C.ReadSamples(samples, nsamp, false); - } - - master_audio_clock = 0; - } - - public void GetSamplesAsync(short[] samples) - { - throw new NotSupportedException("Async is not available"); - } - - public void DiscardSamples() - { - _blip_C.Clear(); - master_audio_clock = 0; - } - - private void GetSamples(short[] samples) - { - - } - - public void DisposeSound() - { - _blip_C.Clear(); - _blip_C.Dispose(); - _blip_C = null; - } - - #endregion - } -} \ No newline at end of file diff --git a/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/MemoryMap.cs b/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/MemoryMap.cs index 6921955868..161f17cf7b 100644 --- a/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/MemoryMap.cs +++ b/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/MemoryMap.cs @@ -80,10 +80,6 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk } if (ppu_en && !copy_en) { - if ((addr_latch >= 0xA7) || (addr_latch <= 0xAA)) - { - return audio.ReadReg(addr_latch); - } return ppu.ReadReg(addr_latch); } @@ -134,14 +130,8 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk } if (ppu_en) { - if ((addr_latch >= 0xA7) || (addr_latch <= 0xAA)) - { - audio.WriteReg(addr_latch, value); - } - else - { - ppu.WriteReg(addr_latch, value); - } + ppu.WriteReg(addr_latch, value); + //Console.WriteLine((addr_latch) + " " + value); } } } @@ -155,6 +145,8 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk kybrd_en = !value.Bit(2); cart_b1 = value.Bit(1); cart_b0 = value.Bit(0); + + //Console.WriteLine("main ctrl: " + value + " " + ppu_en + " " + RAM_en); } else { diff --git a/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.IEmulator.cs b/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.IEmulator.cs index 9dc8cb7f31..ebea0ab315 100644 --- a/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.IEmulator.cs +++ b/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.IEmulator.cs @@ -52,10 +52,11 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk { for (int i = 0; i < 10000; i++) { - audio.tick(); + ppu.tick(); ppu.tick(); ppu.DMA_tick(); serialport.serial_transfer_tick(); + ppu.Audio_tick(); cpu.ExecuteOne(); if (in_vblank && !in_vblank_old) @@ -82,10 +83,11 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk public void do_single_step() { - audio.tick(); + ppu.tick(); ppu.tick(); ppu.DMA_tick(); serialport.serial_transfer_tick(); + ppu.Audio_tick(); cpu.ExecuteOne(); } @@ -138,7 +140,7 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk public void Dispose() { - audio.DisposeSound(); + ppu.DisposeSound(); } #region Video provider diff --git a/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.IStatable.cs b/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.IStatable.cs index 3030adff46..ff886bc27e 100644 --- a/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.IStatable.cs +++ b/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.IStatable.cs @@ -51,7 +51,6 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk mapper.SyncState(ser); ppu.SyncState(ser); serialport.SyncState(ser); - audio.SyncState(ser); ser.BeginSection("Odyssey2"); ser.Sync(nameof(core), ref core, false); diff --git a/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.cs b/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.cs index 3db97d260d..f76f4872f2 100644 --- a/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.cs +++ b/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.cs @@ -35,7 +35,7 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk public byte[] cart_RAM; public bool has_bat; - private int _frame = 0; + public int _frame = 0; public MapperBase mapper; @@ -43,7 +43,6 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk public I8048 cpu; public PPU ppu; - public Audio audio; public SerialPort serialport; [CoreConstructor("O2")] @@ -62,7 +61,6 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk OnExecFetch = ExecFetch, }; - audio = new Audio(); serialport = new SerialPort(); CoreComm = comm; @@ -92,12 +90,11 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk _frameHz = 60; - audio.Core = this; ppu.Core = this; serialport.Core = this; ser.Register(this); - ser.Register(audio); + ser.Register(ppu); ServiceProvider = ser; _settings = (O2Settings)settings ?? new O2Settings(); @@ -118,6 +115,11 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk { RAM[j] = (byte)j; } + + for (int k = 0; k < 0x100; k++) + { + ppu.WriteReg(k, (byte)k); + } } public DisplayType Region => DisplayType.NTSC; @@ -132,7 +134,6 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk RAM_Bank = 1; // RAM bank always starts as 1 (even writing zero still sets 1) ppu.Reset(); - audio.Reset(); serialport.Reset(); cpu.SetCallbacks(ReadMemory, PeekMemory, PeekMemory, WriteMemory); diff --git a/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/PPU.cs b/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/PPU.cs index 8589d23246..7471900a39 100644 --- a/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/PPU.cs +++ b/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/PPU.cs @@ -1,9 +1,13 @@ using System; using BizHawk.Common; +using BizHawk.Common.NumberExtensions; +using BizHawk.Common.BufferExtensions; +using BizHawk.Emulation.Common; + namespace BizHawk.Emulation.Cores.Consoles.O2Hawk { - public class PPU + public class PPU : ISoundProvider { public O2Hawk Core { get; set; } @@ -25,7 +29,7 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk public byte STAT; public byte scroll_y; public byte scroll_x; - public byte LY; + public int LY; public byte LY_actual; public byte LY_inc; public byte LYC; @@ -39,6 +43,9 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk public int DMA_clock; public int DMA_inc; public byte DMA_byte; + public int cycle; + public bool VBL; + public bool HBL; public byte ReadReg(int addr) { @@ -76,6 +83,10 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk { ret = VDC_color; } + else if (addr <= 0xA7) + { + ret = AudioReadReg(addr); + } return ret; } @@ -114,11 +125,47 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk { VDC_color = value; } + else if (addr <= 0xA7) + { + AudioWriteReg(addr, value); + } } public void tick() { + cycle++; + // drawing cycles + if ((cycle >= 43) && !VBL) + { + if (cycle == 43) + { + HBL = false; + // trigger timer tick if enabled + if (Core.cpu.counter_en) { Core.cpu.T1 = false; } + } + } + + // end of scanline + if (cycle == 228) + { + cycle = 0; + HBL = true; + if (VDC_ctrl.Bit(0)) { Core.cpu.IRQPending = true;} + + // trigger timer tick if enabled + if (Core.cpu.counter_en) { Core.cpu.T1 = true; } + + LY++; + if (LY == 262) + { + LY = 0; + HBL = false; + VBL = true; + } + + if (LY == 22) { VBL = false; } + } } // might be needed, not sure yet @@ -151,7 +198,7 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk public void Reset() { - + AudioReset(); } public static readonly byte[] Internal_Graphics = { 0x3C, 0x66, 0x66, 0x66, 0x66, 0x66, 0x3C, // 0 0x00 @@ -220,6 +267,7 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk 0x00, 0x00, 0x00, 0x54, 0x54, 0xFF, 0x7E, // (boat 3 unk) 0x3F }; + public void SyncState(Serializer ser) { ser.Sync(nameof(Sprites), ref Sprites, false); @@ -255,6 +303,168 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk ser.Sync(nameof(DMA_clock), ref DMA_clock); ser.Sync(nameof(DMA_inc), ref DMA_inc); ser.Sync(nameof(DMA_byte), ref DMA_byte); + ser.Sync(nameof(cycle), ref cycle); + ser.Sync(nameof(VBL), ref VBL); + ser.Sync(nameof(HBL), ref HBL); + + AudioSyncState(ser); } + + private BlipBuffer _blip_C = new BlipBuffer(15000); + + public byte sample; + + public byte shift_0, shift_1, shift_2, aud_ctrl; + + public uint master_audio_clock; + + public int tick_cnt, output_bit; + + public int latched_sample_C; + + public byte AudioReadReg(int addr) + { + byte ret = 0; + + switch (addr) + { + case 0xA7: ret = shift_0; break; + case 0xA8: ret = shift_1; break; + case 0xA9: ret = shift_2; break; + case 0xAA: ret = aud_ctrl; break; + } + + return ret; + } + + public void AudioWriteReg(int addr, byte value) + { + switch (addr) + { + case 0xA7: shift_0 = value; break; + case 0xA8: shift_1 = value; break; + case 0xA9: shift_2 = value; break; + case 0xAA: aud_ctrl = value; break; + } + + } + + public void Audio_tick() + { + int C_final = 0; + + if (aud_ctrl.Bit(7)) + { + tick_cnt++; + if (tick_cnt > (aud_ctrl.Bit(5) ? 455 : 1820)) + { + tick_cnt = 0; + + output_bit = (shift_0 >> 1) & 1; + + shift_0 = (byte)((shift_0 >> 1) | ((shift_1 & 1) << 3)); + shift_1 = (byte)((shift_1 >> 1) | ((shift_2 & 1) << 3)); + + if (aud_ctrl.Bit(6)) + { + shift_2 = (byte)((shift_2 >> 1) | ((output_bit) << 3)); + } + else + { + shift_0 = (byte)(shift_2 >> 1); + } + } + + C_final = output_bit; + C_final *= ((aud_ctrl & 0xF) + 1) * 40; + } + + if (C_final != latched_sample_C) + { + _blip_C.AddDelta(master_audio_clock, C_final - latched_sample_C); + latched_sample_C = C_final; + } + + master_audio_clock++; + } + + public void AudioReset() + { + master_audio_clock = 0; + + sample = 0; + + _blip_C.SetRates(4194304, 44100); + } + + public void AudioSyncState(Serializer ser) + { + ser.Sync(nameof(master_audio_clock), ref master_audio_clock); + + ser.Sync(nameof(sample), ref sample); + ser.Sync(nameof(latched_sample_C), ref latched_sample_C); + + ser.Sync(nameof(aud_ctrl), ref aud_ctrl); + ser.Sync(nameof(shift_0), ref shift_0); + ser.Sync(nameof(shift_1), ref shift_1); + ser.Sync(nameof(shift_2), ref shift_2); + ser.Sync(nameof(tick_cnt), ref tick_cnt); + ser.Sync(nameof(output_bit), ref output_bit); + } + + #region audio + + public bool CanProvideAsync => false; + + public void SetSyncMode(SyncSoundMode mode) + { + if (mode != SyncSoundMode.Sync) + { + throw new InvalidOperationException("Only Sync mode is supported_"); + } + } + + public SyncSoundMode SyncMode => SyncSoundMode.Sync; + + public void GetSamplesSync(out short[] samples, out int nsamp) + { + _blip_C.EndFrame(master_audio_clock); + + nsamp = _blip_C.SamplesAvailable(); + + samples = new short[nsamp * 2]; + + if (nsamp != 0) + { + _blip_C.ReadSamples(samples, nsamp, false); + } + + master_audio_clock = 0; + } + + public void GetSamplesAsync(short[] samples) + { + throw new NotSupportedException("Async is not available"); + } + + public void DiscardSamples() + { + _blip_C.Clear(); + master_audio_clock = 0; + } + + private void GetSamples(short[] samples) + { + + } + + public void DisposeSound() + { + _blip_C.Clear(); + _blip_C.Dispose(); + _blip_C = null; + } + + #endregion } } diff --git a/BizHawk.sln.DotSettings b/BizHawk.sln.DotSettings index 33cc80db5f..ddd4c5b89d 100644 --- a/BizHawk.sln.DotSettings +++ b/BizHawk.sln.DotSettings @@ -193,10 +193,12 @@ True True True + True True True True True + True True True True @@ -242,6 +244,7 @@ True True True + True True True True @@ -252,6 +255,7 @@ True True True + True True True True @@ -315,6 +319,7 @@ True True True + True True True True