Misc cleanups in Client.Common, documentation fixes

This commit is contained in:
adelikat 2017-05-17 11:16:55 -05:00
parent f576cb14b0
commit dfea029fe4
35 changed files with 1203 additions and 1134 deletions

View File

@ -325,8 +325,7 @@ namespace BizHawk.Client.Common
public BinaryStateSaver(string path, bool notamovie = true) // notamovie is hack, really should have separate something public BinaryStateSaver(string path, bool notamovie = true) // notamovie is hack, really should have separate something
{ {
_zip = new IonicZipWriter(path, notamovie ? Global.Config.SaveStateCompressionLevelNormal _zip = new IonicZipWriter(path, notamovie ? Global.Config.SaveStateCompressionLevelNormal : Global.Config.MovieCompressionLevel);
: Global.Config.MovieCompressionLevel);
////_zip = new SharpZipWriter(path, Global.Config.SaveStateCompressionLevelNormal); ////_zip = new SharpZipWriter(path, Global.Config.SaveStateCompressionLevelNormal);
////_zip = new SevenZipWriter(path, Global.Config.SaveStateCompressionLevelNormal); ////_zip = new SevenZipWriter(path, Global.Config.SaveStateCompressionLevelNormal);

View File

@ -32,7 +32,6 @@ namespace BizHawk.Client.Common
return PathManager.SaveRamPath(Global.Game); return PathManager.SaveRamPath(Global.Game);
} }
public string GetRetroSaveRAMDirectory() public string GetRetroSaveRAMDirectory()
{ {
return PathManager.RetroSaveRAMDirectory(Global.Game); return PathManager.RetroSaveRAMDirectory(Global.Game);

View File

@ -1,9 +1,10 @@
using BizHawk.Emulation.Common; using System.Collections.Generic;
using BizHawk.Emulation.Common;
using BizHawk.Emulation.Cores.Nintendo.Gameboy; using BizHawk.Emulation.Cores.Nintendo.Gameboy;
using BizHawk.Emulation.Cores.Sega.MasterSystem; using BizHawk.Emulation.Cores.Sega.MasterSystem;
using System.Collections.Generic; // ReSharper disable StyleCop.SA1401
namespace BizHawk.Client.Common namespace BizHawk.Client.Common
{ {
public static class Global public static class Global
@ -23,7 +24,7 @@ namespace BizHawk.Client.Common
public static bool DisableSecondaryThrottling; public static bool DisableSecondaryThrottling;
/// <summary> /// <summary>
/// The maximum number of millseconds the sound output buffer can go below full before causing a noticable sound interruption. /// The maximum number of milliseconds the sound output buffer can go below full before causing a noticeable sound interruption.
/// </summary> /// </summary>
public static int SoundMaxBufferDeficitMs; public static int SoundMaxBufferDeficitMs;

View File

@ -158,7 +158,6 @@ namespace BizHawk.Client.Common
// output[i + 3] = source[i]; // output[i + 3] = source[i];
// output[i + 1] = source[i + 2]; // output[i + 1] = source[i + 2];
// output[i + 2] = source[i + 1]; // output[i + 2] = source[i + 1];
byte temp = pSource[i]; byte temp = pSource[i];
pSource[i] = source[i + 3]; pSource[i] = source[i + 3];
pSource[i + 3] = temp; pSource[i + 3] = temp;
@ -192,7 +191,10 @@ namespace BizHawk.Client.Common
} }
} }
} }
catch (Exception) { } // No need for errors in patching to propagate. catch (Exception)
{
// No need for errors in patching to propagate.
}
} }
} }
} }

View File

@ -124,7 +124,9 @@ namespace BizHawk.Client.Common
buff[i] = j; buff[i] = j;
} }
} }
catch (EndOfStreamException) { } catch (EndOfStreamException)
{
}
} }
} }

View File

@ -308,11 +308,11 @@ namespace BizHawk.Client.Common
} }
} }
SevenZip.SevenZipCompressor svc; private SevenZip.SevenZipCompressor svc;
bool first = true; private bool first = true;
string path; private string path;
int compressionlevel; private int compressionlevel;
public SevenZipWriter(string path, int compressionlevel) public SevenZipWriter(string path, int compressionlevel)
{ {
@ -325,16 +325,28 @@ namespace BizHawk.Client.Common
switch (compressionlevel) switch (compressionlevel)
{ {
default: default:
case 0: svc.CompressionLevel = SevenZip.CompressionLevel.None; break; case 0:
svc.CompressionLevel = SevenZip.CompressionLevel.None;
break;
case 1: case 1:
case 2: svc.CompressionLevel = SevenZip.CompressionLevel.Fast; break; case 2:
svc.CompressionLevel = SevenZip.CompressionLevel.Fast;
break;
case 3: case 3:
case 4: svc.CompressionLevel = SevenZip.CompressionLevel.Low; break; case 4:
svc.CompressionLevel = SevenZip.CompressionLevel.Low;
break;
case 5: case 5:
case 6: svc.CompressionLevel = SevenZip.CompressionLevel.Normal; break; case 6:
svc.CompressionLevel = SevenZip.CompressionLevel.Normal;
break;
case 7: case 7:
case 8: svc.CompressionLevel = SevenZip.CompressionLevel.High; break; case 8:
case 9: svc.CompressionLevel = SevenZip.CompressionLevel.Ultra; break; svc.CompressionLevel = SevenZip.CompressionLevel.High;
break;
case 9:
svc.CompressionLevel = SevenZip.CompressionLevel.Ultra;
break;
} }
} }

View File

@ -21,7 +21,7 @@ namespace BizHawk.Client.Common
#region cTor(s) #region cTor(s)
/// <summary> /// <summary>
/// Initialize a new instance of <see cref="SystemInfo"/> /// Initializes a new instance of the <see cref="SystemInfo"/> class
/// </summary> /// </summary>
/// <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>
/// <param name="system">A <see cref="CoreSystem"/> that specify what core is used</param> /// <param name="system">A <see cref="CoreSystem"/> that specify what core is used</param>
@ -45,17 +45,17 @@ namespace BizHawk.Client.Common
/// <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 Libretro { get; } = new SystemInfo("Libretro", CoreSystem.Libretro, 1); public static SystemInfo Libretro { get; } = new SystemInfo("Libretro", CoreSystem.Libretro, 1);
/// <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 { get; } = new SystemInfo("Apple II", CoreSystem.AppleII, 1); public static SystemInfo AppleII { get; } = new SystemInfo("Apple II", CoreSystem.AppleII, 1);
/// <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 { get; } = new SystemInfo("Atari 2600", CoreSystem.Atari2600, 1); public static SystemInfo Atari2600 { get; } = new SystemInfo("Atari 2600", CoreSystem.Atari2600, 1);
/// <summary> /// <summary>
@ -184,7 +184,7 @@ namespace BizHawk.Client.Common
/// Get a <see cref="SystemInfo"/> by its <see cref="CoreSystem"/> /// Get a <see cref="SystemInfo"/> by its <see cref="CoreSystem"/>
/// </summary> /// </summary>
/// <param name="system"><see cref="CoreSystem"/> you're looking for</param> /// <param name="system"><see cref="CoreSystem"/> you're looking for</param>
/// <returns>Mathing <see cref="SystemInfo"/></returns> /// <returns><see cref="SystemInfo"/></returns>
public static SystemInfo FindByCoreSystem(CoreSystem system) public static SystemInfo FindByCoreSystem(CoreSystem system)
{ {
return _allSystemInfos.Find(s => s.System == system); return _allSystemInfos.Find(s => s.System == system);
@ -193,7 +193,7 @@ namespace BizHawk.Client.Common
/// <summary> /// <summary>
/// Determine if this <see cref="SystemInfo"/> is equal to specified <see cref="object"/> /// Determine if this <see cref="SystemInfo"/> is equal to specified <see cref="object"/>
/// </summary> /// </summary>
/// <param name="obj"><see cref="object"/> to comapre to</param> /// <param name="obj"><see cref="object"/> to compare to</param>
/// <returns>True if object is equal to this instance; otherwise, false</returns> /// <returns>True if object is equal to this instance; otherwise, false</returns>
public override bool Equals(object obj) public override bool Equals(object obj)
{ {
@ -218,7 +218,6 @@ namespace BizHawk.Client.Common
/// Returns a <see cref="string"/> representation of current <see cref="SystemInfo"/> /// Returns a <see cref="string"/> representation of current <see cref="SystemInfo"/>
/// In fact, return the same as DisplayName property /// In fact, return the same as DisplayName property
/// </summary> /// </summary>
/// <returns></returns>
public override string ToString() public override string ToString()
{ {
return DisplayName; return DisplayName;
@ -258,7 +257,7 @@ namespace BizHawk.Client.Common
public JoypadButton AvailableButtons { get; } public JoypadButton AvailableButtons { get; }
/// <summary> /// <summary>
/// Gets the sytem name as <see cref="string"/> /// Gets the system name as <see cref="string"/>
/// </summary> /// </summary>
public string DisplayName { get; } public string DisplayName { get; }

View File

@ -10,7 +10,7 @@ namespace BizHawk.Client.Common
{ {
public static class ConfigService public static class ConfigService
{ {
private static JsonSerializer Serializer; private static readonly JsonSerializer Serializer;
static ConfigService() static ConfigService()
{ {

View File

@ -44,7 +44,6 @@ namespace BizHawk.Client.Common
{ {
_wndx = value; _wndx = value;
} }
} }
} }
@ -62,12 +61,11 @@ namespace BizHawk.Client.Common
{ {
_wndy = value; _wndy = value;
} }
} }
} }
/// <summary> /// <summary>
/// Represents the top left corner coordinate, if Wndx and Wndy form a valid point /// Gets a value that represents the top left corner coordinate, if Wndx and Wndy form a valid point
/// Throws an InvalidOperationException if Wndx or Wndy is null /// Throws an InvalidOperationException if Wndx or Wndy is null
/// It is expected to check for this before using this property /// It is expected to check for this before using this property
/// </summary> /// </summary>

View File

@ -7,9 +7,6 @@
public readonly int Loop = 0; public readonly int Loop = 0;
private int _index = 0; private int _index = 0;
/// <summary>
/// Autohold.
/// </summary>
public AutoPatternBool() public AutoPatternBool()
{ {
Pattern = new[] { true }; Pattern = new[] { true };

View File

@ -184,7 +184,10 @@ namespace BizHawk.Client.Common
} }
} }
} }
catch { /*Eat it*/ } catch
{
/*Eat it*/
}
} }
} }
} }

View File

