Establish basic style analyzer rules (#3759)

* Fix analyzer nullable error

can't disable them in CA1305 xdd

* .editorconfig -> .globalconfig

* Add basic set of style analyzer rules

* dotnet format output

* Some additional fixes

* Apply manual simplification

* Transform some enum comparisons

* fix typo

* add TODO
This commit is contained in:
Moritz Bender 2023-08-30 14:08:21 -07:00 committed by GitHub
parent 7193313e12
commit 362269c982
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
254 changed files with 547 additions and 587 deletions

View File

@ -12,19 +12,107 @@ csharp_indent_switch_labels = true
csharp_indent_case_contents = true csharp_indent_case_contents = true
csharp_indent_labels = one_less_than_current csharp_indent_labels = one_less_than_current
# Globalization rules # Style rules
dotnet_code_quality.CA1305.excluded_symbol_names = T:System.Byte|T:System.SByte|T:System.Int16|T:System.UInt16|T:System.Int32|T:System.UInt32|T:System.Int64|T:System.UInt64|T:System.String|T:System.Text.StringBuilder|T:System.Convert # Can't be in .globalconfig because dotnet format doesn't respect that https://github.com/dotnet/format/issues/1643
dotnet_diagnostic.CA1305.severity = error # Remove unnecessary cast
dotnet_diagnostic.CA2101.severity = suggestion dotnet_diagnostic.IDE0004.severity = warning
# Remove unnecessary import
dotnet_diagnostic.IDE0005.severity = warning
# Use var instead of explicit type
dotnet_diagnostic.IDE0007.severity = suggestion
# Use explicit type instead of var
dotnet_diagnostic.IDE0008.severity = suggestion
# Inline variable declaration
dotnet_diagnostic.IDE0018.severity = warning
# Use pattern matching to avoid as followed by a null check
dotnet_diagnostic.IDE0019.severity = warning
# Use pattern matching to avoid is check followed by a cast (with variable)
dotnet_diagnostic.IDE0020.severity = warning
# Use expression body for methods
dotnet_diagnostic.IDE0022.severity = suggestion
# Use expression body for properties
dotnet_diagnostic.IDE0025.severity = suggestion
# Use expression body for indexers
dotnet_diagnostic.IDE0026.severity = suggestion
# Use expression body for accessors
dotnet_diagnostic.IDE0027.severity = suggestion
# Null check can be simplified
dotnet_diagnostic.IDE0029.severity = warning
# Null check can be simplified
dotnet_diagnostic.IDE0030.severity = warning
# Use null propagation
dotnet_diagnostic.IDE0031.severity = warning
# Use auto property
dotnet_diagnostic.IDE0032.severity = suggestion
# Simplify default expression
dotnet_diagnostic.IDE0034.severity = suggestion
# Use pattern matching to avoid is check followed by a cast (without variable)
dotnet_diagnostic.IDE0038.severity = warning
# Use is null check
dotnet_diagnostic.IDE0041.severity = warning
# Deconstruct variable declaration
dotnet_diagnostic.IDE0042.severity = suggestion
# dotnet_diagnostic.IDE0049.severity = error # see SA1121
# Remove unused private member
dotnet_diagnostic.IDE0051.severity = suggestion
# Remove unread private member
dotnet_diagnostic.IDE0052.severity = silent # TODO: should be warning imo, but there's too much violation currently
# Use compound assignment
dotnet_diagnostic.IDE0054.severity = warning
# Use index operator
dotnet_diagnostic.IDE0056.severity = warning
# Use range operator
dotnet_diagnostic.IDE0057.severity = warning
# Use simple using statement
dotnet_diagnostic.IDE0063.severity = suggestion
# Make struct fields writable
dotnet_diagnostic.IDE0064.severity = error
# using directive placement
dotnet_diagnostic.IDE0065.severity = error
# Use switch expression
dotnet_diagnostic.IDE0066.severity = suggestion
# Use System.HashCode.Combine
dotnet_diagnostic.IDE0070.severity = warning
# Simplify interpolation
dotnet_diagnostic.IDE0071.severity = suggestion
# Use coalesce compound assignment
dotnet_diagnostic.IDE0074.severity = suggestion
# Use pattern matching
dotnet_diagnostic.IDE0078.severity = suggestion
# Convert typeof to nameof
dotnet_diagnostic.IDE0082.severity = warning
# Use pattern matching (not operator)
dotnet_diagnostic.IDE0083.severity = warning
# Simplify new expression
dotnet_diagnostic.IDE0090.severity = suggestion
# Remove unnecessary equality operator
dotnet_diagnostic.IDE0100.severity = warning
# Remove unnecessary discard
dotnet_diagnostic.IDE0110.severity = warning
# Simplify LINQ expression
dotnet_diagnostic.IDE0120.severity = error
# Namespace does not match folder structure
dotnet_diagnostic.IDE0130.severity = silent # should be warning imo
# Use tuple to swap values
dotnet_diagnostic.IDE0180.severity = suggestion
# Use UTF-8 string literal
dotnet_diagnostic.IDE0230.severity = warning
# Nullable directive is redundant
dotnet_diagnostic.IDE0240.severity = warning
# Nullable directive is unnecessary
dotnet_diagnostic.IDE0241.severity = warning
# Struct can be made 'readonly'
dotnet_diagnostic.IDE0250.severity = suggestion
# Use pattern matching
dotnet_diagnostic.IDE0260.severity = suggestion
# Use nameof
dotnet_diagnostic.IDE0280.severity = error
# Performance rules csharp_style_var_when_type_is_apparent = true
dotnet_code_quality.CA1826.exclude_ordefault_methods = true csharp_style_var_elsewhere = true
dotnet_diagnostic.CA1805.severity = silent csharp_style_expression_bodied_methods = when_on_single_line
dotnet_diagnostic.CA1822.severity = silent csharp_style_expression_bodied_properties = when_on_single_line
dotnet_diagnostic.CA1838.severity = suggestion csharp_style_expression_bodied_indexers = when_on_single_line
csharp_style_expression_bodied_accessors = when_on_single_line
# Usage rules
dotnet_diagnostic.CA1816.severity = none
dotnet_diagnostic.CA2201.severity = suggestion

18
.globalconfig Normal file
View File

@ -0,0 +1,18 @@
is_global = true
# Globalization rules
dotnet_code_quality.CA1305.excluded_symbol_names = T:System.Byte|T:System.SByte|T:System.Int16|T:System.UInt16|T:System.Int32|T:System.UInt32|T:System.Int64|T:System.UInt64|T:System.String|T:System.Text.StringBuilder|T:System.Convert
dotnet_diagnostic.CA1305.severity = error
dotnet_diagnostic.CA2101.severity = suggestion
# Performance rules
dotnet_code_quality.CA1826.exclude_ordefault_methods = true
dotnet_diagnostic.CA1805.severity = silent
dotnet_diagnostic.CA1822.severity = silent
dotnet_diagnostic.CA1838.severity = suggestion
# Usage rules
dotnet_diagnostic.CA1816.severity = none
dotnet_diagnostic.CA2201.severity = suggestion

View File

@ -6,6 +6,7 @@
<AnalysisModeReliability>Recommended</AnalysisModeReliability> <AnalysisModeReliability>Recommended</AnalysisModeReliability>
<AnalysisModePerformance>Recommended</AnalysisModePerformance> <AnalysisModePerformance>Recommended</AnalysisModePerformance>
<AnalysisModeUsage>Recommended</AnalysisModeUsage> <AnalysisModeUsage>Recommended</AnalysisModeUsage>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
<CodeAnalysisRuleSet>$(MSBuildProjectDirectory)/../../Common.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRuleSet>$(MSBuildProjectDirectory)/../../Common.ruleset</CodeAnalysisRuleSet>
<ContinuousIntegrationBuild Condition=" '$(GITLAB_CI)' != '' Or '$(APPVEYOR)' != '' ">true</ContinuousIntegrationBuild> <ContinuousIntegrationBuild Condition=" '$(GITLAB_CI)' != '' Or '$(APPVEYOR)' != '' ">true</ContinuousIntegrationBuild>
<EnableNETAnalyzers>true</EnableNETAnalyzers> <EnableNETAnalyzers>true</EnableNETAnalyzers>

View File

@ -67,8 +67,7 @@ namespace BizHawk.BizInvoke
foreach (var a in methods) foreach (var a in methods)
{ {
MethodBuilder unused; var delegateType = BizInvokeUtilities.CreateDelegateType(a.Info, a.Attr!.CallingConvention, typeBuilder, out _).CreateType()!;
var delegateType = BizInvokeUtilities.CreateDelegateType(a.Info, a.Attr!.CallingConvention, typeBuilder, out unused).CreateType()!;
DelegateTypes.Add(new StoredDelegateInfo(a.Info, delegateType, a.Attr.EntryPoint ?? a.Info.Name)); DelegateTypes.Add(new StoredDelegateInfo(a.Info, delegateType, a.Attr.EntryPoint ?? a.Info.Name));
} }
StorageType = typeBuilder.CreateType()!; StorageType = typeBuilder.CreateType()!;

View File

@ -167,7 +167,7 @@ namespace BizHawk.BizInvoke
{ {
WaterboxWrapper = OSTailoredCode.IsUnixHost WaterboxWrapper = OSTailoredCode.IsUnixHost
? new NativeConvention() ? new NativeConvention()
: (ICallingConventionAdapter)new MsHostSysVGuest(); : new MsHostSysVGuest();
} }
private readonly Dictionary<Delegate, int>? _slots; private readonly Dictionary<Delegate, int>? _slots;
@ -247,7 +247,7 @@ namespace BizHawk.BizInvoke
public MsHostSysVGuest() public MsHostSysVGuest()
{ {
const int size = 4 * 1024 * 1024; const int size = 4 * 1024 * 1024;
_memory = new((ulong)size); _memory = new(size);
_refs = new WeakReference[size / BlockSize]; _refs = new WeakReference[size / BlockSize];
} }

View File

@ -1,7 +1,5 @@
using System; using System;
using System.IO; using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using BizHawk.Common; using BizHawk.Common;
namespace BizHawk.BizInvoke namespace BizHawk.BizInvoke
@ -19,7 +17,7 @@ namespace BizHawk.BizInvoke
Size = WaterboxUtils.AlignUp(size); Size = WaterboxUtils.AlignUp(size);
_pal = OSTailoredCode.IsUnixHost _pal = OSTailoredCode.IsUnixHost
? (IMemoryBlockPal)new MemoryBlockLinuxPal(Size) ? new MemoryBlockLinuxPal(Size)
: new MemoryBlockWindowsPal(Size); : new MemoryBlockWindowsPal(Size);
Start = _pal!.Start; Start = _pal!.Start;
EndExclusive = Start + Size; EndExclusive = Start + Size;

View File

@ -1,6 +1,5 @@
using System; using System;
using System.IO; using System.IO;
using System.Runtime.InteropServices;
using BizHawk.Common; using BizHawk.Common;
namespace BizHawk.BizInvoke namespace BizHawk.BizInvoke

View File

@ -1,8 +1,6 @@
using System; using System;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using static BizHawk.BizInvoke.MemoryBlock;
namespace BizHawk.BizInvoke namespace BizHawk.BizInvoke
{ {
public static class POSIXLibC public static class POSIXLibC

View File

@ -527,7 +527,7 @@ namespace BizHawk.Bizware.BizwareGL
k--; k--;
for (var i = 1; i < 32; i <<= 1) for (var i = 1; i < 32; i <<= 1)
{ {
k = k | k >> i; k |= k >> i;
} }
var candidate = k + 1; var candidate = k + 1;

View File

@ -1,7 +1,5 @@
using System; using System;
using Silk.NET.OpenGL.Legacy;
using static SDL2.SDL; using static SDL2.SDL;
namespace BizHawk.Bizware.Graphics namespace BizHawk.Bizware.Graphics

View File

@ -1,8 +1,6 @@
using System; using System;
using System.Drawing; using System.Drawing;
using System.IO; using System.IO;
using BizHawk.Common;
using BizHawk.Emulation.Common; using BizHawk.Emulation.Common;
namespace BizHawk.Client.Common namespace BizHawk.Client.Common

View File

@ -58,7 +58,7 @@ namespace BizHawk.Client.Common
// ALL button names with P{controller} prefixes // ALL button names with P{controller} prefixes
foreach (var button in _inputManager.ActiveController.ToBoolButtonNameList(controller)) foreach (var button in _inputManager.ActiveController.ToBoolButtonNameList(controller))
{ {
Set(button, buttons.TryGetValue(button, out var state) ? state : (bool?) null, controller); Set(button, buttons.TryGetValue(button, out var state) ? state : null, controller);
} }
} }

View File

@ -3,7 +3,6 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using BizHawk.Common; using BizHawk.Common;
using BizHawk.Common.BufferExtensions;
using BizHawk.Emulation.Common; using BizHawk.Emulation.Common;
namespace BizHawk.Client.Common namespace BizHawk.Client.Common

View File

@ -1,5 +1,3 @@
#pragma warning disable CA2007
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net.Http; using System.Net.Http;

View File

@ -763,7 +763,6 @@ namespace BizHawk.Client.Common
} }
var videoProvider = job.VideoProvider; var videoProvider = job.VideoProvider;
var glTextureProvider = videoProvider as IGLTextureProvider;
var simulate = job.Simulate; var simulate = job.Simulate;
var chainOutsize = job.ChainOutsize; var chainOutsize = job.ChainOutsize;
@ -824,7 +823,7 @@ namespace BizHawk.Client.Common
Texture2d videoTexture = null; Texture2d videoTexture = null;
if (!simulate) if (!simulate)
{ {
if (glTextureProvider != null && _gl.DispMethodEnum == EDispMethod.OpenGL) if (videoProvider is IGLTextureProvider glTextureProvider && _gl.DispMethodEnum == EDispMethod.OpenGL)
{ {
// FYI: this is a million years from happening on n64, since it's all geriatric non-FBO code // FYI: this is a million years from happening on n64, since it's all geriatric non-FBO code
videoTexture = _gl.WrapGLTexture2d(new(glTextureProvider.GetGLTexture()), bufferWidth, bufferHeight); videoTexture = _gl.WrapGLTexture2d(new(glTextureProvider.GetGLTexture()), bufferWidth, bufferHeight);

View File

@ -1,7 +1,5 @@
using System.Drawing; using System.Drawing;
using BizHawk.Bizware.BizwareGL;
namespace BizHawk.Client.Common namespace BizHawk.Client.Common
{ {
/// <summary> /// <summary>

View File

@ -3,8 +3,6 @@ using System.Linq;
using System.Text; using System.Text;
using System.Drawing; using System.Drawing;
using System.Collections.Generic; using System.Collections.Generic;
using BizHawk.Bizware.BizwareGL;
using BizHawk.Emulation.Common; using BizHawk.Emulation.Common;
namespace BizHawk.Client.Common namespace BizHawk.Client.Common

View File

@ -1,7 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Linq;
// ReSharper disable UnusedMember.Global // ReSharper disable UnusedMember.Global
namespace BizHawk.Client.Common namespace BizHawk.Client.Common

View File

@ -143,7 +143,7 @@ namespace BizHawk.Client.Common
nhs.DispBackground = show; nhs.DispBackground = show;
Settings = nhs; Settings = nhs;
break; break;
case QuickNES.QuickNESSettings _: case QuickNES.QuickNESSettings:
return; return;
default: default:
throw new InvalidOperationException(); throw new InvalidOperationException();
@ -209,7 +209,7 @@ namespace BizHawk.Client.Common
Settings = nhs; Settings = nhs;
break; break;
case QuickNES.QuickNESSettings _: case QuickNES.QuickNESSettings:
return; return;
default: default:
throw new InvalidOperationException(); throw new InvalidOperationException();

View File

@ -1,7 +1,6 @@
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text;
using System.IO; using System.IO;
using BizHawk.Common; using BizHawk.Common;

View File

@ -15,7 +15,7 @@ namespace BizHawk.Client.Common
get get
{ {
var result = _lagLog.TryGetValue(frame, out var lag); var result = _lagLog.TryGetValue(frame, out var lag);
return result ? (bool?)lag : null; return result ? lag : null;
} }
set set

View File

@ -1,6 +1,5 @@
using System; using System;
using System.IO; using System.IO;
using System.Runtime.InteropServices;
using System.Threading.Tasks; using System.Threading.Tasks;
using BizHawk.Common; using BizHawk.Common;
using BizHawk.Emulation.Common; using BizHawk.Emulation.Common;

View File

@ -67,9 +67,9 @@ namespace BizHawk.Client.Common
public long? Address => _watch.Address; public long? Address => _watch.Address;
public int? Value => IsSeparator ? (int?)null : _val; public int? Value => IsSeparator ? null : _val;
public bool? BigEndian => IsSeparator ? (bool?)null : _watch.BigEndian; public bool? BigEndian => IsSeparator ? null : _watch.BigEndian;
public int? Compare => _compare.HasValue && !IsSeparator ? _compare : null; public int? Compare => _compare.HasValue && !IsSeparator ? _compare : null;
@ -304,7 +304,7 @@ namespace BizHawk.Client.Common
public static bool operator ==(Cheat a, Cheat b) public static bool operator ==(Cheat a, Cheat b)
{ {
// If one is null, but not both, return false. // If one is null, but not both, return false.
if ((object)a == null || (object)b == null) if (a is null || b is null)
{ {
return false; return false;
} }
@ -320,7 +320,7 @@ namespace BizHawk.Client.Common
public static bool operator ==(Cheat a, Watch b) public static bool operator ==(Cheat a, Watch b)
{ {
// If one is null, but not both, return false. // If one is null, but not both, return false.
if ((object)a == null || (object)b == null) if (a is null || b is null)
{ {
return false; return false;
} }

View File

@ -141,7 +141,7 @@ namespace BizHawk.Client.Common
/// Get a string representation of difference /// Get a string representation of difference
/// between current value and the previous one /// between current value and the previous one
/// </summary> /// </summary>
public override string Diff => $"{_value - (short)_previous:+#;-#;0}"; public override string Diff => $"{_value - _previous:+#;-#;0}";
/// <summary> /// <summary>
/// Returns true if the Watch is valid, false otherwise /// Returns true if the Watch is valid, false otherwise

View File

@ -150,7 +150,7 @@ namespace BizHawk.Client.Common
/// <returns>True if both watch are equals; otherwise, false</returns> /// <returns>True if both watch are equals; otherwise, false</returns>
public static bool operator ==(Watch a, Watch b) public static bool operator ==(Watch a, Watch b)
{ {
if (ReferenceEquals(a, null) || ReferenceEquals(b, null)) if (a is null || b is null)
{ {
return false; return false;
} }
@ -171,7 +171,7 @@ namespace BizHawk.Client.Common
/// <returns>True if they are equals; otherwise, false</returns> /// <returns>True if they are equals; otherwise, false</returns>
public static bool operator ==(Watch a, Cheat b) public static bool operator ==(Watch a, Cheat b)
{ {
if (ReferenceEquals(a, null) || ReferenceEquals(b, null)) if (a is null || b is null)
{ {
return false; return false;
} }
@ -325,7 +325,7 @@ namespace BizHawk.Client.Common
/// <returns>True if both object are equals; otherwise, false</returns> /// <returns>True if both object are equals; otherwise, false</returns>
public bool Equals(Watch other) public bool Equals(Watch other)
{ {
if (ReferenceEquals(other, null)) if (other is null)
{ {
return false; return false;
} }
@ -342,7 +342,7 @@ namespace BizHawk.Client.Common
/// <returns>True if both object are equals; otherwise, false</returns> /// <returns>True if both object are equals; otherwise, false</returns>
public bool Equals(Cheat other) public bool Equals(Cheat other)
{ {
return !ReferenceEquals(other, null) return other is not null
&& _domain == other.Domain && _domain == other.Domain
&& Address == other.Address && Address == other.Address
&& Size == other.Size; && Size == other.Size;

View File

@ -18,12 +18,12 @@ namespace BizHawk.Client.Common
/// <returns>True if <see cref="Watch"/> are equal; otherwise, false</returns> /// <returns>True if <see cref="Watch"/> are equal; otherwise, false</returns>
public bool Equals(Watch x, Watch y) public bool Equals(Watch x, Watch y)
{ {
if (ReferenceEquals(x, null)) if (x is null)
{ {
return ReferenceEquals(y, null); return y is null;
} }
if (ReferenceEquals(y, null)) if (y is null)
{ {
return false; return false;
} }

View File

@ -146,7 +146,7 @@ namespace BizHawk.Client.Common
/// Get a string representation of difference /// Get a string representation of difference
/// between current value and the previous one /// between current value and the previous one
/// </summary> /// </summary>
public override string Diff => $"{_value - (int)_previous:+#;-#;0}"; public override string Diff => $"{_value - _previous:+#;-#;0}";
/// <summary> /// <summary>
/// Returns true if the Watch is valid, false otherwise /// Returns true if the Watch is valid, false otherwise

View File

@ -3,9 +3,6 @@ using System.Runtime.InteropServices;
using System.Reflection; using System.Reflection;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using BizHawk.Common;
using BizHawk.Common.PathExtensions;
using BizHawk.Emulation.DiscSystem; using BizHawk.Emulation.DiscSystem;
using OSTC = EXE_PROJECT.OSTailoredCode; using OSTC = EXE_PROJECT.OSTailoredCode;

View File

@ -644,7 +644,7 @@ namespace BizHawk.Client.EmuHawk
IntPtr* pStream = &stream; IntPtr* pStream = &stream;
AVIWriterImports.AVICOMPRESSOPTIONS* popts = _popts; AVIWriterImports.AVICOMPRESSOPTIONS* popts = _popts;
AVIWriterImports.AVICOMPRESSOPTIONS** ppopts = &popts; AVIWriterImports.AVICOMPRESSOPTIONS** ppopts = &popts;
return AVIWriterImports.AVISaveOptions(owner, 0, 1, (void*)pStream, (void*)ppopts); return AVIWriterImports.AVISaveOptions(owner, 0, 1, pStream, ppopts);
} }
} }
@ -654,10 +654,10 @@ namespace BizHawk.Client.EmuHawk
public void OpenFile(string destPath, Parameters parameters, CodecToken videoCodecToken) public void OpenFile(string destPath, Parameters parameters, CodecToken videoCodecToken)
{ {
static int mmioFOURCC(string str) => ( static int mmioFOURCC(string str) => (
((int)(byte)(str[0])) (byte)(str[0])
| ((int)(byte)(str[1]) << 8) | ((byte)(str[1]) << 8)
| ((int)(byte)(str[2]) << 16) | ((byte)(str[2]) << 16)
| ((int)(byte)(str[3]) << 24) | ((byte)(str[3]) << 24)
); );
this._parameters = parameters; this._parameters = parameters;

View File

@ -9,7 +9,6 @@ using System.Threading;
using BizHawk.Client.Common; using BizHawk.Client.Common;
using BizHawk.Emulation.Common; using BizHawk.Emulation.Common;
using BizHawk.Common;
namespace BizHawk.Client.EmuHawk namespace BizHawk.Client.EmuHawk
{ {

View File

@ -51,8 +51,8 @@ namespace BizHawk.Client.EmuHawk
foreach (var line in lines) foreach (var line in lines)
{ {
int idx = line.IndexOf('='); int idx = line.IndexOf('=');
string key = line.Substring(0, idx); string key = line[..idx];
string value = line.Substring(idx + 1, line.Length - (idx + 1)); string value = line[(idx + 1)..];
if (key == "framesdir") if (key == "framesdir")
{ {
framesDir = value; framesDir = value;

View File

@ -136,7 +136,7 @@ namespace BizHawk.Client.EmuHawk
catch (ArgumentException ex) catch (ArgumentException ex)
{ {
string errMsg = ex.Message; string errMsg = ex.Message;
errMsg = errMsg.Substring(errMsg.IndexOf('-') + 2); errMsg = errMsg[(errMsg.IndexOf('-') + 2)..];
// Balloon is bugged on first invocation // Balloon is bugged on first invocation
_errorBalloon.Show($"Error parsing RegEx: {errMsg}", tb); _errorBalloon.Show($"Error parsing RegEx: {errMsg}", tb);

View File

@ -285,7 +285,7 @@ namespace BizHawk.Client.EmuHawk
public void SetFromRawInt(int? val) public void SetFromRawInt(int? val)
{ {
Text = val.HasValue ? val.ToString() : ""; Text = val?.ToString() ?? "";
} }
} }
} }

View File

@ -37,7 +37,7 @@ namespace BizHawk.Client.EmuHawk
public static bool operator ==(Cell a, Cell b) public static bool operator ==(Cell a, Cell b)
{ {
return a?.Equals(b) ?? ReferenceEquals(b, null); return a?.Equals(b) ?? b is null;
} }
public static bool operator !=(Cell a, Cell b) public static bool operator !=(Cell a, Cell b)

View File

@ -2,8 +2,6 @@
using System.Drawing; using System.Drawing;
using System.Windows.Forms; using System.Windows.Forms;
using BizHawk.Common;
// http://www.codeproject.com/Articles/154680/A-customizable-NET-WinForms-Message-Box // http://www.codeproject.com/Articles/154680/A-customizable-NET-WinForms-Message-Box
namespace BizHawk.Client.EmuHawk.CustomControls namespace BizHawk.Client.EmuHawk.CustomControls
{ {

View File

@ -9,7 +9,6 @@ using BizHawk.Emulation.Cores.Consoles.Sega.gpgx;
using BizHawk.Emulation.Cores.Arcades.MAME; using BizHawk.Emulation.Cores.Arcades.MAME;
using BizHawk.Emulation.Cores.Consoles.Nintendo.NDS; using BizHawk.Emulation.Cores.Consoles.Nintendo.NDS;
using BizHawk.Emulation.Cores.Nintendo.GBA; using BizHawk.Emulation.Cores.Nintendo.GBA;
using BizHawk.Emulation.Cores.Sega.MasterSystem;
namespace BizHawk.Client.EmuHawk.CoreExtensions namespace BizHawk.Client.EmuHawk.CoreExtensions
{ {

View File

@ -92,7 +92,7 @@ namespace BizHawk.Client.EmuHawk
if (invoked) if (invoked)
{ {
//basically an easy way to post an update message which should hopefully happen before anything else happens (redraw or user interaction) //basically an easy way to post an update message which should hopefully happen before anything else happens (redraw or user interaction)
BeginInvoke((Action)doUpdateListSize); BeginInvoke(doUpdateListSize);
} }
else else
doUpdateListSize(); doUpdateListSize();

View File

@ -1,6 +1,5 @@
using System; using System;
using System.IO; using System.IO;
using System.Windows.Forms;
using System.Linq; using System.Linq;
using System.Collections.Generic; using System.Collections.Generic;

View File

@ -1208,7 +1208,7 @@ namespace BizHawk.Client.EmuHawk
//NOTE: these must go together, because in the case of screen rotation, X and Y are transformed together //NOTE: these must go together, because in the case of screen rotation, X and Y are transformed together
if(mouseX != null && mouseY != null) if(mouseX != null && mouseY != null)
{ {
var p = DisplayManager.UntransformPoint(new Point((int) mouseX.Value.Value, (int) mouseY.Value.Value)); var p = DisplayManager.UntransformPoint(new Point(mouseX.Value.Value, mouseY.Value.Value));
float x = p.X / (float)_currentVideoProvider.BufferWidth; float x = p.X / (float)_currentVideoProvider.BufferWidth;
float y = p.Y / (float)_currentVideoProvider.BufferHeight; float y = p.Y / (float)_currentVideoProvider.BufferHeight;
finalHostController.AcceptNewAxis("WMouse X", (int) ((x * 20000) - 10000)); finalHostController.AcceptNewAxis("WMouse X", (int) ((x * 20000) - 10000));
@ -3810,8 +3810,6 @@ namespace BizHawk.Client.EmuHawk
IOpenAdvanced ioa = args.OpenAdvanced; IOpenAdvanced ioa = args.OpenAdvanced;
var oaOpenrom = ioa as OpenAdvanced_OpenRom; var oaOpenrom = ioa as OpenAdvanced_OpenRom;
var oaMame = ioa as OpenAdvanced_MAME;
var oaRetro = ioa as OpenAdvanced_Libretro;
var ioaRetro = ioa as IOpenAdvancedLibretro; var ioaRetro = ioa as IOpenAdvancedLibretro;
// we need to inform LoadRom which Libretro core to use... // we need to inform LoadRom which Libretro core to use...
@ -3846,7 +3844,7 @@ namespace BizHawk.Client.EmuHawk
// we need to replace the path in the OpenAdvanced with the canonical one the user chose. // we need to replace the path in the OpenAdvanced with the canonical one the user chose.
// It can't be done until loader.LoadRom happens (for CanonicalFullPath) // It can't be done until loader.LoadRom happens (for CanonicalFullPath)
// i'm not sure this needs to be more abstractly engineered yet until we have more OpenAdvanced examples // i'm not sure this needs to be more abstractly engineered yet until we have more OpenAdvanced examples
if (oaRetro != null) if (ioa is OpenAdvanced_Libretro oaRetro)
{ {
oaRetro.token.Path = loader.CanonicalFullPath; oaRetro.token.Path = loader.CanonicalFullPath;
} }
@ -3856,7 +3854,7 @@ namespace BizHawk.Client.EmuHawk
oaOpenrom.Path = loader.CanonicalFullPath; oaOpenrom.Path = loader.CanonicalFullPath;
} }
if (oaMame != null) if (ioa is OpenAdvanced_MAME oaMame)
{ {
oaMame.Path = loader.CanonicalFullPath; oaMame.Path = loader.CanonicalFullPath;
} }
@ -3871,7 +3869,7 @@ namespace BizHawk.Client.EmuHawk
InputManager.SyncControls(Emulator, MovieSession, Config); InputManager.SyncControls(Emulator, MovieSession, Config);
_multiDiskMode = false; _multiDiskMode = false;
if (oaOpenrom != null && Path.GetExtension(oaOpenrom.Path.Replace("|", "")).ToLowerInvariant() == ".xml" && !(Emulator is LibsnesCore)) if (oaOpenrom != null && Path.GetExtension(oaOpenrom.Path.Replace("|", "")).ToLowerInvariant() == ".xml" && Emulator is not LibsnesCore)
{ {
// this is a multi-disk bundler file // this is a multi-disk bundler file
// determine the xml assets and create RomStatusDetails for all of them // determine the xml assets and create RomStatusDetails for all of them

View File

@ -1,6 +1,5 @@
using System; using System;
using System.IO; using System.IO;
using System.Linq;
using System.Threading; using System.Threading;
using System.Windows.Forms; using System.Windows.Forms;

View File

@ -119,7 +119,7 @@ namespace BizHawk.Client.EmuHawk
// end of the path has ; // end of the path has ;
var end = exePath.IndexOf(';'); var end = exePath.IndexOf(';');
if (end < 0) break; if (end < 0) break;
exePath = exePath.Substring(index, end - index); exePath = exePath[index..end];
} }
buffer.AddRange(Encoding.ASCII.GetBytes(exePath)); buffer.AddRange(Encoding.ASCII.GetBytes(exePath));

View File

@ -40,7 +40,7 @@ namespace BizHawk.Client.EmuHawk
} }
private static readonly IScreenBlankTimer _screenBlankTimer = OSTailoredCode.IsUnixHost private static readonly IScreenBlankTimer _screenBlankTimer = OSTailoredCode.IsUnixHost
? (IScreenBlankTimer) new UnixScreenBlankTimer() ? new UnixScreenBlankTimer()
: new Win32ScreenBlankTimer(); : new Win32ScreenBlankTimer();
private static int ctr; private static int ctr;

View File

@ -43,7 +43,7 @@ namespace BizHawk.Client.EmuHawk
{ {
// if DirectSound or XAudio is chosen, use OpenAL, otherwise comply with the user's choice // if DirectSound or XAudio is chosen, use OpenAL, otherwise comply with the user's choice
_outputDevice = config.SoundOutputMethod == ESoundOutputMethod.Dummy _outputDevice = config.SoundOutputMethod == ESoundOutputMethod.Dummy
? (ISoundOutput) new DummySoundOutput(this) ? new DummySoundOutput(this)
: new OpenALSoundOutput(this, config.SoundDevice); : new OpenALSoundOutput(this, config.SoundDevice);
} }
else else

View File

@ -139,7 +139,7 @@ namespace BizHawk.Client.EmuHawk
private static readonly Func<uint, uint> TimeBeginPeriod = OSTailoredCode.IsUnixHost private static readonly Func<uint, uint> TimeBeginPeriod = OSTailoredCode.IsUnixHost
? u => u ? u => u
: (Func<uint, uint>) Win32Imports.timeBeginPeriod; : Win32Imports.timeBeginPeriod;
private static readonly int tmethod; private static readonly int tmethod;
private static readonly ulong afsfreq; private static readonly ulong afsfreq;

View File

@ -4,8 +4,6 @@ using System.Drawing;
using System.Linq; using System.Linq;
using System.Windows.Forms; using System.Windows.Forms;
using BizHawk.Client.Common;
namespace BizHawk.Client.EmuHawk namespace BizHawk.Client.EmuHawk
{ {
// this is a little messy right now because of remnants of the old config system // this is a little messy right now because of remnants of the old config system

View File

@ -183,7 +183,7 @@ namespace BizHawk.Client.EmuHawk
lvFirmwares.Groups.Add( lvFirmwares.Groups.Add(
key: sysID, key: sysID,
headerText: SystemGroupNames.TryGetValue(sysID, out var name) ? name : "FIX ME (FirmwaresConfig.cs)"); headerText: SystemGroupNames.TryGetValue(sysID, out var name) ? name : "FIX ME (FirmwaresConfig.cs)");
return lvFirmwares.Groups[lvFirmwares.Groups.Count - 1]; return lvFirmwares.Groups[^1];
} }
// we'll use this font for displaying the hash, so they don't look all jagged in a long list // we'll use this font for displaying the hash, so they don't look all jagged in a long list

View File

@ -192,7 +192,7 @@ namespace BizHawk.Client.EmuHawk
try try
{ {
lines.Add(line.Substring(0, i), int.Parse(line.Substring(i + 1))); lines.Add(line[..i], int.Parse(line[(i + 1)..]));
} }
catch (FormatException) catch (FormatException)
{ {

View File

@ -162,7 +162,7 @@ namespace BizHawk.Client.EmuHawk
try try
{ {
lines.Add(line.Substring(0, i), int.Parse(line.Substring(i + 1))); lines.Add(line[..i], int.Parse(line[(i + 1)..]));
} }
catch (FormatException) catch (FormatException)
{ {

View File

@ -1,5 +1,4 @@
using System; using System;
using BizHawk.Client.Common;
using BizHawk.Emulation.Cores.Nintendo.NES; using BizHawk.Emulation.Cores.Nintendo.NES;
using BizHawk.Emulation.Common; using BizHawk.Emulation.Common;

View File

@ -23,10 +23,10 @@ namespace BizHawk.Client.EmuHawk.ForDebugging
public FirmwareAutopatchDebugToolForm() public FirmwareAutopatchDebugToolForm()
{ {
static string LabelFragment(string hash) static string LabelFragment(string hash)
=> $"{hash.Substring(0, 8)}... {FirmwareDatabase.FirmwareFilesByHash[hash].RecommendedName}"; => $"{hash[..8]}... {FirmwareDatabase.FirmwareFilesByHash[hash].RecommendedName}";
List<(string Label, FirmwarePatchOption PatchOption)> patches = FirmwareDatabase.AllPatches List<(string Label, FirmwarePatchOption PatchOption)> patches = FirmwareDatabase.AllPatches
.Select(static fpo => ($"{LabelFragment(fpo.BaseHash)} --> {LabelFragment(fpo.TargetHash)}", fpo)).ToList(); .Select(static fpo => ($"{LabelFragment(fpo.BaseHash)} --> {LabelFragment(fpo.TargetHash)}", fpo)).ToList();
patches.Sort(static (a, b) => a.Label.CompareTo(b.Label)); patches.Sort(static (a, b) => string.CompareOrdinal(a.Label, b.Label));
ComboBox comboPatchsets = new() { Size = new(300, 23) }; ComboBox comboPatchsets = new() { Size = new(300, 23) };
foreach (var tuple in patches) comboPatchsets.Items.Add(tuple.Label); foreach (var tuple in patches) comboPatchsets.Items.Add(tuple.Label);
SzTextBoxEx txtBaseFile = new() { Size = new(224, 23) }; SzTextBoxEx txtBaseFile = new() { Size = new(224, 23) };

View File

@ -452,7 +452,7 @@ namespace BizHawk.Client.EmuHawk
{ {
var indices = SelectedIndices.ToList(); var indices = SelectedIndices.ToList();
if (indices.Count == 0 if (indices.Count == 0
|| indices[indices.Count - 1] == MainForm.CheatList.Count - 1) // at end already || indices[^1] == MainForm.CheatList.Count - 1) // at end already
{ {
return; return;
} }

View File

@ -1374,7 +1374,7 @@ namespace BizHawk.Client.EmuHawk
// and add HighlightedAddress if present // and add HighlightedAddress if present
if (_highlightedAddress.HasValue) if (_highlightedAddress.HasValue)
{ {
addresses[addresses.Length - 1] = _highlightedAddress.Value; addresses[^1] = _highlightedAddress.Value;
} }
// these need to be sorted. it's not just for HighlightedAddress, _secondaryHighlightedAddresses can even be jumbled // these need to be sorted. it's not just for HighlightedAddress, _secondaryHighlightedAddresses can even be jumbled
@ -2224,7 +2224,7 @@ namespace BizHawk.Client.EmuHawk
{ {
ushort hi = _domain.PeekUshort(((addr+(i<<3)+(j<<1) )^0x0), bigEndian); ushort hi = _domain.PeekUshort(((addr+(i<<3)+(j<<1) )^0x0), bigEndian);
ushort lo = _domain.PeekUshort(((addr+(i<<3)+(j<<1) + 32)^0x0), bigEndian); ushort lo = _domain.PeekUshort(((addr+(i<<3)+(j<<1) + 32)^0x0), bigEndian);
matVals[i,j] = (int)(((hi << 16) | lo)) / 65536.0f; matVals[i,j] = ((hi << 16) | lo) / 65536.0f;
} }
} }

View File

@ -309,7 +309,7 @@ namespace BizHawk.Client.EmuHawk
private void OnLuaFileChanged(LuaFile item) private void OnLuaFileChanged(LuaFile item)
{ {
if (item.Enabled && LuaImp.ScriptList.Contains(item) == true) if (item.Enabled && LuaImp.ScriptList.Contains(item))
{ {
RefreshLuaScript(item); RefreshLuaScript(item);
} }
@ -380,7 +380,7 @@ namespace BizHawk.Client.EmuHawk
{ {
while (LuaImp.ScriptList.Count > 0) while (LuaImp.ScriptList.Count > 0)
{ {
RemoveLuaFile(LuaImp.ScriptList[LuaImp.ScriptList.Count - 1]); RemoveLuaFile(LuaImp.ScriptList[^1]);
} }
} }
@ -1036,7 +1036,7 @@ namespace BizHawk.Client.EmuHawk
{ {
var indices = LuaListView.SelectedRows.ToList(); var indices = LuaListView.SelectedRows.ToList();
if (indices.Count == 0 if (indices.Count == 0
|| indices[indices.Count - 1] == LuaImp.ScriptList.Count - 1) // at end already || indices[^1] == LuaImp.ScriptList.Count - 1) // at end already
{ {
return; return;
} }
@ -1330,7 +1330,7 @@ namespace BizHawk.Client.EmuHawk
var split = words[0].Split(Path.DirectorySeparatorChar); var split = words[0].Split(Path.DirectorySeparatorChar);
luaListTemp.Add(LuaImp.ScriptList[i]); luaListTemp.Add(LuaImp.ScriptList[i]);
luaListTemp[i].Name = split[split.Length - 1]; luaListTemp[i].Name = split[^1];
} }
// Script, Path // Script, Path

View File

@ -5,7 +5,6 @@ using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using System.Text;
using System.Threading; using System.Threading;
using NLua; using NLua;

View File

@ -59,7 +59,7 @@ namespace BizHawk.Client.EmuHawk
} }
} }
key = key.Substring(0, key.Length - 1); key = key[..^1];
SelectedZone.InputKey = key; SelectedZone.InputKey = key;
} }

View File

@ -209,7 +209,7 @@ namespace BizHawk.Client.EmuHawk
return; return;
} }
if (!(CurrentMovie is ITasMovie)) if (CurrentMovie is not ITasMovie)
{ {
SelectedZone.Start = Emulator.Frame; SelectedZone.Start = Emulator.Frame;
} }
@ -238,7 +238,7 @@ namespace BizHawk.Client.EmuHawk
ZonesList.Items.Add($"{loadZone.Name} - length: {loadZone.Length}"); ZonesList.Items.Add($"{loadZone.Name} - length: {loadZone.Length}");
// Options only for TasMovie // Options only for TasMovie
if (!(CurrentMovie is ITasMovie)) if (CurrentMovie is not ITasMovie)
{ {
loadZone.Replace = false; loadZone.Replace = false;
loadZone.Overlay = false; loadZone.Overlay = false;

View File

@ -28,7 +28,7 @@ namespace BizHawk.Client.EmuHawk
} }
key = key.Replace("LogKey:", "").Replace("#", ""); key = key.Replace("LogKey:", "").Replace("#", "");
key = key.Substring(0, key.Length - 1); key = key[..^1];
_inputKey = key; _inputKey = key;
Length = length; Length = length;
@ -41,7 +41,7 @@ namespace BizHawk.Client.EmuHawk
logGenerator.GenerateLogEntry(); // Reference and create all buttons. logGenerator.GenerateLogEntry(); // Reference and create all buttons.
string movieKey = logGenerator.GenerateLogKey().Replace("LogKey:", "").Replace("#", ""); string movieKey = logGenerator.GenerateLogKey().Replace("LogKey:", "").Replace("#", "");
movieKey = movieKey.Substring(0, movieKey.Length - 1); movieKey = movieKey[..^1];
if (key == movieKey) if (key == movieKey)
{ {
for (int i = 0; i < length; i++) for (int i = 0; i < length; i++)
@ -239,7 +239,7 @@ namespace BizHawk.Client.EmuHawk
var lg = _movieSession.Movie.LogGeneratorInstance(_movieSession.MovieController); var lg = _movieSession.Movie.LogGeneratorInstance(_movieSession.MovieController);
string key = lg.GenerateLogKey(); string key = lg.GenerateLogKey();
key = key.Replace("LogKey:", "").Replace("#", ""); key = key.Replace("LogKey:", "").Replace("#", "");
key = key.Substring(0, key.Length - 1); key = key[..^1];
string[] emuKeys = key.Split('|'); string[] emuKeys = key.Split('|');
string[] macroKeys = _inputKey.Split('|'); string[] macroKeys = _inputKey.Split('|');
foreach (var macro in macroKeys) foreach (var macro in macroKeys)

View File

@ -3,13 +3,11 @@ using System.Collections.Generic;
using System.Drawing; using System.Drawing;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Text;
using System.Windows.Forms; using System.Windows.Forms;
using System.Xml.Linq; using System.Xml.Linq;
using BizHawk.Emulation.Common; using BizHawk.Emulation.Common;
using BizHawk.Client.Common; using BizHawk.Client.Common;
using BizHawk.Common;
using BizHawk.Common.PathExtensions; using BizHawk.Common.PathExtensions;
using BizHawk.Common.StringExtensions; using BizHawk.Common.StringExtensions;
using BizHawk.Emulation.Cores.Sega.MasterSystem; using BizHawk.Emulation.Cores.Sega.MasterSystem;
@ -121,15 +119,13 @@ namespace BizHawk.Client.EmuHawk
private void SaveButton_Click(object sender, EventArgs e) private void SaveButton_Click(object sender, EventArgs e)
{ {
FileInfo dummy; DoSave(out var dummy);
DoSave(out dummy);
} }
private void SaveRunButton_Click(object sender, EventArgs e) private void SaveRunButton_Click(object sender, EventArgs e)
{ {
FileInfo fileInfo;
if (!DoSave(out fileInfo)) if (!DoSave(out var fileInfo))
return; return;
DialogResult = DialogResult.OK; DialogResult = DialogResult.OK;

View File

@ -1,7 +1,5 @@
using System; using System;
using System.Drawing; using System.Drawing;
using BizHawk.Client.Common;
using BizHawk.Emulation.Cores.Nintendo.NES; using BizHawk.Emulation.Cores.Nintendo.NES;
using BizHawk.Emulation.Common; using BizHawk.Emulation.Common;

View File

@ -4,7 +4,6 @@ using System.Drawing;
using System.IO; using System.IO;
using System.IO.Compression; using System.IO.Compression;
using System.Linq; using System.Linq;
using System.Text;
using System.Windows.Forms; using System.Windows.Forms;
using System.Xml.XPath; using System.Xml.XPath;
using System.Xml.Linq; using System.Xml.Linq;

View File

@ -53,9 +53,9 @@ namespace BizHawk.Client.EmuHawk
var buf = canvas.Bat.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, canvas.Bat.PixelFormat); var buf = canvas.Bat.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, canvas.Bat.PixelFormat);
var pitch = buf.Stride / 4; var pitch = buf.Stride / 4;
var begin = (int*)buf.Scan0.ToPointer(); var begin = (int*)buf.Scan0.ToPointer();
var vram = (ushort*)view.Vram; var vram = view.Vram;
var patternBuffer = (byte*)view.BackgroundCache; var patternBuffer = view.BackgroundCache;
var palette = (int*)view.PaletteCache; var palette = view.PaletteCache;
int* p = begin; int* p = begin;
for (int y = 0; y < height; ++y) for (int y = 0; y < height; ++y)
@ -118,7 +118,7 @@ namespace BizHawk.Client.EmuHawk
{ {
Viewer.GetGpuData(_vdcType, view => Viewer.GetGpuData(_vdcType, view =>
{ {
var vram = (ushort*)view.Vram; var vram = view.Vram;
int xTile = e.X / 8; int xTile = e.X / 8;
int yTile = e.Y / 8; int yTile = e.Y / 8;
int tileNo = vram[(ushort)((yTile * view.BatWidth) + xTile)] & 0x07FF; int tileNo = vram[(ushort)((yTile * view.BatWidth) + xTile)] & 0x07FF;

View File

@ -81,8 +81,8 @@ namespace BizHawk.Client.EmuHawk
int* dest = (int*)lockData.Scan0; int* dest = (int*)lockData.Scan0;
int pitch = lockData.Stride / sizeof(int); int pitch = lockData.Stride / sizeof(int);
byte* src = (byte*)view.SpriteCache; byte* src = view.SpriteCache;
int* pal = (int*)view.PaletteCache + 256 + _spPalNum * 16; int* pal = view.PaletteCache + 256 + _spPalNum * 16;
for (int tile = 0; tile < 512; tile++) for (int tile = 0; tile < 512; tile++)
{ {
int srcAddr = tile * 256; int srcAddr = tile * 256;
@ -103,8 +103,8 @@ namespace BizHawk.Client.EmuHawk
int* dest = (int*)lockData.Scan0; int* dest = (int*)lockData.Scan0;
int pitch = lockData.Stride / sizeof(int); int pitch = lockData.Stride / sizeof(int);
byte* src = (byte*)view.BackgroundCache; byte* src = view.BackgroundCache;
int* pal = (int*)view.PaletteCache + _bgPalNum * 16; int* pal = view.PaletteCache + _bgPalNum * 16;
for (int tile = 0; tile < 2048; tile++) for (int tile = 0; tile < 2048; tile++)
{ {
int srcAddr = tile * 64; int srcAddr = tile * 64;
@ -121,7 +121,7 @@ namespace BizHawk.Client.EmuHawk
{ {
Viewer.GetGpuData(checkBoxVDC2.Checked ? 1 : 0, view => Viewer.GetGpuData(checkBoxVDC2.Checked ? 1 : 0, view =>
{ {
int* pal = (int*)view.PaletteCache; int* pal = view.PaletteCache;
DrawPalette(bmpViewBGPal.Bmp, pal); DrawPalette(bmpViewBGPal.Bmp, pal);
DrawPalette(bmpViewSPPal.Bmp, pal + 256); DrawPalette(bmpViewSPPal.Bmp, pal + 256);
}); });

View File

@ -1,5 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Drawing; using System.Drawing;
using System.IO; using System.IO;

View File

@ -302,7 +302,7 @@ namespace BizHawk.Client.EmuHawk
{ {
if (p[i] == lastValue) if (p[i] == lastValue)
{ {
_counts[_counts.Count - 1]++; _counts[^1]++;
} }
else else
{ {
@ -335,7 +335,7 @@ namespace BizHawk.Client.EmuHawk
{ {
if (p[i] == lastValue) if (p[i] == lastValue)
{ {
_counts[_counts.Count - 1]++; _counts[^1]++;
} }
else else
{ {

View File

@ -1325,7 +1325,7 @@ namespace BizHawk.Client.EmuHawk
else if (e.KeyCode == Keys.OemMinus || e.KeyCode == Keys.Subtract) else if (e.KeyCode == Keys.OemMinus || e.KeyCode == Keys.Subtract)
{ {
_axisTypedValue = _axisTypedValue.StartsWith('-') _axisTypedValue = _axisTypedValue.StartsWith('-')
? _axisTypedValue.Substring(1) ? _axisTypedValue[1..]
: $"-{_axisTypedValue}"; : $"-{_axisTypedValue}";
} }
else if (e.KeyCode == Keys.Back) else if (e.KeyCode == Keys.Back)
@ -1335,7 +1335,7 @@ namespace BizHawk.Client.EmuHawk
_axisTypedValue = value.ToString(NumberFormatInfo.InvariantInfo); _axisTypedValue = value.ToString(NumberFormatInfo.InvariantInfo);
} }
_axisTypedValue = _axisTypedValue.Substring(0, _axisTypedValue.Length - 1); _axisTypedValue = _axisTypedValue[..^1];
if (_axisTypedValue == "" || _axisTypedValue == "-") if (_axisTypedValue == "" || _axisTypedValue == "-")
{ {
value = 0f; value = 0f;

View File

@ -469,7 +469,7 @@ namespace BizHawk.Client.EmuHawk
{ {
_tasClipboard.Clear(); _tasClipboard.Clear();
int linesToPaste = lines.Length; int linesToPaste = lines.Length;
if (lines[lines.Length - 1] == "") linesToPaste--; if (lines[^1] == "") linesToPaste--;
for (int i = 0; i < linesToPaste; i++) for (int i = 0; i < linesToPaste; i++)
{ {
var line = ControllerFromMnemonicStr(lines[i]); var line = ControllerFromMnemonicStr(lines[i]);
@ -511,7 +511,7 @@ namespace BizHawk.Client.EmuHawk
{ {
_tasClipboard.Clear(); _tasClipboard.Clear();
int linesToPaste = lines.Length; int linesToPaste = lines.Length;
if (lines[lines.Length - 1] == "") linesToPaste--; if (lines[^1] == "") linesToPaste--;
for (int i = 0; i < linesToPaste; i++) for (int i = 0; i < linesToPaste; i++)
{ {
var line = ControllerFromMnemonicStr(lines[i]); var line = ControllerFromMnemonicStr(lines[i]);

View File

@ -11,7 +11,6 @@ using BizHawk.Client.EmuHawk.Properties;
using BizHawk.Common; using BizHawk.Common;
using BizHawk.Common.StringExtensions; using BizHawk.Common.StringExtensions;
using BizHawk.Emulation.Common; using BizHawk.Emulation.Common;
using BizHawk.Emulation.Cores.Nintendo.N64;
namespace BizHawk.Client.EmuHawk namespace BizHawk.Client.EmuHawk
{ {
@ -228,7 +227,7 @@ namespace BizHawk.Client.EmuHawk
} }
// Start Scenario 1: A regular movie is active // Start Scenario 1: A regular movie is active
if (MovieSession.Movie.IsActive() && !(MovieSession.Movie is ITasMovie)) if (MovieSession.Movie.IsActive() && MovieSession.Movie is not ITasMovie)
{ {
var changesString = "Would you like to save the current movie before closing it?"; var changesString = "Would you like to save the current movie before closing it?";
if (MovieSession.Movie.Changes) if (MovieSession.Movie.Changes)
@ -451,8 +450,8 @@ namespace BizHawk.Client.EmuHawk
BoolPatterns[i] = new AutoPatternBool(1, 1); BoolPatterns[i] = new AutoPatternBool(1, 1);
} }
BoolPatterns[BoolPatterns.Length - 2] = new AutoPatternBool(1, 0); BoolPatterns[^2] = new AutoPatternBool(1, 0);
BoolPatterns[BoolPatterns.Length - 1] = new AutoPatternBool( BoolPatterns[^1] = new AutoPatternBool(
Config.AutofireOn, Config.AutofireOff); Config.AutofireOn, Config.AutofireOff);
for (int i = fStart; i < AxisPatterns.Length - 2; i++) for (int i = fStart; i < AxisPatterns.Length - 2; i++)
@ -460,8 +459,8 @@ namespace BizHawk.Client.EmuHawk
AxisPatterns[i] = new AutoPatternAxis(new[] { 1 }); AxisPatterns[i] = new AutoPatternAxis(new[] { 1 });
} }
AxisPatterns[AxisPatterns.Length - 2] = new AutoPatternAxis(new[] { 1 }); AxisPatterns[^2] = new AutoPatternAxis(new[] { 1 });
AxisPatterns[AxisPatterns.Length - 1] = new AutoPatternAxis(1, Config.AutofireOn, 0, Config.AutofireOff); AxisPatterns[^1] = new AutoPatternAxis(1, Config.AutofireOn, 0, Config.AutofireOff);
SetUpToolStripColumns(); SetUpToolStripColumns();
} }

View File

@ -85,10 +85,10 @@ namespace BizHawk.Client.EmuHawk
// If the form inherits ToolFormBase, it will set base properties such as Tools, Config, etc // If the form inherits ToolFormBase, it will set base properties such as Tools, Config, etc
private void SetBaseProperties(IToolForm form) private void SetBaseProperties(IToolForm form)
{ {
if (!(form is FormBase f)) return; if (form is not FormBase f) return;
f.Config = _config; f.Config = _config;
if (!(form is ToolFormBase tool)) return; if (form is not ToolFormBase tool) return;
tool.SetToolFormBaseProps(_displayManager, _inputManager, _owner, _movieSession, this, _game); tool.SetToolFormBaseProps(_displayManager, _inputManager, _owner, _movieSession, this, _game);
} }
@ -121,7 +121,7 @@ namespace BizHawk.Client.EmuHawk
_tools.Remove(existingTool); _tools.Remove(existingTool);
} }
if (!(CreateInstance<T>(toolPath) is T newTool)) return null; if (CreateInstance<T>(toolPath) is not T newTool) return null;
if (newTool is Form form) form.Owner = _owner; if (newTool is Form form) form.Owner = _owner;
if (!ServiceInjector.UpdateServices(_emulator.ServiceProvider, newTool)) return null; //TODO pass `true` for `mayCache` when from EmuHawk assembly if (!ServiceInjector.UpdateServices(_emulator.ServiceProvider, newTool)) return null; //TODO pass `true` for `mayCache` when from EmuHawk assembly
@ -402,7 +402,7 @@ namespace BizHawk.Client.EmuHawk
var converter = TypeDescriptor.GetConverter(prop.PropertyType); var converter = TypeDescriptor.GetConverter(prop.PropertyType);
val = converter.ConvertFromString(null, CultureInfo.InvariantCulture, str); val = converter.ConvertFromString(null, CultureInfo.InvariantCulture, str);
} }
else if (!(val is bool) && prop.PropertyType.IsPrimitive) else if (val is not bool && prop.PropertyType.IsPrimitive)
{ {
// numeric constants are similarly hosed // numeric constants are similarly hosed
val = Convert.ChangeType(val, prop.PropertyType, CultureInfo.InvariantCulture); val = Convert.ChangeType(val, prop.PropertyType, CultureInfo.InvariantCulture);

View File

@ -128,8 +128,7 @@ namespace BizHawk.Client.EmuHawk
{ {
foreach (var control in ControllerPanel.Controls) foreach (var control in ControllerPanel.Controls)
{ {
var vp = control as VirtualPad; if (control is not VirtualPad vp)
if (vp == null)
{ {
continue; continue;
} }

View File

@ -37,7 +37,7 @@ namespace BizHawk.Client.EmuHawk
private void UpdateCoreAssociation() private void UpdateCoreAssociation()
{ {
if (!(_ownerEmulator is Octoshock psx)) if (_ownerEmulator is not Octoshock psx)
{ {
return; return;
} }

View File

@ -170,8 +170,8 @@ namespace BizHawk.Client.EmuHawk
private void SetAnalog() private void SetAnalog()
{ {
_stickyXorAdapter.SetAxis(XName, HasValue ? X : (int?)null); _stickyXorAdapter.SetAxis(XName, HasValue ? X : null);
_stickyXorAdapter.SetAxis(YName, HasValue ? Y : (int?)null); _stickyXorAdapter.SetAxis(YName, HasValue ? Y : null);
Refresh(); Refresh();
} }

View File

@ -415,7 +415,7 @@ namespace BizHawk.Client.EmuHawk
foreach (var row in clipboardRows) foreach (var row in clipboardRows)
{ {
var watch = Watch.FromString(row, MemoryDomains); var watch = Watch.FromString(row, MemoryDomains);
if ((object)watch != null) if (watch is not null)
{ {
_watches.Add(watch); _watches.Add(watch);
} }
@ -910,7 +910,7 @@ namespace BizHawk.Client.EmuHawk
{ {
var indices = SelectedIndices.ToList(); var indices = SelectedIndices.ToList();
if (indices.Count == 0 if (indices.Count == 0
|| indices[indices.Count - 1] == _watches.Count - 1) // at end already || indices[^1] == _watches.Count - 1) // at end already
{ {
return; return;
} }

View File

@ -195,7 +195,7 @@ namespace BizHawk.Client.EmuHawk
{ {
default: default:
case WatchDisplayType.Signed: case WatchDisplayType.Signed:
int? val = ToRawInt() ?? 0; int val = ToRawInt() ?? 0;
if (val == MaxSignedInt) if (val == MaxSignedInt)
{ {
val = MinSignedInt; val = MinSignedInt;
@ -307,12 +307,8 @@ namespace BizHawk.Client.EmuHawk
{ {
default: default:
case WatchDisplayType.Signed: case WatchDisplayType.Signed:
var val = ToRawInt(); int val = ToRawInt() ?? 0;
if (!val.HasValue) if (val == MinSignedInt)
{
Text = "";
}
else if (val == MinSignedInt)
{ {
val = MaxSignedInt; val = MaxSignedInt;
} }
@ -468,7 +464,7 @@ namespace BizHawk.Client.EmuHawk
{ {
default: default:
case WatchDisplayType.Signed: case WatchDisplayType.Signed:
Text = val.ToString(); Text = val.Value.ToString();
break; break;
case WatchDisplayType.Unsigned: case WatchDisplayType.Unsigned:
var uval = (uint)val.Value; var uval = (uint)val.Value;

View File

@ -2,8 +2,6 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Text; using System.Text;
using BizHawk.Common.BufferExtensions;
using BizHawk.Common.CollectionExtensions; using BizHawk.Common.CollectionExtensions;
namespace BizHawk.Common namespace BizHawk.Common

View File

@ -1,4 +1,3 @@
using System;
using System.Diagnostics; using System.Diagnostics;
namespace BizHawk.Common namespace BizHawk.Common

View File

@ -110,7 +110,7 @@ namespace BizHawk.Common
else else
{ {
// All items *after* the item // All items *after* the item
startIndex = startIndex + 1; startIndex++;
} }
if (startIndex < _list.Count) if (startIndex < _list.Count)
{ {

View File

@ -1,5 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;

View File

@ -297,7 +297,7 @@ namespace BizHawk.Common
#if DEBUG #if DEBUG
if (path.IndexOf('|') != i) Console.WriteLine($"{nameof(HawkFile)} path contains multiple '|'"); if (path.IndexOf('|') != i) Console.WriteLine($"{nameof(HawkFile)} path contains multiple '|'");
#endif #endif
return i == -1 ? ((string, string)?) null : (path.Substring(0, i), path.Substring(i + 1)); return i == -1 ? null : (path.Substring(0, i), path.Substring(i + 1));
} }
} }
} }

View File

@ -1,6 +1,4 @@
using System; namespace BizHawk.Common
namespace BizHawk.Common
{ {
public interface IMonitor public interface IMonitor
{ {

View File

@ -1,4 +1,6 @@
#pragma warning disable IDE0240
#nullable enable #nullable enable
#pragma warning restore IDE0240
using System; using System;
using System.Diagnostics; using System.Diagnostics;

View File

@ -1,4 +1,3 @@
using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace BizHawk.Emulation.Common namespace BizHawk.Emulation.Common

View File

@ -5,7 +5,6 @@ using System.Linq;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace BizHawk.Emulation.Common namespace BizHawk.Emulation.Common
{ {

View File

@ -1,4 +1,3 @@
#nullable enable
using System; using System;

View File

@ -1,4 +1,3 @@
#nullable enable
using System.Collections.Generic; using System.Collections.Generic;

View File

@ -2,7 +2,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;

View File

@ -1,5 +1,4 @@
using System; using System;
using System.Runtime.InteropServices;
using BizHawk.Common; using BizHawk.Common;

View File

@ -3,7 +3,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq;
using BizHawk.Common; using BizHawk.Common;

View File

@ -1,6 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Reflection; using System.Reflection;
using BizHawk.Common.ReflectionExtensions; using BizHawk.Common.ReflectionExtensions;

View File

@ -1,8 +1,6 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Drawing; using System.Drawing;
using BizHawk.Emulation.Common;
namespace BizHawk.Emulation.Common namespace BizHawk.Emulation.Common
{ {
public abstract class PadSchemaControl public abstract class PadSchemaControl

View File

@ -1,6 +1,5 @@
using System; using System;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Text;
using BizHawk.BizInvoke; using BizHawk.BizInvoke;

View File

@ -168,7 +168,7 @@ namespace BizHawk.Emulation.Cores.Arcades.MAME
if (hashdata.Contains("^")) if (hashdata.Contains("^"))
{ {
hashdata = hashdata.RemoveSuffix("^"); hashdata = hashdata.RemoveSuffix("^");
name = name + " (BAD DUMP)"; name += " (BAD DUMP)";
} }
hashdata = hashdata.Replace("R", "CRC:").Replace("S", " SHA:"); hashdata = hashdata.Replace("R", "CRC:").Replace("S", " SHA:");

View File

@ -1,6 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using BizHawk.Emulation.Common; using BizHawk.Emulation.Common;

View File

@ -508,7 +508,7 @@ namespace BizHawk.Emulation.Cores.Components.M68000
string address = DisassembleAddress(mode, reg, ref pc); string address = DisassembleAddress(mode, reg, ref pc);
info.Mnemonic = size == 0 ? "movem.w" : "movem.l"; info.Mnemonic = size == 0 ? "movem.w" : "movem.l";
info.Args = DisassembleRegisterList0((uint)registers) + ", " + address; info.Args = DisassembleRegisterList0(registers) + ", " + address;
info.Length = pc - info.PC; info.Length = pc - info.PC;
} }

View File

@ -1126,7 +1126,7 @@ namespace BizHawk.Emulation.Cores.Components.M68000
int quotient = dest / source; int quotient = dest / source;
int remainder = dest % source; int remainder = dest % source;
V = ((int)quotient < short.MinValue || (int)quotient > short.MaxValue); V = (quotient < short.MinValue || quotient > short.MaxValue);
N = (quotient & 0x8000) != 0; N = (quotient & 0x8000) != 0;
Z = quotient == 0; Z = quotient == 0;
C = false; C = false;

View File

@ -58,7 +58,7 @@ namespace BizHawk.Emulation.Cores.Components.M68000
sbyte displacement8 = (sbyte)op; sbyte displacement8 = (sbyte)op;
int cond = (op >> 8) & 0x0F; int cond = (op >> 8) & 0x0F;
if (TestCondition(cond) == true) if (TestCondition(cond))
{ {
if (displacement8 != 0) if (displacement8 != 0)
{ {
@ -169,7 +169,7 @@ namespace BizHawk.Emulation.Cores.Components.M68000
private void DBcc() private void DBcc()
{ {
if (TestCondition((op >> 8) & 0x0F) == true) if (TestCondition((op >> 8) & 0x0F))
{ {
PC += 2; // condition met, break out of loop PC += 2; // condition met, break out of loop
PendingCycles -= 12; PendingCycles -= 12;
@ -712,7 +712,7 @@ namespace BizHawk.Emulation.Cores.Components.M68000
int mode = (op >> 3) & 7; int mode = (op >> 3) & 7;
int reg = (op >> 0) & 7; int reg = (op >> 0) & 7;
if (TestCondition(cond) == true) if (TestCondition(cond))
{ {
WriteValueB(mode, reg, -1); WriteValueB(mode, reg, -1);
if (mode == 0) PendingCycles -= 6; if (mode == 0) PendingCycles -= 6;

View File

@ -29,7 +29,7 @@ namespace BizHawk.Emulation.Cores.Components.M68000
{ {
int mode = (op >> 3) & 7; int mode = (op >> 3) & 7;
int reg = (op >> 0) & 7; int reg = (op >> 0) & 7;
WriteValueW(mode, reg, (short)SR); WriteValueW(mode, reg, SR);
PendingCycles -= (mode == 0) ? 6 : 8 + EACyclesBW[mode, reg]; PendingCycles -= (mode == 0) ? 6 : 8 + EACyclesBW[mode, reg];
} }
@ -151,7 +151,7 @@ namespace BizHawk.Emulation.Cores.Components.M68000
private void TrapVector(int vector) private void TrapVector(int vector)
{ {
short sr = (short)SR; // capture current SR. short sr = SR; // capture current SR.
S = true; // switch to supervisor mode, if not already in it. S = true; // switch to supervisor mode, if not already in it.
A[7].s32 -= 4; // Push PC on stack A[7].s32 -= 4; // Push PC on stack
WriteLong(A[7].s32, PC); WriteLong(A[7].s32, PC);

View File

@ -36,7 +36,7 @@ namespace BizHawk.Emulation.Cores.Components.M68000
set set
{ {
if (value == s) return; if (value == s) return;
if (value == true) // entering supervisor mode if (value) // entering supervisor mode
{ {
Console.WriteLine("&^&^&^&^& ENTER SUPERVISOR MODE"); Console.WriteLine("&^&^&^&^& ENTER SUPERVISOR MODE");
usp = A[7].s32; usp = A[7].s32;
@ -142,7 +142,7 @@ namespace BizHawk.Emulation.Cores.Components.M68000
{ {
// TODO: Entering interrupt is not free. how many cycles does it take? // TODO: Entering interrupt is not free. how many cycles does it take?
//Log.Error("CPU","****** ENTER INTERRUPT {0} *******", Interrupt); //Log.Error("CPU","****** ENTER INTERRUPT {0} *******", Interrupt);
short sr = (short)SR; // capture current SR. short sr = SR; // capture current SR.
S = true; // switch to supervisor mode, if not already in it. S = true; // switch to supervisor mode, if not already in it.
A[7].s32 -= 4; // Push PC on stack A[7].s32 -= 4; // Push PC on stack
WriteLong(A[7].s32, PC); WriteLong(A[7].s32, PC);

View File

@ -1,6 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using BizHawk.Common; using BizHawk.Common;
using BizHawk.Emulation.Common; using BizHawk.Emulation.Common;

View File

@ -19,7 +19,7 @@ namespace BizHawk.Emulation.Cores.Components.FairchildF8
public void IN_Func(byte dest, byte src) public void IN_Func(byte dest, byte src)
{ {
Regs[dest] = ReadHardware((byte)(Regs[src])); Regs[dest] = ReadHardware(Regs[src]);
} }
/// <summary> /// <summary>

View File

@ -174,7 +174,7 @@ namespace BizHawk.Emulation.Cores.Components.FairchildF8
public bool IRQRequest public bool IRQRequest
{ {
get => Regs[IRQR] > 0; get => Regs[IRQR] > 0;
set => Regs[IRQR] = value == true ? (byte)1 : (byte)0; set => Regs[IRQR] = value ? (byte)1 : (byte)0;
} }
/// <summary> /// <summary>

Some files were not shown because too many files have changed in this diff Show More