2017-08-09 10:50:34 +08:00
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
2017-08-09 11:37:47 +08:00
using System ;
2017-08-09 10:50:34 +08:00
using System.Collections.Generic ;
2017-08-09 11:37:47 +08:00
using osu.Framework.Allocation ;
2017-08-09 10:50:34 +08:00
using osu.Framework.Input ;
2017-08-09 11:37:47 +08:00
using osu.Game.Rulesets ;
2017-08-09 10:50:34 +08:00
using OpenTK.Input ;
namespace osu.Game.Input
{
2017-08-09 13:50:10 +08:00
/// <summary>
/// Maps custom action data of type <see cref="T"/> and stores to <see cref="InputState.Data"/>.
/// </summary>
/// <typeparam name="T">The type of the custom action.</typeparam>
2017-08-09 16:10:32 +08:00
public abstract class ActionMappingInputManager < T > : PassThroughInputManager
2017-08-09 10:50:34 +08:00
where T : struct
{
2017-08-09 12:04:11 +08:00
private readonly RulesetInfo ruleset ;
2017-08-09 12:23:23 +08:00
private readonly int? variant ;
2017-08-09 13:50:10 +08:00
/// <summary>
/// Create a new instance.
/// </summary>
/// <param name="ruleset">A reference to identify the current <see cref="Ruleset"/>. Used to lookup mappings. Null for global mappings.</param>
/// <param name="variant">An optional variant for the specified <see cref="Ruleset"/>. Used when a ruleset has more than one possible keyboard layouts.</param>
2017-08-09 12:23:23 +08:00
protected ActionMappingInputManager ( RulesetInfo ruleset = null , int? variant = null )
2017-08-09 12:04:11 +08:00
{
this . ruleset = ruleset ;
2017-08-09 12:23:23 +08:00
this . variant = variant ;
2017-08-09 16:10:32 +08:00
Mappings = CreateDefaultMappings ( ) ;
2017-08-09 12:04:11 +08:00
}
2017-08-09 16:10:32 +08:00
protected IDictionary < Key , T > Mappings { get ; private set ; }
protected abstract IDictionary < Key , T > CreateDefaultMappings ( ) ;
2017-08-09 10:50:34 +08:00
2017-08-09 11:37:47 +08:00
[BackgroundDependencyLoader]
private void load ( BindingStore bindings )
{
2017-08-09 12:04:11 +08:00
var rulesetId = ruleset ? . ID ;
2017-08-09 12:23:23 +08:00
foreach ( var b in bindings . Query < Binding > ( b = > b . RulesetID = = rulesetId & & b . Variant = = variant ) )
2017-08-09 11:37:47 +08:00
Mappings [ b . Key ] = ( T ) ( object ) b . Action ;
}
2017-08-09 10:50:34 +08:00
protected override bool OnKeyDown ( InputState state , KeyDownEventArgs args )
{
mapKey ( state , args . Key ) ;
return base . OnKeyDown ( state , args ) ;
}
protected override bool OnKeyUp ( InputState state , KeyUpEventArgs args )
{
mapKey ( state , args . Key ) ;
return base . OnKeyUp ( state , args ) ;
}
private void mapKey ( InputState state , Key key )
{
T mappedData ;
if ( Mappings . TryGetValue ( key , out mappedData ) )
state . Data = mappedData ;
}
2017-08-09 11:37:47 +08:00
private T parseStringRepresentation ( string str )
{
T res ;
if ( Enum . TryParse ( str , out res ) )
return res ;
return default ( T ) ;
}
}
2017-08-09 10:50:34 +08:00
}