@ -15,13 +15,11 @@ namespace BizHawk.Client.Common
public MemoryLuaLibrary(Lua lua) public MemoryLuaLibrary(Lua lua)
: base(lua) : base(lua)
{ {
} }
public MemoryLuaLibrary(Lua lua, Action<string> logOutputCallback) public MemoryLuaLibrary(Lua lua, Action<string> logOutputCallback)
: base(lua, logOutputCallback) : base(lua, logOutputCallback)
{ {
} }
public override string Name => "memory"; public override string Name => "memory";
@ -41,14 +39,12 @@ namespace BizHawk.Client.Common
return _currentMemoryDomain; return _currentMemoryDomain;
} }
else
{
var error = $"Error: {Emulator.Attributes().CoreName} does not implement memory domains"; var error = $"Error: {Emulator.Attributes().CoreName} does not implement memory domains";
Log(error); Log(error);
throw new NotImplementedException(error); throw new NotImplementedException(error);
} }
} }
}
#region Unique Library Methods #region Unique Library Methods

View File

@ -28,12 +28,9 @@ namespace BizHawk.Client.Common
public IMovie QueuedMovie { get; set; } public IMovie QueuedMovie { get; set; }
// This wrapper but the logic could change, don't make the client code understand these details // This wrapper but the logic could change, don't make the client code understand these details
public bool MovieIsQueued public bool MovieIsQueued => QueuedMovie != null;
{
get { return QueuedMovie != null; }
}
public MultitrackRecorder MultiTrack { get; private set; } public MultitrackRecorder MultiTrack { get; }
public IMovieController MovieControllerAdapter { get; set; } public IMovieController MovieControllerAdapter { get; set; }
public IMovie Movie { get; set; } public IMovie Movie { get; set; }
@ -54,7 +51,6 @@ namespace BizHawk.Client.Common
/// <summary> /// <summary>
/// Simply shortens the verbosity necessary otherwise /// Simply shortens the verbosity necessary otherwise
/// </summary> /// </summary>
/// <returns></returns>
public ILogEntryGenerator LogGeneratorInstance() public ILogEntryGenerator LogGeneratorInstance()
{ {
return Movie.LogGeneratorInstance(); return Movie.LogGeneratorInstance();

View File

@ -2,6 +2,7 @@
using System.IO; using System.IO;
using BizHawk.Common; using BizHawk.Common;
using BizHawk.Common.IOExtensions;
namespace BizHawk.Client.Common namespace BizHawk.Client.Common
{ {
@ -23,10 +24,10 @@ namespace BizHawk.Client.Common
backupName = backupName.Insert(Filename.LastIndexOf("."), $".{DateTime.Now:yyyy-MM-dd HH.mm.ss}"); 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 directoryInfo = new FileInfo(backupName).Directory;
if (directory_info != null) if (directoryInfo != null)
{ {
Directory.CreateDirectory(directory_info.FullName); Directory.CreateDirectory(directoryInfo.FullName);
} }
Write(backupName, backup: true); Write(backupName, backup: true);
@ -109,7 +110,7 @@ namespace BizHawk.Client.Common
bl.GetLump(BinaryStateLump.Input, true, delegate(TextReader tr) bl.GetLump(BinaryStateLump.Input, true, delegate(TextReader tr)
{ {
var errorMessage = ""; string errorMessage;
IsCountingRerecords = false; IsCountingRerecords = false;
ExtractInputLog(tr, out errorMessage); ExtractInputLog(tr, out errorMessage);
IsCountingRerecords = true; IsCountingRerecords = true;
@ -131,10 +132,11 @@ namespace BizHawk.Client.Common
{ {
SavestateFramebuffer = new int[length / sizeof(int)]; SavestateFramebuffer = new int[length / sizeof(int)];
for (int i = 0; i < SavestateFramebuffer.Length; i++) for (int i = 0; i < SavestateFramebuffer.Length; i++)
{
SavestateFramebuffer[i] = br.ReadInt32(); SavestateFramebuffer[i] = br.ReadInt32();
}
}); });
} }
else if (StartsFromSaveRam) else if (StartsFromSaveRam)
{ {
bl.GetLump(BinaryStateLump.MovieSaveRam, false, bl.GetLump(BinaryStateLump.MovieSaveRam, false,
@ -191,8 +193,7 @@ namespace BizHawk.Client.Common
if (SavestateFramebuffer != null) if (SavestateFramebuffer != null)
{ {
bs.PutLump(BinaryStateLump.Framebuffer, bs.PutLump(BinaryStateLump.Framebuffer, (BinaryWriter bw) => bw.Write(SavestateFramebuffer));
(BinaryWriter bw) => BizHawk.Common.IOExtensions.IOExtensions.Write(bw, SavestateFramebuffer));
} }
} }
else if (StartsFromSaveRam) else if (StartsFromSaveRam)

View File

@ -314,10 +314,10 @@ namespace BizHawk.Client.Common
/// <summary> /// <summary>
/// Takes a log entry from a line in an input log, /// Takes a log entry from a line in an input log,
/// 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 converted
/// </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 key used to describe the mnemonic values and positions in the 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

@ -484,7 +484,7 @@ namespace BizHawk.Client.Common
foreach (string name in BkmMnemonicConstants.ANALOGS[ControlType].Keys) foreach (string name in BkmMnemonicConstants.ANALOGS[ControlType].Keys)
{ {
Force("P" + player + " " + name, Int32.Parse(mnemonic.Substring(srcindex + start, 4))); Force("P" + player + " " + name, int.Parse(mnemonic.Substring(srcindex + start, 4)));
start += 5; start += 5;
} }
} }

View File

@ -4,7 +4,10 @@ namespace BizHawk.Client.Common
{ {
public partial class BkmMovie public partial class BkmMovie
{ {
private enum Moviemode { Inactive, Play, Record, Finished } private enum Moviemode
{
Inactive, Play, Record, Finished
}
private Moviemode _mode = Moviemode.Inactive; private Moviemode _mode = Moviemode.Inactive;

View File

@ -28,7 +28,8 @@ namespace BizHawk.Client.Common
{ {
continue; continue;
} }
else if (line[0] == '|')
if (line[0] == '|')
{ {
// TODO: import a frame of input // TODO: import a frame of input
// TODO: report any errors importing this frame and bail out if so // TODO: report any errors importing this frame and bail out if so
@ -44,8 +45,7 @@ namespace BizHawk.Client.Common
} }
else if (line.ToLower().StartsWith("emuversion")) else if (line.ToLower().StartsWith("emuversion"))
{ {
Result.Movie.Comments.Add( Result.Movie.Comments.Add($"{EMULATIONORIGIN} {emulator} version {ParseHeader(line, "emuVersion")}");
string.Format("{0} {1} version {2}", EMULATIONORIGIN, emulator, ParseHeader(line, "emuVersion")));
} }
else if (line.ToLower().StartsWith("version")) else if (line.ToLower().StartsWith("version"))
{ {

View File

@ -1,9 +1,10 @@
using BizHawk.Emulation.Cores.Sony.PSX; using System;
using System;
using System.IO; using System.IO;
using Newtonsoft.Json; using Newtonsoft.Json;
using BizHawk.Emulation.Cores.Sony.PSX;
namespace BizHawk.Client.Common namespace BizHawk.Client.Common
{ {
[ImportExtension(".pjm")] [ImportExtension(".pjm")]
@ -435,8 +436,8 @@ namespace BizHawk.Client.Common
protected class MiscHeaderInfo protected class MiscHeaderInfo
{ {
public bool binaryFormat = true; public bool binaryFormat = true;
public UInt32 controllerDataOffset; public uint controllerDataOffset;
public UInt32 frameCount; public uint frameCount;
public OctoshockDll.ePeripheralType player1Type; public OctoshockDll.ePeripheralType player1Type;
public OctoshockDll.ePeripheralType player2Type; public OctoshockDll.ePeripheralType player2Type;

View File

@ -1,6 +1,6 @@
using System.IO; using System.IO;
namespace BizHawk.Client.Common.movie.import namespace BizHawk.Client.Common.Movie.Import
{ {
// PXM files are directly compatible with binary-format PJM files, with the only // PXM files are directly compatible with binary-format PJM files, with the only
// difference being fewer flags implemented in the header, hence just calling the // difference being fewer flags implemented in the header, hence just calling the

View File

@ -7,34 +7,32 @@ namespace BizHawk.Client.Common
/// <summary> /// <summary>
/// Sets the controller source used to generate an input log entry /// Sets the controller source used to generate an input log entry
/// </summary> /// </summary>
/// <param name="source"></param>
void SetSource(IController source); void SetSource(IController source);
/// <summary> /// <summary>
/// Generates an input log entry for the current state of Source /// Generates an input log entry for the current state of Source
/// </summary> /// </summary>
/// <returns></returns>
string GenerateLogEntry(); string GenerateLogEntry();
/// <summary> /// <summary>
/// Generates a display friendly verion of the input log entry /// Generates a display friendly version of the input log entry
/// </summary> /// </summary>
/// <returns></returns>
string GenerateInputDisplay(); string GenerateInputDisplay();
/// <summary> /// <summary>
/// Returns whether or not the current controller state is "empty" /// Gets a value indicating whether or not the current controller state is "empty"
/// </summary> /// </summary>
bool IsEmpty { get; } bool IsEmpty { get; }
/// <summary> /// <summary>
/// Returns an input log entry that is considered empty. (booleans will be false, floats will be 0) /// Gets an input log entry that is considered empty. (booleans will be false, floats will be 0)
/// </summary> /// </summary>
string EmptyEntry { get; } string EmptyEntry { get; }
/// <summary> /// <summary>
/// Returns a movie controller adapter in the same state /// Gets a movie controller adapter in the same state as the log entry
/// </summary> /// </summary>
/// <seealso cref="IMovieController"/>
IMovieController MovieControllerAdapter { get; } IMovieController MovieControllerAdapter { get; }
} }
} }

View File

@ -35,12 +35,12 @@ namespace BizHawk.Client.Common
int InputLogLength { get; } int InputLogLength { get; }
/// <summary> /// <summary>
/// Returns the file extension for this implementation /// Gets the file extension for the current <see cref="IMovie"/> implementation
/// </summary> /// </summary>
string PreferredExtension { get; } string PreferredExtension { get; }
/// <summary> /// <summary>
/// Sync Settings from the Core /// Gets or sets the Sync Settings from the Core
/// </summary> /// </summary>
string SyncSettingsJson { get; set; } string SyncSettingsJson { get; set; }
@ -74,7 +74,7 @@ namespace BizHawk.Client.Common
bool PreLoadHeaderAndLength(HawkFile hawkFile); bool PreLoadHeaderAndLength(HawkFile hawkFile);
/// <summary> /// <summary>
/// Returns header key value pairs stored in the movie file /// Gets the header key value pairs stored in the movie file
/// </summary> /// </summary>
IDictionary<string, string> HeaderEntries { get; } IDictionary<string, string> HeaderEntries { get; }
@ -111,7 +111,7 @@ namespace BizHawk.Client.Common
/// This is provided as the means for putting the input log into savestates, /// This is provided as the means for putting the input log into savestates,
/// for the purpose of out of order savestate loading (known as "bullet-proof rerecording") /// for the purpose of out of order savestate loading (known as "bullet-proof rerecording")
/// </summary> /// </summary>
/// <returns>returns a string represntation of the input log in its current state</returns> /// <returns>returns a string representation of the input log in its current state</returns>
string GetInputLog(); string GetInputLog();
/// <summary> /// <summary>
@ -123,7 +123,6 @@ namespace BizHawk.Client.Common
/// Gets one frame from the input log. /// Gets one frame from the input log.
/// </summary> /// </summary>
/// <param name="frame">The frame to get.</param> /// <param name="frame">The frame to get.</param>
/// <returns></returns>
string GetInputLogEntry(int frame); string GetInputLogEntry(int frame);
/// <summary> /// <summary>
@ -140,7 +139,6 @@ namespace BizHawk.Client.Common
/// </summary> /// </summary>
/// <param name="reader">The reader containing the contents of the input log</param> /// <param name="reader">The reader containing the contents of the input log</param>
/// <param name="errorMessage">Returns an error message, if any</param> /// <param name="errorMessage">Returns an error message, if any</param>
/// <returns></returns>
bool ExtractInputLog(TextReader reader, out string errorMessage); bool ExtractInputLog(TextReader reader, out string errorMessage);
#endregion #endregion
@ -209,7 +207,7 @@ namespace BizHawk.Client.Common
/// <summary> /// <summary>
/// Instructs the movie to remove all input from its input log after frame, /// Instructs the movie to remove all input from its input log after frame,
/// AFter truncating, frame will be the last frame of input in the movie's input log /// After truncating, frame will be the last frame of input in the movie's input log
/// </summary> /// </summary>
/// <param name="frame">The frame at which to truncate</param> /// <param name="frame">The frame at which to truncate</param>
void Truncate(int frame); void Truncate(int frame);

View File

@ -132,7 +132,7 @@ namespace BizHawk.Client.Common
var header = (dynamic)JsonConvert.DeserializeObject(tr.ReadLine()); var header = (dynamic)JsonConvert.DeserializeObject(tr.ReadLine());
b.Frame = (int)header.Frame; b.Frame = (int)header.Frame;
var timestamp = (dynamic)header.TimeStamp; var timestamp = header.TimeStamp;
if (timestamp != null) if (timestamp != null)
{ {
@ -143,7 +143,7 @@ namespace BizHawk.Client.Common
b.TimeStamp = DateTime.Now; b.TimeStamp = DateTime.Now;
} }
var identifier = (dynamic)header.UniqueIdentifier; var identifier = header.UniqueIdentifier;
if (identifier != null) if (identifier != null)
{ {
b.UniqueIdentifier = (Guid)identifier; b.UniqueIdentifier = (Guid)identifier;
@ -168,7 +168,9 @@ namespace BizHawk.Client.Common
b.InputLog = StringLogUtil.MakeStringLog(); b.InputLog = StringLogUtil.MakeStringLog();
string line; string line;
while ((line = tr.ReadLine()) != null) while ((line = tr.ReadLine()) != null)
{
b.InputLog.Add(line); b.InputLog.Add(line);
}
}); });
bl.GetLump(nframebuffer, true, delegate(Stream s, long length) bl.GetLump(nframebuffer, true, delegate(Stream s, long length)

View File

@ -19,12 +19,12 @@ namespace BizHawk.Client.Common
base.RecordFrame(frame, source); base.RecordFrame(frame, source);
LagLog.RemoveFrom(frame); _lagLog.RemoveFrom(frame);
LagLog[frame] = Global.Emulator.AsInputPollable().IsLagFrame; _lagLog[frame] = Global.Emulator.AsInputPollable().IsLagFrame;
if (IsRecording) if (IsRecording)
{ {
StateManager.Invalidate(frame + 1); _stateManager.Invalidate(frame + 1);
} }
if (frame != 0) if (frame != 0)
@ -45,8 +45,8 @@ namespace BizHawk.Client.Common
base.Truncate(frame); base.Truncate(frame);
LagLog.RemoveFrom(frame); _lagLog.RemoveFrom(frame);
StateManager.Invalidate(frame); _stateManager.Invalidate(frame);
Markers.TruncateAt(frame); Markers.TruncateAt(frame);
ChangeLog.SetGeneralRedo(); ChangeLog.SetGeneralRedo();
@ -70,7 +70,7 @@ namespace BizHawk.Client.Common
{ {
ChangeLog.AddGeneralUndo(frame, frame, "Set Frame At: " + frame); ChangeLog.AddGeneralUndo(frame, frame, "Set Frame At: " + frame);
base.SetFrameAt(frame, source); SetFrameAt(frame, source);
InvalidateAfter(frame); InvalidateAfter(frame);
ChangeLog.SetGeneralRedo(); ChangeLog.SetGeneralRedo();
@ -163,6 +163,7 @@ namespace BizHawk.Client.Common
} }
} }
} }
ChangeLog.IsRecording = wasRecording; ChangeLog.IsRecording = wasRecording;
} }
} }
@ -367,7 +368,6 @@ namespace BizHawk.Client.Common
ChangeLog.IsRecording = wasRecording; ChangeLog.IsRecording = wasRecording;
} }
Changes = true; Changes = true;
InvalidateAfter(frame - 1); InvalidateAfter(frame - 1);
@ -534,8 +534,10 @@ namespace BizHawk.Client.Common
_log[frame + i] = lg.GenerateLogEntry(); _log[frame + i] = lg.GenerateLogEntry();
if (changed == -1 && old != val) if (changed == -1 && old != val)
{
changed = frame + i; changed = frame + i;
} }
}
if (changed != -1) if (changed != -1)
{ {
@ -550,16 +552,17 @@ namespace BizHawk.Client.Common
public void RemoveLagHistory(int frame) public void RemoveLagHistory(int frame)
{ {
LagLog.RemoveHistoryAt(frame); _lagLog.RemoveHistoryAt(frame);
} }
public void InsertLagHistory(int frame, bool isLag) public void InsertLagHistory(int frame, bool isLag)
{ {
LagLog.InsertHistoryAt(frame, isLag); _lagLog.InsertHistoryAt(frame, isLag);
} }
public void SetLag(int frame, bool? value) public void SetLag(int frame, bool? value)
{ {
LagLog[frame] = value; _lagLog[frame] = value;
} }
#endregion #endregion

View File

@ -9,23 +9,31 @@ namespace BizHawk.Client.Common
private readonly List<List<IMovieAction>> History; private readonly List<List<IMovieAction>> History;
public List<string> Names; public List<string> Names;
public int UndoIndex = -1; public int UndoIndex = -1;
int _maxSteps = 100; private int _maxSteps = 100;
public int MaxSteps public int MaxSteps
{ {
get { return _maxSteps; } get
{
return _maxSteps;
}
set set
{ {
_maxSteps = value; _maxSteps = value;
if (History.Count > value) if (History.Count > value)
{ {
if (History.Count <= value) if (History.Count <= value)
{
ClearLog(); ClearLog();
}
else else
{
ClearLog(History.Count - value); ClearLog(History.Count - value);
} }
} }
} }
}
private int _totalSteps = 0; private int _totalSteps = 0;
private bool RecordingBatch = false; private bool RecordingBatch = false;
@ -48,17 +56,23 @@ namespace BizHawk.Client.Common
public void ClearLog(int upTo = -1) public void ClearLog(int upTo = -1)
{ {
if (upTo == -1) if (upTo == -1)
{
upTo = History.Count; upTo = History.Count;
}
History.RemoveRange(0, upTo); History.RemoveRange(0, upTo);
Names.RemoveRange(0, upTo); Names.RemoveRange(0, upTo);
UndoIndex -= upTo; UndoIndex -= upTo;
if (UndoIndex < -1) if (UndoIndex < -1)
{
UndoIndex = -1; UndoIndex = -1;
}
if (History.Count == 0) if (History.Count == 0)
{
RecordingBatch = false; RecordingBatch = false;
} }
}
private void TruncateLog(int from) private void TruncateLog(int from)
{ {
@ -66,7 +80,9 @@ namespace BizHawk.Client.Common
Names.RemoveRange(from, Names.Count - from); Names.RemoveRange(from, Names.Count - from);
if (UndoIndex < History.Count - 1) if (UndoIndex < History.Count - 1)
{
UndoIndex = History.Count - 1; UndoIndex = History.Count - 1;
}
if (RecordingBatch) if (RecordingBatch)
{ {
@ -79,26 +95,34 @@ namespace BizHawk.Client.Common
/// All changes made between calling Begin and End will be one Undo. /// All changes made between calling Begin and End will be one Undo.
/// If already recording in a batch, calls EndBatch. /// If already recording in a batch, calls EndBatch.
/// </summary> /// </summary>
/// <param name="name">The name of the batch</param>
/// <param name="keepOldBatch">If set and a batch is in progress, a new batch will not be created.</param> /// <param name="keepOldBatch">If set and a batch is in progress, a new batch will not be created.</param>
/// <returns>Returns true if a new batch was started; otherwise false.</returns> /// <returns>Returns true if a new batch was started; otherwise false.</returns>
public bool BeginNewBatch(string name = "", bool keepOldBatch = false) public bool BeginNewBatch(string name = "", bool keepOldBatch = false)
{ {
if (!IsRecording) if (!IsRecording)
{
return false; return false;
}
bool ret = true; bool ret = true;
if (RecordingBatch) if (RecordingBatch)
{ {
if (keepOldBatch) if (keepOldBatch)
{
ret = false; ret = false;
}
else else
{
EndBatch(); EndBatch();
} }
}
if (ret) if (ret)
{ {
ret = AddMovieAction(name); ret = AddMovieAction(name);
} }
RecordingBatch = true; RecordingBatch = true;
return ret; return ret;
@ -111,7 +135,9 @@ namespace BizHawk.Client.Common
public void EndBatch() public void EndBatch()
{ {
if (!IsRecording || !RecordingBatch) if (!IsRecording || !RecordingBatch)
{
return; return;
}
RecordingBatch = false; RecordingBatch = false;
List<IMovieAction> last = History.Last(); List<IMovieAction> last = History.Last();
@ -122,8 +148,10 @@ namespace BizHawk.Client.Common
UndoIndex--; UndoIndex--;
} }
else else
{
last.Capacity = last.Count; last.Capacity = last.Count;
} }
}
/// <summary> /// <summary>
/// Undoes the most recent action batch, if any exist. /// Undoes the most recent action batch, if any exist.
@ -132,11 +160,16 @@ namespace BizHawk.Client.Common
public int Undo() public int Undo()
{ {
if (UndoIndex == -1) if (UndoIndex == -1)
{
return Movie.InputLogLength; return Movie.InputLogLength;
}
List<IMovieAction> batch = History[UndoIndex]; List<IMovieAction> batch = History[UndoIndex];
for (int i = batch.Count - 1; i >= 0; i--) for (int i = batch.Count - 1; i >= 0; i--)
{
batch[i].Undo(Movie); batch[i].Undo(Movie);
}
UndoIndex--; UndoIndex--;
RecordingBatch = false; RecordingBatch = false;
@ -156,12 +189,16 @@ namespace BizHawk.Client.Common
public int Redo() public int Redo()
{ {
if (UndoIndex == History.Count - 1) if (UndoIndex == History.Count - 1)
{
return Movie.InputLogLength; return Movie.InputLogLength;
}
UndoIndex++; UndoIndex++;
List<IMovieAction> batch = History[UndoIndex]; List<IMovieAction> batch = History[UndoIndex];
for (int i = 0; i < batch.Count; i++) foreach (IMovieAction b in batch)
batch[i].Redo(Movie); {
b.Redo(Movie);
}
RecordingBatch = false; RecordingBatch = false;
@ -268,7 +305,7 @@ namespace BizHawk.Client.Common
} }
// TODO: These probably aren't the best way to handle undo/redo. // TODO: These probably aren't the best way to handle undo/redo.
private int lastGeneral; private int _lastGeneral;
public void AddGeneralUndo(int first, int last, string name = "", bool force = false) public void AddGeneralUndo(int first, int last, string name = "", bool force = false)
{ {
@ -276,7 +313,7 @@ namespace BizHawk.Client.Common
{ {
AddMovieAction(name); AddMovieAction(name);
History.Last().Add(new MovieAction(first, last, Movie)); History.Last().Add(new MovieAction(first, last, Movie));
lastGeneral = History.Last().Count - 1; _lastGeneral = History.Last().Count - 1;
} }
} }
@ -284,7 +321,7 @@ namespace BizHawk.Client.Common
{ {
if (IsRecording || force) if (IsRecording || force)
{ {
(History.Last()[lastGeneral] as MovieAction).SetRedoLog(Movie); (History.Last()[_lastGeneral] as MovieAction).SetRedoLog(Movie);
} }
} }
@ -311,9 +348,13 @@ namespace BizHawk.Client.Common
if (IsRecording || force) if (IsRecording || force)
{ {
if (oldPosition == -1) if (oldPosition == -1)
{
name = "Set Marker at frame " + newMarker.Frame; name = "Set Marker at frame " + newMarker.Frame;
}
else else
{
name = "Remove Marker at frame " + oldPosition; name = "Remove Marker at frame " + oldPosition;
}
AddMovieAction(name); AddMovieAction(name);
History.Last().Add(new MovieActionMarker(newMarker, oldPosition, old_message)); History.Last().Add(new MovieActionMarker(newMarker, oldPosition, old_message));
@ -348,37 +389,37 @@ namespace BizHawk.Client.Common
public int FirstFrame { get; } public int FirstFrame { get; }
public int LastFrame { get; } public int LastFrame { get; }
private int undoLength; private readonly int _undoLength;
private int redoLength; private int _redoLength;
private int length => LastFrame - FirstFrame + 1; private int length => LastFrame - FirstFrame + 1;
private List<string> oldLog; private readonly List<string> _oldLog;
private List<string> newLog; private List<string> _newLog;
private bool bindMarkers; private readonly bool _bindMarkers;
public MovieAction(int firstFrame, int lastFrame, TasMovie movie) public MovieAction(int firstFrame, int lastFrame, TasMovie movie)
{ {
FirstFrame = firstFrame; FirstFrame = firstFrame;
LastFrame = lastFrame; LastFrame = lastFrame;
oldLog = new List<string>(length); _oldLog = new List<string>(length);
undoLength = Math.Min(LastFrame + 1, movie.InputLogLength) - FirstFrame; _undoLength = Math.Min(LastFrame + 1, movie.InputLogLength) - FirstFrame;
for (int i = 0; i < undoLength; i++) for (int i = 0; i < _undoLength; i++)
{ {
oldLog.Add(movie.GetLogEntries()[FirstFrame + i]); _oldLog.Add(movie.GetLogEntries()[FirstFrame + i]);
} }
bindMarkers = movie.BindMarkersToInput; _bindMarkers = movie.BindMarkersToInput;
} }
public void SetRedoLog(TasMovie movie) public void SetRedoLog(TasMovie movie)
{ {
redoLength = Math.Min(LastFrame + 1, movie.InputLogLength) - FirstFrame; _redoLength = Math.Min(LastFrame + 1, movie.InputLogLength) - FirstFrame;
newLog = new List<string>(); _newLog = new List<string>();
for (int i = 0; i < redoLength; i++) for (int i = 0; i < _redoLength; i++)
{ {
newLog.Add(movie.GetLogEntries()[FirstFrame + i]); _newLog.Add(movie.GetLogEntries()[FirstFrame + i]);
} }
} }
@ -387,18 +428,25 @@ namespace BizHawk.Client.Common
bool wasRecording = movie.ChangeLog.IsRecording; bool wasRecording = movie.ChangeLog.IsRecording;
bool wasBinding = movie.BindMarkersToInput; bool wasBinding = movie.BindMarkersToInput;
movie.ChangeLog.IsRecording = false; movie.ChangeLog.IsRecording = false;
movie.BindMarkersToInput = bindMarkers; movie.BindMarkersToInput = _bindMarkers;
if (redoLength != length) if (_redoLength != length)
movie.InsertEmptyFrame(FirstFrame, length - redoLength, true); {
if (undoLength != length) movie.InsertEmptyFrame(FirstFrame, length - _redoLength, true);
movie.RemoveFrames(FirstFrame, movie.InputLogLength - undoLength, true); }
for (int i = 0; i < undoLength; i++) if (_undoLength != length)
movie.SetFrame(FirstFrame + i, oldLog[i]); {
movie.RemoveFrames(FirstFrame, movie.InputLogLength - _undoLength, true);
}
for (int i = 0; i < _undoLength; i++)
{
movie.SetFrame(FirstFrame + i, _oldLog[i]);
}
movie.ChangeLog.IsRecording = wasRecording; movie.ChangeLog.IsRecording = wasRecording;
movie.BindMarkersToInput = bindMarkers; movie.BindMarkersToInput = _bindMarkers;
} }
public void Redo(TasMovie movie) public void Redo(TasMovie movie)
@ -406,18 +454,24 @@ namespace BizHawk.Client.Common
bool wasRecording = movie.ChangeLog.IsRecording; bool wasRecording = movie.ChangeLog.IsRecording;
bool wasBinding = movie.BindMarkersToInput; bool wasBinding = movie.BindMarkersToInput;
movie.ChangeLog.IsRecording = false; movie.ChangeLog.IsRecording = false;
movie.BindMarkersToInput = bindMarkers; movie.BindMarkersToInput = _bindMarkers;
if (undoLength != length) if (_undoLength != length)
movie.InsertEmptyFrame(FirstFrame, length - undoLength); {
if (redoLength != length) movie.InsertEmptyFrame(FirstFrame, length - _undoLength);
movie.RemoveFrames(FirstFrame, movie.InputLogLength - redoLength); }
if (_redoLength != length)
{
movie.RemoveFrames(FirstFrame, movie.InputLogLength - _redoLength);
}
for (int i = 0; i < redoLength; i++) for (int i = 0; i < _redoLength; i++)
movie.SetFrame(FirstFrame + i, newLog[i]); {
movie.SetFrame(FirstFrame + i, _newLog[i]);
}
movie.ChangeLog.IsRecording = wasRecording; movie.ChangeLog.IsRecording = wasRecording;
movie.BindMarkersToInput = bindMarkers; movie.BindMarkersToInput = _bindMarkers;
} }
} }
@ -426,8 +480,8 @@ namespace BizHawk.Client.Common
public int FirstFrame { get; } public int FirstFrame { get; }
public int LastFrame { get; } public int LastFrame { get; }
private string oldMessage; private readonly string _oldMessage;
private string newMessage; private readonly string _newMessage;
public MovieActionMarker(TasMovieMarker marker, int oldPosition = -1, string old_message = "") public MovieActionMarker(TasMovieMarker marker, int oldPosition = -1, string old_message = "")
{ {
@ -435,69 +489,77 @@ namespace BizHawk.Client.Common
if (marker == null) if (marker == null)
{ {
LastFrame = -1; LastFrame = -1;
oldMessage = old_message; _oldMessage = old_message;
} }
else else
{ {
LastFrame = marker.Frame; LastFrame = marker.Frame;
if (old_message == "") _oldMessage = old_message == "" ? marker.Message : old_message;
oldMessage = marker.Message; _newMessage = marker.Message;
else
oldMessage = old_message;
newMessage = marker.Message;
} }
} }
public void Undo(TasMovie movie) public void Undo(TasMovie movie)
{ {
if (FirstFrame == -1) // Action: Place marker if (FirstFrame == -1) // Action: Place marker
{
movie.Markers.Remove(movie.Markers.Get(LastFrame), true); movie.Markers.Remove(movie.Markers.Get(LastFrame), true);
}
else if (LastFrame == -1) // Action: Remove marker else if (LastFrame == -1) // Action: Remove marker
movie.Markers.Add(FirstFrame, oldMessage, true); {
movie.Markers.Add(FirstFrame, _oldMessage, true);
}
else // Action: Move/rename marker else // Action: Move/rename marker
{ {
movie.Markers.Move(LastFrame, FirstFrame, true); movie.Markers.Move(LastFrame, FirstFrame, true);
movie.Markers.Get(LastFrame).Message = oldMessage; movie.Markers.Get(LastFrame).Message = _oldMessage;
} }
} }
public void Redo(TasMovie movie) public void Redo(TasMovie movie)
{ {
if (FirstFrame == -1) // Action: Place marker if (FirstFrame == -1) // Action: Place marker
movie.Markers.Add(LastFrame, oldMessage, true); {
movie.Markers.Add(LastFrame, _oldMessage, true);
}
else if (LastFrame == -1) // Action: Remove marker else if (LastFrame == -1) // Action: Remove marker
{
movie.Markers.Remove(movie.Markers.Get(FirstFrame), true); movie.Markers.Remove(movie.Markers.Get(FirstFrame), true);
}
else // Action: Move/rename marker else // Action: Move/rename marker
{ {
movie.Markers.Move(FirstFrame, LastFrame, true); movie.Markers.Move(FirstFrame, LastFrame, true);
movie.Markers.Get(LastFrame).Message = newMessage; movie.Markers.Get(LastFrame).Message = _newMessage;
} }
} }
} }
public class MovieActionFrameEdit : IMovieAction public class MovieActionFrameEdit : IMovieAction
{ {
public int FirstFrame { get; private set; } public int FirstFrame { get; }
public int LastFrame { get { return FirstFrame; } } public int LastFrame => FirstFrame;
private float oldState, newState;
private string buttonName; private readonly float _oldState;
private bool isFloat = false; private readonly float _newState;
private readonly string _buttonName;
private readonly bool _isFloat;
public MovieActionFrameEdit(int frame, string button, bool oldS, bool newS) public MovieActionFrameEdit(int frame, string button, bool oldS, bool newS)
{ {
oldState = oldS ? 1 : 0; _oldState = oldS ? 1 : 0;
newState = newS ? 1 : 0; _newState = newS ? 1 : 0;
FirstFrame = frame; FirstFrame = frame;
buttonName = button; _buttonName = button;
} }
public MovieActionFrameEdit(int frame, string button, float oldS, float newS) public MovieActionFrameEdit(int frame, string button, float oldS, float newS)
{ {
oldState = oldS; _oldState = oldS;
newState = newS; _newState = newS;
FirstFrame = frame; FirstFrame = frame;
buttonName = button; _buttonName = button;
isFloat = true; _isFloat = true;
} }
public void Undo(TasMovie movie) public void Undo(TasMovie movie)
@ -505,10 +567,14 @@ namespace BizHawk.Client.Common
bool wasRecording = movie.ChangeLog.IsRecording; bool wasRecording = movie.ChangeLog.IsRecording;
movie.ChangeLog.IsRecording = false; movie.ChangeLog.IsRecording = false;
if (isFloat) if (_isFloat)
movie.SetFloatState(FirstFrame, buttonName, oldState); {
movie.SetFloatState(FirstFrame, _buttonName, _oldState);
}
else else
movie.SetBoolState(FirstFrame, buttonName, oldState == 1); {
movie.SetBoolState(FirstFrame, _buttonName, _oldState == 1);
}
movie.ChangeLog.IsRecording = wasRecording; movie.ChangeLog.IsRecording = wasRecording;
} }
@ -518,10 +584,14 @@ namespace BizHawk.Client.Common
bool wasRecording = movie.ChangeLog.IsRecording; bool wasRecording = movie.ChangeLog.IsRecording;
movie.ChangeLog.IsRecording = false; movie.ChangeLog.IsRecording = false;
if (isFloat) if (_isFloat)
movie.SetFloatState(FirstFrame, buttonName, newState); {
movie.SetFloatState(FirstFrame, _buttonName, _newState);
}
else else
movie.SetBoolState(FirstFrame, buttonName, newState == 1); {
movie.SetBoolState(FirstFrame, _buttonName, _newState == 1);
}
movie.ChangeLog.IsRecording = wasRecording; movie.ChangeLog.IsRecording = wasRecording;
} }
@ -529,36 +599,40 @@ namespace BizHawk.Client.Common
public class MovieActionPaint : IMovieAction public class MovieActionPaint : IMovieAction
{ {
public int FirstFrame { get; private set; } public int FirstFrame { get; }
public int LastFrame { get; private set; } public int LastFrame { get; }
private List<float> oldState; private readonly List<float> _oldState;
private float newState; private readonly float _newState;
private string buttonName; private readonly string _buttonName;
private bool isFloat = false; private readonly bool _isFloat = false;
public MovieActionPaint(int startFrame, int endFrame, string button, bool newS, TasMovie movie) public MovieActionPaint(int startFrame, int endFrame, string button, bool newS, TasMovie movie)
{ {
newState = newS ? 1 : 0; _newState = newS ? 1 : 0;
FirstFrame = startFrame; FirstFrame = startFrame;
LastFrame = endFrame; LastFrame = endFrame;
buttonName = button; _buttonName = button;
oldState = new List<float>(endFrame - startFrame + 1); _oldState = new List<float>(endFrame - startFrame + 1);
for (int i = 0; i < endFrame - startFrame + 1; i++) for (int i = 0; i < endFrame - startFrame + 1; i++)
oldState.Add(movie.BoolIsPressed(startFrame + i, button) ? 1 : 0); {
_oldState.Add(movie.BoolIsPressed(startFrame + i, button) ? 1 : 0);
}
} }
public MovieActionPaint(int startFrame, int endFrame, string button, float newS, TasMovie movie) public MovieActionPaint(int startFrame, int endFrame, string button, float newS, TasMovie movie)
{ {
newState = newS; _newState = newS;
FirstFrame = startFrame; FirstFrame = startFrame;
LastFrame = endFrame; LastFrame = endFrame;
buttonName = button; _buttonName = button;
isFloat = true; _isFloat = true;
oldState = new List<float>(endFrame - startFrame + 1); _oldState = new List<float>(endFrame - startFrame + 1);
for (int i = 0; i < endFrame - startFrame + 1; i++) for (int i = 0; i < endFrame - startFrame + 1; i++)
oldState.Add(movie.BoolIsPressed(startFrame + i, button) ? 1 : 0); {
_oldState.Add(movie.BoolIsPressed(startFrame + i, button) ? 1 : 0);
}
} }
public void Undo(TasMovie movie) public void Undo(TasMovie movie)
@ -566,15 +640,19 @@ namespace BizHawk.Client.Common
bool wasRecording = movie.ChangeLog.IsRecording; bool wasRecording = movie.ChangeLog.IsRecording;
movie.ChangeLog.IsRecording = false; movie.ChangeLog.IsRecording = false;
if (isFloat) if (_isFloat)
{ {
for (int i = 0; i < oldState.Count; i++) for (int i = 0; i < _oldState.Count; i++)
movie.SetFloatState(FirstFrame + i, buttonName, oldState[i]); {
movie.SetFloatState(FirstFrame + i, _buttonName, _oldState[i]);
}
} }
else else
{ {
for (int i = 0; i < oldState.Count; i++) for (int i = 0; i < _oldState.Count; i++)
movie.SetBoolState(FirstFrame + i, buttonName, oldState[i] == 1); {
movie.SetBoolState(FirstFrame + i, _buttonName, _oldState[i] == 1);
}
} }
movie.ChangeLog.IsRecording = wasRecording; movie.ChangeLog.IsRecording = wasRecording;
@ -585,10 +663,14 @@ namespace BizHawk.Client.Common
bool wasRecording = movie.ChangeLog.IsRecording; bool wasRecording = movie.ChangeLog.IsRecording;
movie.ChangeLog.IsRecording = false; movie.ChangeLog.IsRecording = false;
if (isFloat) if (_isFloat)
movie.SetFloatStates(FirstFrame, LastFrame - FirstFrame + 1, buttonName, newState); {
movie.SetFloatStates(FirstFrame, LastFrame - FirstFrame + 1, _buttonName, _newState);
}
else else
movie.SetBoolStates(FirstFrame, LastFrame - FirstFrame + 1, buttonName, newState == 1); {
movie.SetBoolStates(FirstFrame, LastFrame - FirstFrame + 1, _buttonName, _newState == 1);
}
movie.ChangeLog.IsRecording = wasRecording; movie.ChangeLog.IsRecording = wasRecording;
} }
@ -596,20 +678,20 @@ namespace BizHawk.Client.Common
public class MovieActionBindInput : IMovieAction public class MovieActionBindInput : IMovieAction
{ {
public int FirstFrame { get; private set; } public int FirstFrame { get; }
public int LastFrame { get; private set; } public int LastFrame { get; }
private string log; private readonly string _log;
private bool delete; private readonly bool _delete;
private bool bindMarkers; private readonly bool _bindMarkers;
public MovieActionBindInput(TasMovie movie, int frame, bool isDelete) public MovieActionBindInput(TasMovie movie, int frame, bool isDelete)
{ {
FirstFrame = LastFrame = frame; FirstFrame = LastFrame = frame;
log = movie.GetInputLogEntry(frame); _log = movie.GetInputLogEntry(frame);
delete = isDelete; _delete = isDelete;
bindMarkers = movie.BindMarkersToInput; _bindMarkers = movie.BindMarkersToInput;
} }
public void Undo(TasMovie movie) public void Undo(TasMovie movie)
@ -617,11 +699,11 @@ namespace BizHawk.Client.Common
bool wasRecording = movie.ChangeLog.IsRecording; bool wasRecording = movie.ChangeLog.IsRecording;
bool wasBinding = movie.BindMarkersToInput; bool wasBinding = movie.BindMarkersToInput;
movie.ChangeLog.IsRecording = false; movie.ChangeLog.IsRecording = false;
movie.BindMarkersToInput = bindMarkers; movie.BindMarkersToInput = _bindMarkers;
if (delete) // Insert if (_delete) // Insert
{ {
movie.InsertInput(FirstFrame, log); movie.InsertInput(FirstFrame, _log);
movie.InsertLagHistory(FirstFrame + 1, true); movie.InsertLagHistory(FirstFrame + 1, true);
} }
else // Delete else // Delete
@ -631,7 +713,7 @@ namespace BizHawk.Client.Common
} }
movie.ChangeLog.IsRecording = wasRecording; movie.ChangeLog.IsRecording = wasRecording;
movie.BindMarkersToInput = bindMarkers; movie.BindMarkersToInput = _bindMarkers;
} }
public void Redo(TasMovie movie) public void Redo(TasMovie movie)
@ -639,21 +721,21 @@ namespace BizHawk.Client.Common
bool wasRecording = movie.ChangeLog.IsRecording; bool wasRecording = movie.ChangeLog.IsRecording;
bool wasBinding = movie.BindMarkersToInput; bool wasBinding = movie.BindMarkersToInput;
movie.ChangeLog.IsRecording = false; movie.ChangeLog.IsRecording = false;
movie.BindMarkersToInput = bindMarkers; movie.BindMarkersToInput = _bindMarkers;
if (delete) if (_delete)
{ {
movie.RemoveFrame(FirstFrame); movie.RemoveFrame(FirstFrame);
movie.RemoveLagHistory(FirstFrame + 1); movie.RemoveLagHistory(FirstFrame + 1);
} }
else else
{ {
movie.InsertInput(FirstFrame, log); movie.InsertInput(FirstFrame, _log);
movie.InsertLagHistory(FirstFrame + 1, true); movie.InsertLagHistory(FirstFrame + 1, true);
} }
movie.ChangeLog.IsRecording = wasRecording; movie.ChangeLog.IsRecording = wasRecording;
movie.BindMarkersToInput = bindMarkers; movie.BindMarkersToInput = _bindMarkers;
} }
} }

