misc code cleanups in BizHawk.Client.Common

This commit is contained in:
adelikat 2017-04-14 14:59:01 -05:00
parent 7ab8455e84
commit b6f335e4c8
81 changed files with 1405 additions and 1587 deletions

View File

@ -3,7 +3,7 @@
/// <summary> /// <summary>
/// Enumeration of each system emulated by BizHawk /// Enumeration of each system emulated by BizHawk
/// </summary> /// </summary>
public enum CoreSystem : int public enum CoreSystem
{ {
Null = 0, Null = 0,
TI83, TI83,

View File

@ -7,7 +7,7 @@ namespace BizHawk.Client.ApiHawk
/// for all existing controllers /// for all existing controllers
/// </summary> /// </summary>
[Flags] [Flags]
public enum JoypadButton : int public enum JoypadButton
{ {
A = 1, A = 1,
B = 2, B = 2,
@ -28,6 +28,7 @@ namespace BizHawk.Client.ApiHawk
/// Master system Button 1 /// Master system Button 1
/// </summary> /// </summary>
B1 = 16384, B1 = 16384,
/// <summary> /// <summary>
/// Master system Button 1 /// Master system Button 1
/// </summary> /// </summary>
@ -37,18 +38,22 @@ namespace BizHawk.Client.ApiHawk
/// N64 C up /// N64 C up
/// </summary> /// </summary>
CUp = 65536, CUp = 65536,
/// <summary> /// <summary>
/// N64 C down /// N64 C down
/// </summary> /// </summary>
CDown = 131072, CDown = 131072,
/// <summary> /// <summary>
/// N64 C Left /// N64 C Left
/// </summary> /// </summary>
CLeft = 262144, CLeft = 262144,
/// <summary> /// <summary>
/// N64 C Right /// N64 C Right
/// </summary> /// </summary>
CRight = 524288, CRight = 524288,
/// <summary> /// <summary>
/// N64 Analog stick /// N64 Analog stick
/// </summary> /// </summary>

View File

@ -5,7 +5,6 @@ using System.Linq;
using System.Reflection; using System.Reflection;
using ICSharpCode.SharpZipLib.Zip; using ICSharpCode.SharpZipLib.Zip;
//using Ionic.Zip;
namespace BizHawk.Client.Common namespace BizHawk.Client.Common
{ {

View File

@ -19,12 +19,9 @@ namespace BizHawk.Client.Common
} }
} }
public ControllerDefinition Definition public ControllerDefinition Definition => _type;
{
get { return _type; }
}
public bool IsPressed(string button) public bool IsPressed(string button)
{ {
return _buttons[button]; return _buttons[button];
} }
@ -105,11 +102,11 @@ namespace BizHawk.Client.Common
} }
} }
//zero 09-mar-2015 - not sure if adding + 1 here is correct.. but... maybe? // zero 09-mar-2015 - not sure if adding + 1 here is correct.. but... maybe?
var output = (input * multiplier + 10000.0f) * (range.Max - range.Min + 1) / 20000.0f + range.Min; var output = (input * multiplier + 10000.0f) * (range.Max - range.Min + 1) / 20000.0f + range.Min;
//zero 09-mar-2015 - at this point, we should only have integers, since thats all 100% of consoles ever see // zero 09-mar-2015 - at this point, we should only have integers, since thats all 100% of consoles ever see
//if this becomes a problem we can add flags to the range and update GUIs to be able to display floats // if this becomes a problem we can add flags to the range and update GUIs to be able to display floats
output = (int)output; output = (int)output;
float lbound = Math.Min(range.Min, range.Max); float lbound = Math.Min(range.Min, range.Max);
@ -160,7 +157,7 @@ namespace BizHawk.Client.Common
} }
} }
//it's not sure where this should happen, so for backwards compatibility.. do it every time // it's not sure where this should happen, so for backwards compatibility.. do it every time
NormalizeFloats(controller); NormalizeFloats(controller);
} }
@ -288,7 +285,10 @@ namespace BizHawk.Client.Common
_buttonStarts.Clear(); _buttonStarts.Clear();
} }
public float GetFloat(string name) { throw new NotImplementedException(); } public float GetFloat(string name)
{
throw new NotImplementedException();
}
// look for bindings which are activated by the supplied physical button. // look for bindings which are activated by the supplied physical button.
public List<string> SearchBindings(string button) public List<string> SearchBindings(string button)
@ -304,9 +304,9 @@ namespace BizHawk.Client.Common
{ {
foreach (var kvp in _bindings) foreach (var kvp in _bindings)
{ {
foreach (var bound_button in kvp.Value) foreach (var boundBtn in kvp.Value)
{ {
if (_buttons[kvp.Key] == false && controller.IsPressed(bound_button)) if (_buttons[kvp.Key] == false && controller.IsPressed(boundBtn))
{ {
_buttonStarts[kvp.Key] = _emulator.Frame; _buttonStarts[kvp.Key] = _emulator.Frame;
} }

View File

@ -6,7 +6,6 @@ namespace BizHawk.Client.Common
{ {
public MoviePlatformMismatchException(string message) : base(message) public MoviePlatformMismatchException(string message) : base(message)
{ {
} }
} }
} }

View File

@ -17,7 +17,7 @@ namespace BizHawk.Client.Common
public string Hash { get; set; } public string Hash { get; set; }
} }
public List<FirmwareEventArgs> RecentlyServed { get; private set; } public List<FirmwareEventArgs> RecentlyServed { get; }
public class ResolutionInfo public class ResolutionInfo
{ {
@ -53,12 +53,10 @@ namespace BizHawk.Client.Common
public ResolutionInfo Resolve(FirmwareDatabase.FirmwareRecord record, bool forbidScan = false) public ResolutionInfo Resolve(FirmwareDatabase.FirmwareRecord record, bool forbidScan = false)
{ {
//purpose of forbidScan: sometimes this is called from a loop in Scan(). we dont want to repeatedly DoScanAndResolve in that case, its already been done. // purpose of forbidScan: sometimes this is called from a loop in Scan(). we dont want to repeatedly DoScanAndResolve in that case, its already been done.
bool first = true; bool first = true;
RETRY: RETRY:
ResolutionInfo resolved; ResolutionInfo resolved;
_resolutionDictionary.TryGetValue(record, out resolved); _resolutionDictionary.TryGetValue(record, out resolved);
@ -66,7 +64,10 @@ namespace BizHawk.Client.Common
// NOTE: this could result in bad performance in some cases if the scanning happens repeatedly.. // NOTE: this could result in bad performance in some cases if the scanning happens repeatedly..
if (resolved == null && first) if (resolved == null && first)
{ {
if(!forbidScan) DoScanAndResolve(); if (!forbidScan)
{
DoScanAndResolve();
}
first = false; first = false;
goto RETRY; goto RETRY;
} }
@ -78,14 +79,19 @@ namespace BizHawk.Client.Common
public string Request(string sysId, string firmwareId) public string Request(string sysId, string firmwareId)
{ {
var resolved = Resolve(sysId, firmwareId); var resolved = Resolve(sysId, firmwareId);
if (resolved == null) return null; if (resolved == null)
{
return null;
}
RecentlyServed.Add(new FirmwareEventArgs RecentlyServed.Add(new FirmwareEventArgs
{ {
SystemId = sysId, SystemId = sysId,
FirmwareId = firmwareId, FirmwareId = firmwareId,
Hash = resolved.Hash, Hash = resolved.Hash,
Size = resolved.Size Size = resolved.Size
}); });
return resolved.FilePath; return resolved.FilePath;
} }
@ -119,12 +125,14 @@ namespace BizHawk.Client.Common
public void DoScanAndResolve() public void DoScanAndResolve()
{ {
//build a list of file sizes. Only those will be checked during scanning // build a list of file sizes. Only those will be checked during scanning
HashSet<long> sizes = new HashSet<long>(); HashSet<long> sizes = new HashSet<long>();
foreach (var ff in FirmwareDatabase.FirmwareFiles) foreach (var ff in FirmwareDatabase.FirmwareFiles)
{
sizes.Add(ff.size); sizes.Add(ff.size);
}
using(var reader = new RealFirmwareReader()) using (var reader = new RealFirmwareReader())
{ {
// build a list of files under the global firmwares path, and build a hash for each of them while we're at it // build a list of files under the global firmwares path, and build a hash for each of them while we're at it
var todo = new Queue<DirectoryInfo>(); var todo = new Queue<DirectoryInfo>();
@ -135,7 +143,9 @@ namespace BizHawk.Client.Common
var di = todo.Dequeue(); var di = todo.Dequeue();
if (!di.Exists) if (!di.Exists)
{
continue; continue;
}
// we're going to allow recursing into subdirectories, now. its been verified to work OK // we're going to allow recursing into subdirectories, now. its been verified to work OK
foreach (var disub in di.GetDirectories()) foreach (var disub in di.GetDirectories())
@ -145,8 +155,10 @@ namespace BizHawk.Client.Common
foreach (var fi in di.GetFiles()) foreach (var fi in di.GetFiles())
{ {
if(sizes.Contains(fi.Length)) if (sizes.Contains(fi.Length))
{
reader.Read(fi); reader.Read(fi);
}
} }
} }
@ -203,6 +215,7 @@ namespace BizHawk.Client.Common
ri = new ResolutionInfo(); ri = new ResolutionInfo();
_resolutionDictionary[fr] = ri; _resolutionDictionary[fr] = ri;
} }
ri.UserSpecified = true; ri.UserSpecified = true;
ri.KnownFirmwareFile = null; ri.KnownFirmwareFile = null;
ri.FilePath = userSpec; ri.FilePath = userSpec;
@ -239,11 +252,8 @@ namespace BizHawk.Client.Common
} }
} }
} }
} // foreach(firmware record)
} //foreach(firmware record) } // using(new RealFirmwareReader())
} //using(new RealFirmwareReader()) } // DoScanAndResolve()
} //DoScanAndResolve() } // class FirmwareManager
} // namespace
} //class FirmwareManager
} //namespace

View File

@ -29,23 +29,23 @@ namespace BizHawk.Client.Common
public static AutofireController AutofireNullControls; public static AutofireController AutofireNullControls;
//the movie will be spliced inbetween these if it is present // the movie will be spliced inbetween these if it is present
public static CopyControllerAdapter MovieInputSourceAdapter = new CopyControllerAdapter(); public static CopyControllerAdapter MovieInputSourceAdapter = new CopyControllerAdapter();
public static CopyControllerAdapter MovieOutputHardpoint = new CopyControllerAdapter(); public static CopyControllerAdapter MovieOutputHardpoint = new CopyControllerAdapter();
public static MultitrackRewiringControllerAdapter MultitrackRewiringAdapter = new MultitrackRewiringControllerAdapter(); public static MultitrackRewiringControllerAdapter MultitrackRewiringAdapter = new MultitrackRewiringControllerAdapter();
//dont take my word for it, since the final word is actually in RewireInputChain, but here is a guide... // dont take my word for it, since the final word is actually in RewireInputChain, but here is a guide...
//user -> Input -> ActiveController -> UDLR -> StickyXORPlayerInputAdapter -> TurboAdapter(TBD) -> Lua(?TBD?) -> .. // user -> Input -> ActiveController -> UDLR -> StickyXORPlayerInputAdapter -> TurboAdapter(TBD) -> Lua(?TBD?) -> ..
//.. -> MultitrackRewiringControllerAdapter -> MovieInputSourceAdapter -> (MovieSession) -> MovieOutputAdapter -> ControllerOutput(1) -> Game // .. -> MultitrackRewiringControllerAdapter -> MovieInputSourceAdapter -> (MovieSession) -> MovieOutputAdapter -> ControllerOutput(1) -> Game
//(1)->Input Display // (1)->Input Display
//the original source controller, bound to the user, sort of the "input" port for the chain, i think // the original source controller, bound to the user, sort of the "input" port for the chain, i think
public static Controller ActiveController; public static Controller ActiveController;
//rapid fire version on the user controller, has its own key bindings and is OR'ed against ActiveController //rapid fire version on the user controller, has its own key bindings and is OR'ed against ActiveController
public static AutofireController AutoFireController; public static AutofireController AutoFireController;
//the "output" port for the controller chain. // the "output" port for the controller chain.
public static CopyControllerAdapter ControllerOutput = new CopyControllerAdapter(); public static CopyControllerAdapter ControllerOutput = new CopyControllerAdapter();
public static UD_LR_ControllerAdapter UD_LR_ControllerAdapter = new UD_LR_ControllerAdapter(); public static UD_LR_ControllerAdapter UD_LR_ControllerAdapter = new UD_LR_ControllerAdapter();
@ -95,7 +95,8 @@ namespace BizHawk.Client.Common
{ {
return SystemInfo.GG; return SystemInfo.GG;
} }
else if ((Emulator as SMS).IsSG1000)
if ((Emulator as SMS).IsSG1000)
{ {
return SystemInfo.SG; return SystemInfo.SG;
} }

View File

@ -21,7 +21,7 @@ namespace BizHawk.Client.Common
} }
// header verified, loop over patch entries // header verified, loop over patch entries
uint EOF = ('E' * 0x10000 + 'O' * 0x100 + 'F'); uint eof = ('E' * 0x10000) + ('O' * 0x100) + 'F';
var ret = new MemoryStream(rom.Length); var ret = new MemoryStream(rom.Length);
ret.Write(rom, 0, rom.Length); ret.Write(rom, 0, rom.Length);
@ -29,8 +29,11 @@ namespace BizHawk.Client.Common
while (true) while (true)
{ {
uint offset = Read24(patch); uint offset = Read24(patch);
if (offset == EOF) if (offset == eof)
{
return ret.ToArray(); return ret.ToArray();
}
ushort size = Read16(patch); ushort size = Read16(patch);
ret.Seek(offset, SeekOrigin.Begin); ret.Seek(offset, SeekOrigin.Begin);
@ -56,17 +59,17 @@ namespace BizHawk.Client.Common
private static ushort Read16(Stream patch) private static ushort Read16(Stream patch)
{ {
int Upper = patch.ReadByte(); int upper = patch.ReadByte();
int Lower = patch.ReadByte(); int lower = patch.ReadByte();
return (ushort)(Upper * 0x100 + Lower); return (ushort)((upper * 0x100) + lower);
} }
private static uint Read24(Stream patch) private static uint Read24(Stream patch)
{ {
int Upper = patch.ReadByte(); int upper = patch.ReadByte();
int Middle = patch.ReadByte(); int middle = patch.ReadByte();
int Lower = patch.ReadByte(); int lower = patch.ReadByte();
return (uint)(Upper * 0x10000 + Middle * 0x100 + Lower); return (uint)((upper * 0x10000) + (middle * 0x100) + lower);
} }
} }
} }

View File

