A round of code cleanup

This commit is contained in:
adelikat 2014-01-08 03:53:53 +00:00
parent 144a07f088
commit 2f28317f92
12 changed files with 313 additions and 248 deletions

View File

@ -6,7 +6,6 @@ using ICSharpCode.SharpZipLib.Zip;
namespace BizHawk.Client.Common
{
public class BinaryStateFileNames
{
/*
@ -31,10 +30,12 @@ namespace BizHawk.Client.Common
LumpNames[BinaryStateLump.Movieheader] = "Header";
}
public static string Get(BinaryStateLump Lump) { return LumpNames[Lump]; }
public static string Get(BinaryStateLump lump)
{
return LumpNames[lump];
}
}
public enum BinaryStateLump
{
Versiontag,
@ -43,14 +44,13 @@ namespace BizHawk.Client.Common
Input,
CorestateText,
Movieheader
};
}
/// <summary>
/// more accurately should be called ZipStateLoader, as it supports both text and binary core data
/// </summary>
public class BinaryStateLoader : IDisposable
{
private bool _isDisposed;
public void Dispose()
{
@ -66,13 +66,13 @@ namespace BizHawk.Client.Common
if (disposing)
{
zip.Close();
_zip.Close();
}
}
}
private ZipFile zip;
private Version ver;
private ZipFile _zip;
private Version _ver;
private BinaryStateLoader()
{
@ -83,28 +83,29 @@ namespace BizHawk.Client.Common
// the "BizState 1.0" tag contains an integer in it describing the sub version.
if (s.Length == 0)
{
ver = new Version(1, 0, 0); // except for the first release, which doesn't
_ver = new Version(1, 0, 0); // except for the first release, which doesn't
}
else
{
var sr = new StreamReader(s);
ver = new Version(1, 0, int.Parse(sr.ReadLine()));
_ver = new Version(1, 0, int.Parse(sr.ReadLine()));
}
Console.WriteLine("Read a zipstate of version {0}", ver.ToString());
Console.WriteLine("Read a zipstate of version {0}", _ver);
}
public static BinaryStateLoader LoadAndDetect(string Filename)
public static BinaryStateLoader LoadAndDetect(string filename)
{
var ret = new BinaryStateLoader();
// PORTABLE TODO - SKIP THIS.. FOR NOW
// check whether its an archive before we try opening it
int offset;
bool isExecutable;
bool isArchive;
using (var archiveChecker = new SevenZipSharpArchiveHandler())
{
isArchive = archiveChecker.CheckSignature(Filename, out offset, out isExecutable);
int offset;
bool isExecutable;
isArchive = archiveChecker.CheckSignature(filename, out offset, out isExecutable);
}
if (!isArchive)
@ -114,10 +115,10 @@ namespace BizHawk.Client.Common
try
{
ret.zip = new ZipFile(Filename);
ret._zip = new ZipFile(filename);
if (!ret.GetLump(BinaryStateLump.Versiontag, false, ret.ReadVersion))
{
ret.zip.Close();
ret._zip.Close();
return null;
}
@ -132,20 +133,21 @@ namespace BizHawk.Client.Common
/// <summary>
/// Gets a lump
/// </summary>
/// <param name="Lump">lump to retriever</param>
/// <param name="lump">lump to retriever</param>
/// <param name="abort">true to throw exception on failure</param>
/// <param name="callback">function to call with the desired stream</param>
/// <returns>true if callback was called and stream was loaded</returns>
public bool GetLump(BinaryStateLump Lump, bool abort, Action<Stream> callback)
public bool GetLump(BinaryStateLump lump, bool abort, Action<Stream> callback)
{
string Name = BinaryStateFileNames.Get(Lump);
var e = zip.GetEntry(Name);
string Name = BinaryStateFileNames.Get(lump);
var e = _zip.GetEntry(Name);
if (e != null)
{
using (var zs = zip.GetInputStream(e))
using (var zs = _zip.GetInputStream(e))
{
callback(zs);
}
return true;
}
else if (abort)
@ -158,20 +160,20 @@ namespace BizHawk.Client.Common
}
}
public bool GetLump(BinaryStateLump Lump, bool abort, Action<BinaryReader> callback)
public bool GetLump(BinaryStateLump lump, bool abort, Action<BinaryReader> callback)
{
return GetLump(Lump, abort, delegate(Stream s)
return GetLump(lump, abort, delegate(Stream s)
{
BinaryReader br = new BinaryReader(s);
var br = new BinaryReader(s);
callback(br);
});
}
public bool GetLump(BinaryStateLump Lump, bool abort, Action<TextReader> callback)
public bool GetLump(BinaryStateLump lump, bool abort, Action<TextReader> callback)
{
return GetLump(Lump, abort, delegate(Stream s)
return GetLump(lump, abort, delegate(Stream s)
{
TextReader tr = new StreamReader(s);
var tr = new StreamReader(s);
callback(tr);
});
}
@ -182,15 +184,19 @@ namespace BizHawk.Client.Common
public void GetCoreState(Action<Stream> callbackBinary, Action<Stream> callbackText)
{
if (!GetLump(BinaryStateLump.Corestate, false, callbackBinary)
&& !GetLump(BinaryStateLump.CorestateText, false, callbackText))
&& !GetLump(BinaryStateLump.CorestateText, false, callbackText))
{
throw new Exception("Couldn't find Binary or Text savestate");
}
}
public void GetCoreState(Action<BinaryReader> callbackBinary, Action<TextReader> callbackText)
{
if (!GetLump(BinaryStateLump.Corestate, false, callbackBinary)
&& !GetLump(BinaryStateLump.CorestateText, false, callbackText))
&& !GetLump(BinaryStateLump.CorestateText, false, callbackText))
{
throw new Exception("Couldn't find Binary or Text savestate");
}
}
/*
@ -215,7 +221,7 @@ namespace BizHawk.Client.Common
{
private readonly ZipOutputStream zip;
private void WriteVersion(Stream s)
private static void WriteVersion(Stream s)
{
var sw = new StreamWriter(s);
sw.WriteLine("1"); // version 1.0.1
@ -238,18 +244,18 @@ namespace BizHawk.Client.Common
PutLump(BinaryStateLump.Versiontag, WriteVersion);
}
public void PutLump(BinaryStateLump Lump, Action<Stream> callback)
public void PutLump(BinaryStateLump lump, Action<Stream> callback)
{
string Name = BinaryStateFileNames.Get(Lump);
string Name = BinaryStateFileNames.Get(lump);
var e = new ZipEntry(Name) {CompressionMethod = CompressionMethod.Stored};
zip.PutNextEntry(e);
callback(zip);
zip.CloseEntry();
}
public void PutLump(BinaryStateLump Lump, Action<BinaryWriter> callback)
public void PutLump(BinaryStateLump lump, Action<BinaryWriter> callback)
{
PutLump(Lump, delegate(Stream s)
PutLump(lump, delegate(Stream s)
{
var bw = new BinaryWriter(s);
callback(bw);
@ -257,9 +263,9 @@ namespace BizHawk.Client.Common
});
}
public void PutLump(BinaryStateLump Lump, Action<TextWriter> callback)
public void PutLump(BinaryStateLump lump, Action<TextWriter> callback)
{
PutLump(Lump, delegate(Stream s)
PutLump(lump, delegate(Stream s)
{
TextWriter tw = new StreamWriter(s);
callback(tw);

View File

@ -9,23 +9,21 @@ namespace BizHawk.Client.Common
{
public class Controller : IController
{
private readonly WorkingDictionary<string, List<string>> _bindings = new WorkingDictionary<string, List<string>>();
private readonly WorkingDictionary<string, bool> _buttons = new WorkingDictionary<string, bool>();
private readonly WorkingDictionary<string, float> _floatButtons = new WorkingDictionary<string, float>();
private readonly Dictionary<string, ControllerDefinition.FloatRange> _floatRanges = new WorkingDictionary<string, ControllerDefinition.FloatRange>();
private readonly Dictionary<string, Config.AnalogBind> _floatBinds = new Dictionary<string, Config.AnalogBind>();
private ControllerDefinition _type;
private readonly WorkingDictionary<string, List<string>> bindings = new WorkingDictionary<string, List<string>>();
private readonly WorkingDictionary<string, bool> buttons = new WorkingDictionary<string, bool>();
private readonly WorkingDictionary<string, float> FloatButtons = new WorkingDictionary<string, float>();
private readonly Dictionary<string, ControllerDefinition.FloatRange> FloatRanges = new WorkingDictionary<string, ControllerDefinition.FloatRange>();
private readonly Dictionary<string, Config.AnalogBind> FloatBinds = new Dictionary<string, Config.AnalogBind>();
public Controller(ControllerDefinition definition)
{
_type = definition;
for (int i = 0; i < _type.FloatControls.Count; i++)
{
FloatButtons[_type.FloatControls[i]] = _type.FloatRanges[i].Mid;
FloatRanges[_type.FloatControls[i]] = _type.FloatRanges[i];
_floatButtons[_type.FloatControls[i]] = _type.FloatRanges[i].Mid;
_floatRanges[_type.FloatControls[i]] = _type.FloatRanges[i];
}
}
@ -36,21 +34,21 @@ namespace BizHawk.Client.Common
public bool this[string button] { get { return IsPressed(button); } }
public bool IsPressed(string button)
{
return buttons[button];
return _buttons[button];
}
public float GetFloat(string name) { return FloatButtons[name]; }
public float GetFloat(string name) { return _floatButtons[name]; }
// Looks for bindings which are activated by the supplied physical button.
public List<string> SearchBindings(string button)
{
return (from kvp in bindings from bound_button in kvp.Value where bound_button == button select kvp.Key).ToList();
return (from kvp in _bindings from bound_button in kvp.Value where bound_button == button select kvp.Key).ToList();
}
// Searches bindings for the controller and returns true if this binding is mapped somewhere in this controller
public bool HasBinding(string button)
{
return bindings.SelectMany(kvp => kvp.Value).Any(bound_button => bound_button == button);
return _bindings.SelectMany(kvp => kvp.Value).Any(boundButton => boundButton == button);
}
/// <summary>
@ -59,28 +57,28 @@ namespace BizHawk.Client.Common
/// </summary>
public void LatchFromPhysical(IController controller)
{
buttons.Clear();
_buttons.Clear();
foreach (var kvp in bindings)
foreach (var kvp in _bindings)
{
buttons[kvp.Key] = false;
_buttons[kvp.Key] = false;
foreach (var bound_button in kvp.Value)
{
if (controller[bound_button])
{
buttons[kvp.Key] = true;
_buttons[kvp.Key] = true;
}
}
}
foreach (var kvp in FloatBinds)
foreach (var kvp in _floatBinds)
{
float input = controller.GetFloat(kvp.Value.Value);
var input = controller.GetFloat(kvp.Value.Value);
string outkey = kvp.Key;
float multiplier = kvp.Value.Mult;
float deadzone = kvp.Value.Deadzone;
ControllerDefinition.FloatRange range;
if (FloatRanges.TryGetValue(outkey, out range))
if (_floatRanges.TryGetValue(outkey, out range))
{
// input range is assumed to be -10000,0,10000
@ -89,20 +87,30 @@ namespace BizHawk.Client.Common
float absinput = Math.Abs(input);
float zeropoint = deadzone * 10000.0f;
if (absinput < zeropoint)
{
input = 0.0f;
}
else
{
absinput -= zeropoint;
absinput *= 10000.0f;
absinput /= (10000.0f - zeropoint);
absinput /= 10000.0f - zeropoint;
input = absinput * Math.Sign(input);
}
}
float output = (input * multiplier + 10000.0f) * (range.Max - range.Min) / 20000.0f + range.Min;
if (output < range.Min) output = range.Min;
if (output > range.Max) output = range.Max;
FloatButtons[outkey] = output;
var output = (input * multiplier + 10000.0f) * (range.Max - range.Min) / 20000.0f + range.Min;
if (output < range.Min)
{
output = range.Min;
}
if (output > range.Max)
{
output = range.Max;
}
_floatButtons[outkey] = output;
}
}
}
@ -120,7 +128,7 @@ namespace BizHawk.Client.Common
{
if (controller.IsPressed(button))
{
buttons[button] = true;
_buttons[button] = true;
}
}
}
@ -128,7 +136,7 @@ namespace BizHawk.Client.Common
public void BindButton(string button, string control)
{
bindings[button].Add(control);
_bindings[button].Add(control);
}
public void BindMulti(string button, string controlString)
@ -141,13 +149,13 @@ namespace BizHawk.Client.Common
var controlbindings = controlString.Split(',');
foreach (var control in controlbindings)
{
bindings[button].Add(control.Trim());
_bindings[button].Add(control.Trim());
}
}
public void BindFloat(string button, Config.AnalogBind bind)
{
FloatBinds[button] = bind;
_floatBinds[button] = bind;
}
/// <summary>
@ -155,27 +163,28 @@ namespace BizHawk.Client.Common
/// </summary>
public List<KeyValuePair<string, string>> MappingList()
{
return (from key in bindings from binding in key.Value select new KeyValuePair<string, string>(binding, key.Key)).ToList();
return (from key in _bindings from binding in key.Value select new KeyValuePair<string, string>(binding, key.Key)).ToList();
}
public List<string> PressedButtons
{
get
{
return (from button in buttons where button.Value select button.Key).ToList();
return (from button in _buttons where button.Value select button.Key).ToList();
}
}
}
public class AutofireController : IController
{
private readonly ControllerDefinition type;
private readonly WorkingDictionary<string, List<string>> bindings = new WorkingDictionary<string, List<string>>();
private readonly WorkingDictionary<string, bool> buttons = new WorkingDictionary<string, bool>();
public WorkingDictionary<string, int> buttonStarts = new WorkingDictionary<string, int>();
private readonly ControllerDefinition _type;
private readonly WorkingDictionary<string, List<string>> _bindings = new WorkingDictionary<string, List<string>>();
private readonly WorkingDictionary<string, bool> _buttons = new WorkingDictionary<string, bool>();
private readonly WorkingDictionary<string, int> _buttonStarts = new WorkingDictionary<string, int>();
private bool autofire = true;
public bool Autofire { get { return false; } set { autofire = value; } }
private bool _autofire = true;
public bool Autofire { get { return false; } set { _autofire = value; } }
public int On { get; set; }
public int Off { get; set; }
@ -183,28 +192,21 @@ namespace BizHawk.Client.Common
{
On = Global.Config.AutofireOn < 1 ? 0 : Global.Config.AutofireOn;
Off = Global.Config.AutofireOff < 1 ? 0 : Global.Config.AutofireOff;
type = definition;
_type = definition;
}
public ControllerDefinition Type { get { return type; } }
public ControllerDefinition Type { get { return _type; } }
public bool this[string button] { get { return IsPressed(button); } }
public bool IsPressed(string button)
{
if (autofire)
if (_autofire)
{
int a = (Global.Emulator.Frame - buttonStarts[button])%(On + Off);
if (a < On)
{
return buttons[button];
}
else
{
return false;
}
var a = (Global.Emulator.Frame - _buttonStarts[button]) % (On + Off);
return a < On && _buttons[button];
}
else
{
return buttons[button];
return _buttons[button];
}
}
@ -213,7 +215,7 @@ namespace BizHawk.Client.Common
// look for bindings which are activated by the supplied physical button.
public List<string> SearchBindings(string button)
{
return (from kvp in bindings from bound_button in kvp.Value where bound_button == button select kvp.Key).ToList();
return (from kvp in _bindings from bound_button in kvp.Value where bound_button == button select kvp.Key).ToList();
}
/// <summary>
@ -222,26 +224,26 @@ namespace BizHawk.Client.Common
/// </summary>
public void LatchFromPhysical(IController controller)
{
foreach (var kvp in bindings)
foreach (var kvp in _bindings)
{
foreach (var bound_button in kvp.Value)
{
if (buttons[kvp.Key] == false && controller[bound_button])
if (_buttons[kvp.Key] == false && controller[bound_button])
{
buttonStarts[kvp.Key] = Global.Emulator.Frame;
_buttonStarts[kvp.Key] = Global.Emulator.Frame;
}
}
}
buttons.Clear();
foreach (var kvp in bindings)
_buttons.Clear();
foreach (var kvp in _bindings)
{
buttons[kvp.Key] = false;
_buttons[kvp.Key] = false;
foreach (var bound_button in kvp.Value)
{
if (controller[bound_button])
{
buttons[kvp.Key] = true;
_buttons[kvp.Key] = true;
}
}
}
@ -252,16 +254,16 @@ namespace BizHawk.Client.Common
/// </summary>
public void OR_FromLogical(IController controller)
{
foreach (var button in type.BoolButtons.Where(controller.IsPressed))
foreach (var button in _type.BoolButtons.Where(controller.IsPressed))
{
buttons[button] = true;
_buttons[button] = true;
Console.WriteLine(button);
}
}
public void BindButton(string button, string control)
{
bindings[button].Add(control);
_bindings[button].Add(control);
}
public void BindMulti(string button, string controlString)
@ -271,16 +273,16 @@ namespace BizHawk.Client.Common
var controlbindings = controlString.Split(',');
foreach (var control in controlbindings)
{
bindings[button].Add(control.Trim());
_bindings[button].Add(control.Trim());
}
}
}
public void IncrementStarts()
{
foreach (var key in buttonStarts.Keys.ToArray())
foreach (var key in _buttonStarts.Keys.ToArray())
{
buttonStarts[key]++;
_buttonStarts[key]++;
}
}
@ -288,7 +290,7 @@ namespace BizHawk.Client.Common
{
get
{
return (from button in buttons where button.Value select button.Key).ToList();
return (from button in _buttons where button.Value select button.Key).ToList();
}
}
}

View File

@ -7,14 +7,14 @@ namespace BizHawk.Client.Common
{
public class CoreFileProvider : ICoreFileProvider
{
public string SubfileDirectory;
public FirmwareManager FirmwareManager;
public string SubfileDirectory { get; set; }
public FirmwareManager FirmwareManager { get; set; }
Action<string> ShowWarning;
private readonly Action<string> _showWarning;
public CoreFileProvider(Action<string> showWarning)
{
ShowWarning = showWarning;
_showWarning = showWarning;
}
public Stream OpenFirmware(string sysId, string key)
@ -40,11 +40,11 @@ namespace BizHawk.Client.Common
#region EmuLoadHelper api
void FirmwareWarn(string sysID, string firmwareID, bool required, string msg = null)
private void FirmwareWarn(string sysID, string firmwareID, bool required, string msg = null)
{
if (required)
{
string fullmsg = string.Format(
var fullmsg = String.Format(
"Couldn't find required firmware \"{0}:{1}\". This is fatal{2}", sysID, firmwareID, msg != null ? ": " + msg : ".");
throw new Exception(fullmsg);
}
@ -52,29 +52,33 @@ namespace BizHawk.Client.Common
{
if (msg != null)
{
string fullmsg = string.Format(
var fullmsg = String.Format(
"Couldn't find firmware \"{0}:{1}\". Will attempt to continue: {2}", sysID, firmwareID, msg);
ShowWarning(msg);
_showWarning(fullmsg);
}
}
}
public string GetFirmwarePath(string sysID, string firmwareID, bool required, string msg = null)
{
string path = FirmwareManager.Request(sysID, firmwareID);
var path = FirmwareManager.Request(sysID, firmwareID);
if (path != null && !File.Exists(path))
{
path = null;
}
if (path == null)
{
FirmwareWarn(sysID, firmwareID, required, msg);
}
return path;
}
public byte[] GetFirmware(string sysID, string firmwareID, bool required, string msg = null)
{
byte[] ret = null;
string path = GetFirmwarePath(sysID, firmwareID, required, msg);
var path = GetFirmwarePath(sysID, firmwareID, required, msg);
if (path != null && File.Exists(path))
{
try
@ -85,7 +89,10 @@ namespace BizHawk.Client.Common
}
if (ret == null && path != null)
{
FirmwareWarn(sysID, firmwareID, required, msg);
}
return ret;
}

View File

@ -1,36 +1,35 @@
using System.Linq;
using System.Collections.Generic;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using BizHawk.Common;
using BizHawk.Emulation.Common;
//IDEA: put filesizes in DB too. then scans can go real quick by only scanning filesizes that match (and then scanning filesizes that dont match, in case of an emergency)
//this would be adviseable if we end up with a very large firmware file
// IDEA: put filesizes in DB too. then scans can go real quick by only scanning filesizes that match (and then scanning filesizes that dont match, in case of an emergency)
// this would be adviseable if we end up with a very large firmware file
namespace BizHawk.Client.Common
{
public class FirmwareManager
{
//represents a file found on disk in the user's firmware directory matching a file in our database
class RealFirmwareFile
// represents a file found on disk in the user's firmware directory matching a file in our database
public class RealFirmwareFile
{
public FileInfo fi;
public string hash;
public FileInfo FileInfo { get; set; }
public string Hash { get; set; }
}
public class ResolutionInfo
{
public bool UserSpecified;
public bool Missing;
public bool KnownMismatching;
public FirmwareDatabase.FirmwareFile KnownFirmwareFile;
public string FilePath;
public string Hash;
public bool UserSpecified { get; set; }
public bool Missing { get; set; }
public bool KnownMismatching { get; set; }
public FirmwareDatabase.FirmwareFile KnownFirmwareFile { get; set; }
public string FilePath { get; set; }
public string Hash { get; set; }
}
readonly Dictionary<FirmwareDatabase.FirmwareRecord, ResolutionInfo> ResolutionDictionary = new Dictionary<FirmwareDatabase.FirmwareRecord, ResolutionInfo>();
private readonly Dictionary<FirmwareDatabase.FirmwareRecord, ResolutionInfo> _resolutionDictionary = new Dictionary<FirmwareDatabase.FirmwareRecord, ResolutionInfo>();
public ResolutionInfo Resolve(string sysId, string firmwareId)
{
@ -44,9 +43,9 @@ namespace BizHawk.Client.Common
RETRY:
ResolutionInfo resolved;
ResolutionDictionary.TryGetValue(record, out resolved);
_resolutionDictionary.TryGetValue(record, out resolved);
//couldnt find it! do a scan and resolve to try harder
// couldnt find it! do a scan and resolve to try harder
if (resolved == null && first)
{
DoScanAndResolve();
@ -57,7 +56,7 @@ namespace BizHawk.Client.Common
return resolved;
}
//Requests the spcified firmware. tries really hard to scan and resolve as necessary
// Requests the spcified firmware. tries really hard to scan and resolve as necessary
public string Request(string sysId, string firmwareId)
{
var resolved = Resolve(sysId, firmwareId);
@ -65,29 +64,38 @@ namespace BizHawk.Client.Common
return resolved.FilePath;
}
class RealFirmwareReader
public class RealFirmwareReader
{
byte[] buffer = new byte[0];
public RealFirmwareFile Read(FileInfo fi)
{
RealFirmwareFile rff = new RealFirmwareFile {fi = fi};
var rff = new RealFirmwareFile { FileInfo = fi };
long len = fi.Length;
if (len > buffer.Length) buffer = new byte[len];
using (var fs = fi.OpenRead()) fs.Read(buffer, 0, (int)len);
rff.hash = Util.Hash_SHA1(buffer, 0, (int)len);
dict[rff.hash] = rff;
files.Add(rff);
if (len > buffer.Length)
{
buffer = new byte[len];
}
using (var fs = fi.OpenRead())
{
fs.Read(buffer, 0, (int)len);
}
rff.Hash = Util.Hash_SHA1(buffer, 0, (int)len);
dict[rff.Hash] = rff;
_files.Add(rff);
return rff;
}
public readonly Dictionary<string, RealFirmwareFile> dict = new Dictionary<string, RealFirmwareFile>();
private readonly List<RealFirmwareFile> files = new List<RealFirmwareFile>();
private readonly List<RealFirmwareFile> _files = new List<RealFirmwareFile>();
}
public void DoScanAndResolve()
{
RealFirmwareReader reader = new RealFirmwareReader();
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>();
todo.Enqueue(new DirectoryInfo(PathManager.MakeAbsolutePath(Global.Config.PathEntries.FirmwaresPathFragment, null)));
@ -95,8 +103,11 @@ namespace BizHawk.Client.Common
{
var di = todo.Dequeue();
//we're going to allow recursing into subdirectories, now. its been verified to work OK
foreach (var disub in di.GetDirectories()) todo.Enqueue(disub);
// we're going to allow recursing into subdirectories, now. its been verified to work OK
foreach (var disub in di.GetDirectories())
{
todo.Enqueue(disub);
}
foreach (var fi in di.GetFiles())
{
@ -104,34 +115,35 @@ namespace BizHawk.Client.Common
}
}
//now, for each firmware record, try to resolve it
// now, for each firmware record, try to resolve it
foreach (var fr in FirmwareDatabase.FirmwareRecords)
{
//clear previous resolution results
ResolutionDictionary.Remove(fr);
// clear previous resolution results
_resolutionDictionary.Remove(fr);
//get all options for this firmware (in order)
FirmwareDatabase.FirmwareRecord fr1 = fr;
// get all options for this firmware (in order)
var fr1 = fr;
var options =
from fo in FirmwareDatabase.FirmwareOptions
where fo.systemId == fr1.systemId && fo.firmwareId == fr1.firmwareId
select fo;
//try each option
// try each option
foreach (var fo in options)
{
var hash = fo.hash;
//did we find this firmware?
// did we find this firmware?
if (reader.dict.ContainsKey(hash))
{
//rad! then we can use it
// rad! then we can use it
var ri = new ResolutionInfo
{
FilePath = reader.dict[hash].fi.FullName,
FilePath = reader.dict[hash].FileInfo.FullName,
KnownFirmwareFile = FirmwareDatabase.FirmwareFilesByHash[hash],
Hash = hash
};
ResolutionDictionary[fr] = ri;
_resolutionDictionary[fr] = ri;
goto DONE_FIRMWARE;
}
}
@ -140,27 +152,27 @@ namespace BizHawk.Client.Common
}
//apply user overrides
// apply user overrides
foreach (var fr in FirmwareDatabase.FirmwareRecords)
{
string userSpec;
//do we have a user specification for this firmware record?
// do we have a user specification for this firmware record?
if (Global.Config.FirmwareUserSpecifications.TryGetValue(fr.ConfigKey, out userSpec))
{
//flag it as user specified
// flag it as user specified
ResolutionInfo ri;
if (!ResolutionDictionary.TryGetValue(fr, out ri))
if (!_resolutionDictionary.TryGetValue(fr, out ri))
{
ri = new ResolutionInfo();
ResolutionDictionary[fr] = ri;
_resolutionDictionary[fr] = ri;
}
ri.UserSpecified = true;
ri.KnownFirmwareFile = null;
ri.FilePath = userSpec;
ri.Hash = null;
//check whether it exists
// check whether it exists
var fi = new FileInfo(userSpec);
if (!fi.Exists)
{
@ -168,27 +180,29 @@ namespace BizHawk.Client.Common
continue;
}
//compute its hash
// compute its hash
var rff = reader.Read(fi);
ri.Hash = rff.hash;
ri.Hash = rff.Hash;
//check whether it was a known file anyway, and go ahead and bind to the known file, as a perk (the firmwares config doesnt really use this information right now)
// check whether it was a known file anyway, and go ahead and bind to the known file, as a perk (the firmwares config doesnt really use this information right now)
FirmwareDatabase.FirmwareFile ff;
if(FirmwareDatabase.FirmwareFilesByHash.TryGetValue(rff.hash,out ff))
if (FirmwareDatabase.FirmwareFilesByHash.TryGetValue(rff.Hash,out ff))
{
ri.KnownFirmwareFile = ff;
//if the known firmware file is for a different firmware, flag it so we can show a warning
// if the known firmware file is for a different firmware, flag it so we can show a warning
var option =
(from fo in FirmwareDatabase.FirmwareOptions
where fo.hash == rff.hash && fo.ConfigKey != fr.ConfigKey
where fo.hash == rff.Hash && fo.ConfigKey != fr.ConfigKey
select fr).FirstOrDefault();
if (option != null)
{
ri.KnownMismatching = true;
}
}
}
}
}
}
}

View File

@ -8,10 +8,10 @@ namespace BizHawk.Client.Common
{
public class RomGame
{
public byte[] RomData;
public byte[] FileData;
public GameInfo GameInfo;
public string Extension;
public byte[] RomData { get; set; }
public byte[] FileData { get; set; }
public GameInfo GameInfo { get; set; }
public string Extension { get; set; }
private const int BankSize = 1024;
@ -22,15 +22,17 @@ namespace BizHawk.Client.Common
public RomGame(HawkFile file, string patch)
{
if (!file.Exists)
{
throw new Exception("The file needs to exist, yo.");
}
Extension = file.Extension;
var stream = file.GetStream();
int fileLength = (int)stream.Length;
//read the entire contents of the file into memory.
//unfortunate in the case of large files, but thats what we've got to work with for now.
// read the entire contents of the file into memory.
// unfortunate in the case of large files, but thats what we've got to work with for now.
// if we're offset exactly 512 bytes from a 1024-byte boundary,
// assume we have a header of that size. Otherwise, assume it's just all rom.
@ -42,34 +44,40 @@ namespace BizHawk.Client.Common
headerOffset = 0;
}
else if (headerOffset > 0)
{
Console.WriteLine("Assuming header of {0} bytes.", headerOffset);
}
//read the entire file into FileData.
// read the entire file into FileData.
FileData = new byte[fileLength];
stream.Read(FileData, 0, fileLength);
//if there was no header offset, RomData is equivalent to FileData
//(except in cases where the original interleaved file data is necessary.. in that case we'll have problems..
//but this whole architecture is not going to withstand every peculiarity and be fast as well.
// if there was no header offset, RomData is equivalent to FileData
// (except in cases where the original interleaved file data is necessary.. in that case we'll have problems..
// but this whole architecture is not going to withstand every peculiarity and be fast as well.
if (headerOffset == 0)
{
RomData = FileData;
}
else
{
//if there was a header offset, read the whole file into FileData and then copy it into RomData (this is unfortunate, in case RomData isnt needed)
// if there was a header offset, read the whole file into FileData and then copy it into RomData (this is unfortunate, in case RomData isnt needed)
int romLength = fileLength - headerOffset;
RomData = new byte[romLength];
Buffer.BlockCopy(FileData, headerOffset, RomData, 0, romLength);
}
if (file.Extension == ".SMD")
{
RomData = DeInterleaveSMD(RomData);
}
if (file.Extension == ".Z64" || file.Extension == ".N64" || file.Extension == ".V64")
{
RomData = MutateSwapN64(RomData);
}
//note: this will be taking several hashes, of a potentially large amount of data.. yikes!
// note: this will be taking several hashes, of a potentially large amount of data.. yikes!
GameInfo = Database.GetGameInfo(RomData, file.Name);
CheckForPatchOptions();
@ -80,7 +88,9 @@ namespace BizHawk.Client.Common
{
patchFile.BindFirstOf("IPS");
if (patchFile.IsBound)
{
IPS.Patch(RomData, patchFile.GetStream());
}
}
}
}
@ -91,9 +101,13 @@ namespace BizHawk.Client.Common
// odd bytes and the second 8k containing all even bytes.
int size = source.Length;
if (size > 0x400000) size = 0x400000;
if (size > 0x400000)
{
size = 0x400000;
}
int pages = size / 0x4000;
byte[] output = new byte[size];
var output = new byte[size];
for (int page = 0; page < pages; page++)
{
@ -114,7 +128,6 @@ namespace BizHawk.Client.Common
// .V64 = Bytse Swapped
// File extension does not always match the format
int size = source.Length;
// V64 format
@ -129,15 +142,16 @@ namespace BizHawk.Client.Common
pSource[i + 1] = temp;
}
}
// N64 format
else if (pSource[0] == 0x40)
{
for (int i = 0; i < size; i += 4)
{
//output[i] = source[i + 3];
//output[i + 3] = source[i];
//output[i + 1] = source[i + 2];
//output[i + 2] = source[i + 1];
// output[i] = source[i + 3];
// output[i + 3] = source[i];
// output[i + 1] = source[i + 2];
// output[i + 2] = source[i + 1];
byte temp = pSource[i];
pSource[i] = source[i + 3];
@ -148,8 +162,7 @@ namespace BizHawk.Client.Common
pSource[i + 2] = temp;
}
}
// Z64 format (or some other unknown format)
else
else // Z64 format (or some other unknown format)
{
}
}
@ -163,7 +176,7 @@ namespace BizHawk.Client.Common
{
if (GameInfo["PatchBytes"])
{
string args = GameInfo.OptionValue("PatchBytes");
var args = GameInfo.OptionValue("PatchBytes");
foreach (var val in args.Split(','))
{
var split = val.Split(':');

View File

@ -8,13 +8,13 @@ using BizHawk.Emulation.Cores.Atari.Atari7800;
using BizHawk.Emulation.Cores.Calculators;
using BizHawk.Emulation.Cores.ColecoVision;
using BizHawk.Emulation.Cores.Computers.Commodore64;
using BizHawk.Emulation.Cores.Consoles.Nintendo.QuickNES;
using BizHawk.Emulation.Cores.Consoles.Sega.gpgx;
using BizHawk.Emulation.Cores.Intellivision;
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.Consoles.Nintendo.QuickNES;
using BizHawk.Emulation.Cores.Nintendo.SNES;
using BizHawk.Emulation.Cores.PCEngine;
using BizHawk.Emulation.Cores.Sega.MasterSystem;
@ -364,6 +364,7 @@ namespace BizHawk.Client.Common
{
nextEmulator = new QuickNES(nextComm, rom.FileData);
}
break;
case "GB":
case "GBC":
@ -414,7 +415,7 @@ namespace BizHawk.Client.Common
case "GBA":
if (VersionInfo.INTERIM)
{
GBA gba = new GBA(nextComm);
var gba = new GBA(nextComm);
gba.Load(rom.RomData);
nextEmulator = gba;
}

View File

@ -1,4 +1,5 @@
using System.IO;
using System.Linq;
using BizHawk.Emulation.Common;
@ -6,8 +7,8 @@ namespace BizHawk.Client.Common
{
public class SaveSlotManager
{
private readonly bool[] slots = new bool[10];
private readonly bool[] redo = new bool[10];
private readonly bool[] _slots = new bool[10];
private readonly bool[] _redo = new bool[10];
public SaveSlotManager()
{
@ -20,10 +21,12 @@ namespace BizHawk.Client.Common
{
for (int i = 0; i < 10; i++)
{
slots[i] = false;
_slots[i] = false;
}
return;
}
for (int i = 0; i < 10; i++)
{
var file = new FileInfo(
@ -33,7 +36,8 @@ namespace BizHawk.Client.Common
{
file.Directory.Create();
}
slots[i] = file.Exists;
_slots[i] = file.Exists;
}
}
@ -42,11 +46,7 @@ namespace BizHawk.Client.Common
get
{
Update();
for (int i = 0; i < 10; i++)
{
if (slots[i]) return true;
}
return false;
return _slots.Any(slot => slot);
}
}
@ -63,14 +63,14 @@ namespace BizHawk.Client.Common
}
Update();
return slots[slot];
return _slots[slot];
}
public void ClearRedoList()
{
for (int i = 0; i < 10; i++)
{
redo[i] = false;
_redo[i] = false;
}
}
@ -81,7 +81,7 @@ namespace BizHawk.Client.Common
return;
}
redo[slot] ^= true;
_redo[slot] ^= true;
}
public bool IsRedo(int slot)
@ -91,7 +91,7 @@ namespace BizHawk.Client.Common
return false;
}
return redo[slot];
return _redo[slot];
}
public void Clear()

View File

@ -21,16 +21,17 @@ namespace BizHawk.Client.Common
writer.Write("Framebuffer ");
Global.Emulator.VideoProvider.GetVideoBuffer().SaveAsHex(writer);
}
writer.Close();
}
else
{
// binary savestates
using (FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write))
using (BinaryStateSaver bs = new BinaryStateSaver(fs))
using (var fs = new FileStream(filename, FileMode.Create, FileAccess.Write))
using (var bs = new BinaryStateSaver(fs))
{
#if true
bs.PutLump(BinaryStateLump.Corestate, (bw) => Global.Emulator.SaveStateBinary(bw));
bs.PutLump(BinaryStateLump.Corestate, bw => Global.Emulator.SaveStateBinary(bw));
#else
// this would put text states inside the zipfile
bs.PutLump(BinaryStateLump.CorestateText, (tw) => Global.Emulator.SaveStateText(tw));
@ -40,6 +41,7 @@ namespace BizHawk.Client.Common
var buff = Global.Emulator.VideoProvider.GetVideoBuffer();
bs.PutLump(BinaryStateLump.Framebuffer, (BinaryWriter bw) => bw.Write(buff));
}
if (Global.MovieSession.Movie.IsActive)
{
bs.PutLump(BinaryStateLump.Input,
@ -57,30 +59,31 @@ namespace BizHawk.Client.Common
public static bool LoadStateFile(string path, string name)
{
// try to detect binary first
BinaryStateLoader bl = BinaryStateLoader.LoadAndDetect(path);
var bl = BinaryStateLoader.LoadAndDetect(path);
if (bl != null)
{
try
{
bool succeed = false;
var succeed = false;
if (Global.MovieSession.Movie.IsActive)
{
bl.GetLump(BinaryStateLump.Input, true, (tr) => succeed = Global.MovieSession.HandleMovieLoadState(tr));
bl.GetLump(BinaryStateLump.Input, true, tr => succeed = Global.MovieSession.HandleMovieLoadState(tr));
if (!succeed)
{
return false;
}
}
bl.GetCoreState((br) => Global.Emulator.LoadStateBinary(br), (tr) => Global.Emulator.LoadStateText(tr));
bl.GetCoreState(br => Global.Emulator.LoadStateBinary(br), tr => Global.Emulator.LoadStateText(tr));
bl.GetLump(BinaryStateLump.Framebuffer, false,
delegate(BinaryReader br)
{
int i;
var buff = Global.Emulator.VideoProvider.GetVideoBuffer();
try
{
for (i = 0; i < buff.Length; i++)
for (int i = 0; i < buff.Length; i++)
{
int j = br.ReadInt32();
buff[i] = j;
@ -106,17 +109,25 @@ namespace BizHawk.Client.Common
while (true)
{
string str = reader.ReadLine();
if (str == null) break;
if (str.Trim() == "") continue;
var str = reader.ReadLine();
if (str == null)
{
break;
}
if (str.Trim() == String.Empty)
{
continue;
}
string[] args = str.Split(' ');
var args = str.Split(' ');
if (args[0] == "Framebuffer")
{
Global.Emulator.VideoProvider.GetVideoBuffer().ReadFromHex(args[1]);
}
}
}
return true;
}
else

View File

@ -1,6 +1,5 @@
using System;
using System.IO;
using System.Collections.Generic;
using System.IO;
using BizHawk.Common;
@ -11,12 +10,14 @@ namespace BizHawk.Client.Common
/// </summary>
public class SevenZipSharpArchiveHandler : IHawkFileArchiveHandler
{
private SevenZip.SevenZipExtractor _extractor;
public void Dispose()
{
if (extractor != null)
if (_extractor != null)
{
extractor.Dispose();
extractor = null;
_extractor.Dispose();
_extractor = null;
}
}
@ -28,26 +29,33 @@ namespace BizHawk.Client.Common
public IHawkFileArchiveHandler Construct(string path)
{
SevenZipSharpArchiveHandler ret = new SevenZipSharpArchiveHandler();
var ret = new SevenZipSharpArchiveHandler();
ret.Open(path);
return ret;
}
void Open(string path)
private void Open(string path)
{
extractor = new SevenZip.SevenZipExtractor(path);
_extractor = new SevenZip.SevenZipExtractor(path);
}
SevenZip.SevenZipExtractor extractor;
public List<HawkFileArchiveItem> Scan()
{
List<HawkFileArchiveItem> ret = new List<HawkFileArchiveItem>();
for (int i = 0; i < extractor.ArchiveFileData.Count; i++)
var ret = new List<HawkFileArchiveItem>();
for (int i = 0; i < _extractor.ArchiveFileData.Count; i++)
{
var afd = extractor.ArchiveFileData[i];
if (afd.IsDirectory) continue;
var ai = new HawkFileArchiveItem { name = HawkFile.Util_FixArchiveFilename(afd.FileName), size = (long)afd.Size, archiveIndex = i, index = ret.Count };
var afd = _extractor.ArchiveFileData[i];
if (afd.IsDirectory)
{
continue;
}
var ai = new HawkFileArchiveItem
{
name = HawkFile.Util_FixArchiveFilename(afd.FileName),
size = (long)afd.Size, archiveIndex = i, index = ret.Count
};
ret.Add(ai);
}
@ -56,8 +64,7 @@ namespace BizHawk.Client.Common
public void ExtractFile(int index, Stream stream)
{
extractor.ExtractFile(index, stream);
_extractor.ExtractFile(index, stream);
}
}
}

View File

@ -10,7 +10,7 @@ namespace BizHawk.Client.Common
{
public class XmlGame
{
public XmlDocument Xml;
public XmlDocument Xml { get; set; }
public GameInfo GI = new GameInfo();
public Dictionary<string, byte[]> Assets = new Dictionary<string, byte[]>();
@ -22,7 +22,9 @@ namespace BizHawk.Client.Common
x.Load(f.GetStream());
var y = x.SelectSingleNode("./BizHawk-XMLGame");
if (y == null)
{
return null;
}
var ret = new XmlGame
{
@ -38,8 +40,7 @@ namespace BizHawk.Client.Common
var n = y.SelectSingleNode("./LoadAssets");
if (n != null)
{
MemoryStream HashStream = new MemoryStream();
var HashStream = new MemoryStream();
int? OriginalIndex = null;
foreach (XmlNode a in n.ChildNodes)
@ -54,7 +55,10 @@ namespace BizHawk.Client.Common
if (ai != null)
{
if (OriginalIndex == null)
{
OriginalIndex = f.GetBoundIndex();
}
f.Unbind();
f.BindArchiveMember(ai);
data = Util.ReadAllBytes(f.GetStream());
@ -67,7 +71,7 @@ namespace BizHawk.Client.Common
else
{
// relative path
string fullpath = Path.GetDirectoryName(f.CanonicalFullPath.Split('|')[0]) ?? String.Empty;
var fullpath = Path.GetDirectoryName(f.CanonicalFullPath.Split('|')[0]) ?? String.Empty;
fullpath = Path.Combine(fullpath, filename);
try
{
@ -78,6 +82,7 @@ namespace BizHawk.Client.Common
throw new Exception("Couldn't load XMLGame LoadAsset \"" + name + "\"");
}
}
ret.Assets[name] = data;
using (var sha1 = System.Security.Cryptography.SHA1.Create())
@ -86,6 +91,7 @@ namespace BizHawk.Client.Common
HashStream.Write(sha1.Hash, 0, sha1.Hash.Length);
}
}
ret.GI.Hash = Util.Hash_SHA1(HashStream.GetBuffer(), 0, (int)HashStream.Length);
HashStream.Close();
if (OriginalIndex != null)
@ -98,13 +104,13 @@ namespace BizHawk.Client.Common
{
ret.GI.Hash = "0000000000000000000000000000000000000000";
}
return ret;
}
catch(Exception ex)
catch (Exception ex)
{
throw new InvalidOperationException(ex.ToString());
}
}
}
}

View File

@ -6,9 +6,9 @@ using System.Windows.Forms;
using BizHawk.Client.Common;
using BizHawk.Emulation.Cores.Calculators;
using BizHawk.Emulation.Cores.Nintendo.GBA;
using BizHawk.Emulation.Cores.Nintendo.NES;
using BizHawk.Emulation.Cores.Nintendo.SNES;
using BizHawk.Emulation.Cores.Nintendo.GBA;
using BizHawk.Emulation.Cores.PCEngine;
namespace BizHawk.Client.EmuHawk
@ -85,13 +85,11 @@ namespace BizHawk.Client.EmuHawk
private void SetSize()
{
var rows = (int)(Math.Ceiling(ToolBoxItems.Count() / 4.0));
this.Height = 30 + (rows * 30);
var rows = (int)Math.Ceiling(ToolBoxItems.Count() / 4.0);
Height = 30 + (rows * 30);
}
/// <summary>
/// Provide LINQ capabilities to an outdated form collection
/// </summary>
// Provide LINQ capabilities to an outdated form collection
private IEnumerable<ToolStripItem> ToolBoxItems
{
get

View File

@ -2,7 +2,7 @@ static class VersionInfo
{
public const string MAINVERSION = "1.5.2";
public const string RELEASEDATE = "August 22, 2013";
public static bool INTERIM = false;
public static bool INTERIM = true;
public static string GetEmuVersion()
{