View File

@ -27,9 +27,9 @@ namespace BizHawk.Client.Common
bs.PutLump(BinaryStateLump.Input, tw => WriteInputLog(tw)); bs.PutLump(BinaryStateLump.Input, tw => WriteInputLog(tw));
// TasProj extras // TasProj extras
bs.PutLump(BinaryStateLump.StateHistorySettings, tw => tw.WriteLine(StateManager.Settings.ToString())); bs.PutLump(BinaryStateLump.StateHistorySettings, tw => tw.WriteLine(_stateManager.Settings.ToString()));
bs.PutLump(BinaryStateLump.LagLog, (BinaryWriter bw) => LagLog.Save(bw)); bs.PutLump(BinaryStateLump.LagLog, (BinaryWriter bw) => _lagLog.Save(bw));
bs.PutLump(BinaryStateLump.Markers, tw => tw.WriteLine(Markers.ToString())); bs.PutLump(BinaryStateLump.Markers, tw => tw.WriteLine(Markers.ToString()));
if (StartsFromSavestate) if (StartsFromSavestate)
@ -62,17 +62,17 @@ namespace BizHawk.Client.Common
if (Branches.Any()) if (Branches.Any())
{ {
Branches.Save(bs); Branches.Save(bs);
if (StateManager.Settings.BranchStatesInTasproj) if (_stateManager.Settings.BranchStatesInTasproj)
{ {
bs.PutLump(BinaryStateLump.BranchStateHistory, (BinaryWriter bw) => StateManager.SaveBranchStates(bw)); bs.PutLump(BinaryStateLump.BranchStateHistory, (BinaryWriter bw) => _stateManager.SaveBranchStates(bw));
} }
} }
bs.PutLump(BinaryStateLump.Session, tw => tw.WriteLine(Session.ToString())); bs.PutLump(BinaryStateLump.Session, tw => tw.WriteLine(Session.ToString()));
if (StateManager.Settings.SaveStateHistory) if (_stateManager.Settings.SaveStateHistory)
{ {
bs.PutLump(BinaryStateLump.StateHistory, (BinaryWriter bw) => StateManager.Save(bw)); bs.PutLump(BinaryStateLump.StateHistory, (BinaryWriter bw) => _stateManager.Save(bw));
} }
} }
@ -183,12 +183,12 @@ namespace BizHawk.Client.Common
// TasMovie enhanced information // TasMovie enhanced information
bl.GetLump(BinaryStateLump.LagLog, false, delegate(BinaryReader br, long length) bl.GetLump(BinaryStateLump.LagLog, false, delegate(BinaryReader br, long length)
{ {
LagLog.Load(br); _lagLog.Load(br);
}); });
bl.GetLump(BinaryStateLump.StateHistorySettings, false, delegate(TextReader tr) bl.GetLump(BinaryStateLump.StateHistorySettings, false, delegate(TextReader tr)
{ {
StateManager.Settings.PopulateFromString(tr.ReadToEnd()); _stateManager.Settings.PopulateFromString(tr.ReadToEnd());
}); });
bl.GetLump(BinaryStateLump.Markers, false, delegate(TextReader tr) bl.GetLump(BinaryStateLump.Markers, false, delegate(TextReader tr)
@ -243,11 +243,11 @@ namespace BizHawk.Client.Common
}); });
Branches.Load(bl, this); Branches.Load(bl, this);
if (StateManager.Settings.BranchStatesInTasproj) if (_stateManager.Settings.BranchStatesInTasproj)
{ {
bl.GetLump(BinaryStateLump.BranchStateHistory, false, delegate(BinaryReader br, long length) bl.GetLump(BinaryStateLump.BranchStateHistory, false, delegate(BinaryReader br, long length)
{ {
StateManager.LoadBranchStates(br); _stateManager.LoadBranchStates(br);
}); });
} }
@ -258,17 +258,17 @@ namespace BizHawk.Client.Common
if (!preload) if (!preload)
{ {
if (StateManager.Settings.SaveStateHistory) if (_stateManager.Settings.SaveStateHistory)
{ {
bl.GetLump(BinaryStateLump.StateHistory, false, delegate(BinaryReader br, long length) bl.GetLump(BinaryStateLump.StateHistory, false, delegate(BinaryReader br, long length)
{ {
StateManager.Load(br); _stateManager.Load(br);
}); });
} }
// Movie should always have a state at frame 0. // Movie should always have a state at frame 0.
if (!StartsFromSavestate && Global.Emulator.Frame == 0) if (!StartsFromSavestate && Global.Emulator.Frame == 0)
StateManager.Capture(); _stateManager.Capture();
} }
} }
@ -278,8 +278,8 @@ namespace BizHawk.Client.Common
private void ClearTasprojExtras() private void ClearTasprojExtras()
{ {
LagLog.Clear(); _lagLog.Clear();
StateManager.Clear(); _stateManager.Clear();
Markers.Clear(); Markers.Clear();
ChangeLog.ClearLog(); ChangeLog.ClearLog();
} }

