83 lines
2.7 KiB
C#
83 lines
2.7 KiB
C#
|
||
using UnityEngine;
|
||
using TMPro;
|
||
using InputGlyphsFramework;
|
||
|
||
public class GlyphService : MonoBehaviour
|
||
{
|
||
public static GlyphService Instance { get; private set; }
|
||
public InputGlyphDatabase database;
|
||
|
||
void Awake()
|
||
{
|
||
if (Instance != null && Instance != this) { Destroy(this); return; }
|
||
Instance = this;
|
||
}
|
||
|
||
public bool TryGetTMPTagForActionPath(string controlPath, InputDeviceWatcher.InputDeviceCategory device, out string tag, out string displayFallback)
|
||
{
|
||
tag = null;
|
||
displayFallback = null;
|
||
if (string.IsNullOrEmpty(controlPath) || database == null) return false;
|
||
|
||
// 优先查当前设备表
|
||
var entry = database.FindEntryByControlPath(controlPath, device);
|
||
if (entry == null)
|
||
{
|
||
// 回退到 keyboard 表
|
||
entry = database.FindEntryByControlPath(controlPath, InputDeviceWatcher.InputDeviceCategory.Keyboard);
|
||
}
|
||
|
||
if (entry == null)
|
||
{
|
||
displayFallback = GetDisplayNameFromControlPath(controlPath);
|
||
return false;
|
||
}
|
||
|
||
// 需要一个对应的 TMP Sprite Asset 来生成 <sprite> 标签 —— 查找 entry 所在的表(优先当前设备,再 keyboard)
|
||
DeviceGlyphTable table = database.GetTable(device) ?? database.GetTable(InputDeviceWatcher.InputDeviceCategory.Keyboard);
|
||
if (table == null || table.tmpAsset == null)
|
||
{
|
||
displayFallback = GetDisplayNameFromControlPath(controlPath);
|
||
return false;
|
||
}
|
||
|
||
var sprite = entry.Sprite;
|
||
if (sprite == null)
|
||
{
|
||
displayFallback = GetDisplayNameFromControlPath(controlPath);
|
||
return false;
|
||
}
|
||
|
||
var spriteName = sprite.name;
|
||
tag = $"<sprite name=\"{spriteName}\">";
|
||
return true;
|
||
}
|
||
|
||
public bool TryGetUISpriteForActionPath(string controlPath, InputDeviceWatcher.InputDeviceCategory device, out Sprite sprite)
|
||
{
|
||
sprite = null;
|
||
if (string.IsNullOrEmpty(controlPath) || database == null) return false;
|
||
|
||
var entry = database.FindEntryByControlPath(controlPath, device);
|
||
if (entry == null)
|
||
{
|
||
entry = database.FindEntryByControlPath(controlPath, InputDeviceWatcher.InputDeviceCategory.Keyboard);
|
||
}
|
||
if (entry == null) return false;
|
||
if (entry.Sprite == null) return false;
|
||
|
||
sprite = entry.Sprite;
|
||
return true;
|
||
}
|
||
|
||
string GetDisplayNameFromControlPath(string controlPath)
|
||
{
|
||
if (string.IsNullOrEmpty(controlPath)) return string.Empty;
|
||
var parts = controlPath.Split('/');
|
||
var last = parts[parts.Length - 1].Trim(new char[] { '{', '}', '<', '>', '\'', '"' });
|
||
return last;
|
||
}
|
||
}
|
||
|