@ -1,12 +1,9 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO; using System.IO;
namespace BizHawk.Client.Common namespace BizHawk.Client.Common
{ {
interface IZipWriter : IDisposable public interface IZipWriter : IDisposable
{ {
void WriteItem(string name, Action<Stream> callback); void WriteItem(string name, Action<Stream> callback);
} }

View File

@ -1,10 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.IO;
using System.Linq;
using System.Text;
using Ionic.Zip; using Ionic.Zip;
using System.IO;
namespace BizHawk.Client.Common namespace BizHawk.Client.Common
{ {
@ -28,9 +25,14 @@ namespace BizHawk.Client.Common
{ {
var e = z.PutNextEntry(name); var e = z.PutNextEntry(name);
if (level == 0) if (level == 0)
{
e.CompressionMethod = CompressionMethod.None; e.CompressionMethod = CompressionMethod.None;
}
else else
{
e.CompressionMethod = CompressionMethod.Deflate; e.CompressionMethod = CompressionMethod.Deflate;
}
callback(z); callback(z);
// there is no CloseEntry() call // there is no CloseEntry() call
} }

View File

@ -2,6 +2,10 @@
{ {
public class TurboKey public class TurboKey
{ {
private int _upTime, _downTime, _timer;
public bool Value { get; set; }
public void Reset(int downTime, int upTime) public void Reset(int downTime, int upTime)
{ {
Value = false; Value = false;
@ -22,15 +26,15 @@
Value = true; Value = true;
if (_timer > _downTime) if (_timer > _downTime)
{
Value = false; Value = false;
if(_timer > (_upTime+_downTime)) }
if (_timer > _upTime + _downTime)
{ {
_timer = 0; _timer = 0;
Value = true; Value = true;
} }
} }
public bool Value;
private int _upTime, _downTime, _timer;
} }
} }

View File

@ -3,7 +3,6 @@ using System.Linq;
using System.IO; using System.IO;
using System.Reflection; using System.Reflection;
using BizHawk.Common;
using BizHawk.Common.StringExtensions; using BizHawk.Common.StringExtensions;
using BizHawk.Emulation.Common; using BizHawk.Emulation.Common;
using BizHawk.Emulation.Common.IEmulatorExtensions; using BizHawk.Emulation.Common.IEmulatorExtensions;
@ -24,28 +23,27 @@ namespace BizHawk.Client.Common
return path; return path;
} }
/// <summary> /// <summary>
/// Makes a path relative to the %exe% dir /// Makes a path relative to the %exe% directory
/// </summary> /// </summary>
public static string MakeProgramRelativePath(string path) { return MakeAbsolutePath("%exe%/" + path, null); } public static string MakeProgramRelativePath(string path)
{
return MakeAbsolutePath("%exe%/" + path, null);
}
public static string GetDllDirectory() { return Path.Combine(GetExeDirectoryAbsolute(), "dll"); } public static string GetDllDirectory()
{
return Path.Combine(GetExeDirectoryAbsolute(), "dll");
}
/// <summary> /// <summary>
/// The location of the default INI file /// The location of the default INI file
/// </summary> /// </summary>
public static string DefaultIniPath public static string DefaultIniPath => MakeProgramRelativePath("config.ini");
{
get
{
return MakeProgramRelativePath("config.ini");
}
}
/// <summary> /// <summary>
/// Gets absolute base as derived from EXE /// Gets absolute base as derived from EXE
/// </summary> /// </summary>
/// <returns></returns>
public static string GetBasePathAbsolute() public static string GetBasePathAbsolute()
{ {
if (Global.Config.PathEntries.GlobalBaseFragment.Length < 1) // If empty, then EXE path if (Global.Config.PathEntries.GlobalBaseFragment.Length < 1) // If empty, then EXE path
@ -105,7 +103,6 @@ namespace BizHawk.Client.Common
} }
// This function translates relative path and special identifiers in absolute paths // This function translates relative path and special identifiers in absolute paths
if (path.Length < 1) if (path.Length < 1)
{ {
return GetBasePathAbsolute(); return GetBasePathAbsolute();
@ -183,7 +180,7 @@ namespace BizHawk.Client.Common
int z = workingpath.HowMany("\\"); int z = workingpath.HowMany("\\");
if (y >= z) if (y >= z)
{ {
//Return drive letter only, working path must be absolute? // Return drive letter only, working path must be absolute?
} }
return string.Empty; return string.Empty;
@ -259,7 +256,7 @@ namespace BizHawk.Client.Common
var filesystemSafeName = game.Name var filesystemSafeName = game.Name
.Replace("|", "+") .Replace("|", "+")
.Replace(":", " -") // adelikat - Path.GetFileName scraps everything to the left of a colon unfortunately, so we need this hack here .Replace(":", " -") // adelikat - Path.GetFileName scraps everything to the left of a colon unfortunately, so we need this hack here
.Replace("\"", ""); // adelikat - Ivan Ironman Stewart's Super Off-Road has quotes in game name .Replace("\"", string.Empty); // adelikat - Ivan Ironman Stewart's Super Off-Road has quotes in game name
// zero 06-nov-2015 - regarding the below, i changed my mind. for libretro i want subdirectories here. // zero 06-nov-2015 - regarding the below, i changed my mind. for libretro i want subdirectories here.
var filesystemDir = Path.GetDirectoryName(filesystemSafeName); var filesystemDir = Path.GetDirectoryName(filesystemSafeName);
@ -297,10 +294,10 @@ namespace BizHawk.Client.Common
public static string RetroSaveRAMDirectory(GameInfo game) public static string RetroSaveRAMDirectory(GameInfo game)
{ {
//hijinx here to get the core name out of the game name // hijinx here to get the core name out of the game name
var name = FilesystemSafeName(game); var name = FilesystemSafeName(game);
name = Path.GetDirectoryName(name); name = Path.GetDirectoryName(name);
if (name == "") name = FilesystemSafeName(game); if (name == string.Empty) name = FilesystemSafeName(game);
if (Global.MovieSession.Movie.IsActive) if (Global.MovieSession.Movie.IsActive)
{ {
@ -316,10 +313,13 @@ namespace BizHawk.Client.Common
public static string RetroSystemPath(GameInfo game) public static string RetroSystemPath(GameInfo game)
{ {
//hijinx here to get the core name out of the game name // hijinx here to get the core name out of the game name
var name = FilesystemSafeName(game); var name = FilesystemSafeName(game);
name = Path.GetDirectoryName(name); name = Path.GetDirectoryName(name);
if(name == "") name = FilesystemSafeName(game); if (name == string.Empty)
{
name = FilesystemSafeName(game);
}
var pathEntry = Global.Config.PathEntries[game.System, "System"] ?? var pathEntry = Global.Config.PathEntries[game.System, "System"] ??
Global.Config.PathEntries[game.System, "Base"]; Global.Config.PathEntries[game.System, "Base"];
@ -403,9 +403,6 @@ namespace BizHawk.Client.Common
/// Takes an absolute path and attempts to convert it to a relative, based on the system, /// Takes an absolute path and attempts to convert it to a relative, based on the system,
/// or global base if no system is supplied, if it is not a subfolder of the base, it will return the path unaltered /// or global base if no system is supplied, if it is not a subfolder of the base, it will return the path unaltered
/// </summary> /// </summary>
/// <param name="absolutePath"></param>
/// <param name="system"></param>
/// <returns></returns>
public static string TryMakeRelative(string absolutePath, string system = null) public static string TryMakeRelative(string absolutePath, string system = null)
{ {
var parentPath = string.IsNullOrWhiteSpace(system) ? var parentPath = string.IsNullOrWhiteSpace(system) ?
@ -430,8 +427,8 @@ namespace BizHawk.Client.Common
return absolutePath; return absolutePath;
} }
//http://stackoverflow.com/questions/3525775/how-to-check-if-directory-1-is-a-subdirectory-of-dir2-and-vice-versa // http://stackoverflow.com/questions/3525775/how-to-check-if-directory-1-is-a-subdirectory-of-dir2-and-vice-versa
public static bool IsSubfolder(string parentPath, string childPath) private static bool IsSubfolder(string parentPath, string childPath)
{ {
var parentUri = new Uri(parentPath); var parentUri = new Uri(parentPath);
@ -454,14 +451,12 @@ namespace BizHawk.Client.Common
/// Don't only valid system ids to system ID, pathType is ROM, Screenshot, etc /// Don't only valid system ids to system ID, pathType is ROM, Screenshot, etc
/// Returns the desired path, if does not exist, returns platform base, else it returns base /// Returns the desired path, if does not exist, returns platform base, else it returns base
/// </summary> /// </summary>
/// <param name="pathType"></param> private static PathEntry GetPathEntryWithFallback(string pathType, string systemId)
/// <param name="systemID"></param>
public static PathEntry GetPathEntryWithFallback(string pathType, string systemID)
{ {
var entry = Global.Config.PathEntries[systemID, pathType]; var entry = Global.Config.PathEntries[systemId, pathType];
if (entry == null) if (entry == null)
{ {
entry = Global.Config.PathEntries[systemID, "Base"]; entry = Global.Config.PathEntries[systemId, "Base"];
} }
if (entry == null) if (entry == null)

View File

@ -1,16 +1,15 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BizHawk.Emulation.Common;
using System.Runtime.InteropServices;
using System.IO; using System.IO;
using System.Runtime.InteropServices;
using BizHawk.Emulation.Common;
namespace BizHawk.Client.Common namespace BizHawk.Client.Common
{ {
public class QuickBmpFile public class QuickBmpFile
{ {
#region structs #region Structs
[StructLayout(LayoutKind.Sequential, Pack = 1)] [StructLayout(LayoutKind.Sequential, Pack = 1)]
class BITMAPFILEHEADER class BITMAPFILEHEADER
{ {
@ -29,7 +28,10 @@ namespace BizHawk.Client.Common
{ {
var ret = GetObject<BITMAPFILEHEADER>(s); var ret = GetObject<BITMAPFILEHEADER>(s);
if (ret.bfSize != Marshal.SizeOf(typeof(BITMAPFILEHEADER))) if (ret.bfSize != Marshal.SizeOf(typeof(BITMAPFILEHEADER)))
{
throw new InvalidOperationException(); throw new InvalidOperationException();
}
return ret; return ret;
} }
} }
@ -58,12 +60,15 @@ namespace BizHawk.Client.Common
{ {
var ret = GetObject<BITMAPINFOHEADER>(s); var ret = GetObject<BITMAPINFOHEADER>(s);
if (ret.biSize != Marshal.SizeOf(typeof(BITMAPINFOHEADER))) if (ret.biSize != Marshal.SizeOf(typeof(BITMAPINFOHEADER)))
{
throw new InvalidOperationException(); throw new InvalidOperationException();
}
return ret; return ret;
} }
} }
enum BitmapCompressionMode : uint private enum BitmapCompressionMode : uint
{ {
BI_RGB = 0, BI_RGB = 0,
BI_RLE8 = 1, BI_RLE8 = 1,
@ -72,9 +77,10 @@ namespace BizHawk.Client.Common
BI_JPEG = 4, BI_JPEG = 4,
BI_PNG = 5 BI_PNG = 5
} }
#endregion #endregion
private unsafe static byte[] GetBytes(object o) private static unsafe byte[] GetBytes(object o)
{ {
byte[] ret = new byte[Marshal.SizeOf(o)]; byte[] ret = new byte[Marshal.SizeOf(o)];
fixed (byte* p = ret) fixed (byte* p = ret)
@ -84,7 +90,7 @@ namespace BizHawk.Client.Common
return ret; return ret;
} }
private unsafe static T GetObject<T>(Stream s) private static unsafe T GetObject<T>(Stream s)
{ {
byte[] tmp = new byte[Marshal.SizeOf(typeof(T))]; byte[] tmp = new byte[Marshal.SizeOf(typeof(T))];
s.Read(tmp, 0, tmp.Length); s.Read(tmp, 0, tmp.Length);
@ -94,35 +100,42 @@ namespace BizHawk.Client.Common
} }
} }
unsafe struct BMP private unsafe struct BMP
{ {
public int* Data; public int* Data;
public int Width; public int Width;
public int Height; public int Height;
} }
static void Blit(BMP src, BMP dst) private static void Blit(BMP src, BMP dst)
{ {
if (src.Width == dst.Width && src.Height == dst.Height) if (src.Width == dst.Width && src.Height == dst.Height)
{
Blit_Same(src, dst); Blit_Same(src, dst);
}
else else
{
Blit_Any(src, dst); Blit_Any(src, dst);
}
} }
unsafe static void Blit_Same(BMP src, BMP dst) private static unsafe void Blit_Same(BMP src, BMP dst)
{ {
int* sp = src.Data + src.Width * (src.Height - 1); int* sp = src.Data + (src.Width * (src.Height - 1));
int* dp = dst.Data; int* dp = dst.Data;
for (int j = 0; j < src.Height; j++) for (int j = 0; j < src.Height; j++)
{ {
for (int i = 0; i < src.Width; i++) for (int i = 0; i < src.Width; i++)
{
dp[i] = sp[i]; dp[i] = sp[i];
}
sp -= src.Width; sp -= src.Width;
dp += src.Width; dp += src.Width;
} }
} }
unsafe static void Blit_Any(BMP src, BMP dst) private static unsafe void Blit_Any(BMP src, BMP dst)
{ {
int w = dst.Width; int w = dst.Width;
int h = dst.Height; int h = dst.Height;
@ -143,7 +156,7 @@ namespace BizHawk.Client.Common
} }
} }
unsafe static void Blit_Any_NoFlip(BMP src, BMP dst) private static unsafe void Blit_Any_NoFlip(BMP src, BMP dst)
{ {
int w = dst.Width; int w = dst.Width;
int h = dst.Height; int h = dst.Height;
@ -163,7 +176,7 @@ namespace BizHawk.Client.Common
} }
} }
public unsafe static void Copy(IVideoProvider src, IVideoProvider dst) public static unsafe void Copy(IVideoProvider src, IVideoProvider dst)
{ {
if (src.BufferWidth == dst.BufferWidth && src.BufferHeight == dst.BufferHeight) if (src.BufferWidth == dst.BufferWidth && src.BufferHeight == dst.BufferHeight)
{ {
@ -194,16 +207,23 @@ namespace BizHawk.Client.Common
/// </summary> /// </summary>
public class LoadedBMP : IVideoProvider public class LoadedBMP : IVideoProvider
{ {
public int[] VideoBuffer { get; set; } public int[] VideoBuffer { get; set; }
public int[] GetVideoBuffer() { return VideoBuffer; }
public int VirtualWidth { get { return BufferWidth; } } public int[] GetVideoBuffer()
public int VirtualHeight { get { return BufferHeight; } } {
public int BufferWidth { get; set; } return VideoBuffer;
}
public int VirtualWidth => BufferWidth;
public int VirtualHeight => BufferHeight;
public int BufferWidth { get; set; }
public int BufferHeight { get; set; } public int BufferHeight { get; set; }
public int BackgroundColor { get { return unchecked((int)0xff000000); } } public int BackgroundColor => unchecked((int)0xff000000);
} }
public unsafe static bool Load(IVideoProvider v, Stream s) public static unsafe bool Load(IVideoProvider v, Stream s)
{ {
var bf = BITMAPFILEHEADER.FromStream(s); var bf = BITMAPFILEHEADER.FromStream(s);
var bi = BITMAPINFOHEADER.FromStream(s); var bi = BITMAPINFOHEADER.FromStream(s);
@ -212,7 +232,10 @@ namespace BizHawk.Client.Common
|| bi.biPlanes != 1 || bi.biPlanes != 1
|| bi.biBitCount != 32 || bi.biBitCount != 32
|| bi.biCompression != BitmapCompressionMode.BI_RGB) || bi.biCompression != BitmapCompressionMode.BI_RGB)
{
return false; return false;
}
int in_w = bi.biWidth; int in_w = bi.biWidth;
int in_h = bi.biHeight; int in_h = bi.biHeight;
@ -225,9 +248,10 @@ namespace BizHawk.Client.Common
l.BufferHeight = in_h; l.BufferHeight = in_h;
l.VideoBuffer = new int[in_w * in_h]; l.VideoBuffer = new int[in_w * in_h];
} }
int[] dst = v.GetVideoBuffer(); int[] dst = v.GetVideoBuffer();
fixed (byte *srcp = src) fixed (byte* srcp = src)
fixed (int* dstp = dst) fixed (int* dstp = dst)
{ {
using (new BizHawk.Common.SimpleTime("Blit")) using (new BizHawk.Common.SimpleTime("Blit"))
@ -248,7 +272,7 @@ namespace BizHawk.Client.Common
return true; return true;
} }
public unsafe static void Save(IVideoProvider v, Stream s, int w, int h) public static unsafe void Save(IVideoProvider v, Stream s, int w, int h)
{ {
var bf = new BITMAPFILEHEADER(); var bf = new BITMAPFILEHEADER();
var bi = new BITMAPINFOHEADER(); var bi = new BITMAPINFOHEADER();

View File

@ -9,8 +9,13 @@ namespace BizHawk.Client.Common
[JsonObject] [JsonObject]
public class RecentFiles : IEnumerable public class RecentFiles : IEnumerable
{ {
private List<string> recentlist; private readonly List<string> recentlist;
public RecentFiles() : this(8) { }
public RecentFiles()
: this(8)
{
}
public RecentFiles(int max) public RecentFiles(int max)
{ {
recentlist = new List<string>(); recentlist = new List<string>();
@ -26,27 +31,15 @@ namespace BizHawk.Client.Common
public bool Frozen { get; set; } public bool Frozen { get; set; }
[JsonIgnore] [JsonIgnore]
public bool Empty public bool Empty => !recentlist.Any();
{
get { return !recentlist.Any(); }
}
[JsonIgnore] [JsonIgnore]
public int Count public int Count => recentlist.Count;
{
get { return recentlist.Count; }
}
[JsonIgnore] [JsonIgnore]
public string MostRecent public string MostRecent => recentlist.Any() ? recentlist[0] : string.Empty;
{
get
{
return recentlist.Any() ? recentlist[0] : string.Empty;
}
}
public string this[int index] public string this[int index]
{ {
get get
{ {

View File

@ -9,16 +9,21 @@ namespace BizHawk.Client.Common
{ {
public class RomGame public class RomGame
{ {
public byte[] RomData { get; set; } public byte[] RomData { get; }
public byte[] FileData { get; set; } public byte[] FileData { get; }
public GameInfo GameInfo { get; set; } public GameInfo GameInfo { get; }
public string Extension { get; set; } public string Extension { get; }
private const int BankSize = 1024; private const int BankSize = 1024;
public RomGame() { } public RomGame()
{
}
public RomGame(HawkFile file) : this(file, null) { } public RomGame(HawkFile file)
: this(file, null)
{
}
public RomGame(HawkFile file, string patch) public RomGame(HawkFile file, string patch)
{ {
@ -101,7 +106,6 @@ namespace BizHawk.Client.Common
{ {
// SMD files are interleaved in pages of 16k, with the first 8k containing all // SMD files are interleaved in pages of 16k, with the first 8k containing all
// odd bytes and the second 8k containing all even bytes. // odd bytes and the second 8k containing all even bytes.
int size = source.Length; int size = source.Length;
if (size > 0x400000) if (size > 0x400000)
{ {
@ -122,7 +126,7 @@ namespace BizHawk.Client.Common
return output; return output;
} }
private unsafe static byte[] MutateSwapN64(byte[] source) private static unsafe byte[] MutateSwapN64(byte[] source)
{ {
// N64 roms are in one of the following formats: // N64 roms are in one of the following formats:
// .Z64 = No swapping // .Z64 = No swapping

View File

@ -1,32 +1,25 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.IO; using System.IO;
using System.Linq;
using BizHawk.Common; using BizHawk.Common;
using BizHawk.Emulation.Common; using BizHawk.Emulation.Common;
using BizHawk.Emulation.Cores; using BizHawk.Emulation.Cores;
using BizHawk.Emulation.Cores.Atari.Atari2600;
using BizHawk.Emulation.Cores.Atari.Atari7800; using BizHawk.Emulation.Cores.Atari.Atari7800;
using BizHawk.Emulation.Cores.Calculators; using BizHawk.Emulation.Cores.Calculators;
using BizHawk.Emulation.Cores.ColecoVision; using BizHawk.Emulation.Cores.Computers.AppleII;
using BizHawk.Emulation.Cores.Computers.Commodore64; using BizHawk.Emulation.Cores.Computers.Commodore64;
using BizHawk.Emulation.Cores.Consoles.Nintendo.QuickNES;
using BizHawk.Emulation.Cores.Consoles.Sega.gpgx; using BizHawk.Emulation.Cores.Consoles.Sega.gpgx;
using GPGX64=BizHawk.Emulation.Cores.Consoles.Sega.gpgx64;
using BizHawk.Emulation.Cores.Intellivision;
using BizHawk.Emulation.Cores.Nintendo.Gameboy; using BizHawk.Emulation.Cores.Nintendo.Gameboy;
using BizHawk.Emulation.Cores.Nintendo.GBA;
using BizHawk.Emulation.Cores.Nintendo.N64;
using BizHawk.Emulation.Cores.Nintendo.NES;
using BizHawk.Emulation.Cores.Nintendo.SNES; using BizHawk.Emulation.Cores.Nintendo.SNES;
using BizHawk.Emulation.Cores.PCEngine; using BizHawk.Emulation.Cores.PCEngine;
using BizHawk.Emulation.Cores.Sega.MasterSystem;
using BizHawk.Emulation.Cores.Sega.Saturn; using BizHawk.Emulation.Cores.Sega.Saturn;
using BizHawk.Emulation.Cores.Sony.PSP; using BizHawk.Emulation.Cores.Sony.PSP;
using BizHawk.Emulation.Cores.Sony.PSX; using BizHawk.Emulation.Cores.Sony.PSX;
using BizHawk.Emulation.DiscSystem; using BizHawk.Emulation.DiscSystem;
using BizHawk.Emulation.Cores.WonderSwan;
using BizHawk.Emulation.Cores.Computers.AppleII; using GPGX64 = BizHawk.Emulation.Cores.Consoles.Sega.gpgx64;
namespace BizHawk.Client.Common namespace BizHawk.Client.Common
{ {
@ -50,36 +43,23 @@ namespace BizHawk.Client.Common
private object GetCoreSettings(Type t) private object GetCoreSettings(Type t)
{ {
var e = new SettingsLoadArgs(t); var e = new SettingsLoadArgs(t);
if (OnLoadSettings != null) OnLoadSettings?.Invoke(this, e);
{
OnLoadSettings(this, e);
}
return e.Settings; return e.Settings;
} }
private object GetCoreSyncSettings(Type t) private object GetCoreSyncSettings(Type t)
{ {
var e = new SettingsLoadArgs(t); var e = new SettingsLoadArgs(t);
if (OnLoadSyncSettings != null) OnLoadSyncSettings?.Invoke(this, e);
{
OnLoadSyncSettings(this, e);
}
return e.Settings; return e.Settings;
} }
public RomLoader()
{
}
// For not throwing errors but simply outputing information to the screen // For not throwing errors but simply outputing information to the screen
public Action<string> MessageCallback { get; set; } public Action<string> MessageCallback { get; set; }
private void DoMessageCallback(string message) private void DoMessageCallback(string message)
{ {
if (MessageCallback != null) MessageCallback?.Invoke(message);
{
MessageCallback(message);
}
} }
// TODO: reconsider the need for exposing these; // TODO: reconsider the need for exposing these;
@ -138,11 +118,13 @@ namespace BizHawk.Client.Common
public Func<RomGame, string> ChoosePlatform { get; set; } public Func<RomGame, string> ChoosePlatform { get; set; }
// in case we get sent back through the picker more than once, use the same choice the second time // in case we get sent back through the picker more than once, use the same choice the second time
int? previouschoice; private int? previouschoice;
private int? HandleArchive(HawkFile file) private int? HandleArchive(HawkFile file)
{ {
if (previouschoice.HasValue) if (previouschoice.HasValue)
{
return previouschoice; return previouschoice;
}
if (ChooseArchive != null) if (ChooseArchive != null)
{ {
@ -153,21 +135,15 @@ namespace BizHawk.Client.Common
return null; return null;
} }
//May want to phase out this method in favor of the overload with more paramaters // May want to phase out this method in favor of the overload with more paramaters
private void DoLoadErrorCallback(string message, string systemId, LoadErrorType type = LoadErrorType.Unknown) private void DoLoadErrorCallback(string message, string systemId, LoadErrorType type = LoadErrorType.Unknown)
{ {
if (OnLoadError != null) OnLoadError?.Invoke(this, new RomErrorArgs(message, systemId, type));
{
OnLoadError(this, new RomErrorArgs(message, systemId, type));
}
} }
private void DoLoadErrorCallback(string message, string systemId, string path, bool det, LoadErrorType type = LoadErrorType.Unknown) private void DoLoadErrorCallback(string message, string systemId, string path, bool det, LoadErrorType type = LoadErrorType.Unknown)
{ {
if (OnLoadError != null) OnLoadError?.Invoke(this, new RomErrorArgs(message, systemId, path, det, type));
{
OnLoadError(this, new RomErrorArgs(message, systemId, path, det, type));
}
} }
private bool PreferredPlatformIsDefined(string extension) private bool PreferredPlatformIsDefined(string extension)
@ -180,9 +156,9 @@ namespace BizHawk.Client.Common
return false; return false;
} }
public bool AsLibretro; public bool AsLibretro { get; set; }
bool HandleArchiveBinding(HawkFile file) private bool HandleArchiveBinding(HawkFile file)
{ {
var romExtensions = new[] { "SMS", "SMC", "SFC", "PCE", "SGX", "GG", "SG", "BIN", "GEN", "MD", "SMD", "GB", "NES", "FDS", "ROM", "INT", "GBC", "UNF", "A78", "CRT", "COL", "XML", "Z64", "V64", "N64", "WS", "WSC", "GBA" }; var romExtensions = new[] { "SMS", "SMC", "SFC", "PCE", "SGX", "GG", "SG", "BIN", "GEN", "MD", "SMD", "GB", "NES", "FDS", "ROM", "INT", "GBC", "UNF", "A78", "CRT", "COL", "XML", "Z64", "V64", "N64", "WS", "WSC", "GBA" };
@ -216,7 +192,7 @@ namespace BizHawk.Client.Common
{ {
if (recursiveCount > 1) // hack to stop recursive calls from endlessly rerunning if we can't load it if (recursiveCount > 1) // hack to stop recursive calls from endlessly rerunning if we can't load it
{ {
DoLoadErrorCallback("Failed multiple attempts to load ROM.", ""); DoLoadErrorCallback("Failed multiple attempts to load ROM.", string.Empty);
return false; return false;
} }
@ -230,7 +206,7 @@ namespace BizHawk.Client.Common
using (var file = new HawkFile()) using (var file = new HawkFile())
{ {
//only try mounting a file if a filename was given // only try mounting a file if a filename was given
if (!string.IsNullOrEmpty(path)) if (!string.IsNullOrEmpty(path))
{ {
// lets not use this unless we need to // lets not use this unless we need to
@ -261,17 +237,17 @@ namespace BizHawk.Client.Common
var retro = new LibRetroEmulator(nextComm, nextComm.LaunchLibretroCore); var retro = new LibRetroEmulator(nextComm, nextComm.LaunchLibretroCore);
nextEmulator = retro; nextEmulator = retro;
//kind of dirty.. we need to stash this, and then we can unstash it in a moment, in case the core doesnt fail // kind of dirty.. we need to stash this, and then we can unstash it in a moment, in case the core doesnt fail
var oldGame = Global.Game; var oldGame = Global.Game;
if (retro.Description.SupportsNoGame && string.IsNullOrEmpty(path)) if (retro.Description.SupportsNoGame && string.IsNullOrEmpty(path))
{ {
//must be done before LoadNoGame (which triggers retro_init and the paths to be consumed by the core) // must be done before LoadNoGame (which triggers retro_init and the paths to be consumed by the core)
//game name == name of core // game name == name of core
var gameName = codePathPart; var gameName = codePathPart;
Global.Game = game = new GameInfo { Name = gameName, System = "Libretro" }; Global.Game = game = new GameInfo { Name = gameName, System = "Libretro" };
//if we are allowed to run NoGame and we dont have a game, boot up the core that way // if we are allowed to run NoGame and we dont have a game, boot up the core that way
bool ret = retro.LoadNoGame(); bool ret = retro.LoadNoGame();
Global.Game = oldGame; Global.Game = oldGame;
@ -287,32 +263,41 @@ namespace BizHawk.Client.Common
{ {
bool ret; bool ret;
//must be done before LoadNoGame (which triggers retro_init and the paths to be consumed by the core) // must be done before LoadNoGame (which triggers retro_init and the paths to be consumed by the core)
//game name == name of core + extensionless_game_filename // game name == name of core + extensionless_game_filename
var gameName = Path.Combine(codePathPart, Path.GetFileNameWithoutExtension(file.Name)); var gameName = Path.Combine(codePathPart, Path.GetFileNameWithoutExtension(file.Name));
Global.Game = game = new GameInfo { Name = gameName, System = "Libretro" }; Global.Game = game = new GameInfo { Name = gameName, System = "Libretro" };
//if the core requires an archive file, then try passing the filename of the archive // if the core requires an archive file, then try passing the filename of the archive
//(but do we ever need to actually load the contents of the archive file into ram?) // (but do we ever need to actually load the contents of the archive file into ram?)
if (retro.Description.NeedsArchives) if (retro.Description.NeedsArchives)
{ {
if (file.IsArchiveMember) if (file.IsArchiveMember)
{
throw new InvalidOperationException("Should not have bound file member for libretro block_extract core"); throw new InvalidOperationException("Should not have bound file member for libretro block_extract core");
}
ret = retro.LoadPath(file.FullPathWithoutMember); ret = retro.LoadPath(file.FullPathWithoutMember);
} }
else else
{ {
//otherwise load the data or pass the filename, as requested. but.. // otherwise load the data or pass the filename, as requested. but..
if (retro.Description.NeedsRomAsPath && file.IsArchiveMember) if (retro.Description.NeedsRomAsPath && file.IsArchiveMember)
{
throw new InvalidOperationException("Cannot pass archive member to libretro needs_fullpath core"); throw new InvalidOperationException("Cannot pass archive member to libretro needs_fullpath core");
}
if (retro.Description.NeedsRomAsPath) if (retro.Description.NeedsRomAsPath)
{
ret = retro.LoadPath(file.FullPathWithoutMember); ret = retro.LoadPath(file.FullPathWithoutMember);
}
else else
{ {
ret = HandleArchiveBinding(file); ret = HandleArchiveBinding(file);
if (ret) if (ret)
{
ret = retro.LoadData(file.ReadAllBytes()); ret = retro.LoadData(file.ReadAllBytes());
}
} }
} }
@ -325,31 +310,39 @@ namespace BizHawk.Client.Common
return false; return false;
} }
} }
} }
else else
{ {
//if not libretro: // if not libretro:
// do extension checknig
//do extension checknig
ext = file.Extension.ToLowerInvariant(); ext = file.Extension.ToLowerInvariant();
//do the archive binding we had to skip // do the archive binding we had to skip
if (!HandleArchiveBinding(file)) if (!HandleArchiveBinding(file))
{
return false; return false;
}
} }
if (string.IsNullOrEmpty(ext)) { } if (string.IsNullOrEmpty(ext))
{
}
else if (ext == ".m3u") else if (ext == ".m3u")
{ {
//HACK ZONE - currently only psx supports m3u // HACK ZONE - currently only psx supports m3u
M3U_File m3u; M3U_File m3u;
using(var sr = new StreamReader(path)) using (var sr = new StreamReader(path))
{
m3u = M3U_File.Read(sr); m3u = M3U_File.Read(sr);
if(m3u.Entries.Count == 0) }
if (m3u.Entries.Count == 0)
{
throw new InvalidOperationException("Can't load an empty M3U"); throw new InvalidOperationException("Can't load an empty M3U");
//load discs for all the m3u }
// load discs for all the m3u
m3u.Rebase(Path.GetDirectoryName(path)); m3u.Rebase(Path.GetDirectoryName(path));
List<Disc> discs = new List<Disc>(); List<Disc> discs = new List<Disc>();
List<string> discNames = new List<string>(); List<string> discNames = new List<string>();
@ -367,15 +360,19 @@ namespace BizHawk.Client.Common
if (discMountJob.OUT_SlowLoadAborted) if (discMountJob.OUT_SlowLoadAborted)
{ {
DoLoadErrorCallback("This disc would take too long to load. Run it through discohawk first, or find a new rip because this one is probably junk", "", LoadErrorType.DiscError); DoLoadErrorCallback("This disc would take too long to load. Run it through discohawk first, or find a new rip because this one is probably junk", string.Empty, LoadErrorType.DiscError);
return false; return false;
} }
if (discMountJob.OUT_ErrorLevel) if (discMountJob.OUT_ErrorLevel)
{
throw new InvalidOperationException("\r\n" + discMountJob.OUT_Log); throw new InvalidOperationException("\r\n" + discMountJob.OUT_Log);
}
if(disc == null) if (disc == null)
{
throw new InvalidOperationException("Can't load one of the files specified in the M3U"); throw new InvalidOperationException("Can't load one of the files specified in the M3U");
}
var discName = Path.GetFileNameWithoutExtension(discPath); var discName = Path.GetFileNameWithoutExtension(discPath);
discNames.Add(discName); discNames.Add(discName);
@ -388,7 +385,9 @@ namespace BizHawk.Client.Common
string discHash = new DiscHasher(disc).Calculate_PSX_BizIDHash().ToString("X8"); string discHash = new DiscHasher(disc).Calculate_PSX_BizIDHash().ToString("X8");
game = Database.CheckDatabase(discHash); game = Database.CheckDatabase(discHash);
if (game == null || game.IsRomStatusBad() || game.Status == RomStatus.NotInDatabase) if (game == null || game.IsRomStatusBad() || game.Status == RomStatus.NotInDatabase)
{
sw.WriteLine("Disc could not be identified as known-good. Look for a better rip."); sw.WriteLine("Disc could not be identified as known-good. Look for a better rip.");
}
else else
{ {
sw.WriteLine("Disc was identified (99.99% confidently) as known good with disc id hash CRC32:{0:X8}",discHash); sw.WriteLine("Disc was identified (99.99% confidently) as known good with disc id hash CRC32:{0:X8}",discHash);
@ -402,13 +401,17 @@ namespace BizHawk.Client.Common
{ {
sw.WriteLine("Not a PSX disc"); sw.WriteLine("Not a PSX disc");
} }
sw.WriteLine("-------------------------"); sw.WriteLine("-------------------------");
} }
nextEmulator = new Octoshock(nextComm, discs, discNames, null, GetCoreSettings<Octoshock>(), GetCoreSyncSettings<Octoshock>()); nextEmulator = new Octoshock(nextComm, discs, discNames, null, GetCoreSettings<Octoshock>(), GetCoreSyncSettings<Octoshock>());
nextEmulator.CoreComm.RomStatusDetails = sw.ToString(); nextEmulator.CoreComm.RomStatusDetails = sw.ToString();
game = new GameInfo { Name = Path.GetFileNameWithoutExtension(file.Name) }; game = new GameInfo
game.System = "PSX"; {
Name = Path.GetFileNameWithoutExtension(file.Name),
System = "PSX"
};
} }
else if (ext == ".iso" || ext == ".cue" || ext == ".ccd") else if (ext == ".iso" || ext == ".cue" || ext == ".ccd")
{ {
@ -420,27 +423,33 @@ namespace BizHawk.Client.Common
string discHash = null; string discHash = null;
//--- load the disc in a context which will let us abort if it's going to take too long //--- load the disc in a context which will let us abort if it's going to take too long
var discMountJob = new DiscMountJob { IN_FromPath = path }; var discMountJob = new DiscMountJob { IN_FromPath = path, IN_SlowLoadAbortThreshold = 8 };
discMountJob.IN_SlowLoadAbortThreshold = 8;
discMountJob.Run(); discMountJob.Run();
if (discMountJob.OUT_SlowLoadAborted) if (discMountJob.OUT_SlowLoadAborted)
{ {
DoLoadErrorCallback("This disc would take too long to load. Run it through discohawk first, or find a new rip because this one is probably junk", "", LoadErrorType.DiscError); DoLoadErrorCallback("This disc would take too long to load. Run it through discohawk first, or find a new rip because this one is probably junk", string.Empty, LoadErrorType.DiscError);
return false; return false;
} }
if (discMountJob.OUT_ErrorLevel) if (discMountJob.OUT_ErrorLevel)
{
throw new InvalidOperationException("\r\n" + discMountJob.OUT_Log); throw new InvalidOperationException("\r\n" + discMountJob.OUT_Log);
}
var disc = discMountJob.OUT_Disc; var disc = discMountJob.OUT_Disc;
//-----------
// -----------
//TODO - use more sophisticated IDer // TODO - use more sophisticated IDer
var discType = new DiscIdentifier(disc).DetectDiscType(); var discType = new DiscIdentifier(disc).DetectDiscType();
if (discType == DiscType.SonyPSX) if (discType == DiscType.SonyPSX)
{
discHash = new DiscHasher(disc).Calculate_PSX_BizIDHash().ToString("X8"); discHash = new DiscHasher(disc).Calculate_PSX_BizIDHash().ToString("X8");
else discHash = new DiscHasher(disc).OldHash(); }
else
{
discHash = new DiscHasher(disc).OldHash();
}
game = Database.CheckDatabase(discHash); game = Database.CheckDatabase(discHash);
if (game == null) if (game == null)
@ -493,9 +502,11 @@ namespace BizHawk.Client.Common
nextEmulator = new PSP(nextComm, file.Name); nextEmulator = new PSP(nextComm, file.Name);
break; break;
case "PSX": case "PSX":
nextEmulator = new Octoshock(nextComm, new List<Disc>(new[]{disc}), new List<string>(new[]{Path.GetFileNameWithoutExtension(path)}), null, GetCoreSettings<Octoshock>(), GetCoreSyncSettings<Octoshock>()); nextEmulator = new Octoshock(nextComm, new List<Disc>(new[] { disc }), new List<string>(new[] { Path.GetFileNameWithoutExtension(path) }), null, GetCoreSettings<Octoshock>(), GetCoreSyncSettings<Octoshock>());
if (game.IsRomStatusBad() || game.Status == RomStatus.NotInDatabase) if (game.IsRomStatusBad() || game.Status == RomStatus.NotInDatabase)
{
nextEmulator.CoreComm.RomStatusDetails = "Disc could not be identified as known-good. Look for a better rip."; nextEmulator.CoreComm.RomStatusDetails = "Disc could not be identified as known-good. Look for a better rip.";
}
else else
{ {
StringWriter sw = new StringWriter(); StringWriter sw = new StringWriter();
@ -554,10 +565,9 @@ namespace BizHawk.Client.Common
case "C64": case "C64":
nextEmulator = new C64( nextEmulator = new C64(
nextComm, nextComm,
xmlGame.Assets.Select(a => a.Value), xmlGame.Assets.Select(a => a.Value),
(C64.C64Settings)GetCoreSettings<C64>(), (C64.C64Settings)GetCoreSettings<C64>(),
(C64.C64SyncSettings)GetCoreSyncSettings<C64>() (C64.C64SyncSettings)GetCoreSyncSettings<C64>());
);
break; break;
case "PSX": case "PSX":
var entries = xmlGame.AssetFullPaths; var entries = xmlGame.AssetFullPaths;
@ -570,8 +580,7 @@ namespace BizHawk.Client.Common
string discPath = e; string discPath = e;
//--- load the disc in a context which will let us abort if it's going to take too long //--- load the disc in a context which will let us abort if it's going to take too long
var discMountJob = new DiscMountJob { IN_FromPath = discPath }; var discMountJob = new DiscMountJob { IN_FromPath = discPath, IN_SlowLoadAbortThreshold = 8 };
discMountJob.IN_SlowLoadAbortThreshold = 8;
discMountJob.Run(); discMountJob.Run();
disc = discMountJob.OUT_Disc; disc = discMountJob.OUT_Disc;
@ -582,10 +591,14 @@ namespace BizHawk.Client.Common
} }
if (discMountJob.OUT_ErrorLevel) if (discMountJob.OUT_ErrorLevel)
{
throw new InvalidOperationException("\r\n" + discMountJob.OUT_Log); throw new InvalidOperationException("\r\n" + discMountJob.OUT_Log);
}
if (disc == null) if (disc == null)
{
throw new InvalidOperationException("Can't load one of the files specified in the M3U"); throw new InvalidOperationException("Can't load one of the files specified in the M3U");
}
var discName = Path.GetFileNameWithoutExtension(discPath); var discName = Path.GetFileNameWithoutExtension(discPath);
discNames.Add(discName); discNames.Add(discName);
@ -598,7 +611,9 @@ namespace BizHawk.Client.Common
string discHash = new DiscHasher(disc).Calculate_PSX_BizIDHash().ToString("X8"); string discHash = new DiscHasher(disc).Calculate_PSX_BizIDHash().ToString("X8");
game = Database.CheckDatabase(discHash); game = Database.CheckDatabase(discHash);
if (game == null || game.IsRomStatusBad() || game.Status == RomStatus.NotInDatabase) if (game == null || game.IsRomStatusBad() || game.Status == RomStatus.NotInDatabase)
{
sw.WriteLine("Disc could not be identified as known-good. Look for a better rip."); sw.WriteLine("Disc could not be identified as known-good. Look for a better rip.");
}
else else
{ {
sw.WriteLine("Disc was identified (99.99% confidently) as known good with disc id hash CRC32:{0:X8}", discHash); sw.WriteLine("Disc was identified (99.99% confidently) as known good with disc id hash CRC32:{0:X8}", discHash);
@ -612,15 +627,18 @@ namespace BizHawk.Client.Common
{ {
sw.WriteLine("Not a PSX disc"); sw.WriteLine("Not a PSX disc");
} }
sw.WriteLine("-------------------------"); sw.WriteLine("-------------------------");
} }
// todo: copy pasta from PSX .cue section // todo: copy pasta from PSX .cue section
nextEmulator = new Octoshock(nextComm, discs, discNames, null, GetCoreSettings<Octoshock>(), GetCoreSyncSettings<Octoshock>()); nextEmulator = new Octoshock(nextComm, discs, discNames, null, GetCoreSettings<Octoshock>(), GetCoreSyncSettings<Octoshock>());
nextEmulator.CoreComm.RomStatusDetails = sw.ToString(); nextEmulator.CoreComm.RomStatusDetails = sw.ToString();
game = new GameInfo { Name = Path.GetFileNameWithoutExtension(file.Name) }; game = new GameInfo
game.System = "PSX"; {
Name = Path.GetFileNameWithoutExtension(file.Name),
System = "PSX"
};
break; break;
default: default:
return false; return false;
@ -672,11 +690,15 @@ namespace BizHawk.Client.Common
{ {
rom = new RomGame(file); rom = new RomGame(file);
//hacky for now // hacky for now
if (file.Extension.ToLowerInvariant() == ".exe") if (file.Extension.ToLowerInvariant() == ".exe")
{
rom.GameInfo.System = "PSX"; rom.GameInfo.System = "PSX";
}
else if (file.Extension.ToLowerInvariant() == ".nsf") else if (file.Extension.ToLowerInvariant() == ".nsf")
{
rom.GameInfo.System = "NES"; rom.GameInfo.System = "NES";
}
if (string.IsNullOrEmpty(rom.GameInfo.System)) if (string.IsNullOrEmpty(rom.GameInfo.System))
@ -753,16 +775,24 @@ namespace BizHawk.Client.Common
break; break;
case "NES": case "NES":
{ {
//apply main spur-of-the-moment switcheroo as lowest priority // apply main spur-of-the-moment switcheroo as lowest priority
string preference = "neshawk"; string preference = "neshawk";
if(Global.Config.NES_InQuickNES) preference = "quicknes"; if (Global.Config.NES_InQuickNES)
{
preference = "quicknes";
}
//if user has saw fit to override in gamedb, apply that // if user has saw fit to override in gamedb, apply that
if (Global.Config.CoreForcingViaGameDB && !string.IsNullOrEmpty(game.ForcedCore)) if (Global.Config.CoreForcingViaGameDB && !string.IsNullOrEmpty(game.ForcedCore))
{
preference = game.ForcedCore; preference = game.ForcedCore;
}
//but only neshawk is accurate // but only neshawk is accurate
if (forceAccurateCore) preference = "neshawk"; if (forceAccurateCore)
{
preference = "neshawk";
}
if (preference == "neshawk") if (preference == "neshawk")
{ {
@ -809,7 +839,7 @@ namespace BizHawk.Client.Common
nextEmulator = c64; nextEmulator = c64;
break; break;
case "GBA": case "GBA":
//core = CoreInventory.Instance["GBA", "Meteor"]; // core = CoreInventory.Instance["GBA", "Meteor"];
if (Global.Config.GBA_UsemGBA) if (Global.Config.GBA_UsemGBA)
{ {
core = CoreInventory.Instance["GBA", "mGBA"]; core = CoreInventory.Instance["GBA", "mGBA"];
@ -825,10 +855,15 @@ namespace BizHawk.Client.Common
break; break;
case "GEN": case "GEN":
// discard "Genplus-gx64", auto-added due to implementing IEmulator // HUH? // discard "Genplus-gx64", auto-added due to implementing IEmulator // HUH?
//core = CoreInventory.Instance["GEN", "Genplus-gx"]; // core = CoreInventory.Instance["GEN", "Genplus-gx"];
if (Environment.Is64BitProcess) if (Environment.Is64BitProcess)
{
core = CoreInventory.Instance["GEN", "Genplus-gx64"]; core = CoreInventory.Instance["GEN", "Genplus-gx64"];
else core = CoreInventory.Instance["GEN", "Genplus-gx"]; }
else
{
core = CoreInventory.Instance["GEN", "Genplus-gx"];
}
break; break;
} }
@ -845,6 +880,7 @@ namespace BizHawk.Client.Common
{ {
DoLoadErrorCallback("No core could load the rom.", null); DoLoadErrorCallback("No core could load the rom.", null);
} }
return false; return false;
} }
} }
@ -859,7 +895,9 @@ namespace BizHawk.Client.Common
// all of the specific exceptions we're trying to catch here aren't expected to have inner exceptions, // all of the specific exceptions we're trying to catch here aren't expected to have inner exceptions,
// so drill down in case we got a TargetInvocationException or something like that // so drill down in case we got a TargetInvocationException or something like that
while (ex.InnerException != null) while (ex.InnerException != null)
{
ex = ex.InnerException; ex = ex.InnerException;
}
// Specific hack here, as we get more cores of the same system, this isn't scalable // Specific hack here, as we get more cores of the same system, this isn't scalable
if (ex is UnsupportedGameException) if (ex is UnsupportedGameException)

View File

@ -30,8 +30,7 @@ namespace BizHawk.Client.Common
for (int i = 0; i < 10; i++) for (int i = 0; i < 10; i++)
{ {
var file = new FileInfo( var file = new FileInfo(
PathManager.SaveStatePrefix(Global.Game) + "." + "QuickSave" + i + ".State" PathManager.SaveStatePrefix(Global.Game) + "." + "QuickSave" + i + ".State");
);
if (file.Directory != null && file.Directory.Exists == false) if (file.Directory != null && file.Directory.Exists == false)
{ {
file.Directory.Create(); file.Directory.Create();

View File

@ -1,13 +1,10 @@
using System; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using BizHawk.Common; using BizHawk.Common;
using BizHawk.Common.BufferExtensions; using BizHawk.Common.BufferExtensions;
using BizHawk.Common.IOExtensions;
using BizHawk.Emulation.Common;
using BizHawk.Emulation.Common.IEmulatorExtensions; using BizHawk.Emulation.Common.IEmulatorExtensions;
using System.Collections.Generic;
namespace BizHawk.Client.Common namespace BizHawk.Client.Common
{ {
@ -16,6 +13,7 @@ namespace BizHawk.Client.Common
public static void SaveStateFile(string filename, string name) public static void SaveStateFile(string filename, string name)
{ {
var core = Global.Emulator.AsStatable(); var core = Global.Emulator.AsStatable();
// the old method of text savestate save is now gone. // the old method of text savestate save is now gone.
// a text savestate is just like a binary savestate, but with a different core lump // a text savestate is just like a binary savestate, but with a different core lump
using (var bs = new BinaryStateSaver(filename)) using (var bs = new BinaryStateSaver(filename))
@ -25,13 +23,17 @@ namespace BizHawk.Client.Common
{ {
// text savestate format // text savestate format
using (new SimpleTime("Save Core")) using (new SimpleTime("Save Core"))
{
bs.PutLump(BinaryStateLump.CorestateText, (tw) => core.SaveStateText(tw)); bs.PutLump(BinaryStateLump.CorestateText, (tw) => core.SaveStateText(tw));
}
} }
else else
{ {
// binary core lump format // binary core lump format
using (new SimpleTime("Save Core")) using (new SimpleTime("Save Core"))
{
bs.PutLump(BinaryStateLump.Corestate, bw => core.SaveStateBinary(bw)); bs.PutLump(BinaryStateLump.Corestate, bw => core.SaveStateBinary(bw));
}
} }
if (Global.Config.SaveScreenshotWithStates && Global.Emulator.HasVideoProvider()) if (Global.Config.SaveScreenshotWithStates && Global.Emulator.HasVideoProvider())
@ -40,11 +42,11 @@ namespace BizHawk.Client.Common
var buff = vp.GetVideoBuffer(); var buff = vp.GetVideoBuffer();
if (buff.Length == 1) if (buff.Length == 1)
{ {
//is a hacky opengl texture ID. can't handle this now! // is a hacky opengl texture ID. can't handle this now!
//need to discuss options // need to discuss options
//1. cores must be able to provide a pixels videoprovider in addition to a texture ID, on command (not very hard overall but interface changing and work per core) // 1. cores must be able to provide a pixels videoprovider in addition to a texture ID, on command (not very hard overall but interface changing and work per core)
//2. SavestateManager must be setup with a mechanism for resolving texture IDs (even less work, but sloppy) // 2. SavestateManager must be setup with a mechanism for resolving texture IDs (even less work, but sloppy)
//There are additional problems with AVWriting. They depend on VideoProvider providing pixels. // There are additional problems with AVWriting. They depend on VideoProvider providing pixels.
} }
else else
{ {
@ -57,8 +59,11 @@ namespace BizHawk.Client.Common
out_w /= 2; out_w /= 2;
out_h /= 2; out_h /= 2;
} }
using (new SimpleTime("Save Framebuffer")) using (new SimpleTime("Save Framebuffer"))
{
bs.PutLump(BinaryStateLump.Framebuffer, (s) => QuickBmpFile.Save(Global.Emulator.AsVideoProvider(), s, out_w, out_h)); bs.PutLump(BinaryStateLump.Framebuffer, (s) => QuickBmpFile.Save(Global.Emulator.AsVideoProvider(), s, out_w, out_h));
}
} }
} }
@ -104,7 +109,9 @@ namespace BizHawk.Client.Common
try try
{ {
using (new SimpleTime("Load Framebuffer")) using (new SimpleTime("Load Framebuffer"))
{
QuickBmpFile.Load(Global.Emulator.AsVideoProvider(), br.BaseStream); QuickBmpFile.Load(Global.Emulator.AsVideoProvider(), br.BaseStream);
}
} }
catch catch
{ {
@ -160,7 +167,9 @@ namespace BizHawk.Client.Common
} }
using (new SimpleTime("Load Core")) using (new SimpleTime("Load Core"))
{
bl.GetCoreState(br => core.LoadStateBinary(br), tr => core.LoadStateText(tr)); bl.GetCoreState(br => core.LoadStateBinary(br), tr => core.LoadStateText(tr));
}
bl.GetLump(BinaryStateLump.Framebuffer, false, PopulateFramebuffer); bl.GetLump(BinaryStateLump.Framebuffer, false, PopulateFramebuffer);

View File

@ -1,7 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO; using System.IO;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Threading; using System.Threading;
@ -26,8 +24,8 @@ namespace BizHawk.Client.Common
ManualResetEvent full = new ManualResetEvent(true); ManualResetEvent full = new ManualResetEvent(true);
ManualResetEvent empty = new ManualResetEvent(false); ManualResetEvent empty = new ManualResetEvent(false);
public Stream W { get; private set; } public Stream W { get; }
public Stream R { get; private set; } public Stream R { get; }
public RangBuffer() public RangBuffer()
{ {

View File

@ -1,47 +1,49 @@
using System; using System;
using System.Collections.Generic; using System.IO;
using System.Linq;
using System.Text;
using ICSharpCode.SharpZipLib.Zip; using ICSharpCode.SharpZipLib.Zip;
using System.IO;
namespace BizHawk.Client.Common namespace BizHawk.Client.Common
{ {
public class SharpZipWriter : IZipWriter public class SharpZipWriter : IZipWriter
{ {
private ZipOutputStream z; private readonly int _level;
private int level; private ZipOutputStream _zipOutputStream;
public SharpZipWriter(string path, int compressionlevel) public SharpZipWriter(string path, int compressionlevel)
{ {
level = compressionlevel; _level = compressionlevel;
z = new ZipOutputStream(new FileStream(path, FileMode.Create, FileAccess.Write)) _zipOutputStream = new ZipOutputStream(new FileStream(path, FileMode.Create, FileAccess.Write))
{ {
IsStreamOwner = true, IsStreamOwner = true,
UseZip64 = UseZip64.Off UseZip64 = UseZip64.Off
}; };
z.SetLevel(level); _zipOutputStream.SetLevel(_level);
} }
public void WriteItem(string name, Action<Stream> callback) public void WriteItem(string name, Action<Stream> callback)
{ {
var e = new ZipEntry(name); var e = new ZipEntry(name);
if (level == 0) if (_level == 0)
{
e.CompressionMethod = CompressionMethod.Stored; e.CompressionMethod = CompressionMethod.Stored;
}
else else
{
e.CompressionMethod = CompressionMethod.Deflated; e.CompressionMethod = CompressionMethod.Deflated;
z.PutNextEntry(e); }
callback(z);
z.CloseEntry(); _zipOutputStream.PutNextEntry(e);
callback(_zipOutputStream);
_zipOutputStream.CloseEntry();
} }
public void Dispose() public void Dispose()
{ {
if (z != null) if (_zipOutputStream != null)
{ {
z.Dispose(); _zipOutputStream.Dispose();
z = null; _zipOutputStream = null;
} }
} }
} }

View File

@ -5,7 +5,7 @@ namespace BizHawk.Client.Common
{ {
/// <summary> /// <summary>
/// This class holds logic for System information. /// This class holds logic for System information.
/// That means specifiactions about a system that BizHawk emulate /// That means specifications about a system that BizHawk emulates
/// </summary> /// </summary>
public sealed class SystemInfo public sealed class SystemInfo
{ {
@ -26,39 +26,43 @@ namespace BizHawk.Client.Common
#region cTor(s) #region cTor(s)
/// <summary> /// <summary>
/// Initializes static members of the <see cref="SystemInfo"/> class.
/// Global initialization stuff /// Global initialization stuff
/// </summary> /// </summary>
/// <remarks>DO NOT CHANGE List order because properties depends on it (and it is hardcoded)</remarks> /// <remarks>
/// DO NOT CHANGE List order because properties depends on it (and it is hardcoded)
/// </remarks>
static SystemInfo() static SystemInfo()
{ {
allSystemInfos = new List<SystemInfo>(26); allSystemInfos = new List<SystemInfo>(26)
{
allSystemInfos.Add(new SystemInfo(string.Empty)); new SystemInfo(string.Empty),
allSystemInfos.Add(new SystemInfo("NES", CoreSystem.NES, 2, StandardButtons)); new SystemInfo("NES", CoreSystem.NES, 2, StandardButtons),
allSystemInfos.Add(new SystemInfo("Intellivision", CoreSystem.Intellivision, 2)); new SystemInfo("Intellivision", CoreSystem.Intellivision, 2),
allSystemInfos.Add(new SystemInfo("Sega Master System", CoreSystem.MasterSystem, 2, UpDownLeftRight | JoypadButton.B1 | JoypadButton.B2)); new SystemInfo("Sega Master System", CoreSystem.MasterSystem, 2, UpDownLeftRight | JoypadButton.B1 | JoypadButton.B2),
allSystemInfos.Add(new SystemInfo("SG-1000", CoreSystem.MasterSystem, 1)); new SystemInfo("SG-1000", CoreSystem.MasterSystem, 1),
allSystemInfos.Add(new SystemInfo("Game Gear", CoreSystem.MasterSystem, 1, UpDownLeftRight | JoypadButton.B1 | JoypadButton.B2)); new SystemInfo("Game Gear", CoreSystem.MasterSystem, 1, UpDownLeftRight | JoypadButton.B1 | JoypadButton.B2),
allSystemInfos.Add(new SystemInfo("TurboGrafx-16", CoreSystem.PCEngine, 1)); new SystemInfo("TurboGrafx-16", CoreSystem.PCEngine, 1),
allSystemInfos.Add(new SystemInfo("TurboGrafx - 16(CD)", CoreSystem.PCEngine, 1)); new SystemInfo("TurboGrafx - 16(CD)", CoreSystem.PCEngine, 1),
allSystemInfos.Add(new SystemInfo("SuperGrafx", CoreSystem.PCEngine, 1)); new SystemInfo("SuperGrafx", CoreSystem.PCEngine, 1),
allSystemInfos.Add(new SystemInfo("Genesis", CoreSystem.Genesis, 2, UpDownLeftRight | JoypadButton.A | JoypadButton.B | JoypadButton.C | JoypadButton.X | JoypadButton.Y | JoypadButton.Z)); new SystemInfo("Genesis", CoreSystem.Genesis, 2, UpDownLeftRight | JoypadButton.A | JoypadButton.B | JoypadButton.C | JoypadButton.X | JoypadButton.Y | JoypadButton.Z),
allSystemInfos.Add(new SystemInfo("TI - 83", CoreSystem.TI83, 1)); new SystemInfo("TI - 83", CoreSystem.TI83, 1),
allSystemInfos.Add(new SystemInfo("SNES", CoreSystem.SNES, 8, StandardButtons | JoypadButton.X | JoypadButton.Y | JoypadButton.L | JoypadButton.R)); new SystemInfo("SNES", CoreSystem.SNES, 8, StandardButtons | JoypadButton.X | JoypadButton.Y | JoypadButton.L | JoypadButton.R),
allSystemInfos.Add(new SystemInfo("GB", CoreSystem.GameBoy, 1, StandardButtons)); new SystemInfo("GB", CoreSystem.GameBoy, 1, StandardButtons),
allSystemInfos.Add(new SystemInfo("Gameboy Color", CoreSystem.GameBoy, 1, StandardButtons)); //13 (0 based) new SystemInfo("Gameboy Color", CoreSystem.GameBoy, 1, StandardButtons), // 13 (0 based)
allSystemInfos.Add(new SystemInfo("Atari 2600", CoreSystem.Atari2600, 1)); new SystemInfo("Atari 2600", CoreSystem.Atari2600, 1),
allSystemInfos.Add(new SystemInfo("Atari 7800", CoreSystem.Atari7800, 1)); new SystemInfo("Atari 7800", CoreSystem.Atari7800, 1),
allSystemInfos.Add(new SystemInfo("Commodore 64", CoreSystem.Commodore64, 1)); new SystemInfo("Commodore 64", CoreSystem.Commodore64, 1),
allSystemInfos.Add(new SystemInfo("ColecoVision", CoreSystem.ColecoVision, 1)); new SystemInfo("ColecoVision", CoreSystem.ColecoVision, 1),
allSystemInfos.Add(new SystemInfo("Gameboy Advance", CoreSystem.GameBoyAdvance, 1, StandardButtons | JoypadButton.L | JoypadButton.R)); new SystemInfo("Gameboy Advance", CoreSystem.GameBoyAdvance, 1, StandardButtons | JoypadButton.L | JoypadButton.R),
allSystemInfos.Add(new SystemInfo("Nintendo 64", CoreSystem.Nintendo64, 4, StandardButtons ^ JoypadButton.Select | JoypadButton.Z | JoypadButton.CUp | JoypadButton.CDown | JoypadButton.CLeft | JoypadButton.CRight | JoypadButton.AnalogStick | JoypadButton.L | JoypadButton.R)); new SystemInfo("Nintendo 64", CoreSystem.Nintendo64, 4, StandardButtons ^ JoypadButton.Select | JoypadButton.Z | JoypadButton.CUp | JoypadButton.CDown | JoypadButton.CLeft | JoypadButton.CRight | JoypadButton.AnalogStick | JoypadButton.L | JoypadButton.R),
allSystemInfos.Add(new SystemInfo("Saturn", CoreSystem.Saturn, 2, UpDownLeftRight | JoypadButton.A | JoypadButton.B | JoypadButton.C | JoypadButton.X | JoypadButton.Y | JoypadButton.Z)); new SystemInfo("Saturn", CoreSystem.Saturn, 2, UpDownLeftRight | JoypadButton.A | JoypadButton.B | JoypadButton.C | JoypadButton.X | JoypadButton.Y | JoypadButton.Z),
allSystemInfos.Add(new SystemInfo("Game Boy Link", CoreSystem.DualGameBoy, 2, StandardButtons)); new SystemInfo("Game Boy Link", CoreSystem.DualGameBoy, 2, StandardButtons),
allSystemInfos.Add(new SystemInfo("WonderSwan", CoreSystem.WonderSwan, 1)); new SystemInfo("WonderSwan", CoreSystem.WonderSwan, 1),
allSystemInfos.Add(new SystemInfo("Lynx", CoreSystem.Lynx, 1)); new SystemInfo("Lynx", CoreSystem.Lynx, 1),
allSystemInfos.Add(new SystemInfo("PlayStation", CoreSystem.Playstation, 2)); new SystemInfo("PlayStation", CoreSystem.Playstation, 2),
allSystemInfos.Add(new SystemInfo("Apple II", CoreSystem.AppleII, 1)); new SystemInfo("Apple II", CoreSystem.AppleII, 1)
};
} }
/// <summary> /// <summary>
@ -84,7 +88,8 @@ namespace BizHawk.Client.Common
/// <param name="maxControllers">Maximum controller allowed by this system</param> /// <param name="maxControllers">Maximum controller allowed by this system</param>
private SystemInfo(string displayName, CoreSystem system, int maxControllers) private SystemInfo(string displayName, CoreSystem system, int maxControllers)
: this(displayName, system, maxControllers, 0) : this(displayName, system, maxControllers, 0)
{ } {
}
/// <summary> /// <summary>
/// Initialize a new instance of <see cref="SystemInfo"/> /// Initialize a new instance of <see cref="SystemInfo"/>
@ -92,324 +97,145 @@ namespace BizHawk.Client.Common
/// <param name="displayName">A <see cref="string"/> that specify how the system name is displayed</param> /// <param name="displayName">A <see cref="string"/> that specify how the system name is displayed</param>
private SystemInfo(string displayName) private SystemInfo(string displayName)
: this(displayName, CoreSystem.Null, 0, 0) : this(displayName, CoreSystem.Null, 0, 0)
{ } {
}
#endregion #endregion
#region Methods #region Methods
#region Get SystemInfo #region Get SystemInfo
/// <summary> /// <summary>
/// Gets the <see cref="SystemInfo"/> instance for Apple II /// Gets the <see cref="SystemInfo"/> instance for Apple II
/// </summary /// </summary
public static SystemInfo AppleII public static SystemInfo AppleII => allSystemInfos[25];
{
get
{
return allSystemInfos[25];
}
}
/// <summary> /// <summary>
/// Gets the <see cref="SystemInfo"/> instance for Atari 2600 /// Gets the <see cref="SystemInfo"/> instance for Atari 2600
/// </summary /// </summary
public static SystemInfo Atari2600 public static SystemInfo Atari2600 => allSystemInfos[14];
{
get
{
return allSystemInfos[14];
}
}
/// <summary> /// <summary>
/// Gets the <see cref="SystemInfo"/> instance for Atari 7800 /// Gets the <see cref="SystemInfo"/> instance for Atari 7800
/// </summary> /// </summary>
public static SystemInfo Atari7800 public static SystemInfo Atari7800 => allSystemInfos[15];
{
get
{
return allSystemInfos[15];
}
}
/// <summary> /// <summary>
/// Gets the <see cref="SystemInfo"/> instance for Commodore 64 /// Gets the <see cref="SystemInfo"/> instance for Commodore 64
/// </summary> /// </summary>
public static SystemInfo C64 public static SystemInfo C64 => allSystemInfos[16];
{
get
{
return allSystemInfos[16];
}
}
/// <summary> /// <summary>
/// Gets the <see cref="SystemInfo"/> instance for Coleco Vision /// Gets the <see cref="SystemInfo"/> instance for Coleco Vision
/// </summary> /// </summary>
public static SystemInfo Coleco public static SystemInfo Coleco => allSystemInfos[17];
{
get
{
return allSystemInfos[17];
}
}
/// <summary> /// <summary>
/// Gets the <see cref="SystemInfo"/> instance for Dual Gameboy /// Gets the <see cref="SystemInfo"/> instance for Dual Gameboy
/// </summary> /// </summary>
public static SystemInfo DualGB public static SystemInfo DualGB => allSystemInfos[21];
{
get
{
return allSystemInfos[21];
}
}
/// <summary> /// <summary>
/// Gets the <see cref="SystemInfo"/> instance for Gameboy /// Gets the <see cref="SystemInfo"/> instance for Gameboy
/// </summary> /// </summary>
public static SystemInfo GB public static SystemInfo GB => allSystemInfos[12];
{
get
{
return allSystemInfos[12];
}
}
/// <summary> /// <summary>
/// Gets the <see cref="SystemInfo"/> instance for Gameboy Advance /// Gets the <see cref="SystemInfo"/> instance for Gameboy Advance
/// </summary> /// </summary>
public static SystemInfo GBA public static SystemInfo GBA => allSystemInfos[18];
{
get
{
return allSystemInfos[18];
}
}
/// <summary> /// <summary>
/// Gets the <see cref="SystemInfo"/> instance for Gameboy Color /// Gets the <see cref="SystemInfo"/> instance for Gameboy Color
/// </summary> /// </summary>
public static SystemInfo GBC public static SystemInfo GBC => allSystemInfos[13];
{
get
{
return allSystemInfos[13];
}
}
/// <summary> /// <summary>
/// Gets the <see cref="SystemInfo"/> instance for Genesis /// Gets the <see cref="SystemInfo"/> instance for Genesis
/// </summary> /// </summary>
public static SystemInfo Genesis public static SystemInfo Genesis => allSystemInfos[9];
{
get
{
return allSystemInfos[9];
}
}
/// <summary> /// <summary>
/// Gets the <see cref="SystemInfo"/> instance for Game Gear /// Gets the <see cref="SystemInfo"/> instance for Game Gear
/// </summary> /// </summary>
public static SystemInfo GG public static SystemInfo GG => allSystemInfos[5];
{
get
{
return allSystemInfos[5];
}
}
/// <summary> /// <summary>
/// Gets the <see cref="SystemInfo"/> instance for Intellivision /// Gets the <see cref="SystemInfo"/> instance for Intellivision
/// </summary> /// </summary>
public static SystemInfo Intellivision public static SystemInfo Intellivision => allSystemInfos[2];
{
get
{
return allSystemInfos[2];
}
}
/// <summary> /// <summary>
/// Gets the <see cref="SystemInfo"/> instance for Lynx /// Gets the <see cref="SystemInfo"/> instance for Lynx
/// </summary> /// </summary>
public static SystemInfo Lynx public static SystemInfo Lynx => allSystemInfos[23];
{
get
{
return allSystemInfos[23];
}
}
/// <summary> /// <summary>
/// Gets the <see cref="SystemInfo"/> instance for NES /// Gets the <see cref="SystemInfo"/> instance for NES
/// </summary> /// </summary>
public static SystemInfo Nes public static SystemInfo Nes => allSystemInfos[1];
{
get
{
return allSystemInfos[1];
}
}
/// <summary> /// <summary>
/// Gets the <see cref="SystemInfo"/> instance for Nintendo 64 /// Gets the <see cref="SystemInfo"/> instance for Nintendo 64
/// </summary> /// </summary>
public static SystemInfo N64 public static SystemInfo N64 => allSystemInfos[19];
{
get
{
return allSystemInfos[19];
}
}
/// <summary> /// <summary>
/// Gets the <see cref="SystemInfo"/> instance for Null (i.e. nothing is emulated) emulator /// Gets the <see cref="SystemInfo"/> instance for Null (i.e. nothing is emulated) emulator
/// </summary> /// </summary>
public static SystemInfo Null public static SystemInfo Null => allSystemInfos[0];
{
get
{
return allSystemInfos[0];
}
}
/// <summary> /// <summary>
/// Gets the <see cref="SystemInfo"/> instance for PCEngine (TurboGrafx-16) /// Gets the <see cref="SystemInfo"/> instance for PCEngine (TurboGrafx-16)
/// </summary> /// </summary>
public static SystemInfo PCE public static SystemInfo PCE => allSystemInfos[6];
{
get
{
return allSystemInfos[6];
}
}
/// <summary> /// <summary>
/// Gets the <see cref="SystemInfo"/> instance for PCEngine (TurboGrafx-16) + CD /// Gets the <see cref="SystemInfo"/> instance for PCEngine (TurboGrafx-16) + CD
/// </summary> /// </summary>
public static SystemInfo PCECD public static SystemInfo PCECD => allSystemInfos[7];
{
get
{
return allSystemInfos[7];
}
}
/// <summary> /// <summary>
/// Gets the <see cref="SystemInfo"/> instance for PlayStation /// Gets the <see cref="SystemInfo"/> instance for PlayStation
/// </summary> /// </summary>
public static SystemInfo PSX public static SystemInfo PSX => allSystemInfos[24];
{
get
{
return allSystemInfos[24];
}
}
/// <summary> /// <summary>
/// Gets the <see cref="SystemInfo"/> instance for Sega Saturn /// Gets the <see cref="SystemInfo"/> instance for Sega Saturn
/// </summary> /// </summary>
public static SystemInfo Saturn public static SystemInfo Saturn => allSystemInfos[20];
{
get
{
return allSystemInfos[20];
}
}
/// <summary> /// <summary>
/// Gets the <see cref="SystemInfo"/> instance for SG-1000 (Sega Game 1000) /// Gets the <see cref="SystemInfo"/> instance for SG-1000 (Sega Game 1000)
/// </summary> /// </summary>
public static SystemInfo SG public static SystemInfo SG => allSystemInfos[4];
{
get
{
return allSystemInfos[4];
}
}
/// <summary> /// <summary>
/// Gets the <see cref="SystemInfo"/> instance for PCEngine (Supergraph FX) /// Gets the <see cref="SystemInfo"/> instance for PCEngine (Supergraph FX)
/// </summary> /// </summary>
public static SystemInfo SGX public static SystemInfo SGX => allSystemInfos[8];
{
get
{
return allSystemInfos[8];
}
}
/// <summary> /// <summary>
/// Gets the <see cref="SystemInfo"/> instance for Sega Master System /// Gets the <see cref="SystemInfo"/> instance for Sega Master System
/// </summary> /// </summary>
public static SystemInfo SMS public static SystemInfo SMS => allSystemInfos[3];
{
get
{
return allSystemInfos[3];
}
}
/// <summary> /// <summary>
/// Gets the <see cref="SystemInfo"/> instance for SNES /// Gets the <see cref="SystemInfo"/> instance for SNES
/// </summary> /// </summary>
public static SystemInfo SNES public static SystemInfo SNES => allSystemInfos[11];
{
get
{
return allSystemInfos[11];
}
}
/// <summary> /// <summary>
/// Gets the <see cref="SystemInfo"/> instance for TI-83 /// Gets the <see cref="SystemInfo"/> instance for TI-83
/// </summary> /// </summary>
public static SystemInfo TI83 public static SystemInfo TI83 => allSystemInfos[10];
{
get
{
return allSystemInfos[10];
}
}
/// <summary> /// <summary>
/// Gets the <see cref="SystemInfo"/> instance for TI-83 /// Gets the <see cref="SystemInfo"/> instance for TI-83
/// </summary> /// </summary>
public static SystemInfo WonderSwan public static SystemInfo WonderSwan => allSystemInfos[22];
{
get
{
return allSystemInfos[22];
}
}
#endregion Get SystemInfo #endregion Get SystemInfo
/// <summary> /// <summary>
@ -433,10 +259,8 @@ namespace BizHawk.Client.Common
{ {
return this == (SystemInfo)obj; return this == (SystemInfo)obj;
} }
else
{ return base.Equals(obj);
return base.Equals(obj);
}
} }
/// <summary> /// <summary>
@ -490,48 +314,23 @@ namespace BizHawk.Client.Common
/// <summary> /// <summary>
/// Gets <see cref="JoypadButton"/> available for this system /// Gets <see cref="JoypadButton"/> available for this system
/// </summary> /// </summary>
public JoypadButton AvailableButtons public JoypadButton AvailableButtons => _AvailableButtons;
{
get
{
return _AvailableButtons;
}
}
/// <summary> /// <summary>
/// Gets the sytem name as <see cref="string"/> /// Gets the sytem name as <see cref="string"/>
/// </summary> /// </summary>
public string DisplayName public string DisplayName => _DisplayName;
{
get
{
return _DisplayName;
}
}
/// <summary>
/// <summary>
/// Gets the maximum amount of controller allowed for this system /// Gets the maximum amount of controller allowed for this system
/// </summary> /// </summary>
public int MaxControllers public int MaxControllers => _MaxControllers;
{
get
{
return _MaxControllers;
}
}
/// <summary> /// <summary>
/// Gets core used for this system as <see cref="CoreSystem"/> enum /// Gets core used for this system as <see cref="CoreSystem"/> enum
/// </summary> /// </summary>
public CoreSystem System public CoreSystem System => _System;
{
get
{
return _System;
}
}
#endregion #endregion
} }
} }

View File

@ -21,9 +21,9 @@ namespace BizHawk.Client.Common
} }
public XmlDocument Xml { get; set; } public XmlDocument Xml { get; set; }
public GameInfo GI { get; set; } public GameInfo GI { get; }
public IList<KeyValuePair<string, byte[]>> Assets { get; set; } public IList<KeyValuePair<string, byte[]>> Assets { get; }
public IList<string> AssetFullPaths { get; set; } // TODO: Hack work around, to avoid having to refactor Assets into a object array, should be refactored! public IList<string> AssetFullPaths { get; } // TODO: Hack work around, to avoid having to refactor Assets into a object array, should be refactored!
public static XmlGame Create(HawkFile f) public static XmlGame Create(HawkFile f)
{ {
@ -38,15 +38,15 @@ namespace BizHawk.Client.Common
} }
var ret = new XmlGame var ret = new XmlGame
{
GI =
{ {
GI = System = y.Attributes["System"].Value,
{ Name = y.Attributes["Name"].Value,
System = y.Attributes["System"].Value, Status = RomStatus.Unknown
Name = y.Attributes["Name"].Value, },
Status = RomStatus.Unknown Xml = x
}, };
Xml = x
};
string fullpath = string.Empty; string fullpath = string.Empty;
var n = y.SelectSingleNode("./LoadAssets"); var n = y.SelectSingleNode("./LoadAssets");
@ -100,8 +100,6 @@ namespace BizHawk.Client.Common
data = File.ReadAllBytes(fullpath.Split('|').First()); data = File.ReadAllBytes(fullpath.Split('|').First());
} }
} }
} }
catch catch
{ {

View File

@ -2,16 +2,15 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
//TODO [LARP] - It's pointless and annoying to store such a big structure filled with static information // TODO [LARP] - It's pointless and annoying to store such a big structure filled with static information
//use this instead // use this instead
//public class UserBinding // public class UserBinding
//{ // {
// public string DisplayName; // public string DisplayName;
// public string Bindings; // public string Bindings;
//} // }
//...also. We should consider using something other than DisplayName for keying, maybe make a KEYNAME distinct from displayname. // ...also. We should consider using something other than DisplayName for keying, maybe make a KEYNAME distinct from displayname.
//displayname is OK for now though. // displayname is OK for now though.
namespace BizHawk.Client.Common namespace BizHawk.Client.Common
{ {
public class Binding public class Binding
@ -27,7 +26,7 @@ namespace BizHawk.Client.Common
[Newtonsoft.Json.JsonObject] [Newtonsoft.Json.JsonObject]
public class BindingCollection : IEnumerable<Binding> public class BindingCollection : IEnumerable<Binding>
{ {
public List<Binding> Bindings { get; private set; } public List<Binding> Bindings { get; }
[Newtonsoft.Json.JsonConstructor] [Newtonsoft.Json.JsonConstructor]
public BindingCollection(List<Binding> Bindings) public BindingCollection(List<Binding> Bindings)
@ -75,7 +74,7 @@ namespace BizHawk.Client.Common
{ {
//TODO - this method is potentially disastrously O(N^2) slow due to linear search nested in loop //TODO - this method is potentially disastrously O(N^2) slow due to linear search nested in loop
//Add missing entries // Add missing entries
foreach (Binding default_binding in DefaultValues) foreach (Binding default_binding in DefaultValues)
{ {
var binding = Bindings.FirstOrDefault(x => x.DisplayName == default_binding.DisplayName); var binding = Bindings.FirstOrDefault(x => x.DisplayName == default_binding.DisplayName);
@ -85,7 +84,7 @@ namespace BizHawk.Client.Common
} }
else else
{ {
//patch entries with updated settings (necessary because of TODO LARP // patch entries with updated settings (necessary because of TODO LARP
binding.Ordinal = default_binding.Ordinal; binding.Ordinal = default_binding.Ordinal;
binding.DefaultBinding = default_binding.DefaultBinding; binding.DefaultBinding = default_binding.DefaultBinding;
binding.TabGroup = default_binding.TabGroup; binding.TabGroup = default_binding.TabGroup;
@ -96,13 +95,11 @@ namespace BizHawk.Client.Common
List<Binding> entriesToRemove = (from entry in Bindings let binding = DefaultValues.FirstOrDefault(x => x.DisplayName == entry.DisplayName) where binding == null select entry).ToList(); List<Binding> entriesToRemove = (from entry in Bindings let binding = DefaultValues.FirstOrDefault(x => x.DisplayName == entry.DisplayName) where binding == null select entry).ToList();
//Remove entries that no longer exist in defaults // Remove entries that no longer exist in defaults
foreach (Binding entry in entriesToRemove) foreach (Binding entry in entriesToRemove)
{ {
Bindings.Remove(entry); Bindings.Remove(entry);
} }
} }
static List<Binding> s_DefaultValues; static List<Binding> s_DefaultValues;
@ -257,13 +254,14 @@ namespace BizHawk.Client.Common
Bind("Analog", "X Down Large", toolTip: "For Virtual Pad"), Bind("Analog", "X Down Large", toolTip: "For Virtual Pad"),
Bind("Tools", "Toggle All Cheats"), Bind("Tools", "Toggle All Cheats"),
}; };
//set ordinals based on order in list // set ordinals based on order in list
for (int i = 0; i < s_DefaultValues.Count; i++) for (int i = 0; i < s_DefaultValues.Count; i++)
{
s_DefaultValues[i].Ordinal = i; s_DefaultValues[i].Ordinal = i;
} //if (s_DefaultValues == null) }
} // if (s_DefaultValues == null)
return s_DefaultValues; return s_DefaultValues;
} }

View File

@ -1,7 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BizHawk.Client.EmuHawk namespace BizHawk.Client.EmuHawk
{ {

View File

@ -10,7 +10,7 @@ namespace BizHawk.Client.Common
{ {
public static class ConfigService public static class ConfigService
{ {
static JsonSerializer Serializer; private static JsonSerializer Serializer;
static ConfigService() static ConfigService()
{ {
@ -39,11 +39,13 @@ namespace BizHawk.Client.Common
{ {
var file = new FileInfo(filepath); var file = new FileInfo(filepath);
if (file.Exists) if (file.Exists)
{
using (var reader = file.OpenText()) using (var reader = file.OpenText())
{ {
var r = new JsonTextReader(reader); var r = new JsonTextReader(reader);
config = (T)Serializer.Deserialize(r, typeof(T)); config = (T)Serializer.Deserialize(r, typeof(T));
} }
}
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -51,7 +53,9 @@ namespace BizHawk.Client.Common
} }
if (config == null) if (config == null)
{
return new T(); return new T();
}
return config; return config;
} }
@ -74,7 +78,6 @@ namespace BizHawk.Client.Common
} }
// movie 1.0 header stuff // movie 1.0 header stuff
private class TypeNameEncapsulator private class TypeNameEncapsulator
{ {
public object o; public object o;
@ -86,12 +89,10 @@ namespace BizHawk.Client.Common
using (JsonTextReader jr = new JsonTextReader(tr)) using (JsonTextReader jr = new JsonTextReader(tr))
{ {
TypeNameEncapsulator tne = (TypeNameEncapsulator)Serializer.Deserialize(jr, typeof(TypeNameEncapsulator)); TypeNameEncapsulator tne = (TypeNameEncapsulator)Serializer.Deserialize(jr, typeof(TypeNameEncapsulator));
// in the case of trying to deserialize nothing, tne will be nothing // in the case of trying to deserialize nothing, tne will be nothing
// we want to return nothing // we want to return nothing
if (tne != null) return tne?.o;
return tne.o;
else
return null;
} }
} }

View File

@ -27,7 +27,7 @@ namespace BizHawk.Client.Common
[Newtonsoft.Json.JsonObject] [Newtonsoft.Json.JsonObject]
public class PathEntryCollection : IEnumerable<PathEntry> public class PathEntryCollection : IEnumerable<PathEntry>
{ {
public List<PathEntry> Paths { get; private set; } public List<PathEntry> Paths { get; }
public PathEntryCollection() public PathEntryCollection()
{ {
@ -36,9 +36,9 @@ namespace BizHawk.Client.Common
} }
[Newtonsoft.Json.JsonConstructor] [Newtonsoft.Json.JsonConstructor]
public PathEntryCollection(List<PathEntry> Paths) public PathEntryCollection(List<PathEntry> paths)
{ {
this.Paths = Paths; Paths = paths;
} }
public void Add(PathEntry p) public void Add(PathEntry p)
@ -78,12 +78,12 @@ namespace BizHawk.Client.Common
Paths.AddRange(new[] Paths.AddRange(new[]
{ {
new PathEntry { System = system, SystemDisplayName=systemdisp, Type = "Base", Path= Path.Combine(".", systempath), Ordinal = 0 }, new PathEntry { System = system, SystemDisplayName = systemdisp, Type = "Base", Path = Path.Combine(".", systempath), Ordinal = 0 },
new PathEntry { System = system, SystemDisplayName=systemdisp, Type = "ROM", Path = ".", Ordinal = 1 }, new PathEntry { System = system, SystemDisplayName = systemdisp, Type = "ROM", Path = ".", Ordinal = 1 },
new PathEntry { System = system, SystemDisplayName=systemdisp, Type = "Savestates", Path= Path.Combine(".", "State"), Ordinal = 2 }, new PathEntry { System = system, SystemDisplayName = systemdisp, Type = "Savestates", Path = Path.Combine(".", "State"), Ordinal = 2 },
new PathEntry { System = system, SystemDisplayName=systemdisp, Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 }, new PathEntry { System = system, SystemDisplayName = systemdisp, Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 },
new PathEntry { System = system, SystemDisplayName=systemdisp, Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 }, new PathEntry { System = system, SystemDisplayName = systemdisp, Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 },
new PathEntry { System = system, SystemDisplayName=systemdisp, Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 } new PathEntry { System = system, SystemDisplayName = systemdisp, Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 }
}); });
return this[system, type]; return this[system, type];
@ -91,7 +91,7 @@ namespace BizHawk.Client.Common
public void ResolveWithDefaults() public void ResolveWithDefaults()
{ {
//Add missing entries // Add missing entries
foreach (PathEntry defaultpath in DefaultValues) foreach (PathEntry defaultpath in DefaultValues)
{ {
var path = Paths.FirstOrDefault(x => x.System == defaultpath.System && x.Type == defaultpath.Type); var path = Paths.FirstOrDefault(x => x.System == defaultpath.System && x.Type == defaultpath.Type);
@ -103,7 +103,7 @@ namespace BizHawk.Client.Common
List<PathEntry> entriesToRemove = new List<PathEntry>(); List<PathEntry> entriesToRemove = new List<PathEntry>();
//Remove entries that no longer exist in defaults // Remove entries that no longer exist in defaults
foreach (PathEntry pathEntry in Paths) foreach (PathEntry pathEntry in Paths)
{ {
var path = DefaultValues.FirstOrDefault(x => x.System == pathEntry.System && x.Type == pathEntry.Type); var path = DefaultValues.FirstOrDefault(x => x.System == pathEntry.System && x.Type == pathEntry.Type);
@ -118,21 +118,15 @@ namespace BizHawk.Client.Common
Paths.Remove(entry); Paths.Remove(entry);
} }
//Add missing displaynames // Add missing displaynames
var missingDisplayPaths = Paths.Where(x => x.SystemDisplayName == null).ToList(); var missingDisplayPaths = Paths.Where(x => x.SystemDisplayName == null).ToList();
foreach (PathEntry path in missingDisplayPaths) foreach (PathEntry path in missingDisplayPaths)
{ {
path.SystemDisplayName = DefaultValues.FirstOrDefault(x => x.System == path.System).SystemDisplayName; path.SystemDisplayName = DefaultValues.FirstOrDefault(x => x.System == path.System).SystemDisplayName;
} }
} }
public string ToolsPathFragment private static string ResolveToolsPath(string subPath)
{
get { return Global.Config.PathEntries["Global", "Tools"].Path; }
}
private static string ResolveToolsPath(string subPath)
{ {
if (Path.IsPathRooted(subPath)) if (Path.IsPathRooted(subPath))
{ {
@ -150,216 +144,206 @@ namespace BizHawk.Client.Common
return Path.Combine(toolsPath, subPath); return Path.Combine(toolsPath, subPath);
} }
//Some frequently requested paths, made into a property for convenience // Some frequently requested paths, made into a property for convenience
public string WatchPathFragment public string ToolsPathFragment => Global.Config.PathEntries["Global", "Tools"].Path;
public string WatchPathFragment => ResolveToolsPath(Global.Config.PathEntries["Global", "Watch (.wch)"].Path);
public string MultiDiskBundlesFragment => ResolveToolsPath(Global.Config.PathEntries["Global", "Multi-Disk Bundles"].Path);
public string LogPathFragment => ResolveToolsPath(Global.Config.PathEntries["Global", "Debug Logs"].Path);
public string MoviesPathFragment => Global.Config.PathEntries["Global", "Movies"].Path;
public string LuaPathFragment => Global.Config.PathEntries["Global", "Lua"].Path;
public string FirmwaresPathFragment => Global.Config.PathEntries["Global", "Firmware"].Path;
public string AvPathFragment => Global.Config.PathEntries["Global", "A/V Dumps"].Path;
public string GlobalRomFragment => Global.Config.PathEntries["Global", "ROM"].Path;
// this one is special
public string GlobalBaseFragment => Global.Config.PathEntries["Global", "Base"].Path;
public static List<PathEntry> DefaultValues => new List<PathEntry>
{ {
get { return ResolveToolsPath(Global.Config.PathEntries["Global", "Watch (.wch)"].Path); } new PathEntry { System = "Global_NULL", SystemDisplayName = "Global", Type = "Base", Path = ".", Ordinal = 1 },
} new PathEntry { System = "Global_NULL", SystemDisplayName = "Global", Type = "ROM", Path = ".", Ordinal = 2 },
new PathEntry { System = "Global_NULL", SystemDisplayName = "Global", Type = "Firmware", Path = Path.Combine(".", "Firmware"), Ordinal = 3 },
new PathEntry { System = "Global_NULL", SystemDisplayName = "Global", Type = "Movies", Path = Path.Combine(".", "Movies"), Ordinal = 4 },
new PathEntry { System = "Global_NULL", SystemDisplayName = "Global", Type = "Movie backups", Path = Path.Combine(".", "Movies", "backup"), Ordinal = 5 },
new PathEntry { System = "Global_NULL", SystemDisplayName = "Global", Type = "A/V Dumps", Path = ".", Ordinal = 6 },
new PathEntry { System = "Global_NULL", SystemDisplayName = "Global", Type = "Tools", Path = Path.Combine(".", "Tools"), Ordinal = 7 },
new PathEntry { System = "Global_NULL", SystemDisplayName = "Global", Type = "Lua", Path = Path.Combine(".", "Lua"), Ordinal = 8 },
new PathEntry { System = "Global_NULL", SystemDisplayName = "Global", Type = "Watch (.wch)", Path = Path.Combine(".", "."), Ordinal = 9 },
new PathEntry { System = "Global_NULL", SystemDisplayName = "Global", Type = "Debug Logs", Path = Path.Combine(".", string.Empty), Ordinal = 10 },
new PathEntry { System = "Global_NULL", SystemDisplayName = "Global", Type = "Macros", Path = Path.Combine(".", "Movies", "Macros"), Ordinal = 11 },
new PathEntry { System = "Global_NULL", SystemDisplayName = "Global", Type = "TAStudio states", Path = Path.Combine(".", "Movies", "TAStudio states"), Ordinal = 12 },
new PathEntry { System = "Global_NULL", SystemDisplayName = "Global", Type = "Multi-Disk Bundles", Path = Path.Combine(".", string.Empty), Ordinal = 13 },
new PathEntry { System = "Global_NULL", SystemDisplayName = "Global", Type = "External Tools", Path = Path.Combine(".", "ExternalTools"), Ordinal = 14 },
public string MultiDiskBundlesFragment new PathEntry { System = "INTV", SystemDisplayName = "Intellivision", Type = "Base", Path = Path.Combine(".", "Intellivision"), Ordinal = 0 },
{ new PathEntry { System = "INTV", SystemDisplayName = "Intellivision", Type = "ROM", Path = ".", Ordinal = 1 },
get { return ResolveToolsPath(Global.Config.PathEntries["Global", "Multi-Disk Bundles"].Path); } new PathEntry { System = "INTV", SystemDisplayName = "Intellivision", Type = "Savestates", Path = Path.Combine(".", "State"), Ordinal = 2 },
} new PathEntry { System = "INTV", SystemDisplayName = "Intellivision", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 },
new PathEntry { System = "INTV", SystemDisplayName = "Intellivision", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 },
new PathEntry { System = "INTV", SystemDisplayName = "Intellivision", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 },
new PathEntry { System = "INTV", SystemDisplayName = "Intellivision", Type = "Palettes", Path = Path.Combine(".", "Palettes"), Ordinal = 6 },
public string LogPathFragment new PathEntry { System = "NES", SystemDisplayName = "NES", Type = "Base", Path = Path.Combine(".", "NES"), Ordinal = 0 },
{ new PathEntry { System = "NES", SystemDisplayName = "NES", Type = "ROM", Path = ".", Ordinal = 1 },
get { return ResolveToolsPath(Global.Config.PathEntries["Global", "Debug Logs"].Path); } new PathEntry { System = "NES", SystemDisplayName = "NES", Type = "Savestates", Path = Path.Combine(".", "State"), Ordinal = 2 },
} new PathEntry { System = "NES", SystemDisplayName = "NES", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 },
new PathEntry { System = "NES", SystemDisplayName = "NES", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 },
new PathEntry { System = "NES", SystemDisplayName = "NES", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 },
new PathEntry { System = "NES", SystemDisplayName = "NES", Type = "Palettes", Path = Path.Combine(".", "Palettes"), Ordinal = 6 },
public string MoviesPathFragment { get { return Global.Config.PathEntries["Global", "Movies"].Path; } } new PathEntry { System = "SNES_SGB", SystemDisplayName = "SNES", Type = "Base", Path = Path.Combine(".", "SNES"), Ordinal = 0 },
public string LuaPathFragment { get { return Global.Config.PathEntries["Global", "Lua"].Path; } } new PathEntry { System = "SNES_SGB", SystemDisplayName = "SNES", Type = "ROM", Path = ".", Ordinal = 1 },
public string FirmwaresPathFragment { get { return Global.Config.PathEntries["Global", "Firmware"].Path; } } new PathEntry { System = "SNES_SGB", SystemDisplayName = "SNES", Type = "Savestates", Path = Path.Combine(".", "State"), Ordinal = 2 },
public string AvPathFragment { get { return Global.Config.PathEntries["Global", "A/V Dumps"].Path; } } new PathEntry { System = "SNES_SGB", SystemDisplayName = "SNES", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 },
public string GlobalRomFragment { get { return Global.Config.PathEntries["Global", "ROM"].Path; } } new PathEntry { System = "SNES_SGB", SystemDisplayName = "SNES", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 },
new PathEntry { System = "SNES_SGB", SystemDisplayName = "SNES", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 },
//this one is special new PathEntry { System = "GBA", SystemDisplayName = "GBA", Type = "Base", Path = Path.Combine(".", "GBA"), Ordinal = 0 },
public string GlobalBaseFragment { get { return Global.Config.PathEntries["Global", "Base"].Path; } } new PathEntry { System = "GBA", SystemDisplayName = "GBA", Type = "ROM", Path = ".", Ordinal = 1 },
new PathEntry { System = "GBA", SystemDisplayName = "GBA", Type = "Savestates", Path = Path.Combine(".", "State"), Ordinal = 2 },
new PathEntry { System = "GBA", SystemDisplayName = "GBA", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 },
new PathEntry { System = "GBA", SystemDisplayName = "GBA", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 },
new PathEntry { System = "GBA", SystemDisplayName = "GBA", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 },
public static List<PathEntry> DefaultValues new PathEntry { System = "SMS", SystemDisplayName = "SMS", Type = "Base", Path = Path.Combine(".", "SMS"), Ordinal = 0 },
{ new PathEntry { System = "SMS", SystemDisplayName = "SMS", Type = "ROM", Path = ".", Ordinal = 1 },
get new PathEntry { System = "SMS", SystemDisplayName = "SMS", Type = "Savestates", Path = Path.Combine(".", "State"), Ordinal = 2 },
{ new PathEntry { System = "SMS", SystemDisplayName = "SMS", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 },
return new List<PathEntry> new PathEntry { System = "SMS", SystemDisplayName = "SMS", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 },
{ new PathEntry { System = "SMS", SystemDisplayName = "SMS", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 },
new PathEntry { System = "Global_NULL", SystemDisplayName="Global", Type = "Base", Path = ".", Ordinal = 1 },
new PathEntry { System = "Global_NULL", SystemDisplayName="Global", Type = "ROM", Path = ".", Ordinal = 2 },
new PathEntry { System = "Global_NULL", SystemDisplayName="Global", Type = "Firmware", Path = Path.Combine(".", "Firmware"), Ordinal = 3 },
new PathEntry { System = "Global_NULL", SystemDisplayName="Global", Type = "Movies", Path = Path.Combine(".", "Movies"), Ordinal = 4 },
new PathEntry { System = "Global_NULL", SystemDisplayName="Global", Type = "Movie backups", Path = Path.Combine(".", "Movies", "backup"), Ordinal = 5 },
new PathEntry { System = "Global_NULL", SystemDisplayName="Global", Type = "A/V Dumps", Path = ".", Ordinal = 6 },
new PathEntry { System = "Global_NULL", SystemDisplayName="Global", Type = "Tools", Path = Path.Combine(".", "Tools"), Ordinal = 7 },
new PathEntry { System = "Global_NULL", SystemDisplayName="Global", Type = "Lua", Path = Path.Combine(".", "Lua"), Ordinal = 8 },
new PathEntry { System = "Global_NULL", SystemDisplayName="Global", Type = "Watch (.wch)", Path = Path.Combine(".", "."), Ordinal = 9 },
new PathEntry { System = "Global_NULL", SystemDisplayName="Global", Type = "Debug Logs", Path = Path.Combine(".", ""), Ordinal = 10 },
new PathEntry { System = "Global_NULL", SystemDisplayName="Global", Type = "Macros", Path = Path.Combine(".", "Movies", "Macros"), Ordinal = 11 },
new PathEntry { System = "Global_NULL", SystemDisplayName="Global", Type = "TAStudio states", Path = Path.Combine(".", "Movies", "TAStudio states"), Ordinal = 12 },
new PathEntry { System = "Global_NULL", SystemDisplayName="Global", Type = "Multi-Disk Bundles", Path = Path.Combine(".", ""), Ordinal = 13 },
new PathEntry { System = "Global_NULL", SystemDisplayName="Global", Type = "External Tools", Path = Path.Combine(".", "ExternalTools"), Ordinal = 14 },
new PathEntry { System = "INTV", SystemDisplayName="Intellivision", Type = "Base", Path = Path.Combine(".", "Intellivision"), Ordinal = 0 }, new PathEntry { System = "GG", SystemDisplayName = "GG", Type = "Base", Path = Path.Combine(".", "Game Gear"), Ordinal = 0 },
new PathEntry { System = "INTV", SystemDisplayName="Intellivision", Type = "ROM", Path = ".", Ordinal = 1 }, new PathEntry { System = "GG", SystemDisplayName = "GG", Type = "ROM", Path = ".", Ordinal = 1 },
new PathEntry { System = "INTV", SystemDisplayName="Intellivision", Type = "Savestates", Path= Path.Combine(".", "State"), Ordinal = 2 }, new PathEntry { System = "GG", SystemDisplayName = "GG", Type = "Savestates", Path = Path.Combine(".", "State"), Ordinal = 2 },
new PathEntry { System = "INTV", SystemDisplayName="Intellivision", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 }, new PathEntry { System = "GG", SystemDisplayName = "GG", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 },
new PathEntry { System = "INTV", SystemDisplayName="Intellivision", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 }, new PathEntry { System = "GG", SystemDisplayName = "GG", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 },
new PathEntry { System = "INTV", SystemDisplayName="Intellivision", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 }, new PathEntry { System = "GG", SystemDisplayName = "GG", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 },
new PathEntry { System = "INTV", SystemDisplayName="Intellivision", Type = "Palettes", Path = Path.Combine(".", "Palettes"), Ordinal = 6 },
new PathEntry { System = "NES", SystemDisplayName="NES", Type = "Base", Path = Path.Combine(".", "NES"), Ordinal = 0 }, new PathEntry { System = "SG", SystemDisplayName = "SG", Type = "Base", Path = Path.Combine(".", "SG-1000"), Ordinal = 0 },
new PathEntry { System = "NES", SystemDisplayName="NES", Type = "ROM", Path = ".", Ordinal = 1 }, new PathEntry { System = "SG", SystemDisplayName = "SG", Type = "ROM", Path = ".", Ordinal = 1 },
new PathEntry { System = "NES", SystemDisplayName="NES", Type = "Savestates", Path= Path.Combine(".", "State"), Ordinal = 2 }, new PathEntry { System = "SG", SystemDisplayName = "SG", Type = "Savestates", Path = Path.Combine(".", "State"), Ordinal = 2 },
new PathEntry { System = "NES", SystemDisplayName="NES", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 }, new PathEntry { System = "SG", SystemDisplayName = "SG", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 },
new PathEntry { System = "NES", SystemDisplayName="NES", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 }, new PathEntry { System = "SG", SystemDisplayName = "SG", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 },
new PathEntry { System = "NES", SystemDisplayName="NES", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 }, new PathEntry { System = "SG", SystemDisplayName = "SG", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 },
new PathEntry { System = "NES", SystemDisplayName="NES", Type = "Palettes", Path = Path.Combine(".", "Palettes"), Ordinal = 6 },
new PathEntry { System = "SNES_SGB", SystemDisplayName="SNES", Type = "Base", Path = Path.Combine(".", "SNES"), Ordinal = 0 }, new PathEntry { System = "GEN", SystemDisplayName = "Genesis", Type = "Base", Path = Path.Combine(".", "Genesis"), Ordinal = 0 },
new PathEntry { System = "SNES_SGB", SystemDisplayName="SNES", Type = "ROM", Path = ".", Ordinal = 1 }, new PathEntry { System = "GEN", SystemDisplayName = "Genesis", Type = "ROM", Path = ".", Ordinal = 1 },
new PathEntry { System = "SNES_SGB", SystemDisplayName="SNES", Type = "Savestates", Path= Path.Combine(".", "State"), Ordinal = 2 }, new PathEntry { System = "GEN", SystemDisplayName = "Genesis", Type = "Savestates", Path = Path.Combine(".", "State"), Ordinal = 2 },
new PathEntry { System = "SNES_SGB", SystemDisplayName="SNES", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 }, new PathEntry { System = "GEN", SystemDisplayName = "Genesis", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 },
new PathEntry { System = "SNES_SGB", SystemDisplayName="SNES", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 }, new PathEntry { System = "GEN", SystemDisplayName = "Genesis", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 },
new PathEntry { System = "SNES_SGB", SystemDisplayName="SNES", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 }, new PathEntry { System = "GEN", SystemDisplayName = "Genesis", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 },
new PathEntry { System = "GBA", SystemDisplayName="GBA", Type = "Base", Path = Path.Combine(".", "GBA"), Ordinal = 0 }, new PathEntry { System = "PCE_PCECD_SGX", SystemDisplayName = "PC Engine", Type = "Base", Path = Path.Combine(".", "PC Engine"), Ordinal = 0 },
new PathEntry { System = "GBA", SystemDisplayName="GBA", Type = "ROM", Path = ".", Ordinal = 1 }, new PathEntry { System = "PCE_PCECD_SGX", SystemDisplayName = "PC Engine", Type = "ROM", Path = ".", Ordinal = 1 },
new PathEntry { System = "GBA", SystemDisplayName="GBA", Type = "Savestates", Path = Path.Combine(".", "State"), Ordinal = 2 }, new PathEntry { System = "PCE_PCECD_SGX", SystemDisplayName = "PC Engine", Type = "Savestates", Path = Path.Combine(".", "State"), Ordinal = 2 },
new PathEntry { System = "GBA", SystemDisplayName="GBA", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 }, new PathEntry { System = "PCE_PCECD_SGX", SystemDisplayName = "PC Engine", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 },
new PathEntry { System = "GBA", SystemDisplayName="GBA", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 }, new PathEntry { System = "PCE_PCECD_SGX", SystemDisplayName = "PC Engine", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 },
new PathEntry { System = "GBA", SystemDisplayName="GBA", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 }, new PathEntry { System = "PCE_PCECD_SGX", SystemDisplayName = "PC Engine", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 },
new PathEntry { System = "SMS", SystemDisplayName="SMS", Type = "Base", Path= Path.Combine(".", "SMS"), Ordinal = 0 }, new PathEntry { System = "GB_GBC", SystemDisplayName = "Gameboy", Type = "Base", Path = Path.Combine(".", "Gameboy"), Ordinal = 0 },
new PathEntry { System = "SMS", SystemDisplayName="SMS", Type = "ROM", Path = ".", Ordinal = 1 }, new PathEntry { System = "GB_GBC", SystemDisplayName = "Gameboy", Type = "ROM", Path = ".", Ordinal = 1 },
new PathEntry { System = "SMS", SystemDisplayName="SMS", Type = "Savestates", Path= Path.Combine(".", "State"), Ordinal = 2 }, new PathEntry { System = "GB_GBC", SystemDisplayName = "Gameboy", Type = "Savestates", Path = Path.Combine(".", "State"), Ordinal = 2 },
new PathEntry { System = "SMS", SystemDisplayName="SMS", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 }, new PathEntry { System = "GB_GBC", SystemDisplayName = "Gameboy", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 },
new PathEntry { System = "SMS", SystemDisplayName="SMS", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 }, new PathEntry { System = "GB_GBC", SystemDisplayName = "Gameboy", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 },
new PathEntry { System = "SMS", SystemDisplayName="SMS", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 }, new PathEntry { System = "GB_GBC", SystemDisplayName = "Gameboy", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 },
new PathEntry { System = "GB_GBC", SystemDisplayName = "Gameboy", Type = "Palettes", Path = Path.Combine(".", "Palettes"), Ordinal = 6 },
new PathEntry { System = "GG", SystemDisplayName="GG", Type = "Base", Path = Path.Combine(".", "Game Gear"), Ordinal = 0 }, new PathEntry { System = "DGB", SystemDisplayName = "Dual Gameboy", Type = "Base", Path = Path.Combine(".", "Dual Gameboy"), Ordinal = 0 },
new PathEntry { System = "GG", SystemDisplayName="GG", Type = "ROM", Path = ".", Ordinal = 1 }, new PathEntry { System = "DGB", SystemDisplayName = "Dual Gameboy", Type = "ROM", Path = ".", Ordinal = 1 },
new PathEntry { System = "GG", SystemDisplayName="GG", Type = "Savestates", Path= Path.Combine(".", "State"), Ordinal = 2 }, new PathEntry { System = "DGB", SystemDisplayName = "Dual Gameboy", Type = "Savestates", Path = Path.Combine(".", "State"), Ordinal = 2 },
new PathEntry { System = "GG", SystemDisplayName="GG", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 }, new PathEntry { System = "DGB", SystemDisplayName = "Dual Gameboy", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 },
new PathEntry { System = "GG", SystemDisplayName="GG", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 }, new PathEntry { System = "DGB", SystemDisplayName = "Dual Gameboy", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 },
new PathEntry { System = "GG", SystemDisplayName="GG", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 }, new PathEntry { System = "DGB", SystemDisplayName = "Dual Gameboy", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 },
new PathEntry { System = "DGB", SystemDisplayName = "Dual Gameboy", Type = "Palettes", Path = Path.Combine(".", "Palettes"), Ordinal = 6 },
new PathEntry { System = "SG", SystemDisplayName="SG", Type = "Base", Path = Path.Combine(".", "SG-1000"), Ordinal = 0 }, new PathEntry { System = "TI83", SystemDisplayName = "TI83", Type = "Base", Path = Path.Combine(".", "TI83"), Ordinal = 0 },
new PathEntry { System = "SG", SystemDisplayName="SG", Type = "ROM", Path = ".", Ordinal = 1 }, new PathEntry { System = "TI83", SystemDisplayName = "TI83", Type = "ROM", Path = ".", Ordinal = 1 },
new PathEntry { System = "SG", SystemDisplayName="SG", Type = "Savestates", Path = Path.Combine(".", "State"), Ordinal = 2 }, new PathEntry { System = "TI83", SystemDisplayName = "TI83", Type = "Savestates", Path = Path.Combine(".", "State"), Ordinal = 2 },
new PathEntry { System = "SG", SystemDisplayName="SG", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 }, new PathEntry { System = "TI83", SystemDisplayName = "TI83", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 },
new PathEntry { System = "SG", SystemDisplayName="SG", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 }, new PathEntry { System = "TI83", SystemDisplayName = "TI83", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 },
new PathEntry { System = "SG", SystemDisplayName="SG", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 }, new PathEntry { System = "TI83", SystemDisplayName = "TI83", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 },
new PathEntry { System = "GEN", SystemDisplayName="Genesis", Type = "Base", Path = Path.Combine(".", "Genesis"), Ordinal = 0 }, new PathEntry { System = "A26", SystemDisplayName = "Atari 2600", Type = "Base", Path = Path.Combine(".", "Atari 2600"), Ordinal = 0 },
new PathEntry { System = "GEN", SystemDisplayName="Genesis", Type = "ROM", Path = ".", Ordinal = 1 }, new PathEntry { System = "A26", SystemDisplayName = "Atari 2600", Type = "ROM", Path = ".", Ordinal = 1 },
new PathEntry { System = "GEN", SystemDisplayName="Genesis", Type = "Savestates", Path= Path.Combine(".", "State"), Ordinal = 2 }, new PathEntry { System = "A26", SystemDisplayName = "Atari 2600", Type = "Savestates", Path = Path.Combine(".", "State"), Ordinal = 2 },
new PathEntry { System = "GEN", SystemDisplayName="Genesis", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 }, new PathEntry { System = "A26", SystemDisplayName = "Atari 2600", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 },
new PathEntry { System = "GEN", SystemDisplayName="Genesis", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 }, new PathEntry { System = "A26", SystemDisplayName = "Atari 2600", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 },
new PathEntry { System = "GEN", SystemDisplayName="Genesis", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 },
new PathEntry { System = "PCE_PCECD_SGX", SystemDisplayName="PC Engine", Type = "Base", Path = Path.Combine(".", "PC Engine"), Ordinal = 0 }, new PathEntry { System = "A78", SystemDisplayName = "Atari 7800", Type = "Base", Path = Path.Combine(".", "Atari 7800"), Ordinal = 0 },
new PathEntry { System = "PCE_PCECD_SGX", SystemDisplayName="PC Engine", Type = "ROM", Path = ".", Ordinal = 1 }, new PathEntry { System = "A78", SystemDisplayName = "Atari 7800", Type = "ROM", Path = ".", Ordinal = 1 },
new PathEntry { System = "PCE_PCECD_SGX", SystemDisplayName="PC Engine", Type = "Savestates", Path= Path.Combine(".", "State"), Ordinal = 2 }, new PathEntry { System = "A78", SystemDisplayName = "Atari 7800", Type = "Savestates", Path = Path.Combine(".", "State"), Ordinal = 2 },
new PathEntry { System = "PCE_PCECD_SGX", SystemDisplayName="PC Engine", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 }, new PathEntry { System = "A78", SystemDisplayName = "Atari 7800", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 },
new PathEntry { System = "PCE_PCECD_SGX", SystemDisplayName="PC Engine", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 }, new PathEntry { System = "A78", SystemDisplayName = "Atari 7800", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 },
new PathEntry { System = "PCE_PCECD_SGX", SystemDisplayName="PC Engine", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 }, new PathEntry { System = "A78", SystemDisplayName = "Atari 7800", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 },
new PathEntry { System = "GB_GBC", SystemDisplayName="Gameboy", Type = "Base", Path= Path.Combine(".", "Gameboy"), Ordinal = 0 }, new PathEntry { System = "C64", SystemDisplayName = "Commodore 64", Type = "Base", Path = Path.Combine(".", "C64"), Ordinal = 0 },
new PathEntry { System = "GB_GBC", SystemDisplayName="Gameboy", Type = "ROM", Path = ".", Ordinal = 1 }, new PathEntry { System = "C64", SystemDisplayName = "Commodore 64", Type = "ROM", Path = ".", Ordinal = 1 },
new PathEntry { System = "GB_GBC", SystemDisplayName="Gameboy", Type = "Savestates", Path= Path.Combine(".", "State"), Ordinal = 2 }, new PathEntry { System = "C64", SystemDisplayName = "Commodore 64", Type = "Savestates", Path = Path.Combine(".", "State"), Ordinal = 2 },
new PathEntry { System = "GB_GBC", SystemDisplayName="Gameboy", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 }, new PathEntry { System = "C64", SystemDisplayName = "Commodore 64", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 },
new PathEntry { System = "GB_GBC", SystemDisplayName="Gameboy", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 }, new PathEntry { System = "C64", SystemDisplayName = "Commodore 64", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 },
new PathEntry { System = "GB_GBC", SystemDisplayName="Gameboy", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 },
new PathEntry { System = "GB_GBC", SystemDisplayName="Gameboy", Type = "Palettes", Path = Path.Combine(".", "Palettes"), Ordinal = 6 },
new PathEntry { System = "DGB", SystemDisplayName="Dual Gameboy", Type = "Base", Path= Path.Combine(".", "Dual Gameboy"), Ordinal = 0 }, new PathEntry { System = "PSX", SystemDisplayName = "Playstation", Type = "Base", Path = Path.Combine(".", "PSX"), Ordinal = 0 },
new PathEntry { System = "DGB", SystemDisplayName="Dual Gameboy", Type = "ROM", Path = ".", Ordinal = 1 }, new PathEntry { System = "PSX", SystemDisplayName = "Playstation", Type = "ROM", Path = ".", Ordinal = 1 },
new PathEntry { System = "DGB", SystemDisplayName="Dual Gameboy", Type = "Savestates", Path= Path.Combine(".", "State"), Ordinal = 2 }, new PathEntry { System = "PSX", SystemDisplayName = "Playstation", Type = "Savestates", Path = Path.Combine(".", "State"), Ordinal = 2 },
new PathEntry { System = "DGB", SystemDisplayName="Dual Gameboy", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 }, new PathEntry { System = "PSX", SystemDisplayName = "Playstation", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 },
new PathEntry { System = "DGB", SystemDisplayName="Dual Gameboy", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 }, new PathEntry { System = "PSX", SystemDisplayName = "Playstation", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 },
new PathEntry { System = "DGB", SystemDisplayName="Dual Gameboy", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 }, new PathEntry { System = "PSX", SystemDisplayName = "Playstation", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 },
new PathEntry { System = "DGB", SystemDisplayName="Dual Gameboy", Type = "Palettes", Path = Path.Combine(".", "Palettes"), Ordinal = 6 },
new PathEntry { System = "TI83", SystemDisplayName="TI83", Type = "Base", Path = Path.Combine(".", "TI83"), Ordinal = 0 }, new PathEntry { System = "Coleco", SystemDisplayName = "Coleco", Type = "Base", Path = Path.Combine(".", "Coleco"), Ordinal = 0 },
new PathEntry { System = "TI83", SystemDisplayName="TI83", Type = "ROM", Path = ".", Ordinal = 1 }, new PathEntry { System = "Coleco", SystemDisplayName = "Coleco", Type = "ROM", Path = ".", Ordinal = 1 },
new PathEntry { System = "TI83", SystemDisplayName="TI83", Type = "Savestates", Path = Path.Combine(".", "State"), Ordinal = 2 }, new PathEntry { System = "Coleco", SystemDisplayName = "Coleco", Type = "Savestates", Path = Path.Combine(".", "State"), Ordinal = 2 },
new PathEntry { System = "TI83", SystemDisplayName="TI83", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 }, new PathEntry { System = "Coleco", SystemDisplayName = "Coleco", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 },
new PathEntry { System = "TI83", SystemDisplayName="TI83", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 }, new PathEntry { System = "Coleco", SystemDisplayName = "Coleco", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 },
new PathEntry { System = "TI83", SystemDisplayName="TI83", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 },
new PathEntry { System = "A26", SystemDisplayName="Atari 2600", Type = "Base", Path = Path.Combine(".", "Atari 2600"), Ordinal = 0 }, new PathEntry { System = "N64", SystemDisplayName = "N64", Type = "Base", Path = Path.Combine(".", "N64"), Ordinal = 0 },
new PathEntry { System = "A26", SystemDisplayName="Atari 2600", Type = "ROM", Path = ".", Ordinal = 1 }, new PathEntry { System = "N64", SystemDisplayName = "N64", Type = "ROM", Path = ".", Ordinal = 1 },
new PathEntry { System = "A26", SystemDisplayName="Atari 2600", Type = "Savestates", Path= Path.Combine(".", "State"), Ordinal = 2 }, new PathEntry { System = "N64", SystemDisplayName = "N64", Type = "Savestates", Path = Path.Combine(".", "State"), Ordinal = 2 },
new PathEntry { System = "A26", SystemDisplayName="Atari 2600", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 }, new PathEntry { System = "N64", SystemDisplayName = "N64", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 },
new PathEntry { System = "A26", SystemDisplayName="Atari 2600", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 }, new PathEntry { System = "N64", SystemDisplayName = "N64", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 },
new PathEntry { System = "N64", SystemDisplayName = "N64", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 },
new PathEntry { System = "A78", SystemDisplayName="Atari 7800", Type = "Base", Path = Path.Combine(".", "Atari 7800"), Ordinal = 0 }, new PathEntry { System = "SAT", SystemDisplayName = "Saturn", Type = "Base", Path = Path.Combine(".", "Saturn"), Ordinal = 0 },
new PathEntry { System = "A78", SystemDisplayName="Atari 7800", Type = "ROM", Path = ".", Ordinal = 1 }, new PathEntry { System = "SAT", SystemDisplayName = "Saturn", Type = "ROM", Path = ".", Ordinal = 1 },
new PathEntry { System = "A78", SystemDisplayName="Atari 7800", Type = "Savestates", Path= Path.Combine(".", "State"), Ordinal = 2 }, new PathEntry { System = "SAT", SystemDisplayName = "Saturn", Type = "Savestates", Path = Path.Combine(".", "State"), Ordinal = 2 },
new PathEntry { System = "A78", SystemDisplayName="Atari 7800", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 }, new PathEntry { System = "SAT", SystemDisplayName = "Saturn", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 },
new PathEntry { System = "A78", SystemDisplayName="Atari 7800", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 }, new PathEntry { System = "SAT", SystemDisplayName = "Saturn", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 },
new PathEntry { System = "A78", SystemDisplayName="Atari 7800", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 }, new PathEntry { System = "SAT", SystemDisplayName = "Saturn", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 },
new PathEntry { System = "C64", SystemDisplayName="Commodore 64", Type = "Base", Path = Path.Combine(".", "C64"), Ordinal = 0 }, new PathEntry { System = "WSWAN", SystemDisplayName = "WonderSwan", Type = "Base", Path = Path.Combine(".", "WonderSwan"), Ordinal = 0 },
new PathEntry { System = "C64", SystemDisplayName="Commodore 64", Type = "ROM", Path = ".", Ordinal = 1 }, new PathEntry { System = "WSWAN", SystemDisplayName = "WonderSwan", Type = "ROM", Path = ".", Ordinal = 1 },
new PathEntry { System = "C64", SystemDisplayName="Commodore 64", Type = "Savestates", Path= Path.Combine(".", "State"), Ordinal = 2 }, new PathEntry { System = "WSWAN", SystemDisplayName = "WonderSwan", Type = "Savestates", Path = Path.Combine(".", "State"), Ordinal = 2 },
new PathEntry { System = "C64", SystemDisplayName="Commodore 64", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 }, new PathEntry { System = "WSWAN", SystemDisplayName = "WonderSwan", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 },
new PathEntry { System = "C64", SystemDisplayName="Commodore 64", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 }, new PathEntry { System = "WSWAN", SystemDisplayName = "WonderSwan", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 },
new PathEntry { System = "WSWAN", SystemDisplayName = "WonderSwan", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 },
new PathEntry { System = "PSX", SystemDisplayName="Playstation", Type = "Base", Path = Path.Combine(".", "PSX"), Ordinal = 0 }, new PathEntry { System = "Lynx", SystemDisplayName = "Lynx", Type = "Base", Path = Path.Combine(".", "Lynx"), Ordinal = 0 },
new PathEntry { System = "PSX", SystemDisplayName="Playstation", Type = "ROM", Path = ".", Ordinal = 1 }, new PathEntry { System = "Lynx", SystemDisplayName = "Lynx", Type = "ROM", Path = ".", Ordinal = 1 },
new PathEntry { System = "PSX", SystemDisplayName="Playstation", Type = "Savestates", Path = Path.Combine(".", "State"), Ordinal = 2 }, new PathEntry { System = "Lynx", SystemDisplayName = "Lynx", Type = "Savestates", Path = Path.Combine(".", "State"), Ordinal = 2 },
new PathEntry { System = "PSX", SystemDisplayName="Playstation", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 }, new PathEntry { System = "Lynx", SystemDisplayName = "Lynx", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 },
new PathEntry { System = "PSX", SystemDisplayName="Playstation", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 }, new PathEntry { System = "Lynx", SystemDisplayName = "Lynx", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 },
new PathEntry { System = "PSX", SystemDisplayName="Playstation", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 }, new PathEntry { System = "Lynx", SystemDisplayName = "Lynx", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 },
new PathEntry { System = "Coleco", SystemDisplayName = "Coleco", Type = "Base", Path = Path.Combine(".", "Coleco"), Ordinal = 0 }, new PathEntry { System = "AppleII", SystemDisplayName = "Apple II", Type = "Base", Path = Path.Combine(".", "Apple II"), Ordinal = 0 },
new PathEntry { System = "Coleco", SystemDisplayName = "Coleco", Type = "ROM", Path = ".", Ordinal = 1 }, new PathEntry { System = "AppleII", SystemDisplayName = "Apple II", Type = "ROM", Path = ".", Ordinal = 1 },
new PathEntry { System = "Coleco", SystemDisplayName = "Coleco", Type = "Savestates", Path= Path.Combine(".", "State"), Ordinal = 2 }, new PathEntry { System = "AppleII", SystemDisplayName = "Apple II", Type = "Savestates", Path = Path.Combine(".", "State"), Ordinal = 2 },
new PathEntry { System = "Coleco", SystemDisplayName = "Coleco", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 }, new PathEntry { System = "AppleII", SystemDisplayName = "Apple II", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 },
new PathEntry { System = "Coleco", SystemDisplayName = "Coleco", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 }, new PathEntry { System = "AppleII", SystemDisplayName = "Apple II", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 },
new PathEntry { System = "N64", SystemDisplayName = "N64", Type = "Base", Path= Path.Combine(".", "N64"), Ordinal = 0 }, new PathEntry { System = "Libretro", SystemDisplayName = "Libretro", Type = "Base", Path = Path.Combine(".", "Libretro"), Ordinal = 0 },
new PathEntry { System = "N64", SystemDisplayName = "N64", Type = "ROM", Path = ".", Ordinal = 1 }, new PathEntry { System = "Libretro", SystemDisplayName = "Libretro", Type = "Cores", Path = Path.Combine(".", "Cores"), Ordinal = 1 },
new PathEntry { System = "N64", SystemDisplayName = "N64", Type = "Savestates", Path= Path.Combine(".", "State"), Ordinal = 2 }, new PathEntry { System = "Libretro", SystemDisplayName = "Libretro", Type = "System", Path = Path.Combine(".", "System"), Ordinal = 2 },
new PathEntry { System = "N64", SystemDisplayName = "N64", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 }, new PathEntry { System = "Libretro", SystemDisplayName = "Libretro", Type = "Savestates", Path = Path.Combine(".", "State"), Ordinal = 3 },
new PathEntry { System = "N64", SystemDisplayName = "N64", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 }, new PathEntry { System = "Libretro", SystemDisplayName = "Libretro", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 4 },
new PathEntry { System = "N64", SystemDisplayName = "N64", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 }, new PathEntry { System = "Libretro", SystemDisplayName = "Libretro", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 5 },
new PathEntry { System = "Libretro", SystemDisplayName = "Libretro", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 6 },
new PathEntry { System = "SAT", SystemDisplayName = "Saturn", Type = "Base", Path = Path.Combine(".", "Saturn"), Ordinal = 0 }, };
new PathEntry { System = "SAT", SystemDisplayName = "Saturn", Type = "ROM", Path = ".", Ordinal = 1 },
new PathEntry { System = "SAT", SystemDisplayName = "Saturn", Type = "Savestates", Path= Path.Combine(".", "State"), Ordinal = 2 },
new PathEntry { System = "SAT", SystemDisplayName = "Saturn", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 },
new PathEntry { System = "SAT", SystemDisplayName = "Saturn", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 },
new PathEntry { System = "SAT", SystemDisplayName = "Saturn", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 },
new PathEntry { System = "WSWAN", SystemDisplayName = "WonderSwan", Type = "Base", Path = Path.Combine(".", "WonderSwan"), Ordinal = 0 },
new PathEntry { System = "WSWAN", SystemDisplayName = "WonderSwan", Type = "ROM", Path = ".", Ordinal = 1 },
new PathEntry { System = "WSWAN", SystemDisplayName = "WonderSwan", Type = "Savestates", Path= Path.Combine(".", "State"), Ordinal = 2 },
new PathEntry { System = "WSWAN", SystemDisplayName = "WonderSwan", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 },
new PathEntry { System = "WSWAN", SystemDisplayName = "WonderSwan", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 },
new PathEntry { System = "WSWAN", SystemDisplayName = "WonderSwan", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 },
new PathEntry { System = "Lynx", SystemDisplayName = "Lynx", Type = "Base", Path = Path.Combine(".", "Lynx"), Ordinal = 0 },
new PathEntry { System = "Lynx", SystemDisplayName = "Lynx", Type = "ROM", Path = ".", Ordinal = 1 },
new PathEntry { System = "Lynx", SystemDisplayName = "Lynx", Type = "Savestates", Path= Path.Combine(".", "State"), Ordinal = 2 },
new PathEntry { System = "Lynx", SystemDisplayName = "Lynx", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 3 },
new PathEntry { System = "Lynx", SystemDisplayName = "Lynx", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 },
new PathEntry { System = "Lynx", SystemDisplayName = "Lynx", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 },
new PathEntry { System = "AppleII", SystemDisplayName = "Apple II", Type = "Base", Path = Path.Combine(".", "Apple II"), Ordinal = 0 },
new PathEntry { System = "AppleII", SystemDisplayName = "Apple II", Type = "ROM", Path = ".", Ordinal = 1 },
new PathEntry { System = "AppleII", SystemDisplayName = "Apple II", Type = "Savestates", Path= Path.Combine(".", "State"), Ordinal = 2 },
new PathEntry { System = "AppleII", SystemDisplayName = "Apple II", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 4 },
new PathEntry { System = "AppleII", SystemDisplayName = "Apple II", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 5 },
new PathEntry { System = "Libretro", SystemDisplayName = "Libretro", Type = "Base", Path = Path.Combine(".", "Libretro"), Ordinal = 0 },
new PathEntry { System = "Libretro", SystemDisplayName = "Libretro", Type = "Cores", Path = Path.Combine(".", "Cores"), Ordinal = 1 },
new PathEntry { System = "Libretro", SystemDisplayName = "Libretro", Type = "System", Path = Path.Combine(".", "System"), Ordinal = 2 },
new PathEntry { System = "Libretro", SystemDisplayName = "Libretro", Type = "Savestates", Path = Path.Combine(".", "State"), Ordinal = 3 },
new PathEntry { System = "Libretro", SystemDisplayName = "Libretro", Type = "Save RAM", Path = Path.Combine(".", "SaveRAM"), Ordinal = 4 },
new PathEntry { System = "Libretro", SystemDisplayName = "Libretro", Type = "Screenshots", Path = Path.Combine(".", "Screenshots"), Ordinal = 5 },
new PathEntry { System = "Libretro", SystemDisplayName = "Libretro", Type = "Cheats", Path = Path.Combine(".", "Cheats"), Ordinal = 6 },
};
}
}
} }
} }

View File

@ -33,7 +33,11 @@ namespace BizHawk.Client.Common
[JsonIgnore] [JsonIgnore]
public int? Wndx public int? Wndx
{ {
get { return _wndx; } get
{
return _wndx;
}
set set
{ {
if (value != -32000) if (value != -32000)
@ -47,7 +51,11 @@ namespace BizHawk.Client.Common
[JsonIgnore] [JsonIgnore]
public int? Wndy public int? Wndy
{ {
get { return _wndy; } get
{
return _wndy;
}
set set
{ {
if (value != -32000) if (value != -32000)

View File

@ -12,25 +12,28 @@
/// </summary> /// </summary>
public AutoPatternBool() public AutoPatternBool()
{ {
Pattern = new bool[] { true }; Pattern = new[] { true };
} }
/// <summary> /// <summary>
/// Simple on/off pattern. /// Initializes a new instance of the <see cref="AutoPatternBool"/> class.
/// A simple on/off pattern.
/// </summary> /// </summary>
/// <param name="on"></param> public AutoPatternBool(int on, int off, bool skipLag = true, int offset = 0, int loop = 0)
/// <param name="off"></param>
public AutoPatternBool(int on, int off, bool skip_lag = true, int offset = 0, int loop = 0)
{ {
SkipsLag = skip_lag; SkipsLag = skipLag;
_index = offset; _index = offset;
Pattern = new bool[on + off]; Pattern = new bool[on + off];
Loop = loop; Loop = loop;
for (int i = 0; i < on; i++) for (int i = 0; i < on; i++)
{
Pattern[i] = true; Pattern[i] = true;
}
} }
public AutoPatternBool(bool[] pattern, bool skip_lag = true, int offset = 0, int loop = 0)
public AutoPatternBool(bool[] pattern, bool skipLag = true, int offset = 0, int loop = 0)
{ {
SkipsLag = skip_lag; SkipsLag = skipLag;
Pattern = pattern; Pattern = pattern;
_index = offset; _index = offset;
Loop = loop; Loop = loop;
@ -39,7 +42,6 @@
/// <summary> /// <summary>
/// Gets the next value and increments index. /// Gets the next value and increments index.
/// </summary> /// </summary>
/// <returns></returns>
public bool GetNextValue(bool isLag = false) public bool GetNextValue(bool isLag = false)
{ {
bool ret = Pattern[_index]; bool ret = Pattern[_index];
@ -47,7 +49,9 @@
{ {
_index++; _index++;
if (_index == Pattern.Length) if (_index == Pattern.Length)
{
_index = Loop; _index = Loop;
}
} }
return ret; return ret;
@ -56,12 +60,15 @@
/// <summary> /// <summary>
/// Gets the next value without incrementing index. /// Gets the next value without incrementing index.
/// </summary> /// </summary>
/// <returns></returns>
public bool PeekNextValue() public bool PeekNextValue()
{ return Pattern[_index]; } {
return Pattern[_index];
}
public void Reset() public void Reset()
{ _index = 0; } {
_index = 0;
}
} }
public class AutoPatternFloat public class AutoPatternFloat
@ -72,12 +79,14 @@
private int _index; private int _index;
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="AutoPatternFloat"/> class.
/// Defaults to 0. /// Defaults to 0.
/// </summary> /// </summary>
public AutoPatternFloat() public AutoPatternFloat()
{ {
Pattern = new float[] { 0f }; Pattern = new[] { 0f };
} }
/// <summary> /// <summary>
/// Sinple on/off pattern, using the given values as on/off. /// Sinple on/off pattern, using the given values as on/off.
/// </summary> /// </summary>
@ -88,10 +97,16 @@
Loop = loop; Loop = loop;
Pattern = new float[on + off]; Pattern = new float[on + off];
for (int i = 0; i < on; i++) for (int i = 0; i < on; i++)
{
Pattern[i] = valueOn; Pattern[i] = valueOn;
}
for (int i = on; i < Pattern.Length; i++) for (int i = on; i < Pattern.Length; i++)
{
Pattern[i] = valueOff; Pattern[i] = valueOff;
}
} }
public AutoPatternFloat(float[] pattern, bool skip_lag = true, int offset = 0, int loop = 0) public AutoPatternFloat(float[] pattern, bool skip_lag = true, int offset = 0, int loop = 0)
{ {
SkipsLag = skip_lag; SkipsLag = skip_lag;
@ -103,7 +118,6 @@
/// <summary> /// <summary>
/// Gets the next value and increments index. /// Gets the next value and increments index.
/// </summary> /// </summary>
/// <returns></returns>
public float GetNextValue(bool isLag = false) public float GetNextValue(bool isLag = false)
{ {
float ret = Pattern[_index]; float ret = Pattern[_index];
@ -111,7 +125,9 @@
{ {
_index++; _index++;
if (_index == Pattern.Length) if (_index == Pattern.Length)
{
_index = Loop; _index = Loop;
}
} }
return ret; return ret;
@ -120,11 +136,14 @@
/// <summary> /// <summary>
/// Gets the next value without incrementing index. /// Gets the next value without incrementing index.
/// </summary> /// </summary>
/// <returns></returns>
public float PeekNextValue() public float PeekNextValue()
{ return Pattern[_index]; } {
return Pattern[_index];
}
public void Reset() public void Reset()
{ _index = 0; } {
_index = 0;
}
} }
} }

View File

@ -4,12 +4,9 @@ namespace BizHawk.Client.Common
{ {
public class AndAdapter : IController public class AndAdapter : IController
{ {
public ControllerDefinition Definition public ControllerDefinition Definition => Source.Definition;
{
get { return Source.Definition; }
}
public bool IsPressed(string button) public bool IsPressed(string button)
{ {
if (Source != null && SourceAnd != null) if (Source != null && SourceAnd != null)
{ {
@ -32,15 +29,12 @@ namespace BizHawk.Client.Common
public class ORAdapter : IController public class ORAdapter : IController
{ {
public ControllerDefinition Definition public ControllerDefinition Definition => Source.Definition;
{
get { return Source.Definition; }
}
public bool IsPressed(string button) public bool IsPressed(string button)
{ {
return (Source != null ? Source.IsPressed(button) : false) return (Source?.IsPressed(button) ?? false)
| (SourceOr != null ? SourceOr.IsPressed(button) : false); | (SourceOr?.IsPressed(button) ?? false);
} }
// pass floats solely from the original source // pass floats solely from the original source

View File

@ -69,5 +69,4 @@ namespace BizHawk.Client.Common
private readonly HashSet<string> _pressed = new HashSet<string>(); private readonly HashSet<string> _pressed = new HashSet<string>();
} }
} }

View File

@ -3,16 +3,13 @@
namespace BizHawk.Client.Common namespace BizHawk.Client.Common
{ {
/// <summary> /// <summary>
/// Just copies source to sink, or returns whatever a NullController would if it is disconnected. useful for immovable hardpoints. /// Just copies source to sink, or returns whatever a NullController would if it is disconnected. useful for immovable hard-points.
/// </summary> /// </summary>
public class CopyControllerAdapter : IController public class CopyControllerAdapter : IController
{ {
public ControllerDefinition Definition public ControllerDefinition Definition => Curr.Definition;
{
get { return Curr.Definition; }
}
public bool IsPressed(string button) public bool IsPressed(string button)
{ {
return Curr.IsPressed(button); return Curr.IsPressed(button);
} }
@ -24,14 +21,6 @@ namespace BizHawk.Client.Common
public IController Source { get; set; } public IController Source { get; set; }
private IController Curr private IController Curr => Source ?? NullController.Instance;
{
get
{
return Source == null
? NullController.Instance
: Source;
}
}
} }
} }

View File

@ -2,6 +2,7 @@
using BizHawk.Emulation.Common; using BizHawk.Emulation.Common;
using BizHawk.Client.Common.InputAdapterExtensions; using BizHawk.Client.Common.InputAdapterExtensions;
namespace BizHawk.Client.Common namespace BizHawk.Client.Common
{ {
public static class InputManager public static class InputManager

View File

@ -16,13 +16,13 @@ namespace BizHawk.Client.Common
protected WorkingDictionary<string, bool> Buttons = new WorkingDictionary<string, bool>(); protected WorkingDictionary<string, bool> Buttons = new WorkingDictionary<string, bool>();
protected WorkingDictionary<string, float> Floats = new WorkingDictionary<string, float>(); protected WorkingDictionary<string, float> Floats = new WorkingDictionary<string, float>();
public virtual void Clear() public void Clear()
{ {
Buttons = new WorkingDictionary<string, bool>(); Buttons = new WorkingDictionary<string, bool>();
Floats = new WorkingDictionary<string, float>(); Floats = new WorkingDictionary<string, float>();
} }
public virtual bool this[string button] public bool this[string button]
{ {
get { return Buttons[button]; } get { return Buttons[button]; }
set { Buttons[button] = value; } set { Buttons[button] = value; }
@ -43,7 +43,7 @@ namespace BizHawk.Client.Common
return Buttons; return Buttons;
} }
public virtual void LatchFrom(IController source) public void LatchFrom(IController source)
{ {
foreach (var button in source.Definition.BoolButtons) foreach (var button in source.Definition.BoolButtons)
{ {

View File

@ -17,12 +17,9 @@ namespace BizHawk.Client.Common
/// </summary> /// </summary>
public class StickyOrAdapter : IController public class StickyOrAdapter : IController
{ {
public ControllerDefinition Definition public ControllerDefinition Definition => Source.Definition;
{
get { return Source.Definition; }
}
public bool IsPressed(string button) public bool IsPressed(string button)
{ {
return Source.StickyIsInEffect(button) return Source.StickyIsInEffect(button)
|| SourceStickyOr.StickyIsInEffect(button); || SourceStickyOr.StickyIsInEffect(button);
@ -56,12 +53,9 @@ namespace BizHawk.Client.Common
return false; return false;
} }
public ControllerDefinition Definition public ControllerDefinition Definition => Source.Definition;
{
get { return Source.Definition; }
}
public bool IsPressed(string button) public bool IsPressed(string button)
{ {
var source = Source.IsPressed(button); var source = Source.IsPressed(button);
source ^= stickySet.Contains(button); source ^= stickySet.Contains(button);
@ -137,13 +131,7 @@ namespace BizHawk.Client.Common
return stickySet.Contains(button); return stickySet.Contains(button);
} }
public HashSet<string> CurrentStickies public HashSet<string> CurrentStickies => stickySet;
{
get
{
return stickySet;
}
}
public void ClearStickies() public void ClearStickies()
{ {
@ -229,12 +217,13 @@ namespace BizHawk.Client.Common
Off = Global.Config.AutofireOff < 1 ? 0 : Global.Config.AutofireOff; Off = Global.Config.AutofireOff < 1 ? 0 : Global.Config.AutofireOff;
} }
private WorkingDictionary<string, AutoPatternBool> _boolPatterns = new WorkingDictionary<string, AutoPatternBool>(); private readonly WorkingDictionary<string, AutoPatternBool> _boolPatterns = new WorkingDictionary<string, AutoPatternBool>();
private WorkingDictionary<string, AutoPatternFloat> _floatPatterns = new WorkingDictionary<string, AutoPatternFloat>(); private readonly WorkingDictionary<string, AutoPatternFloat> _floatPatterns = new WorkingDictionary<string, AutoPatternFloat>();
public AutoFireStickyXorAdapter() public AutoFireStickyXorAdapter()
{ {
On = 1; Off = 1; On = 1;
Off = 1;
} }
public IController Source { get; set; } public IController Source { get; set; }
@ -246,7 +235,10 @@ namespace BizHawk.Client.Common
if (value.HasValue) if (value.HasValue)
{ {
if (pattern == null) if (pattern == null)
{
pattern = new AutoPatternFloat(value.Value, On, 0, Off); pattern = new AutoPatternFloat(value.Value, On, 0, Off);
}
_floatPatterns[name] = pattern; _floatPatterns[name] = pattern;
} }
else else
@ -265,7 +257,10 @@ namespace BizHawk.Client.Common
if (isSticky) if (isSticky)
{ {
if (pattern == null) if (pattern == null)
{
pattern = new AutoPatternBool(On, Off); pattern = new AutoPatternBool(On, Off);
}
_boolPatterns[button] = pattern; _boolPatterns[button] = pattern;
} }
else else
@ -285,15 +280,9 @@ namespace BizHawk.Client.Common
return _boolPatterns.ContainsKey(button) || _floatPatterns.ContainsKey(button); return _boolPatterns.ContainsKey(button) || _floatPatterns.ContainsKey(button);
} }
public HashSet<string> CurrentStickies public HashSet<string> CurrentStickies => new HashSet<string>(_boolPatterns.Keys);
{
get
{
return new HashSet<string>(_boolPatterns.Keys);
}
}
public void ClearStickies() public void ClearStickies()
{ {
_boolPatterns.Clear(); _boolPatterns.Clear();
_floatPatterns.Clear(); _floatPatterns.Clear();
@ -302,9 +291,14 @@ namespace BizHawk.Client.Common
public void IncrementLoops(bool lagged) public void IncrementLoops(bool lagged)
{ {
for (int i = 0; i < _boolPatterns.Count; i++) for (int i = 0; i < _boolPatterns.Count; i++)
{
_boolPatterns.ElementAt(i).Value.GetNextValue(lagged); _boolPatterns.ElementAt(i).Value.GetNextValue(lagged);
}
for (int i = 0; i < _floatPatterns.Count; i++) for (int i = 0; i < _floatPatterns.Count; i++)
{
_floatPatterns.ElementAt(i).Value.GetNextValue(lagged); _floatPatterns.ElementAt(i).Value.GetNextValue(lagged);
}
} }
private List<string> _justPressed = new List<string>(); private List<string> _justPressed = new List<string>();
@ -313,10 +307,7 @@ namespace BizHawk.Client.Common
{ {
foreach (var button in buttons.Where(button => !_justPressed.Contains(button))) foreach (var button in buttons.Where(button => !_justPressed.Contains(button)))
{ {
if (_boolPatterns.ContainsKey(button)) SetSticky(button, !_boolPatterns.ContainsKey(button));
SetSticky(button, false);
else
SetSticky(button, true);
} }
_justPressed = buttons; _justPressed = buttons;

View File

@ -11,15 +11,10 @@ namespace BizHawk.Client.Common
/// </summary> /// </summary>
public class UD_LR_ControllerAdapter : IController public class UD_LR_ControllerAdapter : IController
{ {
public ControllerDefinition Definition public ControllerDefinition Definition => Source.Definition;
{
get { return Source.Definition; }
}
public bool IsPressed(string button) public bool IsPressed(string button)
{ {
bool PriorityUD_LR = !Global.Config.AllowUD_LR && !Global.Config.ForbidUD_LR; // implied by neither of the others being set (left as non-enum for back-compatibility)
if (Global.Config.AllowUD_LR) if (Global.Config.AllowUD_LR)
{ {
return Source.IsPressed(button); return Source.IsPressed(button);
@ -27,10 +22,8 @@ namespace BizHawk.Client.Common
string prefix; string prefix;
//" C " is for N64 "P1 C Up" and the like, which should not be subject to mutexing // " C " is for N64 "P1 C Up" and the like, which should not be subject to mutexing
// regarding the unpressing and UDLR logic...... don't think about it. don't question it. don't look at it.
//regarding the unpressing and UDLR logic...... don't think about it. don't question it. don't look at it.
if (button.Contains("Down") && !button.Contains(" C ")) if (button.Contains("Down") && !button.Contains(" C "))
{ {
if (!Source.IsPressed(button)) if (!Source.IsPressed(button))

View File

@ -14,9 +14,9 @@ namespace BizHawk.Client.Common
public BitLuaLibrary(Lua lua, Action<string> logOutputCallback) public BitLuaLibrary(Lua lua, Action<string> logOutputCallback)
: base(lua, logOutputCallback) { } : base(lua, logOutputCallback) { }
public override string Name { get { return "bit"; } } public override string Name => "bit";
[LuaMethodAttributes( [LuaMethodAttributes(
"band", "band",
"Bitwise AND of 'val' against 'amt'" "Bitwise AND of 'val' against 'amt'"
)] )]

View File

@ -1,8 +1,5 @@
using System; using System;
using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Linq;
using System.Reflection;
using BizHawk.Emulation.Common; using BizHawk.Emulation.Common;
using BizHawk.Emulation.Common.IEmulatorExtensions; using BizHawk.Emulation.Common.IEmulatorExtensions;
@ -46,9 +43,9 @@ namespace BizHawk.Client.Common
public EmulatorLuaLibrary(Lua lua, Action<string> logOutputCallback) public EmulatorLuaLibrary(Lua lua, Action<string> logOutputCallback)
: base(lua, logOutputCallback) { } : base(lua, logOutputCallback) { }
public override string Name { get { return "emu"; } } public override string Name => "emu";
[LuaMethodAttributes( [LuaMethodAttributes(
"displayvsync", "displayvsync",
"Sets the display vsync property of the emulator" "Sets the display vsync property of the emulator"
)] )]
@ -157,9 +154,7 @@ namespace BizHawk.Client.Common
} }
catch (NotImplementedException) catch (NotImplementedException)
{ {
Log(string.Format( Log($"Error: {Emulator.Attributes().CoreName} does not yet implement getregisters()");
"Error: {0} does not yet implement getregisters()",
Emulator.Attributes().CoreName));
} }
return table; return table;
@ -182,9 +177,7 @@ namespace BizHawk.Client.Common
} }
catch (NotImplementedException) catch (NotImplementedException)
{ {
Log(string.Format( Log($"Error: {Emulator.Attributes().CoreName} does not yet implement setregister()");
"Error: {0} does not yet implement setregister()",
Emulator.Attributes().CoreName));
} }
} }
@ -232,11 +225,9 @@ namespace BizHawk.Client.Common
{ {
return InputPollableCore.IsLagFrame; return InputPollableCore.IsLagFrame;
} }
else
{ Log($"Can not get lag information, {Emulator.Attributes().CoreName} does not implement IInputPollable");
Log(string.Format("Can not get lag information, {0} does not implement IInputPollable", Emulator.Attributes().CoreName)); return false;
return false;
}
} }
[LuaMethodAttributes( [LuaMethodAttributes(
@ -251,7 +242,7 @@ namespace BizHawk.Client.Common
} }
else else
{ {
Log(string.Format("Can not set lag information, {0} does not implement IInputPollable", Emulator.Attributes().CoreName)); Log($"Can not set lag information, {Emulator.Attributes().CoreName} does not implement IInputPollable");
} }
} }
@ -265,11 +256,9 @@ namespace BizHawk.Client.Common
{ {
return InputPollableCore.LagCount; return InputPollableCore.LagCount;
} }
else
{ Log($"Can not get lag information, {Emulator.Attributes().CoreName} does not implement IInputPollable");
Log(string.Format("Can not get lag information, {0} does not implement IInputPollable", Emulator.Attributes().CoreName)); return 0;
return 0;
}
} }
[LuaMethodAttributes( [LuaMethodAttributes(
@ -326,12 +315,18 @@ namespace BizHawk.Client.Common
{ {
var quicknes = Emulator as QuickNES; var quicknes = Emulator as QuickNES;
var s = quicknes.GetSettings(); var s = quicknes.GetSettings();
// this core doesn't support disabling BG // this core doesn't support disabling BG
bool showsp = GetSetting(0, luaParam); bool showsp = GetSetting(0, luaParam);
if (showsp && s.NumSprites == 0) if (showsp && s.NumSprites == 0)
{
s.NumSprites = 8; s.NumSprites = 8;
}
else if (!showsp && s.NumSprites > 0) else if (!showsp && s.NumSprites > 0)
{
s.NumSprites = 0; s.NumSprites = 0;
}
quicknes.PutSettings(s); quicknes.PutSettings(s);
} }
else if (Emulator is PCEngine) else if (Emulator is PCEngine)

View File

@ -30,9 +30,9 @@ namespace BizHawk.Client.Common
public EventLuaLibrary(Lua lua, Action<string> logOutputCallback) public EventLuaLibrary(Lua lua, Action<string> logOutputCallback)
: base(lua, logOutputCallback) { } : base(lua, logOutputCallback) { }
public override string Name { get { return "event"; } } public override string Name => "event";
#region Events Library Helpers #region Events Library Helpers
public void CallExitEvent(Lua thread) public void CallExitEvent(Lua thread)
{ {
@ -202,11 +202,9 @@ namespace BizHawk.Client.Common
return Guid.Empty.ToString(); return Guid.Empty.ToString();
} }
} }
else
{ LogNotImplemented();
LogNotImplemented(); return Guid.Empty.ToString();
return Guid.Empty.ToString();
}
} }
private void LogNotImplemented() private void LogNotImplemented()
@ -237,7 +235,9 @@ namespace BizHawk.Client.Common
DebuggableCore.MemoryCallbacks.ExecuteCallbacksAvailable) DebuggableCore.MemoryCallbacks.ExecuteCallbacksAvailable)
{ {
if (N64CoreTypeDynarec()) if (N64CoreTypeDynarec())
{
return Guid.Empty.ToString(); return Guid.Empty.ToString();
}
var nlf = new NamedLuaFunction(luaf, "OnMemoryExecute", LogOutputCallback, CurrentThread, name); var nlf = new NamedLuaFunction(luaf, "OnMemoryExecute", LogOutputCallback, CurrentThread, name);
_luaFunctions.Add(nlf); _luaFunctions.Add(nlf);
@ -247,7 +247,7 @@ namespace BizHawk.Client.Common
return nlf.Guid.ToString(); return nlf.Guid.ToString();
} }
} }
catch(NotImplementedException) catch (NotImplementedException)
{ {
LogMemoryExecuteCallbacksNotImplemented(); LogMemoryExecuteCallbacksNotImplemented();
return Guid.Empty.ToString(); return Guid.Empty.ToString();
@ -268,7 +268,9 @@ namespace BizHawk.Client.Common
if (DebuggableCore != null && DebuggableCore.MemoryCallbacksAvailable()) if (DebuggableCore != null && DebuggableCore.MemoryCallbacksAvailable())
{ {
if (N64CoreTypeDynarec()) if (N64CoreTypeDynarec())
{
return Guid.Empty.ToString(); return Guid.Empty.ToString();
}
var nlf = new NamedLuaFunction(luaf, "OnMemoryRead", LogOutputCallback, CurrentThread, name); var nlf = new NamedLuaFunction(luaf, "OnMemoryRead", LogOutputCallback, CurrentThread, name);
_luaFunctions.Add(nlf); _luaFunctions.Add(nlf);
@ -299,7 +301,9 @@ namespace BizHawk.Client.Common
if (DebuggableCore != null && DebuggableCore.MemoryCallbacksAvailable()) if (DebuggableCore != null && DebuggableCore.MemoryCallbacksAvailable())
{ {
if (N64CoreTypeDynarec()) if (N64CoreTypeDynarec())
{
return Guid.Empty.ToString(); return Guid.Empty.ToString();
}
var nlf = new NamedLuaFunction(luaf, "OnMemoryWrite", LogOutputCallback, CurrentThread, name); var nlf = new NamedLuaFunction(luaf, "OnMemoryWrite", LogOutputCallback, CurrentThread, name);
_luaFunctions.Add(nlf); _luaFunctions.Add(nlf);

View File

@ -15,9 +15,9 @@ namespace BizHawk.Client.Common
public GameInfoLuaLibrary(Lua lua, Action<string> logOutputCallback) public GameInfoLuaLibrary(Lua lua, Action<string> logOutputCallback)
: base(lua, logOutputCallback) { } : base(lua, logOutputCallback) { }
public override string Name { get { return "gameinfo"; } } public override string Name => "gameinfo";
[LuaMethodAttributes( [LuaMethodAttributes(
"getromname", "getromname",
"returns the path of the currently loaded rom, if a rom is loaded" "returns the path of the currently loaded rom, if a rom is loaded"
)] )]
@ -93,7 +93,7 @@ namespace BizHawk.Client.Common
)] )]
public string GetBoardType() public string GetBoardType()
{ {
return Emulator.BoardName ?? ""; return Emulator.BoardName ?? string.Empty;
} }
[LuaMethodAttributes( [LuaMethodAttributes(

View File

@ -18,9 +18,9 @@ namespace BizHawk.Client.Common
public GenesisLuaLibrary(Lua lua, Action<string> logOutputCallback) public GenesisLuaLibrary(Lua lua, Action<string> logOutputCallback)
: base(lua, logOutputCallback) { } : base(lua, logOutputCallback) { }
public override string Name { get { return "genesis"; } } public override string Name => "genesis";
private GPGX.GPGXSettings GetSettings() private GPGX.GPGXSettings GetSettings()
{ {
if (Genesis != null) if (Genesis != null)
{ {
@ -32,10 +32,7 @@ namespace BizHawk.Client.Common
private void PutSettings(GPGX.GPGXSettings settings) private void PutSettings(GPGX.GPGXSettings settings)
{ {
if (Genesis != null) Genesis?.PutSettings(settings);
{
Genesis.PutSettings(settings);
}
} }
[LuaMethodAttributes( [LuaMethodAttributes(

View File

@ -11,9 +11,9 @@ namespace BizHawk.Client.Common
public JoypadLuaLibrary(Lua lua, Action<string> logOutputCallback) public JoypadLuaLibrary(Lua lua, Action<string> logOutputCallback)
: base(lua, logOutputCallback) { } : base(lua, logOutputCallback) { }
public override string Name { get { return "joypad"; } } public override string Name => "joypad";
[LuaMethodAttributes( [LuaMethodAttributes(
"get", "get",
"returns a lua table of the controller buttons pressed. If supplied, it will only return a table of buttons for the given controller" "returns a lua table of the controller buttons pressed. If supplied, it will only return a table of buttons for the given controller"
)] )]
@ -109,7 +109,7 @@ namespace BizHawk.Client.Common
bool? theValue; bool? theValue;
var theValueStr = buttons[button].ToString(); var theValueStr = buttons[button].ToString();
if (!String.IsNullOrWhiteSpace(theValueStr)) if (!string.IsNullOrWhiteSpace(theValueStr))
{ {
if (theValueStr.ToLower() == "false") if (theValueStr.ToLower() == "false")
{ {
@ -175,11 +175,13 @@ namespace BizHawk.Client.Common
var theValueStr = controls[name].ToString(); var theValueStr = controls[name].ToString();
float? theValue = null; float? theValue = null;
if (!String.IsNullOrWhiteSpace(theValueStr)) if (!string.IsNullOrWhiteSpace(theValueStr))
{ {
float f; float f;
if (float.TryParse(theValueStr, out f)) if (float.TryParse(theValueStr, out f))
{
theValue = f; theValue = f;
}
} }
if (controller == null) if (controller == null)
@ -190,7 +192,6 @@ namespace BizHawk.Client.Common
{ {
Global.StickyXORAdapter.SetFloat("P" + controller + " " + name, theValue); Global.StickyXORAdapter.SetFloat("P" + controller + " " + name, theValue);
} }
} }
} }
catch { /*Eat it*/ } catch { /*Eat it*/ }

View File

@ -16,9 +16,9 @@ namespace BizHawk.Client.Common
public MainMemoryLuaLibrary(Lua lua, Action<string> logOutputCallback) public MainMemoryLuaLibrary(Lua lua, Action<string> logOutputCallback)
: base(lua, logOutputCallback) { } : base(lua, logOutputCallback) { }
public override string Name { get { return "mainmemory"; } } public override string Name => "mainmemory";
protected override MemoryDomain Domain protected override MemoryDomain Domain
{ {
get get
{ {
@ -28,7 +28,7 @@ namespace BizHawk.Client.Common
} }
else else
{ {
var error = string.Format("Error: {0} does not implement memory domains", Emulator.Attributes().CoreName); var error = $"Error: {Emulator.Attributes().CoreName} does not implement memory domains";
Log(error); Log(error);
throw new NotImplementedException(error); throw new NotImplementedException(error);
} }

View File

@ -24,9 +24,9 @@ namespace BizHawk.Client.Common
} }
public override string Name { get { return "memory"; } } public override string Name => "memory";
protected override MemoryDomain Domain protected override MemoryDomain Domain
{ {
get get
{ {
@ -34,21 +34,16 @@ namespace BizHawk.Client.Common
{ {
if (_currentMemoryDomain == null) if (_currentMemoryDomain == null)
{ {
if (MemoryDomainCore.HasSystemBus) _currentMemoryDomain = MemoryDomainCore.HasSystemBus
{ ? MemoryDomainCore.SystemBus
_currentMemoryDomain = MemoryDomainCore.SystemBus; : MemoryDomainCore.MainMemory;
}
else
{
_currentMemoryDomain = MemoryDomainCore.MainMemory;
}
} }
return _currentMemoryDomain; return _currentMemoryDomain;
} }
else else
{ {
var error = string.Format("Error: {0} does not implement memory domains", Emulator.Attributes().CoreName); var error = $"Error: {Emulator.Attributes().CoreName} does not implement memory domains";
Log(error); Log(error);
throw new NotImplementedException(error); throw new NotImplementedException(error);
} }
@ -120,14 +115,14 @@ namespace BizHawk.Client.Common
} }
else else
{ {
Log(string.Format("Unable to find domain: {0}", domain)); Log($"Unable to find domain: {domain}");
return false; return false;
} }
} }
catch // Just in case catch // Just in case
{ {
Log(string.Format("Unable to find domain: {0}", domain)); Log($"Unable to find domain: {domain}");
} }
return false; return false;

View File

@ -1,84 +1,83 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using LuaInterface; using LuaInterface;
using BizHawk.Emulation.Common; using BizHawk.Emulation.Common;
using BizHawk.Emulation.Common.IEmulatorExtensions;
namespace BizHawk.Client.Common
namespace BizHawk.Client.Common {
{ public sealed class MemorySavestateEmuLuaLibrary : LuaLibraryBase
public sealed class MemorySavestateEmuLuaLibrary : LuaLibraryBase {
{ public MemorySavestateEmuLuaLibrary(Lua lua)
public MemorySavestateEmuLuaLibrary(Lua lua) : base(lua) { }
: base(lua) { }
public MemorySavestateEmuLuaLibrary(Lua lua, Action<string> logOutputCallback)
public MemorySavestateEmuLuaLibrary(Lua lua, Action<string> logOutputCallback) : base(lua, logOutputCallback) { }
: base(lua, logOutputCallback) { }
public override string Name => "memorysavestate";
public override string Name { get { return "memorysavestate"; } }
private readonly Dictionary<Guid, byte[]> MemorySavestates = new Dictionary<Guid, byte[]>();
private readonly Dictionary<Guid, byte[]> MemorySavestates = new Dictionary<Guid, byte[]>();
[RequiredService]
[RequiredService] private IStatable _statableCore { get; set; }
private IStatable _statableCore { get; set; }
[LuaMethodAttributes(
[LuaMethodAttributes( "savecorestate",
"savecorestate", "creates a core savestate and stores it in memory. Note: a core savestate is only the raw data from the core, and not extras such as movie input logs, or framebuffers. Returns a unique identifer for the savestate"
"creates a core savestate and stores it in memory. Note: a core savestate is only the raw data from the core, and not extras such as movie input logs, or framebuffers. Returns a unique identifer for the savestate" )]
)] public string SaveCoreStateToMemory()
public string SaveCoreStateToMemory() {
{ var guid = Guid.NewGuid();
var guid = Guid.NewGuid(); var bytes = (byte[])_statableCore.SaveStateBinary().Clone();
var bytes = (byte[])_statableCore.SaveStateBinary().Clone();
MemorySavestates.Add(guid, bytes); MemorySavestates.Add(guid, bytes);
return guid.ToString(); return guid.ToString();
} }
[LuaMethodAttributes( [LuaMethodAttributes(
"loadcorestate", "loadcorestate",
"loads an in memory state with the given identifier" "loads an in memory state with the given identifier"
)] )]
public void LoadCoreStateFromMemory(string identifier) public void LoadCoreStateFromMemory(string identifier)
{ {
var guid = new Guid(identifier); var guid = new Guid(identifier);
try try
{ {
var state = MemorySavestates[guid]; var state = MemorySavestates[guid];
using (MemoryStream ms = new MemoryStream(state)) using (var ms = new MemoryStream(state))
using (BinaryReader br = new BinaryReader(ms)) using (var br = new BinaryReader(ms))
{ {
_statableCore.LoadStateBinary(br); _statableCore.LoadStateBinary(br);
} }
} }
catch catch
{ {
Log("Unable to find the given savestate in memory"); Log("Unable to find the given savestate in memory");
} }
} }
[LuaMethodAttributes( [LuaMethodAttributes(
"removestate", "removestate",
"removes the savestate with the given identifier from memory" "removes the savestate with the given identifier from memory"
)] )]
public void DeleteState(string identifier) public void DeleteState(string identifier)
{ {
var guid = new Guid(identifier); var guid = new Guid(identifier);
MemorySavestates.Remove(guid); MemorySavestates.Remove(guid);
} }
[LuaMethodAttributes( [LuaMethodAttributes(
"clearstatesfrommemory", "clearstatesfrommemory",
"clears all savestates stored in memory" "clears all savestates stored in memory"
)] )]
public void ClearInMemoryStates() public void ClearInMemoryStates()
{ {
MemorySavestates.Clear(); MemorySavestates.Clear();
} }
} }
} }

View File

@ -13,9 +13,9 @@ namespace BizHawk.Client.Common
: base(lua, logOutputCallback) { } : base(lua, logOutputCallback) { }
public override string Name { get { return "movie"; } } public override string Name => "movie";
[LuaMethodAttributes( [LuaMethodAttributes(
"startsfromsavestate", "startsfromsavestate",
"Returns whether or not the movie is a savestate-anchored movie" "Returns whether or not the movie is a savestate-anchored movie"
)] )]
@ -177,7 +177,9 @@ namespace BizHawk.Client.Common
public void Save(string filename = "") public void Save(string filename = "")
{ {
if (!Global.MovieSession.Movie.IsActive) if (!Global.MovieSession.Movie.IsActive)
{
return; return;
}
if (!string.IsNullOrEmpty(filename)) if (!string.IsNullOrEmpty(filename))
{ {
@ -185,11 +187,13 @@ namespace BizHawk.Client.Common
var test = new FileInfo(filename); var test = new FileInfo(filename);
if (test.Exists) if (test.Exists)
{ {
Log(string.Format("File {0} already exists, will not overwrite", filename)); Log($"File {filename} already exists, will not overwrite");
return; return;
} }
Global.MovieSession.Movie.Filename = filename; Global.MovieSession.Movie.Filename = filename;
} }
Global.MovieSession.Movie.Save(); Global.MovieSession.Movie.Save();
} }
@ -210,10 +214,12 @@ namespace BizHawk.Client.Common
{ {
// Lua numbers are always double, integer precision holds up // Lua numbers are always double, integer precision holds up
// to 53 bits, so throw an error if it's bigger than that. // 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."); throw new Exception("Rerecord count exceeds Lua integer precision.");
}
Global.MovieSession.Movie.Rerecords = (ulong)count; Global.MovieSession.Movie.Rerecords = (ulong)count;
} }

View File

@ -29,16 +29,16 @@ namespace BizHawk.Client.Common
[OptionalService] [OptionalService]
private IMemoryDomains _memoryDomains { get; set; } private IMemoryDomains _memoryDomains { get; set; }
private bool NESAvailable { get { return _neshawk != null || _quicknes != null; } } private bool NESAvailable => _neshawk != null || _quicknes != null;
private bool HasMemoryDOmains { get { return _memoryDomains != null; } } private bool HasMemoryDOmains => _memoryDomains != null;
public NesLuaLibrary(Lua lua, Action<string> logOutputCallback) public NesLuaLibrary(Lua lua, Action<string> logOutputCallback)
: base(lua, logOutputCallback) { } : base(lua, logOutputCallback) { }
public override string Name { get { return "nes"; } } public override string Name => "nes";
[LuaMethodAttributes( [LuaMethodAttributes(
"addgamegenie", "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" "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"
)] )]
@ -72,6 +72,7 @@ namespace BizHawk.Client.Common
{ {
return _quicknes.GetSettings().NumSprites != 8; return _quicknes.GetSettings().NumSprites != 8;
} }
if (_neshawk != null) if (_neshawk != null)
{ {
return _neshawk.GetSettings().AllowMoreThanEightSprites; return _neshawk.GetSettings().AllowMoreThanEightSprites;
@ -210,7 +211,6 @@ namespace BizHawk.Client.Common
var s = _quicknes.GetSettings(); var s = _quicknes.GetSettings();
s.NumSprites = allow ? 64 : 8; s.NumSprites = allow ? 64 : 8;
_quicknes.PutSettings(s); _quicknes.PutSettings(s);
} }
} }

View File

@ -18,9 +18,9 @@ namespace BizHawk.Client.Common
public SnesLuaLibrary(Lua lua, Action<string> logOutputCallback) public SnesLuaLibrary(Lua lua, Action<string> logOutputCallback)
: base(lua, logOutputCallback) { } : base(lua, logOutputCallback) { }
public override string Name { get { return "snes"; } } public override string Name => "snes";
private LibsnesCore.SnesSettings GetSettings() private LibsnesCore.SnesSettings GetSettings()
{ {
if (Snes != null) if (Snes != null)
{ {
@ -32,10 +32,7 @@ namespace BizHawk.Client.Common
private void PutSettings(LibsnesCore.SnesSettings settings) private void PutSettings(LibsnesCore.SnesSettings settings)
{ {
if (Snes != null) Snes?.PutSettings(settings);
{
Snes.PutSettings(settings);
}
} }
[LuaMethodAttributes( [LuaMethodAttributes(

View File

@ -9,9 +9,9 @@ namespace BizHawk.Client.Common
[Description("A library exposing standard .NET string methods")] [Description("A library exposing standard .NET string methods")]
public sealed class StringLuaLibrary : LuaLibraryBase public sealed class StringLuaLibrary : LuaLibraryBase
{ {
public override string Name { get { return "bizstring"; } } public override string Name => "bizstring";
public StringLuaLibrary(Lua lua) public StringLuaLibrary(Lua lua)
: base(lua) { } : base(lua) { }
public StringLuaLibrary(Lua lua, Action<string> logOutputCallback) public StringLuaLibrary(Lua lua, Action<string> logOutputCallback)
@ -23,7 +23,7 @@ namespace BizHawk.Client.Common
)] )]
public static string Hex(long num) public static string Hex(long num)
{ {
var hex = string.Format("{0:X}", num); var hex = $"{num:X}";
if (hex.Length == 1) if (hex.Length == 1)
{ {
hex = "0" + hex; hex = "0" + hex;

View File

@ -19,9 +19,9 @@ namespace BizHawk.Client.EmuHawk
public UserDataLibrary(Lua lua, Action<string> logOutputCallback) public UserDataLibrary(Lua lua, Action<string> logOutputCallback)
: base(lua, logOutputCallback) { } : base(lua, logOutputCallback) { }
public override string Name { get { return "userdata"; } } public override string Name => "userdata";
[LuaMethodAttributes( [LuaMethodAttributes(
"set", "set",
"adds or updates the data with the given key with the given value" "adds or updates the data with the given key with the given value"
)] )]

View File

@ -1,17 +1,13 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//TODO - kill this file (or renew the concept as distinct from the LuaSandbox?)
// TODO - kill this file (or renew the concept as distinct from the LuaSandbox?)
namespace BizHawk.Client.Common namespace BizHawk.Client.Common
{ {
public class EnvironmentSandbox public class EnvironmentSandbox
{ {
public static void Sandbox(Action callback) public static void Sandbox(Action callback)
{ {
//just a stub for right now // just a stub for right now
callback(); callback();
} }
} }

View File

@ -11,8 +11,8 @@ namespace BizHawk.Client.Common
Description = description; Description = description;
} }
public string Name { get; set; } public string Name { get; }
public string Description { get; set; } public string Description { get; }
} }
[AttributeUsage(AttributeTargets.Class)] [AttributeUsage(AttributeTargets.Class)]
@ -23,6 +23,6 @@ namespace BizHawk.Client.Common
Released = released; Released = released;
} }
public bool Released { get; set; } public bool Released { get; }
} }
} }

View File

@ -1,5 +1,4 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using System.Text; using System.Text;
@ -10,7 +9,7 @@ namespace BizHawk.Client.Common
public class LuaDocumentation : List<LibraryFunction> public class LuaDocumentation : List<LibraryFunction>
{ {
public LuaDocumentation() public LuaDocumentation()
:base() { } : base() { }
public string ToTASVideosWikiMarkup() public string ToTASVideosWikiMarkup()
{ {
@ -114,7 +113,7 @@ __Types and notation__
if (f.ParameterList.Any()) if (f.ParameterList.Any())
{ {
sb sb
.Append(string.Format("{0}.{1}(", f.Library, f.Name)); .Append($"{f.Library}.{f.Name}(");
var parameters = f.Method.GetParameters() var parameters = f.Method.GetParameters()
.ToList(); .ToList();
@ -128,7 +127,7 @@ __Types and notation__
if (parameters[i].IsOptional) if (parameters[i].IsOptional)
{ {
sb.Append(string.Format("[{0}]", parameters[i].Name)); sb.Append($"[{parameters[i].Name}]");
} }
else else
{ {
@ -147,7 +146,7 @@ __Types and notation__
} }
else else
{ {
sb.Append(string.Format("{0}.{1}()", f.Library, f.Name)); sb.Append($"{f.Library}.{f.Name}()");
} }
completion.Contents = sb.ToString(); completion.Contents = sb.ToString();
@ -178,22 +177,16 @@ __Types and notation__
LibraryDescription = libraryDescription; LibraryDescription = libraryDescription;
} }
public string Library { get; private set; } public string Library { get; }
public string LibraryDescription { get; private set; } public string LibraryDescription { get; }
public MethodInfo Method { get { return _method; } } public MethodInfo Method => _method;
public string Name public string Name => _luaAttributes.Name;
{
get { return _luaAttributes.Name; }
}
public string Description public string Description => _luaAttributes.Description;
{
get { return _luaAttributes.Description; }
}
private string _paramterList = null; private string _paramterList = null;
public string ParameterList public string ParameterList
{ {

View File

@ -30,8 +30,8 @@
public string Name { get; set; } public string Name { get; set; }
public string Path { get; set; } public string Path { get; set; }
public bool Enabled { get { return State != RunState.Disabled; } } public bool Enabled => State != RunState.Disabled;
public bool Paused { get { return State == RunState.Paused; } } public bool Paused => State == RunState.Paused;
public bool IsSeparator { get; set; } public bool IsSeparator { get; set; }
public LuaInterface.Lua Thread { get; set; } public LuaInterface.Lua Thread { get; set; }
public bool FrameWaiting { get; set; } public bool FrameWaiting { get; set; }
@ -44,12 +44,9 @@
public RunState State { get; set; } public RunState State { get; set; }
public static LuaFile SeparatorInstance public static LuaFile SeparatorInstance => new LuaFile(true);
{
get { return new LuaFile(true); }
}
public void Stop() public void Stop()
{ {
State = RunState.Disabled; State = RunState.Disabled;
Thread = null; Thread = null;
@ -75,9 +72,13 @@
public void TogglePause() public void TogglePause()
{ {
if (State == RunState.Paused) if (State == RunState.Paused)
{
State = RunState.Running; State = RunState.Running;
else if(State == RunState.Running) }
else if (State == RunState.Running)
{
State = RunState.Paused; State = RunState.Paused;
}
} }
} }
} }

View File

@ -105,10 +105,9 @@ namespace BizHawk.Client.Common
Add(new LuaFile(scriptPath) Add(new LuaFile(scriptPath)
{ {
State = ( State = !Global.Config.DisableLuaScriptsOnLoad && line.Substring(0, 1) == "1"
!Global.Config.DisableLuaScriptsOnLoad ? LuaFile.RunState.Running
&& line.Substring(0, 1) == "1" : LuaFile.RunState.Disabled
) ? LuaFile.RunState.Running : LuaFile.RunState.Disabled
}); });
} }
} }

View File

@ -1,7 +1,6 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using BizHawk.Emulation.Common;
using BizHawk.Emulation.Common.IEmulatorExtensions; using BizHawk.Emulation.Common.IEmulatorExtensions;
namespace BizHawk.Client.Common namespace BizHawk.Client.Common
@ -40,8 +39,8 @@ namespace BizHawk.Client.Common
if (Global.Emulator.MemoryCallbacksAvailable()) if (Global.Emulator.MemoryCallbacksAvailable())
{ {
var cbSys = Global.Emulator.AsDebuggable().MemoryCallbacks; var memoryCallbacks = Global.Emulator.AsDebuggable().MemoryCallbacks;
cbSys.RemoveAll(this.Select(x => x.Callback)); memoryCallbacks.RemoveAll(this.Select(x => x.Callback));
} }
Clear(); Clear();

View File

@ -1,9 +1,4 @@
using System; using LuaInterface;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LuaInterface;
using System.Reflection;
namespace BizHawk.Client.Common namespace BizHawk.Client.Common
{ {
@ -20,7 +15,7 @@ namespace BizHawk.Client.Common
{ {
if (method.IsPublic) if (method.IsPublic)
{ {
table[method.Name] = lua.RegisterFunction("", obj, method); table[method.Name] = lua.RegisterFunction(string.Empty, obj, method);
} }
} }

View File

@ -43,7 +43,10 @@ namespace BizHawk.Client.Common
lock (ThreadMutex) lock (ThreadMutex)
{ {
if (CurrentHostThread != null) if (CurrentHostThread != null)
{
throw new InvalidOperationException("Can't have lua running in two host threads at a time!"); throw new InvalidOperationException("Can't have lua running in two host threads at a time!");
}
CurrentHostThread = Thread.CurrentThread; CurrentHostThread = Thread.CurrentThread;
CurrentThread = luaThread; CurrentThread = luaThread;
} }
@ -52,10 +55,7 @@ namespace BizHawk.Client.Common
protected void Log(object message) protected void Log(object message)
{ {
if (LogOutputCallback != null) LogOutputCallback?.Invoke(message.ToString());
{
LogOutputCallback(message.ToString());
}
} }
public virtual void LuaRegister(Type callingLibrary, LuaDocumentation docs = null) public virtual void LuaRegister(Type callingLibrary, LuaDocumentation docs = null)
@ -74,10 +74,7 @@ namespace BizHawk.Client.Common
var luaName = Name + "." + luaMethodAttr.Name; var luaName = Name + "." + luaMethodAttr.Name;
Lua.RegisterFunction(luaName, this, method); Lua.RegisterFunction(luaName, this, method);
if (docs != null) docs?.Add(new LibraryFunction(Name, callingLibrary.Description(), method));
{
docs.Add(new LibraryFunction(Name, callingLibrary.Description(), method));
}
} }
} }

View File

@ -32,12 +32,10 @@ namespace BizHawk.Client.Common
{ {
return MemoryDomainCore; return MemoryDomainCore;
} }
else
{ var error = $"Error: {Emulator.Attributes().CoreName} does not implement memory domains";
var error = string.Format("Error: {0} does not implement memory domains", Emulator.Attributes().CoreName); Log(error);
Log(error); throw new NotImplementedException(error);
throw new NotImplementedException(error);
}
} }
} }
@ -47,25 +45,22 @@ namespace BizHawk.Client.Common
{ {
if (DomainList[domain] == null) if (DomainList[domain] == null)
{ {
Log(string.Format("Unable to find domain: {0}, falling back to current", domain)); Log($"Unable to find domain: {domain}, falling back to current");
return Domain.Name; return Domain.Name;
} }
else
{
return domain;
}
return domain;
} }
catch // Just in case catch // Just in case
{ {
Log(string.Format("Unable to find domain: {0}, falling back to current", domain)); Log($"Unable to find domain: {domain}, falling back to current");
} }
return Domain.Name; return Domain.Name;
} }
protected uint ReadUnsignedByte(int addr, string domain = null) protected uint ReadUnsignedByte(int addr, string domain = null)
{ {
var d = (string.IsNullOrEmpty(domain)) ? Domain : DomainList[VerifyMemoryDomain(domain)]; var d = string.IsNullOrEmpty(domain) ? Domain : DomainList[VerifyMemoryDomain(domain)];
if (addr < d.Size) if (addr < d.Size)
{ {
return d.PeekByte(addr); return d.PeekByte(addr);
@ -78,7 +73,7 @@ namespace BizHawk.Client.Common
protected void WriteUnsignedByte(int addr, uint v, string domain = null) protected void WriteUnsignedByte(int addr, uint v, string domain = null)
{ {
var d = (string.IsNullOrEmpty(domain)) ? Domain : DomainList[VerifyMemoryDomain(domain)]; var d = string.IsNullOrEmpty(domain) ? Domain : DomainList[VerifyMemoryDomain(domain)];
if (d.CanPoke()) if (d.CanPoke())
{ {
if (addr < Domain.Size) if (addr < Domain.Size)
@ -93,7 +88,7 @@ namespace BizHawk.Client.Common
} }
else else
{ {
Log(string.Format("Error: the domain {0} is not writable", d.Name)); Log($"Error: the domain {d.Name} is not writable");
} }
} }
@ -178,12 +173,12 @@ namespace BizHawk.Client.Common
protected LuaTable ReadByteRange(int addr, int length, string domain = null) protected LuaTable ReadByteRange(int addr, int length, string domain = null)
{ {
var d = (string.IsNullOrEmpty(domain)) ? Domain : DomainList[VerifyMemoryDomain(domain)]; var d = string.IsNullOrEmpty(domain) ? Domain : DomainList[VerifyMemoryDomain(domain)];
var lastAddr = length + addr; var lastAddr = length + addr;
var table = Lua.NewTable(); var table = Lua.NewTable();
if (lastAddr < d.Size) if (lastAddr < d.Size)
{ {
for (var i = 0; i <length ; i++) for (var i = 0; i < length; i++)
{ {
int a = addr + i; int a = addr + i;
var v = d.PeekByte(a); var v = d.PeekByte(a);
@ -201,7 +196,7 @@ namespace BizHawk.Client.Common
protected void WriteByteRange(LuaTable memoryblock, string domain = null) protected void WriteByteRange(LuaTable memoryblock, string domain = null)
{ {
var d = (string.IsNullOrEmpty(domain)) ? Domain : DomainList[VerifyMemoryDomain(domain)]; var d = string.IsNullOrEmpty(domain) ? Domain : DomainList[VerifyMemoryDomain(domain)];
if (d.CanPoke()) if (d.CanPoke())
{ {
foreach (var address in memoryblock.Keys) foreach (var address in memoryblock.Keys)
@ -220,31 +215,29 @@ namespace BizHawk.Client.Common
} }
else else
{ {
Log(string.Format("Error: the domain {0} is not writable", d.Name)); Log($"Error: the domain {d.Name} is not writable");
} }
} }
protected float ReadFloat(int addr, bool bigendian, string domain = null) protected float ReadFloat(int addr, bool bigendian, string domain = null)
{ {
var d = (string.IsNullOrEmpty(domain)) ? Domain : DomainList[VerifyMemoryDomain(domain)]; var d = string.IsNullOrEmpty(domain) ? Domain : DomainList[VerifyMemoryDomain(domain)];
if (addr < d.Size) if (addr < d.Size)
{ {
var val = d.PeekUint(addr, bigendian); var val = d.PeekUint(addr, bigendian);
var bytes = BitConverter.GetBytes(val); var bytes = BitConverter.GetBytes(val);
return BitConverter.ToSingle(bytes, 0); return BitConverter.ToSingle(bytes, 0);
} }
else
{ Log("Warning: Attempted read " + addr +
Log("Warning: Attempted read " + addr +
" outside memory size of " + d.Size); " outside memory size of " + d.Size);
return 0; return 0;
}
} }
protected void WriteFloat(int addr, double value, bool bigendian, string domain = null) protected void WriteFloat(int addr, double value, bool bigendian, string domain = null)
{ {
var d = (string.IsNullOrEmpty(domain)) ? Domain : DomainList[VerifyMemoryDomain(domain)]; var d = string.IsNullOrEmpty(domain) ? Domain : DomainList[VerifyMemoryDomain(domain)];
if (d.CanPoke()) if (d.CanPoke())
{ {
if (addr < d.Size) if (addr < d.Size)
@ -262,7 +255,7 @@ namespace BizHawk.Client.Common
} }
else else
{ {
Log(string.Format("Error: the domain {0} is not writable", Domain.Name)); Log($"Error: the domain {Domain.Name} is not writable");
} }
} }

View File

@ -1,24 +1,20 @@
using System; using System;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Collections.Generic; using LuaInterface;
using System.Linq;
using System.Text; // TODO - evaluate for re-entrancy problems
using LuaInterface; namespace BizHawk.Client.Common
{
//TODO - evaluate for re-entrancy problems public unsafe class LuaSandbox
{
namespace BizHawk.Client.Common
{
public unsafe class LuaSandbox
{
protected static Action<string> Logger; protected static Action<string> Logger;
static System.Runtime.CompilerServices.ConditionalWeakTable<Lua, LuaSandbox> SandboxForThread = new System.Runtime.CompilerServices.ConditionalWeakTable<Lua, LuaSandbox>(); static System.Runtime.CompilerServices.ConditionalWeakTable<Lua, LuaSandbox> SandboxForThread = new System.Runtime.CompilerServices.ConditionalWeakTable<Lua, LuaSandbox>();
public static Action<string> DefaultLogger; public static Action<string> DefaultLogger;
public void SetLogger(Action<string> logger) public void SetLogger(Action<string> logger)
{ {
Logger = logger; Logger = logger;
} }
public void SetSandboxCurrentDirectory(string dir) public void SetSandboxCurrentDirectory(string dir)
@ -39,26 +35,26 @@ namespace BizHawk.Client.Common
{ {
string target = CurrentDirectory + "\\"; 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: dont 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 // 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? // but you got any better ideas?
if (currDirSpeedHack == null) if (currDirSpeedHack == null)
currDirSpeedHack = CoolGetCurrentDirectory(); currDirSpeedHack = CoolGetCurrentDirectory();
if (currDirSpeedHack == path) if (currDirSpeedHack == path)
return true; return true;
//WARNING: setting the current directory is SLOW!!! security checks for some reason. //WARNING: setting the current directory is SLOW!!! security checks for some reason.
//so we're bypassing it with windows hacks //so we're bypassing it with windows hacks
#if WINDOWS #if WINDOWS
fixed (byte* pstr = &System.Text.Encoding.Unicode.GetBytes(target + "\0")[0]) fixed (byte* pstr = &System.Text.Encoding.Unicode.GetBytes(target + "\0")[0])
return SetCurrentDirectoryW(pstr); return SetCurrentDirectoryW(pstr);
#else #else
if(System.IO.Directory.Exists(CurrentDirectory)) //race condition for great justice if(System.IO.Directory.Exists(CurrentDirectory)) //race condition for great justice
{ {
Environment.CurrentDirectory = CurrentDirectory; //thats right, you can't set a directory as current that doesnt exist because .net's got to do SENSELESS SLOW-ASS SECURITY CHECKS on it and it can't do that on a NONEXISTENT DIRECTORY Environment.CurrentDirectory = CurrentDirectory; //thats right, you can't set a directory as current that doesnt exist because .net's got to do SENSELESS SLOW-ASS SECURITY CHECKS on it and it can't do that on a NONEXISTENT DIRECTORY
return true; return true;
} }
else return false else return false
#endif #endif
} }
@ -69,43 +65,40 @@ namespace BizHawk.Client.Common
//AS IF ASKING FOR THE CURRENT DIRECTORY IS EQUIVALENT TO TRYING TO ACCESS IT //AS IF ASKING FOR THE CURRENT DIRECTORY IS EQUIVALENT TO TRYING TO ACCESS IT
//SCREW YOU //SCREW YOU
#if WINDOWS #if WINDOWS
var buf = new byte[32768]; var buf = new byte[32768];
fixed(byte* pBuf = &buf[0]) fixed(byte* pBuf = &buf[0])
{ {
uint ret = GetCurrentDirectoryW(32767, pBuf); uint ret = GetCurrentDirectoryW(32767, pBuf);
return System.Text.Encoding.Unicode.GetString(buf, 0, (int)ret*2); return System.Text.Encoding.Unicode.GetString(buf, 0, (int)ret*2);
} }
#else #else
return Environment.CurrentDirectory; return Environment.CurrentDirectory;
#endif #endif
} }
void Sandbox(Action callback, Action exceptionCallback) void Sandbox(Action callback, Action exceptionCallback)
{ {
string savedEnvironmentCurrDir = null; string savedEnvironmentCurrDir = null;
try try
{ {
savedEnvironmentCurrDir = Environment.CurrentDirectory; savedEnvironmentCurrDir = Environment.CurrentDirectory;
if (CurrentDirectory != null) if (CurrentDirectory != null)
CoolSetCurrentDirectory(CurrentDirectory, savedEnvironmentCurrDir); CoolSetCurrentDirectory(CurrentDirectory, savedEnvironmentCurrDir);
EnvironmentSandbox.Sandbox(callback); EnvironmentSandbox.Sandbox(callback);
} }
catch (LuaException ex) catch (LuaException ex)
{ {
Console.WriteLine(ex); Console.WriteLine(ex);
Logger(ex.ToString()); Logger(ex.ToString());
if (exceptionCallback != null) exceptionCallback?.Invoke();
{ }
exceptionCallback(); finally
}
}
finally
{ {
if (CurrentDirectory != null) if (CurrentDirectory != null)
CoolSetCurrentDirectory(savedEnvironmentCurrDir); CoolSetCurrentDirectory(savedEnvironmentCurrDir);
} }
} }
public static LuaSandbox CreateSandbox(Lua thread, string initialDirectory) public static LuaSandbox CreateSandbox(Lua thread, string initialDirectory)
@ -119,8 +112,8 @@ namespace BizHawk.Client.Common
public static LuaSandbox GetSandbox(Lua thread) public static LuaSandbox GetSandbox(Lua thread)
{ {
//this is just placeholder. // this is just placeholder.
//we shouldnt be calling a sandbox with no thread--construct a sandbox properly // we shouldnt be calling a sandbox with no thread--construct a sandbox properly
if (thread == null) if (thread == null)
{ {
return new LuaSandbox(); return new LuaSandbox();
@ -133,8 +126,8 @@ namespace BizHawk.Client.Common
return sandbox; return sandbox;
else else
{ {
//for now: throw exception (I want to manually creating them) // for now: throw exception (I want to manually creating them)
//return CreateSandbox(thread); // return CreateSandbox(thread);
throw new InvalidOperationException("HOARY GORILLA HIJINX"); throw new InvalidOperationException("HOARY GORILLA HIJINX");
} }
} }
@ -143,6 +136,6 @@ namespace BizHawk.Client.Common
public static void Sandbox(Lua thread, Action callback, Action exceptionCallback = null) public static void Sandbox(Lua thread, Action callback, Action exceptionCallback = null)
{ {
GetSandbox(thread).Sandbox(callback, exceptionCallback); GetSandbox(thread).Sandbox(callback, exceptionCallback);
} }
} }
} }

View File

@ -50,7 +50,7 @@ namespace BizHawk.Client.Common
{ "A78", 59.9227510135505 }, { "A78", 59.9227510135505 },
{ "Coleco", 59.9227510135505 }, { "Coleco", 59.9227510135505 },
//according to http://problemkaputt.de/psx-spx.htm // according to http://problemkaputt.de/psx-spx.htm
{ "PSX", 44100.0*768*11/7/263/3413 }, // 59.292862562 { "PSX", 44100.0*768*11/7/263/3413 }, // 59.292862562
{ "PSX_PAL", 44100.0*768*11/7/314/3406 }, // 49.7645593576 { "PSX_PAL", 44100.0*768*11/7/314/3406 }, // 49.7645593576
@ -60,7 +60,6 @@ namespace BizHawk.Client.Common
{ "C64_DREAN", PAL_N_CARRIER*2/7/312/65 }, { "C64_DREAN", PAL_N_CARRIER*2/7/312/65 },
{ "INTV", 59.92 } { "INTV", 59.92 }
// according to ryphecha, using // according to ryphecha, using
// clocks[2] = { 53.693182e06, 53.203425e06 }; //ntsc console, pal console // clocks[2] = { 53.693182e06, 53.203425e06 }; //ntsc console, pal console
// lpf[2][2] = { { 263, 262.5 }, { 314, 312.5 } }; //ntsc,pal; noninterlaced, interlaced // lpf[2][2] = { { 263, 262.5 }, { 314, 312.5 } }; //ntsc,pal; noninterlaced, interlaced

View File

@ -30,7 +30,7 @@ namespace BizHawk.Client.Common
{ {
var groups = _logKey.Split(new[] { "#" }, StringSplitOptions.RemoveEmptyEntries); var groups = _logKey.Split(new[] { "#" }, StringSplitOptions.RemoveEmptyEntries);
var controls = groups var controls = groups
.Select(@group => @group.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries).ToList()) .Select(group => group.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries).ToList())
.ToList(); .ToList();
_type.ControlsFromLog = controls; _type.ControlsFromLog = controls;
@ -162,7 +162,7 @@ namespace BizHawk.Client.Common
if (!string.IsNullOrWhiteSpace(mnemonic)) if (!string.IsNullOrWhiteSpace(mnemonic))
{ {
var def = Global.Emulator.ControllerDefinition; var def = Global.Emulator.ControllerDefinition;
var trimmed = mnemonic.Replace("|", ""); var trimmed = mnemonic.Replace("|", string.Empty);
var buttons = Definition.ControlsOrdered.SelectMany(x => x).ToList(); var buttons = Definition.ControlsOrdered.SelectMany(x => x).ToList();
var iterator = 0; var iterator = 0;
@ -177,7 +177,7 @@ namespace BizHawk.Client.Common
{ {
var temp = trimmed.Substring(iterator, 5); var temp = trimmed.Substring(iterator, 5);
var val = int.Parse(temp.Trim()); var val = int.Parse(temp.Trim());
this.MyFloatControls[key] = val; MyFloatControls[key] = val;
iterator += 6; iterator += 6;
} }

View File

@ -9,11 +9,11 @@ namespace BizHawk.Client.Common
get get
{ {
var key = button var key = button
.Replace("P1 ", "") .Replace("P1 ", string.Empty)
.Replace("P2 ", "") .Replace("P2 ", string.Empty)
.Replace("P3 ", "") .Replace("P3 ", string.Empty)
.Replace("P4 ", "") .Replace("P4 ", string.Empty)
.Replace("Key ", ""); .Replace("Key ", string.Empty);
if (SystemOverrides.ContainsKey(Global.Emulator.SystemId) && SystemOverrides[Global.Emulator.SystemId].ContainsKey(key)) if (SystemOverrides.ContainsKey(Global.Emulator.SystemId) && SystemOverrides[Global.Emulator.SystemId].ContainsKey(key))
{ {

View File

@ -1,8 +1,8 @@
using System.Linq; using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Text;
using BizHawk.Emulation.Common; using BizHawk.Emulation.Common;
using System.Collections.Generic;
namespace BizHawk.Client.Common namespace BizHawk.Client.Common
{ {
@ -19,15 +19,9 @@ namespace BizHawk.Client.Common
_logKey = logKey; _logKey = logKey;
} }
public IMovieController MovieControllerAdapter public IMovieController MovieControllerAdapter => new Bk2ControllerAdapter(_logKey);
{
get
{
return new Bk2ControllerAdapter(_logKey);
}
}
#region ILogEntryGenerator Implementation #region ILogEntryGenerator Implementation
public void SetSource(IController source) public void SetSource(IController source)
{ {
@ -39,23 +33,11 @@ namespace BizHawk.Client.Common
return CreateLogEntry(forInputDisplay: true); return CreateLogEntry(forInputDisplay: true);
} }
public bool IsEmpty public bool IsEmpty => EmptyEntry == GenerateLogEntry();
{
get
{
return EmptyEntry == GenerateLogEntry();
}
}
public string EmptyEntry public string EmptyEntry => CreateLogEntry(createEmpty: true);
{
get
{
return CreateLogEntry(createEmpty: true);
}
}
public string GenerateLogEntry() public string GenerateLogEntry()
{ {
return CreateLogEntry(); return CreateLogEntry();
} }
@ -107,7 +89,9 @@ namespace BizHawk.Client.Common
var sb = new StringBuilder(); var sb = new StringBuilder();
if (!forInputDisplay) if (!forInputDisplay)
{
sb.Append('|'); sb.Append('|');
}
foreach (var group in _source.Definition.ControlsOrdered) foreach (var group in _source.Definition.ControlsOrdered)
{ {
@ -131,9 +115,13 @@ namespace BizHawk.Client.Common
} }
if (forInputDisplay && val == mid) if (forInputDisplay && val == mid)
{
sb.Append(" "); sb.Append(" ");
}
else else
{
sb.Append(val.ToString().PadLeft(5, ' ')).Append(','); sb.Append(val.ToString().PadLeft(5, ' ')).Append(',');
}
} }
else if (_source.Definition.BoolButtons.Contains(button)) else if (_source.Definition.BoolButtons.Contains(button))
{ {
@ -149,7 +137,9 @@ namespace BizHawk.Client.Common
} }
if (!forInputDisplay) if (!forInputDisplay)
{
sb.Append('|'); sb.Append('|');
}
} }
} }

View File

@ -8,9 +8,11 @@ namespace BizHawk.Client.Common
{ {
get get
{ {
var key = button.Replace("Key ", ""); var key = button.Replace("Key ", string.Empty);
if (key.StartsWith("P") && key.Length > 1 && key[1] >= '0' && key[1] <= '9') if (key.StartsWith("P") && key.Length > 1 && key[1] >= '0' && key[1] <= '9')
{
key = key.Substring(3); key = key.Substring(3);
}
if (SystemOverrides.ContainsKey(Global.Emulator.SystemId) && SystemOverrides[Global.Emulator.SystemId].ContainsKey(key)) if (SystemOverrides.ContainsKey(Global.Emulator.SystemId) && SystemOverrides[Global.Emulator.SystemId].ContainsKey(key))
{ {

View File

@ -8,17 +8,18 @@ namespace BizHawk.Client.Common
protected readonly Bk2Header Header = new Bk2Header(); protected readonly Bk2Header Header = new Bk2Header();
private string _syncSettingsJson = string.Empty; private string _syncSettingsJson = string.Empty;
public IDictionary<string, string> HeaderEntries public IDictionary<string, string> HeaderEntries => Header;
{
get { return Header; }
}
public SubtitleList Subtitles { get; private set; } public SubtitleList Subtitles { get; }
public IList<string> Comments { get; private set; } public IList<string> Comments { get; }
public string SyncSettingsJson public string SyncSettingsJson
{ {
get { return _syncSettingsJson; } get
{
return _syncSettingsJson;
}
set set
{ {
if (_syncSettingsJson != value) if (_syncSettingsJson != value)
@ -147,7 +148,11 @@ namespace BizHawk.Client.Common
public string Hash public string Hash
{ {
get { return Header[HeaderKeys.SHA1]; } get
{
return Header[HeaderKeys.SHA1];
}
set set
{ {
if (Header[HeaderKeys.SHA1] != value) if (Header[HeaderKeys.SHA1] != value)
@ -160,7 +165,11 @@ namespace BizHawk.Client.Common
public string Author public string Author
{ {
get { return Header[HeaderKeys.AUTHOR]; } get
{
return Header[HeaderKeys.AUTHOR];
}
set set
{ {
if (Header[HeaderKeys.AUTHOR] != value) if (Header[HeaderKeys.AUTHOR] != value)
@ -173,7 +182,11 @@ namespace BizHawk.Client.Common
public string Core public string Core
{ {
get { return Header[HeaderKeys.CORE]; } get
{
return Header[HeaderKeys.CORE];
}
set set
{ {
if (Header[HeaderKeys.CORE] != value) if (Header[HeaderKeys.CORE] != value)
@ -186,7 +199,11 @@ namespace BizHawk.Client.Common
public string BoardName public string BoardName
{ {
get { return Header[HeaderKeys.BOARDNAME]; } get
{
return Header[HeaderKeys.BOARDNAME];
}
set set
{ {
if (Header[HeaderKeys.BOARDNAME] != value) if (Header[HeaderKeys.BOARDNAME] != value)
@ -199,7 +216,11 @@ namespace BizHawk.Client.Common
public string EmulatorVersion public string EmulatorVersion
{ {
get { return Header[HeaderKeys.EMULATIONVERSION]; } get
{
return Header[HeaderKeys.EMULATIONVERSION];
}
set set
{ {
if (Header[HeaderKeys.EMULATIONVERSION] != value) if (Header[HeaderKeys.EMULATIONVERSION] != value)
@ -212,7 +233,11 @@ namespace BizHawk.Client.Common
public string FirmwareHash public string FirmwareHash
{ {
get { return Header[HeaderKeys.FIRMWARESHA1]; } get
{
return Header[HeaderKeys.FIRMWARESHA1];
}
set set
{ {
if (Header[HeaderKeys.FIRMWARESHA1] != value) if (Header[HeaderKeys.FIRMWARESHA1] != value)
@ -253,7 +278,7 @@ namespace BizHawk.Client.Common
{ {
var sb = new StringBuilder(); var sb = new StringBuilder();
foreach(var comment in Comments) foreach (var comment in Comments)
{ {
sb.AppendLine(comment); sb.AppendLine(comment);
} }

View File

@ -21,7 +21,7 @@ namespace BizHawk.Client.Common
} }
var backupName = Filename; var backupName = Filename;
backupName = backupName.Insert(Filename.LastIndexOf("."), string.Format(".{0:yyyy-MM-dd HH.mm.ss}", DateTime.Now)); backupName = backupName.Insert(Filename.LastIndexOf("."), $".{DateTime.Now:yyyy-MM-dd HH.mm.ss}");
backupName = Path.Combine(Global.Config.PathEntries["Global", "Movie backups"].Path, Path.GetFileName(backupName)); backupName = Path.Combine(Global.Config.PathEntries["Global", "Movie backups"].Path, Path.GetFileName(backupName));
var directory_info = new FileInfo(backupName).Directory; var directory_info = new FileInfo(backupName).Directory;
@ -197,6 +197,7 @@ namespace BizHawk.Client.Common
{ {
bs.PutLump(BinaryStateLump.Corestate, (BinaryWriter bw) => bw.Write(BinarySavestate)); bs.PutLump(BinaryStateLump.Corestate, (BinaryWriter bw) => bw.Write(BinarySavestate));
} }
if (SavestateFramebuffer != null) if (SavestateFramebuffer != null)
{ {
bs.PutLump(BinaryStateLump.Framebuffer, bs.PutLump(BinaryStateLump.Framebuffer,
@ -210,7 +211,9 @@ namespace BizHawk.Client.Common
} }
if (!backup) if (!backup)
{
Changes = false; Changes = false;
}
} }
protected void ClearBeforeLoad() protected void ClearBeforeLoad()

View File

@ -77,9 +77,10 @@ namespace BizHawk.Client.Common
{ {
break; break;
} }
// in BK2, this is part of the input log, and not involved with the core state at all
// accordingly, this case (for special neshawk format frame numbers) is irrelevant // in BK2, this is part of the input log, and not involved with the core state at all
// probably // accordingly, this case (for special neshawk format frame numbers) is irrelevant
// probably
else if (line.Contains("Frame 0x")) // NES stores frame count in hex, yay else if (line.Contains("Frame 0x")) // NES stores frame count in hex, yay
{ {
var strs = line.Split('x'); var strs = line.Split('x');
@ -317,7 +318,7 @@ namespace BizHawk.Client.Common
/// If the log key differs from the system's, it will be coverted /// If the log key differs from the system's, it will be coverted
/// </summary> /// </summary>
/// <param name="line">a log entry line of text from the input log</param> /// <param name="line">a log entry line of text from the input log</param>
/// /// <param name="logKey">a log entry line of text from the input log</param> /// <param name="logKey">a log entry line of text from the input log</param>
private string ConvertLogEntryFromFile(string line, string logKey) private string ConvertLogEntryFromFile(string line, string logKey)
{ {
var adapter = new Bk2LogEntryGenerator(logKey).MovieControllerAdapter; var adapter = new Bk2LogEntryGenerator(logKey).MovieControllerAdapter;

View File

@ -7,27 +7,15 @@ namespace BizHawk.Client.Common
protected enum Moviemode { Inactive, Play, Record, Finished } protected enum Moviemode { Inactive, Play, Record, Finished }
protected Moviemode _mode = Moviemode.Inactive; protected Moviemode _mode = Moviemode.Inactive;
public bool IsActive public bool IsActive => _mode != Moviemode.Inactive;
{
get { return _mode != Moviemode.Inactive; }
}
public bool IsPlaying public bool IsPlaying => _mode == Moviemode.Play || _mode == Moviemode.Finished;
{
get { return _mode == Moviemode.Play || _mode == Moviemode.Finished; }
}
public bool IsRecording public bool IsRecording => _mode == Moviemode.Record;
{
get { return _mode == Moviemode.Record; }
}
public bool IsFinished public bool IsFinished => _mode == Moviemode.Finished;
{
get { return _mode == Moviemode.Finished; }
}
public virtual void StartNewRecording() public virtual void StartNewRecording()
{ {
_mode = Moviemode.Record; _mode = Moviemode.Record;
if (Global.Config.EnableBackupMovies && MakeBackup && _log.Any()) if (Global.Config.EnableBackupMovies && MakeBackup && _log.Any())

View File

@ -46,8 +46,9 @@ namespace BizHawk.Client.Common
public string Name { get; private set; } public string Name { get; private set; }
public virtual string PreferredExtension { get { return Extension; } } public virtual string PreferredExtension => Extension;
public const string Extension = "bk2";
public const string Extension = "bk2";
public virtual bool Changes { get; protected set; } public virtual bool Changes { get; protected set; }
public bool IsCountingRerecords { get; set; } public bool IsCountingRerecords { get; set; }
@ -70,12 +71,9 @@ namespace BizHawk.Client.Common
} }
} }
public int InputLogLength public int InputLogLength => _log.Count;
{
get { return _log.Count; }
}
#region Log Editing #region Log Editing
public void AppendFrame(IController source) public void AppendFrame(IController source)
{ {
@ -112,8 +110,6 @@ namespace BizHawk.Client.Common
{ {
_log.RemoveRange(frame, _log.Count - frame); _log.RemoveRange(frame, _log.Count - frame);
Changes = true; Changes = true;
} }
} }
} }
@ -122,7 +118,6 @@ namespace BizHawk.Client.Common
{ {
if (frame < FrameCount && frame >= 0) if (frame < FrameCount && frame >= 0)
{ {
int getframe; int getframe;
if (LoopOffset.HasValue) if (LoopOffset.HasValue)

View File

@ -1,210 +1,225 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization; using System.IO;
using System.IO;
using System.Linq; using BizHawk.Common;
using System.Text;
namespace BizHawk.Client.Common
using BizHawk.Common; {
public static class StringLogUtil
namespace BizHawk.Client.Common {
{
public static class StringLogUtil
{
public static bool DefaultToDisk; public static bool DefaultToDisk;
public static bool DefaultToAWE; public static bool DefaultToAWE;
public static IStringLog MakeStringLog() public static IStringLog MakeStringLog()
{ {
if (DefaultToDisk) if (DefaultToDisk)
return new StreamStringLog(true); {
else if(DefaultToAWE) return new StreamStringLog(true);
return new StreamStringLog(false); }
else return new ListStringLog();
} if (DefaultToAWE)
} {
return new StreamStringLog(false);
public interface IStringLog : IDisposable, IEnumerable<string> }
{
void RemoveAt(int index); return new ListStringLog();
int Count { get; } }
void Clear(); }
void Add(string str);
string this[int index] { get; set; } public interface IStringLog : IDisposable, IEnumerable<string>
void Insert(int index, string val); {
void InsertRange(int index, IEnumerable<string> collection); void RemoveAt(int index);
void AddRange(IEnumerable<string> collection); int Count { get; }
void RemoveRange(int index, int count); void Clear();
IStringLog Clone(); void Add(string str);
void CopyTo(string[] array); string this[int index] { get; set; }
void CopyTo(int index, string[] array, int arrayIndex, int count); void Insert(int index, string val);
} void InsertRange(int index, IEnumerable<string> collection);
void AddRange(IEnumerable<string> collection);
class ListStringLog : List<string>, IStringLog void RemoveRange(int index, int count);
{ IStringLog Clone();
public IStringLog Clone() void CopyTo(string[] array);
{ void CopyTo(int index, string[] array, int arrayIndex, int count);
ListStringLog ret = new ListStringLog(); }
ret.AddRange(this);
return ret; class ListStringLog : List<string>, IStringLog
} {
public IStringLog Clone()
public void Dispose() { } {
} ListStringLog ret = new ListStringLog();
ret.AddRange(this);
/// <summary> return ret;
/// A dumb-ish IStringLog with storage on disk with no provision for recovering lost space, except upon Clear() }
/// The purpose here is to avoid having too complicated buggy logic or a dependency on sqlite or such.
/// It should be faster than those alternatives, but wasteful of disk space. public void Dispose() { }
/// It should also be easier to add new IList<string>-like methods than dealing with a database }
/// </summary>
class StreamStringLog : IStringLog /// <summary>
{ /// A dumb-ish IStringLog with storage on disk with no provision for recovering lost space, except upon Clear()
List<long> Offsets = new List<long>(); /// The purpose here is to avoid having too complicated buggy logic or a dependency on sqlite or such.
long cursor = 0; /// It should be faster than those alternatives, but wasteful of disk space.
BinaryWriter bw; /// It should also be easier to add new IList<string>-like methods than dealing with a database
/// </summary>
class StreamStringLog : IStringLog
{
List<long> Offsets = new List<long>();
long cursor = 0;
BinaryWriter bw;
BinaryReader br; BinaryReader br;
bool mDisk; bool mDisk;
Stream stream; Stream stream;
public StreamStringLog(bool disk) public StreamStringLog(bool disk)
{
mDisk = disk;
if (disk)
{
var path = TempFileCleaner.GetTempFilename("movieOnDisk");
stream = new FileStream(path, FileMode.Create, System.Security.AccessControl.FileSystemRights.FullControl, FileShare.None, 4 * 1024, FileOptions.DeleteOnClose);
}
else
{
stream = new AWEMemoryStream();
}
bw = new BinaryWriter(stream);
br = new BinaryReader(stream);
}
public IStringLog Clone()
{ {
StreamStringLog ret = new StreamStringLog(mDisk); //doesnt necessarily make sense to copy the mDisk value, they could be designated for different targets... mDisk = disk;
for (int i = 0; i < Count; i++) if (disk)
ret.Add(this[i]); {
return ret; var path = TempFileCleaner.GetTempFilename("movieOnDisk");
} stream = new FileStream(path, FileMode.Create, System.Security.AccessControl.FileSystemRights.FullControl, FileShare.None, 4 * 1024, FileOptions.DeleteOnClose);
}
public void Dispose() else
{ {
stream.Dispose(); stream = new AWEMemoryStream();
} }
public int Count { get { return Offsets.Count; } } bw = new BinaryWriter(stream);
br = new BinaryReader(stream);
public void Clear() }
{
stream.SetLength(0); public IStringLog Clone()
Offsets.Clear();
cursor = 0;
}
public void Add(string str)
{ {
stream.Position = stream.Length; StreamStringLog ret = new StreamStringLog(mDisk); // doesnt necessarily make sense to copy the mDisk value, they could be designated for different targets...
Offsets.Add(stream.Position); for (int i = 0; i < Count; i++)
bw.Write(str); {
bw.Flush(); ret.Add(this[i]);
} }
public void RemoveAt(int index) return ret;
{ }
Offsets.RemoveAt(index);
//no garbage collection in the disk file... oh well. public void Dispose()
}
public string this[int index]
{
get
{
stream.Position = Offsets[index];
return br.ReadString();
}
set
{
stream.Position = stream.Length;
Offsets[index] = stream.Position;
bw.Write(value);
bw.Flush();
}
}
public void Insert(int index, string val)
{ {
stream.Position = stream.Length; stream.Dispose();
Offsets.Insert(index, stream.Position); }
bw.Write(val);
bw.Flush(); public int Count => Offsets.Count;
}
public void Clear()
public void InsertRange(int index, IEnumerable<string> collection) {
{ stream.SetLength(0);
foreach(var item in collection) Offsets.Clear();
Insert(index++,item); cursor = 0;
} }
public void AddRange(IEnumerable<string> collection) public void Add(string str)
{ {
foreach (var item in collection) stream.Position = stream.Length;
Add(item); Offsets.Add(stream.Position);
} bw.Write(str);
bw.Flush();
class Enumerator : IEnumerator<string> }
{
public StreamStringLog log; public void RemoveAt(int index)
int index = -1; {
public string Current { get { return log[index]; } } // no garbage collection in the disk file... oh well.
object System.Collections.IEnumerator.Current { get { return log[index]; } } Offsets.RemoveAt(index);
bool System.Collections.IEnumerator.MoveNext() }
{
index++; public string this[int index]
if (index >= log.Count) {
{ get
index = log.Count; {
return false; stream.Position = Offsets[index];
} return br.ReadString();
return true; }
} set
void System.Collections.IEnumerator.Reset() { index = -1; } {
stream.Position = stream.Length;
public void Dispose() { } Offsets[index] = stream.Position;
} bw.Write(value);
bw.Flush();
IEnumerator<string> IEnumerable<string>.GetEnumerator() }
{ }
return new Enumerator() { log = this };
} public void Insert(int index, string val)
{
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() stream.Position = stream.Length;
{ Offsets.Insert(index, stream.Position);
return new Enumerator() { log = this }; bw.Write(val);
} bw.Flush();
}
public void RemoveRange(int index, int count)
{ public void InsertRange(int index, IEnumerable<string> collection)
int end = index + count - 1; {
for (int i = 0; i < count; i++) foreach (var item in collection)
{ {
RemoveAt(end); Insert(index++,item);
end--; }
} }
}
public void AddRange(IEnumerable<string> collection)
public void CopyTo(string[] array) {
{ foreach (var item in collection)
for (int i = 0; i < Count; i++) {
array[i] = this[i]; Add(item);
} }
}
public void CopyTo(int index, string[] array, int arrayIndex, int count)
{ class Enumerator : IEnumerator<string>
for (int i = 0; i < count; i++) {
array[i + arrayIndex] = this[index + i]; public StreamStringLog log;
} int index = -1;
} public string Current { get { return log[index]; } }
} object System.Collections.IEnumerator.Current { get { return log[index]; } }
bool System.Collections.IEnumerator.MoveNext()
{
index++;
if (index >= log.Count)
{
index = log.Count;
return false;
}
return true;
}
void System.Collections.IEnumerator.Reset() { index = -1; }
public void Dispose() { }
}
IEnumerator<string> IEnumerable<string>.GetEnumerator()
{
return new Enumerator { log = this };
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new Enumerator { log = this };
}
public void RemoveRange(int index, int count)
{
int end = index + count - 1;
for (int i = 0; i < count; i++)
{
RemoveAt(end);
end--;
}
}
public void CopyTo(string[] array)
{
for (int i = 0; i < Count; i++)
{
array[i] = this[i];
}
}
public void CopyTo(int index, string[] array, int arrayIndex, int count)
{
for (int i = 0; i < count; i++)
{
array[i + arrayIndex] = this[index + i];
}
}
}
}

View File

@ -236,7 +236,7 @@ namespace BizHawk.Client.Common
{ {
return; return;
} }
string prefix = ""; string prefix = string.Empty;
if (ControlType != "Gameboy Controller" && ControlType != "TI83 Controller") if (ControlType != "Gameboy Controller" && ControlType != "TI83 Controller")
{ {
prefix = "P" + player + " "; prefix = "P" + player + " ";
@ -277,9 +277,9 @@ namespace BizHawk.Client.Common
MyFloatControls[name] = state; MyFloatControls[name] = state;
} }
private string ControlType { get { return Definition.Name; } } private string ControlType => Definition.Name;
private void SetGBAControllersAsMnemonic(string mnemonic) private void SetGBAControllersAsMnemonic(string mnemonic)
{ {
MnemonicChecker c = new MnemonicChecker(mnemonic); MnemonicChecker c = new MnemonicChecker(mnemonic);
MyBoolButtons.Clear(); MyBoolButtons.Clear();

View File

@ -17,8 +17,8 @@ namespace BizHawk.Client.Common
this[HeaderKeys.RERECORDS] = "0"; this[HeaderKeys.RERECORDS] = "0";
} }
public List<string> Comments { get; private set; } public List<string> Comments { get; }
public SubtitleList Subtitles { get; private set; } public SubtitleList Subtitles { get; }
public string SavestateBinaryBase64Blob public string SavestateBinaryBase64Blob
{ {

View File

@ -163,7 +163,7 @@ namespace BizHawk.Client.Common
for (int player = 1; player <= BkmMnemonicConstants.PLAYERS[_controlType]; player++) for (int player = 1; player <= BkmMnemonicConstants.PLAYERS[_controlType]; player++)
{ {
var prefix = String.Empty; var prefix = string.Empty;
if (_controlType != "Gameboy Controller" && _controlType != "TI83 Controller") if (_controlType != "Gameboy Controller" && _controlType != "TI83 Controller")
{ {
prefix = "P" + player + " "; prefix = "P" + player + " ";
@ -199,19 +199,13 @@ namespace BizHawk.Client.Common
{ {
return GenerateLogEntry() return GenerateLogEntry()
.Replace(".", " ") .Replace(".", " ")
.Replace("|", "") .Replace("|", string.Empty)
.Replace(" 000, 000", " "); .Replace(" 000, 000", " ");
} }
public bool IsEmpty public bool IsEmpty => EmptyEntry == GenerateLogEntry();
{
get
{
return EmptyEntry == GenerateLogEntry();
}
}
public string EmptyEntry public string EmptyEntry
{ {
get get
{ {
@ -260,15 +254,9 @@ namespace BizHawk.Client.Common
} }
} }
public IMovieController MovieControllerAdapter public IMovieController MovieControllerAdapter => new BkmControllerAdapter();
{
get
{
return new BkmControllerAdapter();
}
}
#region Privates #region Privates
private bool IsBasePressed(string name) private bool IsBasePressed(string name)
{ {
@ -511,7 +499,7 @@ namespace BizHawk.Client.Common
input.Append(' '); input.Append(' ');
} }
input.Append(String.Format("{0:000}", val)).Append(','); input.Append($"{val:000}").Append(',');
} }
input.Remove(input.Length - 1, 1); input.Remove(input.Length - 1, 1);

View File

@ -10,7 +10,7 @@ namespace BizHawk.Client.Common
{ {
"Gameboy Controller", new Dictionary<string, string> "Gameboy Controller", new Dictionary<string, string>
{ {
{"Up", "U"}, {"Down", "D"}, {"Left", "L"}, {"Right", "R"}, {"Select", "s"}, {"Start", "S"}, {"B", "B"}, {"A", "A"} { "Up", "U" }, { "Down", "D" }, { "Left", "L" }, { "Right", "R" }, { "Select", "s" }, { "Start", "S" }, { "B", "B" }, { "A", "A" }
} }
}, },
{ {

View File

@ -4,25 +4,13 @@ namespace BizHawk.Client.Common
{ {
public partial class BkmMovie public partial class BkmMovie
{ {
public IDictionary<string, string> HeaderEntries public IDictionary<string, string> HeaderEntries => Header;
{
get
{
return Header;
}
}
public SubtitleList Subtitles
{
get { return Header.Subtitles; }
}
public IList<string> Comments public SubtitleList Subtitles => Header.Subtitles;
{
get { return Header.Comments; }
}
public string SyncSettingsJson public IList<string> Comments => Header.Comments;
public string SyncSettingsJson
{ {
get { return Header[HeaderKeys.SYNCSETTINGS]; } get { return Header[HeaderKeys.SYNCSETTINGS]; }
set { Header[HeaderKeys.SYNCSETTINGS] = value; } set { Header[HeaderKeys.SYNCSETTINGS] = value; }
@ -41,7 +29,10 @@ namespace BizHawk.Client.Common
} }
// Bkm doesn't support saveram anchored movies // Bkm doesn't support saveram anchored movies
public bool StartsFromSaveRam { get { return false; } set { } } public bool StartsFromSaveRam
{
get { return false; } set { }
}
public string GameName public string GameName
{ {

View File

@ -46,7 +46,7 @@ namespace BizHawk.Client.Common
} }
var backupName = Filename; var backupName = Filename;
backupName = backupName.Insert(Filename.LastIndexOf("."), string.Format(".{0:yyyy-MM-dd HH.mm.ss}", DateTime.Now)); backupName = backupName.Insert(Filename.LastIndexOf("."), $".{DateTime.Now:yyyy-MM-dd HH.mm.ss}");
backupName = Path.Combine(Global.Config.PathEntries["Global", "Movie backups"].Path, Path.GetFileName(backupName)); backupName = Path.Combine(Global.Config.PathEntries["Global", "Movie backups"].Path, Path.GetFileName(backupName));
var directory_info = new FileInfo(backupName).Directory; var directory_info = new FileInfo(backupName).Directory;
@ -107,8 +107,11 @@ namespace BizHawk.Client.Common
} }
} }
} }
if (Header.SavestateBinaryBase64Blob != null) if (Header.SavestateBinaryBase64Blob != null)
{
BinarySavestate = Convert.FromBase64String(Header.SavestateBinaryBase64Blob); BinarySavestate = Convert.FromBase64String(Header.SavestateBinaryBase64Blob);
}
Loaded = true; Loaded = true;
_changes = false; _changes = false;
@ -138,9 +141,9 @@ namespace BizHawk.Client.Common
// No using block because we're sharing the stream and need to give it back undisposed. // No using block because we're sharing the stream and need to give it back undisposed.
var sr = new StreamReader(hawkFile.GetStream()); var sr = new StreamReader(hawkFile.GetStream());
for (; ; ) for (;;)
{ {
//read to first space (key/value delimeter), or pipe, or EOF // read to first space (key/value delimeter), or pipe, or EOF
int first = sr.Read(); int first = sr.Read();
if (first == -1) if (first == -1)
@ -148,16 +151,16 @@ namespace BizHawk.Client.Common
break; break;
} // EOF } // EOF
if (first == '|') //pipe: begin input log if (first == '|') // pipe: begin input log
{ {
//NOTE - this code is a bit convoluted due to its predating the basic outline of the parser which was upgraded in may 2014 // NOTE - this code is a bit convoluted due to its predating the basic outline of the parser which was upgraded in may 2014
var line = '|' + sr.ReadLine(); var line = '|' + sr.ReadLine();
//how many bytes are left, total? // how many bytes are left, total?
long remain = sr.BaseStream.Length - sr.BaseStream.Position; long remain = sr.BaseStream.Length - sr.BaseStream.Position;
//try to find out whether we use \r\n or \n // try to find out whether we use \r\n or \n
//but only look for 1K characters. // but only look for 1K characters.
bool usesR = false; bool usesR = false;
for (int i = 0; i < 1024; i++) for (int i = 0; i < 1024; i++)
{ {
@ -173,19 +176,22 @@ namespace BizHawk.Client.Common
break; break;
} }
int lineLen = line.Length + 1; //account for \n int lineLen = line.Length + 1; // account for \n
if (usesR) lineLen++; //account for \r if (usesR)
{
lineLen++; // account for \r
}
_preloadFramecount = (int)(remain / lineLen); //length is remaining bytes / length per line _preloadFramecount = (int)(remain / lineLen); // length is remaining bytes / length per line
_preloadFramecount++; //account for the current line _preloadFramecount++; // account for the current line
break; break;
} }
else else
{ {
//a header line. finish reading key token, to make sure it isn't one of the FORBIDDEN keys // a header line. finish reading key token, to make sure it isn't one of the FORBIDDEN keys
var sbLine = new StringBuilder(); var sbLine = new StringBuilder();
sbLine.Append((char)first); sbLine.Append((char)first);
for (; ; ) for (;;)
{ {
int c = sr.Read(); int c = sr.Read();
if (c == -1) break; if (c == -1) break;
@ -196,21 +202,22 @@ namespace BizHawk.Client.Common
var line = sbLine.ToString(); var line = sbLine.ToString();
//ignore these suckers, theyre way too big for preloading. seriously, we will get out of memory errors. // ignore these suckers, theyre way too big for preloading. seriously, we will get out of memory errors.
var skip = line == HeaderKeys.SAVESTATEBINARYBASE64BLOB; var skip = line == HeaderKeys.SAVESTATEBINARYBASE64BLOB;
if (skip) if (skip)
{ {
//skip remainder of the line // skip remainder of the line
sr.DiscardBufferedData(); sr.DiscardBufferedData();
var stream = sr.BaseStream; var stream = sr.BaseStream;
for (; ; ) for (;;)
{ {
int c = stream.ReadByte(); int c = stream.ReadByte();
if (c == -1) break; if (c == -1) break;
if (c == '\n') break; if (c == '\n') break;
} }
//proceed to next line
// proceed to next line
continue; continue;
} }
@ -236,10 +243,9 @@ namespace BizHawk.Client.Common
private void Write(string fn) private void Write(string fn)
{ {
if (BinarySavestate != null) Header.SavestateBinaryBase64Blob = BinarySavestate != null
Header.SavestateBinaryBase64Blob = Convert.ToBase64String(BinarySavestate); ? Convert.ToBase64String(BinarySavestate)
else : null;
Header.SavestateBinaryBase64Blob = null;
using (var fs = new FileStream(fn, FileMode.Create, FileAccess.Write, FileShare.Read)) using (var fs = new FileStream(fn, FileMode.Create, FileAccess.Write, FileShare.Read))
{ {

View File

@ -8,27 +8,15 @@ namespace BizHawk.Client.Common
private Moviemode _mode = Moviemode.Inactive; private Moviemode _mode = Moviemode.Inactive;
public bool IsPlaying public bool IsPlaying => _mode == Moviemode.Play || _mode == Moviemode.Finished;
{
get { return _mode == Moviemode.Play || _mode == Moviemode.Finished; }
}
public bool IsRecording public bool IsRecording => _mode == Moviemode.Record;
{
get { return _mode == Moviemode.Record; }
}
public bool IsActive public bool IsActive => _mode != Moviemode.Inactive;
{
get { return _mode != Moviemode.Inactive; }
}
public bool IsFinished public bool IsFinished => _mode == Moviemode.Finished;
{
get { return _mode == Moviemode.Finished; }
}
public void StartNewRecording() public void StartNewRecording()
{ {
_mode = Moviemode.Record; _mode = Moviemode.Record;
if (Global.Config.EnableBackupMovies && _makeBackup && _log.Any()) if (Global.Config.EnableBackupMovies && _makeBackup && _log.Any())

View File

@ -18,8 +18,7 @@ namespace BizHawk.Client.Common
public BkmMovie() public BkmMovie()
{ {
Header = new BkmHeader(); Header = new BkmHeader { [HeaderKeys.MOVIEVERSION] = "BizHawk v0.0.1" };
Header[HeaderKeys.MOVIEVERSION] = "BizHawk v0.0.1";
Filename = string.Empty; Filename = string.Empty;
_preloadFramecount = 0; _preloadFramecount = 0;
@ -35,20 +34,18 @@ namespace BizHawk.Client.Common
return new BkmLogEntryGenerator(); return new BkmLogEntryGenerator();
} }
public string PreferredExtension { get { return Extension; } } public string PreferredExtension => Extension;
public const string Extension = "bkm";
public BkmHeader Header { get; private set; } public const string Extension = "bkm";
public BkmHeader Header { get; }
public string Filename { get; set; } public string Filename { get; set; }
public bool IsCountingRerecords { get; set; } public bool IsCountingRerecords { get; set; }
public bool Loaded { get; private set; } public bool Loaded { get; private set; }
public int InputLogLength public int InputLogLength => _log.Count;
{
get { return _log.Count; }
}
public double FrameCount public double FrameCount
{ {
get get
{ {
@ -66,10 +63,7 @@ namespace BizHawk.Client.Common
} }
} }
public bool Changes public bool Changes => _changes;
{
get { return _changes; }
}
#endregion #endregion
@ -79,7 +73,6 @@ namespace BizHawk.Client.Common
{ {
if (frame < FrameCount && frame >= 0) if (frame < FrameCount && frame >= 0)
{ {
int getframe; int getframe;
if (_loopOffset.HasValue) if (_loopOffset.HasValue)

View File

@ -115,7 +115,9 @@ namespace BizHawk.Client.Common.MovieConversionExtensions
bk2.SaveRam = old.SaveRam; bk2.SaveRam = old.SaveRam;
if (!backup) if (!backup)
{
bk2.Save(); bk2.Save();
}
return bk2; return bk2;
} }
@ -142,7 +144,7 @@ namespace BizHawk.Client.Common.MovieConversionExtensions
} }
} }
TasMovie tas = new TasMovie(newFilename, true); var tas = new TasMovie(newFilename, true);
tas.BinarySavestate = savestate; tas.BinarySavestate = savestate;
tas.ClearLagLog(); tas.ClearLagLog();
@ -185,7 +187,9 @@ namespace BizHawk.Client.Common.MovieConversionExtensions
foreach (TasMovieMarker marker in old.Markers) foreach (TasMovieMarker marker in old.Markers)
{ {
if (marker.Frame > frame) if (marker.Frame > frame)
{
tas.Markers.Add(new TasMovieMarker(marker.Frame - frame, marker.Message)); tas.Markers.Add(new TasMovieMarker(marker.Frame - frame, marker.Message));
}
} }
tas.TasStateManager.Settings = old.TasStateManager.Settings; tas.TasStateManager.Settings = old.TasStateManager.Settings;
@ -216,7 +220,7 @@ namespace BizHawk.Client.Common.MovieConversionExtensions
} }
} }
TasMovie tas = new TasMovie(newFilename, true); var tas = new TasMovie(newFilename, true);
tas.SaveRam = saveRam; tas.SaveRam = saveRam;
tas.TasStateManager.Clear(); tas.TasStateManager.Clear();
tas.ClearLagLog(); tas.ClearLagLog();

View File

@ -2,10 +2,10 @@
{ {
public enum ToolFormUpdateType public enum ToolFormUpdateType
{ {
//reserved // reserved
Legacy, LegacyFast, Legacy, LegacyFast,
//reserved concept: we can run other events through here (should probably rename then) // reserved concept: we can run other events through here (should probably rename then)
Reset, Reset,
/// <summary> /// <summary>
@ -60,7 +60,7 @@
/// </summary> /// </summary>
bool UpdateBefore { get; } bool UpdateBefore { get; }
//Necessary winform calls // Necessary winform calls
bool Focus(); bool Focus();
bool ContainsFocus { get; } bool ContainsFocus { get; }
void Show(); void Show();
@ -69,4 +69,3 @@
bool IsHandleCreated { get; } bool IsHandleCreated { get; }
} }
} }

View File

@ -16,9 +16,27 @@
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=StyleCop_002ESA1201/@EntryIndexedValue">DO_NOT_SHOW</s:String> <s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=StyleCop_002ESA1201/@EntryIndexedValue">DO_NOT_SHOW</s:String>
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=StyleCop_002ESA1202/@EntryIndexedValue">DO_NOT_SHOW</s:String> <s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=StyleCop_002ESA1202/@EntryIndexedValue">DO_NOT_SHOW</s:String>
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=StyleCop_002ESA1210/@EntryIndexedValue">DO_NOT_SHOW</s:String> <s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=StyleCop_002ESA1210/@EntryIndexedValue">DO_NOT_SHOW</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=AF/@EntryIndexedValue">AF</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=ARGB/@EntryIndexedValue">ARGB</s:String> <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=ARGB/@EntryIndexedValue">ARGB</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=BMP/@EntryIndexedValue">BMP</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=CDL/@EntryIndexedValue">CDL</s:String> <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=CDL/@EntryIndexedValue">CDL</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=CGB/@EntryIndexedValue">CGB</s:String> <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=CGB/@EntryIndexedValue">CGB</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=DB/@EntryIndexedValue">DB</s:String> <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=DB/@EntryIndexedValue">DB</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=IO/@EntryIndexedValue">IO</s:String></wpf:ResourceDictionary> <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=GB/@EntryIndexedValue">GB</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=GBA/@EntryIndexedValue">GBA</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=GBC/@EntryIndexedValue">GBC</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=GG/@EntryIndexedValue">GG</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=II/@EntryIndexedValue">II</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=IO/@EntryIndexedValue">IO</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=IPS/@EntryIndexedValue">IPS</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=NES/@EntryIndexedValue">NES</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=OR/@EntryIndexedValue">OR</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=PC/@EntryIndexedValue">PC</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=PCECD/@EntryIndexedValue">PCECD</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=PSP/@EntryIndexedValue">PSP</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=PSX/@EntryIndexedValue">PSX</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=SG/@EntryIndexedValue">SG</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=SGX/@EntryIndexedValue">SGX</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=SNES/@EntryIndexedValue">SNES</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=TI/@EntryIndexedValue">TI</s:String></wpf:ResourceDictionary>