View File

@ -12,37 +12,45 @@ namespace BizHawk.Client.Common
{ {
public sealed partial class TasMovie : Bk2Movie, INotifyPropertyChanged public sealed partial class TasMovie : Bk2Movie, INotifyPropertyChanged
{ {
private readonly Bk2MnemonicConstants _mnemonics = new Bk2MnemonicConstants();
private readonly TasStateManager _stateManager;
private readonly TasLagLog _lagLog = new TasLagLog();
private readonly Dictionary<int, IController> _inputStateCache = new Dictionary<int, IController>();
private BackgroundWorker _progressReportWorker;
public new const string Extension = "tasproj"; public new const string Extension = "tasproj";
public const string DefaultProjectName = "default"; public const string DefaultProjectName = "default";
public BackgroundWorker _progressReportWorker = null;
public bool LastPositionStable = true; public bool LastPositionStable { get; set; } = true;
public string NewBranchText = ""; public string NewBranchText { get; set; } = "";
public readonly IStringLog VerificationLog = StringLogUtil.MakeStringLog(); // For movies that do not begin with power-on, this is the input required to get into the initial state public readonly IStringLog VerificationLog = StringLogUtil.MakeStringLog(); // For movies that do not begin with power-on, this is the input required to get into the initial state
public readonly TasBranchCollection Branches = new TasBranchCollection(); public readonly TasBranchCollection Branches = new TasBranchCollection();
public readonly TasSession Session; public readonly TasSession Session;
private readonly Bk2MnemonicConstants Mnemonics = new Bk2MnemonicConstants();
private readonly TasStateManager StateManager; public TasLagLog TasLagLog => _lagLog;
private readonly TasLagLog LagLog = new TasLagLog();
private readonly Dictionary<int, IController> InputStateCache = new Dictionary<int, IController>(); public IStringLog InputLog => _log;
public TasLagLog TasLagLog { get { return LagLog; } }
public IStringLog InputLog { get { return _log; } } public TasMovieMarkerList Markers { get; private set; }
public TasMovieMarkerList Markers { get; set; }
public bool BindMarkersToInput { get; set; } public bool BindMarkersToInput { get; set; }
public bool UseInputCache { get; set; } public bool UseInputCache { get; set; }
public int CurrentBranch { get; set; } public int CurrentBranch { get; set; }
public int BranchCount => Branches.Count; public int BranchCount => Branches.Count;
public int LastValidFrame => LagLog.LastValidFrame; public int LastValidFrame => _lagLog.LastValidFrame;
public override string PreferredExtension => Extension; public override string PreferredExtension => Extension;
public TasStateManager TasStateManager => StateManager; public TasStateManager TasStateManager => _stateManager;
public TasMovieRecord this[int index] => new TasMovieRecord public TasMovieRecord this[int index] => new TasMovieRecord
{ {
// State = StateManager[index], // State = StateManager[index],
HasState = StateManager.HasState(index), HasState = _stateManager.HasState(index),
LogEntry = GetInputLogEntry(index), LogEntry = GetInputLogEntry(index),
Lagged = LagLog[index + 1], Lagged = _lagLog[index + 1],
WasLagged = LagLog.History(index + 1) WasLagged = _lagLog.History(index + 1)
}; };
public TasMovie(string path, bool startsFromSavestate = false, BackgroundWorker progressReportWorker = null) public TasMovie(string path, bool startsFromSavestate = false, BackgroundWorker progressReportWorker = null)
@ -56,7 +64,7 @@ namespace BizHawk.Client.Common
} }
ChangeLog = new TasMovieChangeLog(this); ChangeLog = new TasMovieChangeLog(this);
StateManager = new TasStateManager(this); _stateManager = new TasStateManager(this);
Session = new TasSession(this); Session = new TasSession(this);
Header[HeaderKeys.MOVIEVERSION] = "BizHawk v2.0 Tasproj v1.0"; Header[HeaderKeys.MOVIEVERSION] = "BizHawk v2.0 Tasproj v1.0";
Markers = new TasMovieMarkerList(this); Markers = new TasMovieMarkerList(this);
@ -75,7 +83,7 @@ namespace BizHawk.Client.Common
} }
ChangeLog = new TasMovieChangeLog(this); ChangeLog = new TasMovieChangeLog(this);
StateManager = new TasStateManager(this); _stateManager = new TasStateManager(this);
Session = new TasSession(this); Session = new TasSession(this);
Header[HeaderKeys.MOVIEVERSION] = "BizHawk v2.0 Tasproj v1.0"; Header[HeaderKeys.MOVIEVERSION] = "BizHawk v2.0 Tasproj v1.0";
Markers = new TasMovieMarkerList(this); Markers = new TasMovieMarkerList(this);
@ -145,8 +153,8 @@ namespace BizHawk.Client.Common
/// <param name="frame">The last frame that can be valid.</param> /// <param name="frame">The last frame that can be valid.</param>
private void InvalidateAfter(int frame) private void InvalidateAfter(int frame)
{ {
var anyInvalidated = LagLog.RemoveFrom(frame); var anyInvalidated = _lagLog.RemoveFrom(frame);
StateManager.Invalidate(frame + 1); _stateManager.Invalidate(frame + 1);
Changes = true; // TODO check if this actually removed anything before flagging changes Changes = true; // TODO check if this actually removed anything before flagging changes
if (anyInvalidated && Global.MovieSession.Movie.IsCountingRerecords) if (anyInvalidated && Global.MovieSession.Movie.IsCountingRerecords)
@ -161,16 +169,16 @@ namespace BizHawk.Client.Common
/// </summary> /// </summary>
public string DisplayValue(int frame, string buttonName) public string DisplayValue(int frame, string buttonName)
{ {
if (UseInputCache && InputStateCache.ContainsKey(frame)) if (UseInputCache && _inputStateCache.ContainsKey(frame))
{ {
return CreateDisplayValueForButton(InputStateCache[frame], buttonName); return CreateDisplayValueForButton(_inputStateCache[frame], buttonName);
} }
var adapter = GetInputState(frame); var adapter = GetInputState(frame);
if (UseInputCache) if (UseInputCache)
{ {
InputStateCache.Add(frame, adapter); _inputStateCache.Add(frame, adapter);
} }
return CreateDisplayValueForButton(adapter, buttonName); return CreateDisplayValueForButton(adapter, buttonName);
@ -178,7 +186,7 @@ namespace BizHawk.Client.Common
public void FlushInputCache() public void FlushInputCache()
{ {
InputStateCache.Clear(); _inputStateCache.Clear();
} }
public string CreateDisplayValueForButton(IController adapter, string buttonName) public string CreateDisplayValueForButton(IController adapter, string buttonName)
@ -186,7 +194,7 @@ namespace BizHawk.Client.Common
if (adapter.Definition.BoolButtons.Contains(buttonName)) if (adapter.Definition.BoolButtons.Contains(buttonName))
{ {
return adapter.IsPressed(buttonName) return adapter.IsPressed(buttonName)
? Mnemonics[buttonName].ToString() ? _mnemonics[buttonName].ToString()
: ""; : "";
} }
@ -212,9 +220,9 @@ namespace BizHawk.Client.Common
public void ClearGreenzone() public void ClearGreenzone()
{ {
if (StateManager.Any()) if (_stateManager.Any())
{ {
StateManager.ClearStateHistory(); _stateManager.ClearStateHistory();
Changes = true; Changes = true;
} }
} }
@ -227,17 +235,17 @@ namespace BizHawk.Client.Common
LastPositionStable = false; LastPositionStable = false;
} }
LagLog[Global.Emulator.Frame] = Global.Emulator.AsInputPollable().IsLagFrame; _lagLog[Global.Emulator.Frame] = Global.Emulator.AsInputPollable().IsLagFrame;
if (!StateManager.HasState(Global.Emulator.Frame)) if (!_stateManager.HasState(Global.Emulator.Frame))
{ {
StateManager.Capture(); _stateManager.Capture();
} }
} }
public void ClearLagLog() public void ClearLagLog()
{ {
LagLog.Clear(); _lagLog.Clear();
} }
public void DeleteLogBefore(int frame) public void DeleteLogBefore(int frame)
@ -426,7 +434,7 @@ namespace BizHawk.Client.Common
if (TimelineBranchFrame.HasValue) if (TimelineBranchFrame.HasValue)
{ {
LagLog.RemoveFrom(TimelineBranchFrame.Value); _lagLog.RemoveFrom(TimelineBranchFrame.Value);
TasStateManager.Invalidate(TimelineBranchFrame.Value); TasStateManager.Invalidate(TimelineBranchFrame.Value);
} }
@ -512,16 +520,16 @@ namespace BizHawk.Client.Common
// but if there's none, or only *after* divergent point, don't invalidate the entire movie anymore // but if there's none, or only *after* divergent point, don't invalidate the entire movie anymore
if (divergentPoint.HasValue) if (divergentPoint.HasValue)
{ {
StateManager.Invalidate(divergentPoint.Value); _stateManager.Invalidate(divergentPoint.Value);
LagLog.FromLagLog(branch.LagLog); // don't truncate LagLog if the branch's one is shorter, but input is the same _lagLog.FromLagLog(branch.LagLog); // don't truncate LagLog if the branch's one is shorter, but input is the same
} }
else else
{ {
StateManager.Invalidate(branch.InputLog.Count); _stateManager.Invalidate(branch.InputLog.Count);
} }
StateManager.LoadBranch(Branches.IndexOf(branch)); _stateManager.LoadBranch(Branches.IndexOf(branch));
StateManager.SetState(branch.Frame, branch.CoreData); _stateManager.SetState(branch.Frame, branch.CoreData);
////ChangeLog = branch.ChangeLog; ////ChangeLog = branch.ChangeLog;
if (BindMarkersToInput) // pretty critical not to erase them if (BindMarkersToInput) // pretty critical not to erase them

