using System;
using System.Collections.Generic;
using UnityEditor.ShortcutManagement;
namespace UnityEditor.TerrainTools
{
///
/// Provides methods for handling brush shortcuts.
///
/// The key type that represents the keyboard key.
public class BrushShortcutHandler
{
private readonly Dictionary m_OnPressedByKey = new Dictionary();
private readonly Dictionary m_OnReleasedByKey = new Dictionary();
private readonly HashSet m_ActiveKeys = new HashSet();
///
/// Subscribes the key to the passed in press and release s.
///
/// The type to add.
/// The Action to call on key press.
/// The Action to call on key release.
public virtual void AddActions(TKey key, Action onPressed = null, Action onReleased = null)
{
if (onPressed != null)
{
if (m_OnPressedByKey.TryGetValue(key, out Action existingOnPressed))
{
existingOnPressed += onPressed;
m_OnPressedByKey[key] = existingOnPressed;
}
else
{
m_OnPressedByKey.Add(key, onPressed);
}
}
if (onReleased != null)
{
if (m_OnReleasedByKey.TryGetValue(key, out Action existingOnReleased))
{
existingOnReleased += onReleased;
m_OnReleasedByKey[key] = existingOnReleased;
}
else
{
m_OnReleasedByKey.Add(key, onReleased);
}
}
}
///
/// Unsubscribes the key from its press and release actions.
///
/// The type to remove.
public void RemoveActions(TKey key)
{
m_OnPressedByKey.Remove(key);
m_OnReleasedByKey.Remove(key);
m_ActiveKeys.Remove(key);
}
///
/// Determines whether the key is pressed.
///
/// The type to check.
/// Returns true when the key is currently pressed. Otherwise, returns false.
public bool IsShortcutPressed(TKey key)
{
return m_ActiveKeys.Contains(key);
}
///
/// Handles changes when using shortcuts.
///
///
/// This method handles the invocation of a shortcuts on press and release actions using .
///
/// The data for shortcut action methods invoked by the shortcut system.
/// The type to check.
///
///
public void HandleShortcutChanged(ShortcutArguments args, TKey key)
{
switch (args.stage)
{
case ShortcutStage.Begin:
{
if (m_OnPressedByKey.TryGetValue(key, out Action onPressed))
{
m_ActiveKeys.Add(key);
onPressed?.Invoke();
}
break;
}
case ShortcutStage.End:
{
if (m_OnReleasedByKey.TryGetValue(key, out Action onReleased))
{
onReleased?.Invoke();
m_ActiveKeys.Remove(key);
TerrainToolsAnalytics.OnShortcutKeyRelease(key.ToString());
TerrainToolsAnalytics.OnParameterChange();
}
break;
}
default:
throw new ArgumentOutOfRangeException();
} // End of switch.
}
}
}