Replaced event handlers with direct delegates where appropriate.

Cosmetic changes including using C# 4 named and optional parameters.

--HG--
extra : convert_revision : svn%3Affd33b8c-2492-42e0-bdc5-587b920b7d6d/trunk%4046806
This commit is contained in:
Sean Fausett 2010-05-28 10:48:08 +00:00
parent 6700099803
commit 2ba3146299
26 changed files with 107 additions and 216 deletions

View File

@ -5,30 +5,10 @@
namespace Jellyfish.Library namespace Jellyfish.Library
{ {
public sealed class DirectSoundUpdateEventArgs : EventArgs
{
private DirectSoundUpdateEventArgs()
{
}
public static DirectSoundUpdateEventArgs Create(IntPtr buffer, int bufferSize)
{
_instance.Buffer = buffer;
_instance.BufferSize = bufferSize;
return _instance; // use singleton; avoids garbage
}
public IntPtr Buffer { get; private set; }
public int BufferSize { get; private set; }
private static readonly DirectSoundUpdateEventArgs _instance = new DirectSoundUpdateEventArgs();
}
public sealed partial class DirectSound : IDisposable public sealed partial class DirectSound : IDisposable
{ {
[SecurityCritical] [SecurityCritical]
public DirectSound(int sampleRate, int sampleChannels, int sampleBits, int sampleSize) public DirectSound(int sampleRate, int sampleChannels, int sampleBits, int sampleSize, Action<IntPtr, int> updater)
{ {
_sampleRate = sampleRate; _sampleRate = sampleRate;
_sampleChannels = sampleChannels; _sampleChannels = sampleChannels;
@ -36,6 +16,7 @@ public DirectSound(int sampleRate, int sampleChannels, int sampleBits, int sampl
_sampleSize = sampleSize; _sampleSize = sampleSize;
_thread = new Thread(Run) { Name = "DirectSound" }; _thread = new Thread(Run) { Name = "DirectSound" };
_updater = updater;
} }
public void Dispose() public void Dispose()
@ -102,16 +83,7 @@ private void RestoreBuffer()
} }
} }
private void UpdateBuffer(int block) private void UpdateBuffer(int offset, int count, BufferLock flags, Action<IntPtr, int> updater)
{
var handler = Update;
if (handler != null)
{
UpdateBuffer(block * _sampleSize, _sampleSize, BufferLock.None, (buffer, bufferSize) => handler(this, DirectSoundUpdateEventArgs.Create(buffer, bufferSize)));
}
}
private void UpdateBuffer(int offset, int count, BufferLock flags, Action<IntPtr, int> updateBuffer)
{ {
RestoreBuffer(); RestoreBuffer();
@ -122,11 +94,11 @@ private void UpdateBuffer(int offset, int count, BufferLock flags, Action<IntPtr
{ {
if (buffer1 != IntPtr.Zero) if (buffer1 != IntPtr.Zero)
{ {
updateBuffer(buffer1, buffer1Size); updater(buffer1, buffer1Size);
} }
if (buffer2 != IntPtr.Zero) if (buffer2 != IntPtr.Zero)
{ {
updateBuffer(buffer2, buffer2Size); updater(buffer2, buffer2Size);
} }
} }
finally finally
@ -158,15 +130,13 @@ private void Run() // com mta thread
while (index < BlockCount) while (index < BlockCount)
{ {
UpdateBuffer((index + 1) % BlockCount); // update next block in circular buffer UpdateBuffer(((index + 1) % BlockCount) * _sampleSize, _sampleSize, BufferLock.None, _updater); // update next block in circular buffer
index = WaitHandle.WaitAny(eventHandles); index = WaitHandle.WaitAny(eventHandles);
} }
Uninitialize(); Uninitialize();
} }
public event EventHandler<DirectSoundUpdateEventArgs> Update;
private const int BlockCount = 2; private const int BlockCount = 2;
private int _sampleRate; private int _sampleRate;
@ -178,6 +148,7 @@ private void Run() // com mta thread
private IntPtr _window; private IntPtr _window;
private IDirectSound _device; private IDirectSound _device;
private IDirectSoundBuffer _buffer; private IDirectSoundBuffer _buffer;
private Action<IntPtr, int> _updater;
private AutoResetEvent _position1Event = new AutoResetEvent(false); private AutoResetEvent _position1Event = new AutoResetEvent(false);
private AutoResetEvent _position2Event = new AutoResetEvent(false); private AutoResetEvent _position2Event = new AutoResetEvent(false);

View File

@ -36,8 +36,7 @@ public GeneralAccessRule(IdentityReference identity, int rights, InheritanceFlag
{ {
} }
public GeneralAccessRule(IdentityReference identity, int rights, bool isInherited, InheritanceFlags inheritance, PropagationFlags propagation, public GeneralAccessRule(IdentityReference identity, int rights, bool isInherited, InheritanceFlags inheritance, PropagationFlags propagation, AccessControlType type) :
AccessControlType type) :
base(identity, rights, isInherited, inheritance, propagation, type) base(identity, rights, isInherited, inheritance, propagation, type)
{ {
} }
@ -57,8 +56,7 @@ public GeneralAuditRule(IdentityReference identity, int rights, InheritanceFlags
{ {
} }
public GeneralAuditRule(IdentityReference identity, int rights, bool isInherited, InheritanceFlags inheritance, PropagationFlags propagation, public GeneralAuditRule(IdentityReference identity, int rights, bool isInherited, InheritanceFlags inheritance, PropagationFlags propagation, AuditFlags audit) :
AuditFlags audit) :
base(identity, rights, isInherited, inheritance, propagation, audit) base(identity, rights, isInherited, inheritance, propagation, audit)
{ {
} }
@ -73,34 +71,22 @@ public GeneralSecurity(bool isContainer, ResourceType resourceType) :
{ {
} }
public GeneralSecurity(bool isContainer, ResourceType resourceType, SafeHandle handle) : public GeneralSecurity(bool isContainer, ResourceType resourceType, SafeHandle handle, AccessControlSections includeSections = AccessControlSections.Access | AccessControlSections.Group | AccessControlSections.Owner) :
base(isContainer, resourceType, handle, AccessControlSections.Access | AccessControlSections.Group | AccessControlSections.Owner)
{
}
public GeneralSecurity(bool isContainer, ResourceType resourceType, SafeHandle handle, AccessControlSections includeSections) :
base(isContainer, resourceType, handle, includeSections) base(isContainer, resourceType, handle, includeSections)
{ {
} }
public GeneralSecurity(bool isContainer, ResourceType resourceType, string name) : public GeneralSecurity(bool isContainer, ResourceType resourceType, string name, AccessControlSections includeSections = AccessControlSections.Access | AccessControlSections.Group | AccessControlSections.Owner) :
base(isContainer, resourceType, name, AccessControlSections.Access | AccessControlSections.Group | AccessControlSections.Owner)
{
}
public GeneralSecurity(bool isContainer, ResourceType resourceType, string name, AccessControlSections includeSections) :
base(isContainer, resourceType, name, includeSections) base(isContainer, resourceType, name, includeSections)
{ {
} }
public override AccessRule AccessRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, public override AccessRule AccessRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type)
PropagationFlags propagationFlags, AccessControlType type)
{ {
return new GeneralAccessRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, type); return new GeneralAccessRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, type);
} }
public override AuditRule AuditRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, public override AuditRule AuditRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags)
PropagationFlags propagationFlags, AuditFlags flags)
{ {
return new GeneralAuditRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, flags); return new GeneralAuditRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, flags);
} }
@ -118,13 +104,13 @@ public void AddAuditRule(GeneralAuditRule rule)
} }
[SecurityCritical] [SecurityCritical]
public void GetSecurityAttributes(bool inheritable, Action<SecurityAttributes> action) public void GetSecurityAttributes(Action<SecurityAttributes> action, bool inheritable = false)
{ {
GetSecurityAttributes(this, inheritable, action); GetSecurityAttributes(this, action, inheritable);
} }
[SecurityCritical] [SecurityCritical]
public static void GetSecurityAttributes(ObjectSecurity security, bool inheritable, Action<SecurityAttributes> action) public static void GetSecurityAttributes(ObjectSecurity security, Action<SecurityAttributes> action, bool inheritable = false)
{ {
if (action == null) if (action == null)
{ {

View File

@ -22,7 +22,7 @@ public sealed class SafeGlobalAllocHandle : SafeAllocHandle
{ {
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public SafeGlobalAllocHandle() : public SafeGlobalAllocHandle() :
base(true) base(ownsHandle: true)
{ {
} }
@ -33,12 +33,6 @@ public SafeGlobalAllocHandle(IntPtr existingHandle, bool ownsHandle) :
SetHandle(existingHandle); SetHandle(existingHandle);
} }
[SecurityCritical]
public static SafeGlobalAllocHandle Allocate(int size)
{
return Allocate(0x0, size);
}
[SecurityCritical] [SecurityCritical]
public static SafeGlobalAllocHandle Allocate(byte[] value) public static SafeGlobalAllocHandle Allocate(byte[] value)
{ {
@ -53,15 +47,8 @@ public static SafeGlobalAllocHandle Allocate(byte[] value)
return alloc; return alloc;
} }
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[SecurityCritical] [SecurityCritical]
protected override bool ReleaseHandle() public static SafeGlobalAllocHandle Allocate(int size, uint flags = 0x0)
{
return (NativeMethods.GlobalFree(handle) == IntPtr.Zero);
}
[SecurityCritical]
private static SafeGlobalAllocHandle Allocate(uint flags, int size)
{ {
var alloc = NativeMethods.GlobalAlloc(flags, (IntPtr)size); var alloc = NativeMethods.GlobalAlloc(flags, (IntPtr)size);
if (alloc.IsInvalid) if (alloc.IsInvalid)
@ -72,6 +59,13 @@ private static SafeGlobalAllocHandle Allocate(uint flags, int size)
return alloc; return alloc;
} }
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[SecurityCritical]
protected override bool ReleaseHandle()
{
return (NativeMethods.GlobalFree(handle) == IntPtr.Zero);
}
[SecurityCritical] [SecurityCritical]
[SuppressUnmanagedCodeSecurity] [SuppressUnmanagedCodeSecurity]
private static class NativeMethods private static class NativeMethods
@ -91,7 +85,7 @@ public sealed class SafeLocalAllocHandle : SafeAllocHandle
{ {
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public SafeLocalAllocHandle() : public SafeLocalAllocHandle() :
base(true) base(ownsHandle: true)
{ {
} }
@ -102,12 +96,6 @@ public SafeLocalAllocHandle(IntPtr existingHandle, bool ownsHandle) :
SetHandle(existingHandle); SetHandle(existingHandle);
} }
[SecurityCritical]
public static SafeLocalAllocHandle Allocate(int size)
{
return Allocate(0x0, size);
}
[SecurityCritical] [SecurityCritical]
public static SafeLocalAllocHandle Allocate(byte[] value) public static SafeLocalAllocHandle Allocate(byte[] value)
{ {
@ -122,15 +110,8 @@ public static SafeLocalAllocHandle Allocate(byte[] value)
return alloc; return alloc;
} }
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[SecurityCritical] [SecurityCritical]
protected override bool ReleaseHandle() public static SafeLocalAllocHandle Allocate(int size, uint flags = 0x0)
{
return (NativeMethods.LocalFree(handle) == IntPtr.Zero);
}
[SecurityCritical]
private static SafeLocalAllocHandle Allocate(uint flags, int size)
{ {
var alloc = NativeMethods.LocalAlloc(flags, (IntPtr)size); var alloc = NativeMethods.LocalAlloc(flags, (IntPtr)size);
if (alloc.IsInvalid) if (alloc.IsInvalid)
@ -141,6 +122,13 @@ private static SafeLocalAllocHandle Allocate(uint flags, int size)
return alloc; return alloc;
} }
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[SecurityCritical]
protected override bool ReleaseHandle()
{
return (NativeMethods.LocalFree(handle) == IntPtr.Zero);
}
[SecurityCritical] [SecurityCritical]
[SuppressUnmanagedCodeSecurity] [SuppressUnmanagedCodeSecurity]
private static class NativeMethods private static class NativeMethods

View File

@ -14,7 +14,7 @@ public sealed class SafeFileHandle : SafeHandleZeroOrMinusOneIsInvalid
{ {
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public SafeFileHandle() : public SafeFileHandle() :
base(true) base(ownsHandle: true)
{ {
} }
@ -64,18 +64,18 @@ public void SetAccessControl(GeneralSecurity fileSecurity)
[SecurityCritical] [SecurityCritical]
private static SafeFileHandle CreateFile(string fileName, uint fileAccess, uint fileShare, uint fileMode, uint fileOptions, GeneralSecurity fileSecurity, private static SafeFileHandle CreateFile(string fileName, uint fileAccess, uint fileShare, uint fileMode, uint fileOptions, GeneralSecurity fileSecurity,
bool inheritable) bool inheritable = false)
{ {
var file = new SafeFileHandle(); var file = new SafeFileHandle();
GeneralSecurity.GetSecurityAttributes(fileSecurity, inheritable, securityAttributes => GeneralSecurity.GetSecurityAttributes(fileSecurity, securityAttributes =>
{ {
file = NativeMethods.CreateFile(fileName, fileAccess, fileShare, securityAttributes, fileMode, fileOptions, IntPtr.Zero); file = NativeMethods.CreateFile(fileName, fileAccess, fileShare, securityAttributes, fileMode, fileOptions, IntPtr.Zero);
if (file.IsInvalid) if (file.IsInvalid)
{ {
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
} }
}); }, inheritable);
return file; return file;
} }

View File

@ -6,12 +6,7 @@ namespace Jellyfish.Library
{ {
public class ApplicationBase : Application public class ApplicationBase : Application
{ {
public ApplicationBase() : public ApplicationBase(string name = null)
this(null)
{
}
public ApplicationBase(string name)
{ {
Name = name; Name = name;
@ -21,7 +16,7 @@ public ApplicationBase(string name)
private void OnApplicationUnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e) private void OnApplicationUnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{ {
MessageBox.Show(GetExceptionMessage(e.ExceptionObject), GetExceptionCaption("Application Exception", false), MessageBoxButton.OK); MessageBox.Show(GetExceptionMessage(e.ExceptionObject), GetExceptionCaption("Application Exception"), MessageBoxButton.OK);
e.Handled = true; e.Handled = true;
} }
@ -30,7 +25,7 @@ private void OnApplicationUnhandledException(object sender, ApplicationUnhandled
// MessageBox.Show(GetExceptionMessage(e.ExceptionObject as Exception), GetExceptionCaption("AppDomain Exception", e.IsTerminating), MessageBoxButton.OK); // MessageBox.Show(GetExceptionMessage(e.ExceptionObject as Exception), GetExceptionCaption("AppDomain Exception", e.IsTerminating), MessageBoxButton.OK);
//} //}
private string GetExceptionCaption(string title, bool isTerminating) private string GetExceptionCaption(string title, bool isTerminating = false)
{ {
var caption = new StringBuilder(); var caption = new StringBuilder();
if (!string.IsNullOrEmpty(Name)) if (!string.IsNullOrEmpty(Name))

View File

@ -1,41 +1,20 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO; using System.IO;
using System.Windows.Media; using System.Windows.Media;
namespace Jellyfish.Library namespace Jellyfish.Library
{ {
public sealed class WaveMediaStreamSourceUpdateEventArgs : EventArgs
{
private WaveMediaStreamSourceUpdateEventArgs()
{
}
public static WaveMediaStreamSourceUpdateEventArgs Create(byte[] buffer, int bufferSize)
{
_instance.Buffer = buffer;
_instance.BufferSize = bufferSize;
return _instance; // use singleton; avoids garbage
}
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public byte[] Buffer { get; private set; }
public int BufferSize { get; private set; }
private static readonly WaveMediaStreamSourceUpdateEventArgs _instance = new WaveMediaStreamSourceUpdateEventArgs();
}
public sealed class WaveMediaStreamSource : MediaStreamSource, IDisposable public sealed class WaveMediaStreamSource : MediaStreamSource, IDisposable
{ {
public WaveMediaStreamSource(int sampleRate, int sampleChannels, int sampleBits, int sampleSize, int sampleLatency) public WaveMediaStreamSource(int sampleRate, int sampleChannels, int sampleBits, int sampleSize, int sampleLatency, Action<byte[], int> updater)
{ {
_bufferSize = sampleSize; _bufferSize = sampleSize;
_buffer = new byte[_bufferSize]; _buffer = new byte[_bufferSize];
_bufferStream = new MemoryStream(_buffer); _bufferStream = new MemoryStream(_buffer);
_waveFormat = new WaveFormat(sampleRate, sampleChannels, sampleBits); _waveFormat = new WaveFormat(sampleRate, sampleChannels, sampleBits);
AudioBufferLength = sampleLatency; // ms; avoids audio delay AudioBufferLength = sampleLatency; // ms; avoids audio delay
_updater = updater;
} }
public void Dispose() public void Dispose()
@ -55,11 +34,7 @@ protected override void GetDiagnosticAsync(MediaStreamSourceDiagnosticKind diagn
protected override void GetSampleAsync(MediaStreamType mediaStreamType) protected override void GetSampleAsync(MediaStreamType mediaStreamType)
{ {
var handler = Update; _updater(_buffer, _bufferSize);
if (handler != null)
{
handler(this, WaveMediaStreamSourceUpdateEventArgs.Create(_buffer, _bufferSize));
}
var sample = new MediaStreamSample(_audioDescription, _bufferStream, 0, _bufferSize, _timestamp, _emptySampleDict); var sample = new MediaStreamSample(_audioDescription, _bufferStream, 0, _bufferSize, _timestamp, _emptySampleDict);
_timestamp += _bufferSize * 10000000L / _waveFormat.AverageBytesPerSec; // 100 ns _timestamp += _bufferSize * 10000000L / _waveFormat.AverageBytesPerSec; // 100 ns
@ -89,11 +64,10 @@ protected override void SwitchMediaStreamAsync(MediaStreamDescription mediaStrea
throw new NotImplementedException(); throw new NotImplementedException();
} }
public event EventHandler<WaveMediaStreamSourceUpdateEventArgs> Update;
private byte[] _buffer; private byte[] _buffer;
private int _bufferSize; private int _bufferSize;
private MemoryStream _bufferStream; private MemoryStream _bufferStream;
private Action<byte[], int> _updater;
private WaveFormat _waveFormat; private WaveFormat _waveFormat;
private long _timestamp; private long _timestamp;
private MediaStreamDescription _audioDescription; private MediaStreamDescription _audioDescription;

View File

@ -49,6 +49,20 @@ public static StringBuilder AppendWithoutGarbage(this StringBuilder builder, int
return builder; return builder;
} }
#if WINDOWS_PHONE || XBOX
public static StringBuilder Clear(this StringBuilder builder)
{
if (builder == null)
{
throw new ArgumentNullException("builder");
}
builder.Length = 0;
return builder;
}
#endif
private static readonly char[] Digits = new char[] { '9', '8', '7', '6', '5', '4', '3', '2', '1', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; private static readonly char[] Digits = new char[] { '9', '8', '7', '6', '5', '4', '3', '2', '1', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
} }
} }

View File

@ -10,13 +10,7 @@ namespace Jellyfish.Library
public class ApplicationBase : Application public class ApplicationBase : Application
{ {
[SecurityCritical] [SecurityCritical]
public ApplicationBase() : public ApplicationBase(string name = null)
this(null)
{
}
[SecurityCritical]
public ApplicationBase(string name)
{ {
Name = name; Name = name;
@ -26,7 +20,7 @@ public ApplicationBase(string name)
private void OnApplicationDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) private void OnApplicationDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{ {
MessageBox.Show(GetExceptionMessage(e.Exception), GetExceptionCaption("Application Dispatcher Exception", true)); MessageBox.Show(GetExceptionMessage(e.Exception), GetExceptionCaption("Application Dispatcher Exception", isTerminating: true));
e.Handled = true; e.Handled = true;
Shutdown(); Shutdown();
} }
@ -36,7 +30,7 @@ private void OnAppDomainUnhandledException(object sender, UnhandledExceptionEven
MessageBox.Show(GetExceptionMessage(e.ExceptionObject as Exception), GetExceptionCaption("AppDomain Exception", e.IsTerminating)); MessageBox.Show(GetExceptionMessage(e.ExceptionObject as Exception), GetExceptionCaption("AppDomain Exception", e.IsTerminating));
} }
private string GetExceptionCaption(string title, bool isTerminating) private string GetExceptionCaption(string title, bool isTerminating = false)
{ {
var caption = new StringBuilder(); var caption = new StringBuilder();
caption.AppendFormat("[{0}] ", Process.GetCurrentProcess().Id); caption.AppendFormat("[{0}] ", Process.GetCurrentProcess().Id);

View File

@ -8,13 +8,7 @@ namespace Jellyfish.Library
public static class XmlSerializerHelpers public static class XmlSerializerHelpers
{ {
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")] [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")]
public static T Deserialize<T>(Stream stream) public static T Deserialize<T>(Stream stream, string defaultNamespace = null)
{
return Deserialize<T>(stream, null);
}
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")]
public static T Deserialize<T>(Stream stream, string defaultNamespace)
{ {
using (var reader = XmlReader.Create(stream)) using (var reader = XmlReader.Create(stream))
{ {
@ -23,12 +17,7 @@ public static T Deserialize<T>(Stream stream, string defaultNamespace)
} }
} }
public static void Serialize<T>(Stream stream, T instance) public static void Serialize<T>(Stream stream, T instance, string defaultNamespace = null)
{
Serialize<T>(stream, instance, null);
}
public static void Serialize<T>(Stream stream, T instance, string defaultNamespace)
{ {
using (var writer = XmlWriter.Create(stream)) using (var writer = XmlWriter.Create(stream))
{ {

View File

@ -33,8 +33,7 @@ public override void Draw(GameTime gameTime)
{ {
_frameCount++; _frameCount++;
_frameRateBuilder.Length = 0; _frameRateBuilder.Clear().AppendWithoutGarbage(_frameRate).Append(" fps");
_frameRateBuilder.AppendWithoutGarbage(_frameRate).Append(" fps");
_spriteBatch.Begin(); _spriteBatch.Begin();
//_spriteBatch.DrawString(_spriteFont, _frameRateBuilder, Position - Vector2.UnitX, Color.Black); // rough outline //_spriteBatch.DrawString(_spriteFont, _frameRateBuilder, Position - Vector2.UnitX, Color.Black); // rough outline

View File

@ -31,6 +31,7 @@
<TreatWarningsAsErrors>true</TreatWarningsAsErrors> <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<RunCodeAnalysis>false</RunCodeAnalysis> <RunCodeAnalysis>false</RunCodeAnalysis>
<LangVersion>default</LangVersion>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|Windows Phone' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|Windows Phone' ">
<DebugType>pdbonly</DebugType> <DebugType>pdbonly</DebugType>
@ -45,6 +46,7 @@
<TreatWarningsAsErrors>true</TreatWarningsAsErrors> <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<RunCodeAnalysis>false</RunCodeAnalysis> <RunCodeAnalysis>false</RunCodeAnalysis>
<LangVersion>default</LangVersion>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="Microsoft.Xna.Framework"> <Reference Include="Microsoft.Xna.Framework">

View File

@ -31,6 +31,7 @@
<TreatWarningsAsErrors>true</TreatWarningsAsErrors> <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<RunCodeAnalysis>false</RunCodeAnalysis> <RunCodeAnalysis>false</RunCodeAnalysis>
<LangVersion>default</LangVersion>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|Xbox 360' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|Xbox 360' ">
<DebugType>pdbonly</DebugType> <DebugType>pdbonly</DebugType>
@ -45,6 +46,7 @@
<TreatWarningsAsErrors>true</TreatWarningsAsErrors> <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<RunCodeAnalysis>false</RunCodeAnalysis> <RunCodeAnalysis>false</RunCodeAnalysis>
<LangVersion>default</LangVersion>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="Microsoft.Xna.Framework"> <Reference Include="Microsoft.Xna.Framework">

View File

@ -1,7 +1,5 @@
using System; using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.CodeAnalysis;
using Jellyfish.Virtu.Services; using Jellyfish.Virtu.Services;
using Jellyfish.Virtu.Settings;
namespace Jellyfish.Virtu namespace Jellyfish.Virtu
{ {
@ -16,8 +14,6 @@ public override void Initialize()
{ {
_keyboardService = Machine.Services.GetService<KeyboardService>(); _keyboardService = Machine.Services.GetService<KeyboardService>();
_gamePortService = Machine.Services.GetService<GamePortService>(); _gamePortService = Machine.Services.GetService<GamePortService>();
_keyboardService.AsciiKeyDown += (sender, e) => Latch = e.AsciiKey;
} }
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
@ -121,10 +117,9 @@ public void ResetStrobe()
} }
public bool IsAnyKeyDown { get { return _keyboardService.IsAnyKeyDown; } } public bool IsAnyKeyDown { get { return _keyboardService.IsAnyKeyDown; } }
public int Latch { get { return _latch; } set { _latch = value; Strobe = true; } }
public bool Strobe { get; private set; } public bool Strobe { get; private set; }
private int Latch { get { return _latch; } set { _latch = value; Strobe = true; } }
private KeyboardService _keyboardService; private KeyboardService _keyboardService;
private GamePortService _gamePortService; private GamePortService _gamePortService;

View File

@ -55,7 +55,7 @@ protected void Update(int bufferSize, Action<byte[], int> updateBuffer) // audio
public const int SampleLatency = 40; // ms public const int SampleLatency = 40; // ms
public const int SampleSize = (SampleRate * SampleLatency / 1000) * SampleChannels * (SampleBits / 8); public const int SampleSize = (SampleRate * SampleLatency / 1000) * SampleChannels * (SampleBits / 8);
private static readonly byte[] SampleZero = new byte[SampleSize]; protected static readonly byte[] SampleZero = new byte[SampleSize];
private byte[] _buffer = new byte[SampleSize]; private byte[] _buffer = new byte[SampleSize];
private int _index; private int _index;

View File

@ -1,26 +1,7 @@
using System; using System;
using System.Threading;
namespace Jellyfish.Virtu.Services namespace Jellyfish.Virtu.Services
{ {
public sealed class AsciiKeyEventArgs : EventArgs
{
private AsciiKeyEventArgs()
{
}
public static AsciiKeyEventArgs Create(int asciiKey)
{
_instance.AsciiKey = asciiKey;
return _instance; // use singleton; avoids garbage
}
public int AsciiKey { get; private set; }
private static readonly AsciiKeyEventArgs _instance = new AsciiKeyEventArgs();
}
public abstract class KeyboardService : MachineService public abstract class KeyboardService : MachineService
{ {
protected KeyboardService(Machine machine) : protected KeyboardService(Machine machine) :
@ -48,17 +29,6 @@ public virtual void Update() // main thread
} }
} }
protected void OnAsciiKeyDown(int asciiKey)
{
var handler = AsciiKeyDown;
if (handler != null)
{
handler(this, AsciiKeyEventArgs.Create(asciiKey));
}
}
public event EventHandler<AsciiKeyEventArgs> AsciiKeyDown;
public bool IsAnyKeyDown { get; protected set; } public bool IsAnyKeyDown { get; protected set; }
public bool IsOpenAppleKeyDown { get; protected set; } public bool IsOpenAppleKeyDown { get; protected set; }
public bool IsCloseAppleKeyDown { get; protected set; } public bool IsCloseAppleKeyDown { get; protected set; }

View File

@ -39,12 +39,7 @@ public void ForEach(Action<MachineService> action)
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")] [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")]
public T GetService<T>() public T GetService<T>()
{ {
return (T)GetService(typeof(T)); return (T)((IServiceProvider)this).GetService(typeof(T));
}
public object GetService(Type serviceType)
{
return _serviceProviders.ContainsKey(serviceType) ? _serviceProviders[serviceType] : null;
} }
public void RemoveService(Type serviceType) public void RemoveService(Type serviceType)
@ -52,6 +47,11 @@ public void RemoveService(Type serviceType)
_serviceProviders.Remove(serviceType); _serviceProviders.Remove(serviceType);
} }
object IServiceProvider.GetService(Type serviceType)
{
return _serviceProviders.ContainsKey(serviceType) ? _serviceProviders[serviceType] : null;
}
private Dictionary<Type, MachineService> _serviceProviders = new Dictionary<Type, MachineService>(); private Dictionary<Type, MachineService> _serviceProviders = new Dictionary<Type, MachineService>();
} }
} }

View File

@ -14,12 +14,7 @@ protected StorageService(Machine machine) :
{ {
} }
public static Stream GetResourceStream(string resourceName) public static Stream GetResourceStream(string resourceName, int resourceSize = 0)
{
return GetResourceStream(resourceName, 0);
}
public static Stream GetResourceStream(string resourceName, int resourceSize)
{ {
var resourceManager = new ResourceManager("Jellyfish.Virtu.g", Assembly.GetExecutingAssembly()) { IgnoreCase = true }; var resourceManager = new ResourceManager("Jellyfish.Virtu.g", Assembly.GetExecutingAssembly()) { IgnoreCase = true };
var resourceStream = (Stream)resourceManager.GetObject(resourceName); var resourceStream = (Stream)resourceManager.GetObject(resourceName);

View File

@ -20,15 +20,25 @@ public SilverlightAudioService(Machine machine, UserControl page, MediaElement m
_page = page; _page = page;
_media = media; _media = media;
_mediaSource = new WaveMediaStreamSource(SampleRate, SampleChannels, SampleBits, SampleSize, SampleLatency, OnMediaSourceUpdate);
_page.Loaded += (sender, e) => { _media.SetSource(_mediaSource); _media.Play(); }; _page.Loaded += (sender, e) => { _media.SetSource(_mediaSource); _media.Play(); };
_mediaSource.Update += OnMediaSourceUpdate;
#if !WINDOWS_PHONE #if !WINDOWS_PHONE
_page.Unloaded += (sender, e) => _media.Stop(); _page.Unloaded += (sender, e) => _media.Stop();
#endif #endif
} }
private void OnMediaSourceUpdate(object sender, WaveMediaStreamSourceUpdateEventArgs e) // audio thread protected override void Dispose(bool disposing)
{
if (disposing)
{
_mediaSource.Dispose();
}
base.Dispose(disposing);
}
private void OnMediaSourceUpdate(byte[] buffer, int bufferSize) // audio thread
{ {
//if (_count++ % (1000 / SampleLatency) == 0) //if (_count++ % (1000 / SampleLatency) == 0)
//{ //{
@ -38,12 +48,12 @@ private void OnMediaSourceUpdate(object sender, WaveMediaStreamSourceUpdateEvent
// }); // });
//} //}
Update(e.BufferSize, (source, count) => Buffer.BlockCopy(source, 0, e.Buffer, 0, count)); Update(bufferSize, (source, count) => Buffer.BlockCopy(source, 0, buffer, 0, count));
} }
private UserControl _page; private UserControl _page;
private MediaElement _media; private MediaElement _media;
private WaveMediaStreamSource _mediaSource = new WaveMediaStreamSource(SampleRate, SampleChannels, SampleBits, SampleSize, SampleLatency); private WaveMediaStreamSource _mediaSource;
//private int _count; //private int _count;
} }
} }

View File

@ -71,7 +71,7 @@ private void OnPageKeyDown(object sender, KeyEventArgs e)
int asciiKey = GetAsciiKey(e.Key, e.PlatformKeyCode); int asciiKey = GetAsciiKey(e.Key, e.PlatformKeyCode);
if (asciiKey >= 0) if (asciiKey >= 0)
{ {
OnAsciiKeyDown(asciiKey); Machine.Keyboard.Latch = asciiKey;
e.Handled = true; e.Handled = true;
} }

View File

@ -18,9 +18,9 @@ public WpfAudioService(Machine machine, Window window) :
} }
_window = window; _window = window;
_directSound = new DirectSound(SampleRate, SampleChannels, SampleBits, SampleSize, OnDirectSoundUpdate);
_window.SourceInitialized += (sender, e) => _directSound.Start(_window.GetHandle()); _window.SourceInitialized += (sender, e) => _directSound.Start(_window.GetHandle());
_directSound.Update += OnDirectSoundUpdate;
_window.Closed += (sender, e) => _directSound.Stop(); _window.Closed += (sender, e) => _directSound.Stop();
} }
@ -34,7 +34,7 @@ protected override void Dispose(bool disposing)
base.Dispose(disposing); base.Dispose(disposing);
} }
private void OnDirectSoundUpdate(object sender, DirectSoundUpdateEventArgs e) // audio thread private void OnDirectSoundUpdate(IntPtr buffer, int bufferSize) // audio thread
{ {
//if (_count++ % (1000 / SampleLatency) == 0) //if (_count++ % (1000 / SampleLatency) == 0)
//{ //{
@ -44,11 +44,11 @@ private void OnDirectSoundUpdate(object sender, DirectSoundUpdateEventArgs e) //
// }); // });
//} //}
Update(e.BufferSize, (source, count) => Marshal.Copy(source, 0, e.Buffer, count)); Update(bufferSize, (source, count) => Marshal.Copy(source, 0, buffer, count));
} }
private Window _window; private Window _window;
private DirectSound _directSound = new DirectSound(SampleRate, SampleChannels, SampleBits, SampleSize); private DirectSound _directSound;
//private int _count; //private int _count;
} }
} }

View File

@ -71,7 +71,7 @@ private void OnWindowKeyDown(object sender, KeyEventArgs e)
int asciiKey = GetAsciiKey(e.Key, e.KeyboardDevice); int asciiKey = GetAsciiKey(e.Key, e.KeyboardDevice);
if (asciiKey >= 0) if (asciiKey >= 0)
{ {
OnAsciiKeyDown(asciiKey); Machine.Keyboard.Latch = asciiKey;
e.Handled = true; e.Handled = true;
} }

View File

@ -37,6 +37,7 @@
<TreatWarningsAsErrors>true</TreatWarningsAsErrors> <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<RunCodeAnalysis>false</RunCodeAnalysis> <RunCodeAnalysis>false</RunCodeAnalysis>
<LangVersion>default</LangVersion>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|Windows Phone' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|Windows Phone' ">
<DebugType>pdbonly</DebugType> <DebugType>pdbonly</DebugType>
@ -51,6 +52,7 @@
<TreatWarningsAsErrors>true</TreatWarningsAsErrors> <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<RunCodeAnalysis>false</RunCodeAnalysis> <RunCodeAnalysis>false</RunCodeAnalysis>
<LangVersion>default</LangVersion>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="Microsoft.Xna.Framework"> <Reference Include="Microsoft.Xna.Framework">

View File

@ -33,6 +33,7 @@
<TreatWarningsAsErrors>true</TreatWarningsAsErrors> <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<RunCodeAnalysis>false</RunCodeAnalysis> <RunCodeAnalysis>false</RunCodeAnalysis>
<LangVersion>default</LangVersion>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|Xbox 360' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|Xbox 360' ">
<DebugType>pdbonly</DebugType> <DebugType>pdbonly</DebugType>
@ -47,6 +48,7 @@
<TreatWarningsAsErrors>true</TreatWarningsAsErrors> <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<RunCodeAnalysis>false</RunCodeAnalysis> <RunCodeAnalysis>false</RunCodeAnalysis>
<LangVersion>default</LangVersion>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="Microsoft.Xna.Framework"> <Reference Include="Microsoft.Xna.Framework">

View File

@ -15,6 +15,8 @@ public MainGame() :
GraphicsDeviceManager.PreferredBackBufferWidth = 480; // TODO remove; works around known ctp issue GraphicsDeviceManager.PreferredBackBufferWidth = 480; // TODO remove; works around known ctp issue
GraphicsDeviceManager.PreferredBackBufferHeight = 800; GraphicsDeviceManager.PreferredBackBufferHeight = 800;
#endif #endif
IsMouseVisible = true;
var frameRateCounter = new FrameRateCounter(this); // no initializers; avoids CA2000 var frameRateCounter = new FrameRateCounter(this); // no initializers; avoids CA2000
Components.Add(frameRateCounter); Components.Add(frameRateCounter);
frameRateCounter.DrawOrder = 1; frameRateCounter.DrawOrder = 1;

View File

@ -19,6 +19,7 @@ public XnaAudioService(Machine machine, GameBase game) :
_dynamicSoundEffect.BufferNeeded += OnDynamicSoundEffectBufferNeeded; _dynamicSoundEffect.BufferNeeded += OnDynamicSoundEffectBufferNeeded;
_game.Exiting += (sender, e) => _dynamicSoundEffect.Stop(); _game.Exiting += (sender, e) => _dynamicSoundEffect.Stop();
_dynamicSoundEffect.SubmitBuffer(SampleZero);
_dynamicSoundEffect.Play(); _dynamicSoundEffect.Play();
} }

View File

@ -86,7 +86,7 @@ private void OnKeyDown(Keys key, bool gamePadControl)
int asciiKey = GetAsciiKey(key, gamePadControl); int asciiKey = GetAsciiKey(key, gamePadControl);
if (asciiKey >= 0) if (asciiKey >= 0)
{ {
OnAsciiKeyDown(asciiKey); Machine.Keyboard.Latch = asciiKey;
} }
} }