View File

@ -19,7 +19,7 @@ namespace BizHawk.Client.Common
} }
/// <summary> /// <summary>
/// Parses a Marker from a line of text /// Initializes a new instance of the <see cref="TasMovieMarker"/> class from a line of text
/// </summary> /// </summary>
public TasMovieMarker(string line) public TasMovieMarker(string line)
{ {

View File

@ -666,7 +666,9 @@ namespace BizHawk.Client.Common
////Used += len; ////Used += len;
} }
} }
catch (EndOfStreamException) { } catch (EndOfStreamException)
{
}
} }
public void SaveBranchStates(BinaryWriter bw) public void SaveBranchStates(BinaryWriter bw)
@ -707,7 +709,10 @@ namespace BizHawk.Client.Common
c--; c--;
} }
} }
catch (EndOfStreamException) { } // Bad! catch (EndOfStreamException)
{
// Bad!
}
} }

View File

@ -32,45 +32,45 @@ namespace BizHawk.Client.Common
/// </summary> /// </summary>
[DisplayName("Save History")] [DisplayName("Save History")]
[Description("Whether or not to use savestate history")] [Description("Whether or not to use savestate history")]
public bool SaveStateHistory { get { return DiskSaveCapacitymb != 0; } } public bool SaveStateHistory => DiskSaveCapacitymb != 0;
/// <summary> /// <summary>
/// The size limit to use when saving the tas project to disk. /// Gets or sets the size limit to use when saving the TAS project to disk.
/// </summary> /// </summary>
[DisplayName("Save Capacity (in megabytes)")] [DisplayName("Save Capacity (in megabytes)")]
[Description("The size limit to use when saving the tas project to disk.")] [Description("The size limit to use when saving the tas project to disk.")]
public int DiskSaveCapacitymb { get; set; } public int DiskSaveCapacitymb { get; set; }
/// <summary> /// <summary>
/// The total amount of memory to devote to state history in megabytes /// Gets or sets the total amount of memory to devote to state history in megabytes
/// </summary> /// </summary>
[DisplayName("Capacity (in megabytes)")] [DisplayName("Capacity (in megabytes)")]
[Description("The size limit of the state history buffer. When this limit is reached it will start moving to disk.")] [Description("The size limit of the state history buffer. When this limit is reached it will start moving to disk.")]
public int Capacitymb { get; set; } public int Capacitymb { get; set; }
/// <summary> /// <summary>
/// The total amount of disk space to devote to state history in megabytes /// Gets or sets the total amount of disk space to devote to state history in megabytes
/// </summary> /// </summary>
[DisplayName("Disk Capacity (in megabytes)")] [DisplayName("Disk Capacity (in megabytes)")]
[Description("The size limit of the state history buffer on the disk. When this limit is reached it will start removing previous savestates")] [Description("The size limit of the state history buffer on the disk. When this limit is reached it will start removing previous savestates")]
public int DiskCapacitymb { get; set; } public int DiskCapacitymb { get; set; }
/// <summary> /// <summary>
/// The amount of states to skip during project saving /// Gets or sets the amount of states to skip during project saving
/// </summary> /// </summary>
[DisplayName("State interval for .tasproj")] [DisplayName("State interval for .tasproj")]
[Description("The actual state gap in frames is calculated as Nth power on 2")] [Description("The actual state gap in frames is calculated as Nth power on 2")]
public int StateGap { get; set; } public int StateGap { get; set; }
/// <summary> /// <summary>
/// Put branch states to .tasproj /// Gets or sets a value indicating whether or not to save branch states into the movie file
/// </summary> /// </summary>
[DisplayName("Put branch states to .tasproj")] [DisplayName("Put branch states to .tasproj")]
[Description("Put branch states to .tasproj")] [Description("Put branch states to .tasproj")]
public bool BranchStatesInTasproj { get; set; } public bool BranchStatesInTasproj { get; set; }
/// <summary> /// <summary>
/// Erase branch states before greenzone states when capacity is met /// Gets or sets a value indicating whether or not to erase branch states before greenzone states when capacity is met
/// </summary> /// </summary>
[DisplayName("Erase branch states first")] [DisplayName("Erase branch states first")]
[Description("Erase branch states before greenzone states when capacity is met")] [Description("Erase branch states before greenzone states when capacity is met")]
@ -116,33 +116,20 @@ namespace BizHawk.Client.Common
if (!int.TryParse(lines[0], out refCapacity)) if (!int.TryParse(lines[0], out refCapacity))
{ {
if (bool.Parse(lines[0])) DiskSaveCapacitymb = bool.Parse(lines[0]) ? Capacitymb : 0;
DiskSaveCapacitymb = Capacitymb;
else
DiskSaveCapacitymb = 0;
} }
else else
{
DiskSaveCapacitymb = refCapacity; DiskSaveCapacitymb = refCapacity;
}
if (lines.Length > 2) DiskCapacitymb = lines.Length > 2 ? int.Parse(lines[2]) : 512;
DiskCapacitymb = int.Parse(lines[2]);
else
DiskCapacitymb = 512;
if (lines.Length > 3) BranchStatesInTasproj = lines.Length > 3 && bool.Parse(lines[3]);
BranchStatesInTasproj = bool.Parse(lines[3]);
else
BranchStatesInTasproj = false;
if (lines.Length > 4) EraseBranchStatesFirst = lines.Length <= 4 || bool.Parse(lines[4]);
EraseBranchStatesFirst = bool.Parse(lines[4]);
else
EraseBranchStatesFirst = true;
if (lines.Length > 5) StateGap = lines.Length > 5 ? int.Parse(lines[5]) : 4;
StateGap = int.Parse(lines[5]);
else
StateGap = 4;
} }
catch (Exception) // TODO: this is bad catch (Exception) // TODO: this is bad
{ {

View File

@ -16,11 +16,10 @@ namespace BizHawk.Client.Common
} }
private readonly Watch _watch; private readonly Watch _watch;
private readonly COMPARISONTYPE _comparisonType;
private int? _compare; private int? _compare;
private int _val; private int _val;
private bool _enabled; private bool _enabled;
private readonly COMPARISONTYPE _comparisonType;
public Cheat(Watch watch, int value, int? compare = null, bool enabled = true, COMPARISONTYPE comparisonType = COMPARISONTYPE.NONE) public Cheat(Watch watch, int value, int? compare = null, bool enabled = true, COMPARISONTYPE comparisonType = COMPARISONTYPE.NONE)
{ {

View File

@ -283,6 +283,7 @@ namespace BizHawk.Client.Common
/// Returns the value of a given cheat, or a partial value of a multi-byte cheat /// Returns the value of a given cheat, or a partial value of a multi-byte cheat
/// Note that address + size MUST NOT exceed the range of the cheat or undefined behavior will occur /// Note that address + size MUST NOT exceed the range of the cheat or undefined behavior will occur
/// </summary> /// </summary>
/// <param name="domain">The <seealso cref="MemoryDomain"/> to apply cheats to</param>
/// <param name="addr">The starting address for which you will get the number of bytes</param> /// <param name="addr">The starting address for which you will get the number of bytes</param>
/// <param name="size">The number of bytes of the cheat to return</param> /// <param name="size">The number of bytes of the cheat to return</param>
/// <returns>The value, or null if it can't resolve the address with a given cheat</returns> /// <returns>The value, or null if it can't resolve the address with a given cheat</returns>

View File

@ -587,7 +587,7 @@ namespace BizHawk.Client.Common
/// <summary> /// <summary>
/// Gets or sets a value indicating the endianess of current <see cref="Watch"/> /// Gets or sets a value indicating the endianess of current <see cref="Watch"/>
/// True for big endian, flase for little endian /// True for big endian, false for little endian
/// </summary> /// </summary>
public bool BigEndian { get; set; } public bool BigEndian { get; set; }

View File

@ -29,30 +29,27 @@ namespace BizHawk.Client.Common
public const string DOMAIN = "DomainColumn"; public const string DOMAIN = "DomainColumn";
public const string NOTES = "NotesColumn"; public const string NOTES = "NotesColumn";
private static readonly WatchDomainComparer domainComparer = new WatchDomainComparer(); private static readonly WatchDomainComparer DomainComparer = new WatchDomainComparer();
private static readonly WatchAddressComparer addressComparer = new WatchAddressComparer(); private static readonly WatchAddressComparer AddressComparer = new WatchAddressComparer();
private static readonly WatchValueComparer valueComparer = new WatchValueComparer(); private static readonly WatchValueComparer ValueComparer = new WatchValueComparer();
private static readonly WatchPreviousValueComparer previousValueComparer = new WatchPreviousValueComparer(); private static readonly WatchPreviousValueComparer PreviousValueComparer = new WatchPreviousValueComparer();
private static readonly WatchValueDifferenceComparer valueDifferenceComparer = new WatchValueDifferenceComparer(); private static readonly WatchValueDifferenceComparer ValueDifferenceComparer = new WatchValueDifferenceComparer();
private static readonly WatchChangeCountComparer changeCountComparer = new WatchChangeCountComparer(); private static readonly WatchChangeCountComparer ChangeCountComparer = new WatchChangeCountComparer();
private static readonly WatchNoteComparer noteComparer = new WatchNoteComparer(); private static readonly WatchNoteComparer NoteComparer = new WatchNoteComparer();
private readonly List<Watch> _watchList = new List<Watch>(0);
private readonly string _systemid;
private IMemoryDomains _memoryDomains; private IMemoryDomains _memoryDomains;
private List<Watch> _watchList = new List<Watch>(0);
private string _currentFilename = "";
private string _systemid;
#endregion #endregion
#region cTor(s) #region cTor(s)
/// <summary> /// <summary>
/// Initialize a new instance of <see cref="WatchList"/> that will /// Initializes a new instance of the <see cref="WatchList"/> class
/// contains a set of <see cref="Watch"/> /// that will contains a set of <see cref="Watch"/>
/// </summary> /// </summary>
/// <param name="core">All available memomry domains</param> /// <param name="core">All available memory domains</param>
/// <param name="domain">Domain you want to watch</param>
/// <param name="systemid">System identifier (NES, SNES, ...)</param> /// <param name="systemid">System identifier (NES, SNES, ...)</param>
public WatchList(IMemoryDomains core, string systemid) public WatchList(IMemoryDomains core, string systemid)
{ {
@ -84,7 +81,7 @@ namespace BizHawk.Client.Common
{ {
_watchList.Clear(); _watchList.Clear();
Changes = false; Changes = false;
_currentFilename = ""; CurrentFileName = "";
} }
/// <summary> /// <summary>
@ -92,7 +89,6 @@ namespace BizHawk.Client.Common
/// specified <see cref="Watch"/> /// specified <see cref="Watch"/>
/// </summary> /// </summary>
/// <param name="watch">The object to</param> /// <param name="watch">The object to</param>
/// <returns></returns>
public bool Contains(Watch watch) public bool Contains(Watch watch)
{ {
return _watchList.Contains(watch); return _watchList.Contains(watch);
@ -196,7 +192,7 @@ namespace BizHawk.Client.Common
/// <param name="watches"><see cref="IEnumerable{Watch}"/> of watch to merge</param> /// <param name="watches"><see cref="IEnumerable{Watch}"/> of watch to merge</param>
public void AddRange(IEnumerable<Watch> watches) public void AddRange(IEnumerable<Watch> watches)
{ {
Parallel.ForEach<Watch>(watches, watch => Parallel.ForEach(watches, watch =>
{ {
if (!_watchList.Contains(watch)) if (!_watchList.Contains(watch))
{ {
@ -211,14 +207,14 @@ namespace BizHawk.Client.Common
/// </summary> /// </summary>
public void ClearChangeCounts() public void ClearChangeCounts()
{ {
Parallel.ForEach<Watch>(_watchList, watch => watch.ClearChangeCount()); Parallel.ForEach(_watchList, watch => watch.ClearChangeCount());
} }
/// <summary> /// <summary>
/// Sort the current list based on one of the constant /// Sort the current list based on one of the constant
/// </summary> /// </summary>
/// <param name="column">Value that specify sorting base</param> /// <param name="column">Value that specify sorting base</param>
/// <param name="reverse">Value that define the ordering. Ascending (true) or desceding (false)</param> /// <param name="reverse">Value that define the ordering. Ascending (true) or descending (false)</param>
public void OrderWatches(string column, bool reverse) public void OrderWatches(string column, bool reverse)
{ {
switch (column) switch (column)
@ -226,7 +222,7 @@ namespace BizHawk.Client.Common
case ADDRESS: case ADDRESS:
if (reverse) if (reverse)
{ {
_watchList.Sort(addressComparer); _watchList.Sort(AddressComparer);
_watchList.Reverse(); _watchList.Reverse();
} }
else else
@ -239,12 +235,12 @@ namespace BizHawk.Client.Common
case VALUE: case VALUE:
if (reverse) if (reverse)
{ {
_watchList.Sort(valueComparer); _watchList.Sort(ValueComparer);
_watchList.Reverse(); _watchList.Reverse();
} }
else else
{ {
_watchList.Sort(valueComparer); _watchList.Sort(ValueComparer);
} }
break; break;
@ -252,12 +248,12 @@ namespace BizHawk.Client.Common
case PREV: case PREV:
if (reverse) if (reverse)
{ {
_watchList.Sort(previousValueComparer); _watchList.Sort(PreviousValueComparer);
_watchList.Reverse(); _watchList.Reverse();
} }
else else
{ {
_watchList.Sort(previousValueComparer); _watchList.Sort(PreviousValueComparer);
} }
break; break;
@ -265,24 +261,25 @@ namespace BizHawk.Client.Common
case DIFF: case DIFF:
if (reverse) if (reverse)
{ {
_watchList.Sort(valueDifferenceComparer); _watchList.Sort(ValueDifferenceComparer);
_watchList.Reverse(); _watchList.Reverse();
} }
else else
{ {
_watchList.Sort(valueDifferenceComparer); _watchList.Sort(ValueDifferenceComparer);
} }
break; break;
case CHANGES: case CHANGES:
if (reverse) if (reverse)
{ {
_watchList.Sort(changeCountComparer); _watchList.Sort(ChangeCountComparer);
_watchList.Reverse(); _watchList.Reverse();
} }
else else
{ {
_watchList.Sort(changeCountComparer); _watchList.Sort(ChangeCountComparer);
} }
break; break;
@ -290,12 +287,12 @@ namespace BizHawk.Client.Common
case DOMAIN: case DOMAIN:
if (reverse) if (reverse)
{ {
_watchList.Sort(domainComparer); _watchList.Sort(DomainComparer);
_watchList.Reverse(); _watchList.Reverse();
} }
else else
{ {
_watchList.Sort(domainComparer); _watchList.Sort(DomainComparer);
} }
break; break;
@ -303,12 +300,12 @@ namespace BizHawk.Client.Common
case NOTES: case NOTES:
if (reverse) if (reverse)
{ {
_watchList.Sort(noteComparer); _watchList.Sort(NoteComparer);
_watchList.Reverse(); _watchList.Reverse();
} }
else else
{ {
_watchList.Sort(noteComparer); _watchList.Sort(NoteComparer);
} }
break; break;
@ -323,7 +320,7 @@ namespace BizHawk.Client.Common
public void RefreshDomains(IMemoryDomains core) public void RefreshDomains(IMemoryDomains core)
{ {
_memoryDomains = core; _memoryDomains = core;
Parallel.ForEach<Watch>(_watchList, watch => Parallel.ForEach(_watchList, watch =>
{ {
if (watch.IsSeparator) if (watch.IsSeparator)
{ {
@ -338,11 +335,11 @@ namespace BizHawk.Client.Common
} }
/// <summary> /// <summary>
/// Updates all <see cref="Watch"/> ine the current collection /// Updates all <see cref="Watch"/> in the current collection
/// </summary> /// </summary>
public void UpdateValues() public void UpdateValues()
{ {
Parallel.ForEach<Watch>(_watchList, watch => Parallel.ForEach(_watchList, watch =>
{ {
watch.Update(); watch.Update();
}); });
@ -357,25 +354,13 @@ namespace BizHawk.Client.Common
/// <summary> /// <summary>
/// Gets the number of elements contained in this <see cref="WatchList"/> /// Gets the number of elements contained in this <see cref="WatchList"/>
/// </summary> /// </summary>
public int Count public int Count => _watchList.Count;
{
get
{
return _watchList.Count;
}
}
/// <summary> /// <summary>
/// <see cref="WatchList"/> is alsways read-write /// <see cref="WatchList"/> is always read-write
/// so this value will be always false /// so this value will be always false
/// </summary> /// </summary>
public bool IsReadOnly public bool IsReadOnly => false;
{
get
{
return false;
}
}
#endregion ICollection<Watch> #endregion ICollection<Watch>
@ -392,6 +377,7 @@ namespace BizHawk.Client.Common
{ {
return _watchList[index]; return _watchList[index];
} }
set set
{ {
_watchList[index] = value; _watchList[index] = value;
@ -401,24 +387,14 @@ namespace BizHawk.Client.Common
#endregion IList<Watch> #endregion IList<Watch>
/// <summary> /// <summary>
/// Gets a value indicating if collection has changed or not /// Gets or sets a value indicating whether the collection has changed or not
/// </summary> /// </summary>
public bool Changes { get; set; } public bool Changes { get; set; }
/// <summary> /// <summary>
/// Gets or sets current <see cref="WatchList"/>'s filename /// Gets or sets current <see cref="WatchList"/>'s filename
/// </summary> /// </summary>
public string CurrentFileName public string CurrentFileName { get; set; }
{
get
{
return _currentFilename;
}
set
{
_currentFilename = value;
}
}
/// <summary> /// <summary>
/// Gets the number of <see cref="Watch"/> that are not <see cref="SeparatorWatch"/> /// Gets the number of <see cref="Watch"/> that are not <see cref="SeparatorWatch"/>
@ -427,7 +403,7 @@ namespace BizHawk.Client.Common
{ {
get get
{ {
return _watchList.Count<Watch>(watch => !watch.IsSeparator); return _watchList.Count(watch => !watch.IsSeparator);
} }
} }
@ -613,7 +589,7 @@ namespace BizHawk.Client.Common
notes)); notes));
} }
_currentFilename = path; CurrentFileName = path;
} }
if (!append) if (!append)

View File

@ -70,6 +70,7 @@
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=OSD/@EntryIndexedValue">OSD</s:String> <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=OSD/@EntryIndexedValue">OSD</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=PAL/@EntryIndexedValue">PAL</s:String> <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=PAL/@EntryIndexedValue">PAL</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/=PC/@EntryIndexedValue">PC</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=PCE/@EntryIndexedValue">PCE</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/=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/=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/=PSX/@EntryIndexedValue">PSX</s:String>