using System; using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngine; using UnityEngine.EventSystems; using WI; namespace CHN { public class UserInputManager : MonoBehaviour, ISingle { Dictionary getKeyActionTable = new Dictionary(); Dictionary upKeyActionTable = new Dictionary(); Dictionary downKeyActionTable = new Dictionary(); Dictionary> shortCutActionTable = new (); Stack handlerStack = new(); Action updateLoop; public void SetHandler(InputHandler handler) { SetKeyboardPreset(handler); } public void RemoveHandler(InputHandler handler) { Stack tempStack = new(); while (handlerStack.Count > 0) { var currentHandler = handlerStack.Pop(); if (currentHandler == handler) { RemoveKeyActionPreset(currentHandler); break; } tempStack.Push(currentHandler); } while(tempStack.Count > 0) { var tempHandler = tempStack.Pop(); SetKeyboardPreset(tempHandler); } } void RemoveKeyActionPreset(InputHandler handler) { foreach(var k in handler.getKeyActions) { getKeyActionTable.Remove(k.Key); } foreach(var k in handler.upKeyActions) { upKeyActionTable.Remove(k.Key); } foreach(var k in handler.downKeyActions) { downKeyActionTable.Remove(k.Key); } foreach(var k in handler.shortCutActions) { foreach(var kk in k.Value) { shortCutActionTable[k.Key].Remove(kk.Key); } } updateLoop -= handler.updateLoop; } void SetKeyboardPreset(InputHandler handler) { handlerStack.Push(handler); foreach (var k in handler.getKeyActions) { getKeyActionTable[k.Key] = k.Value; } foreach(var k in handler.upKeyActions) { upKeyActionTable[k.Key]= k.Value; } foreach(var k in handler.downKeyActions) { downKeyActionTable[k.Key]= k.Value; } foreach (var k in handler.shortCutActions) { if (!shortCutActionTable.ContainsKey(k.Key)) { shortCutActionTable.Add(k.Key, new Dictionary()); } foreach (var kk in k.Value) { if (shortCutActionTable[k.Key].ContainsKey(kk.Key)) shortCutActionTable[k.Key].Remove(kk.Key); shortCutActionTable[k.Key].Add(kk.Key, kk.Value); } } updateLoop += handler.updateLoop; } void Update() { if (IsEditInputField()) return; foreach (var key in downKeyActionTable.Keys) { if (Input.GetKeyDown(key)) { downKeyActionTable[key]?.Invoke(); } } foreach (var key in getKeyActionTable.Keys) { if (Input.GetKey(key)) { getKeyActionTable[key]?.Invoke(); } } foreach (var key in upKeyActionTable.Keys) { if (Input.GetKeyUp(key)) { upKeyActionTable[key]?.Invoke(); } } foreach (var key in shortCutActionTable.Keys) { if (Input.GetKey(key)) { if (shortCutActionTable.TryGetValue(key, out var kk)) { foreach (var k in kk) { if (Input.GetKeyDown(k.Key)) { k.Value?.Invoke(); } } } } } updateLoop?.Invoke(); } bool IsEditInputField() { GameObject selectedObj = EventSystem.current.currentSelectedGameObject; if (selectedObj == null) return false; return selectedObj.GetComponent() != null; } } }