暂无描述
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

InputDeviceDebuggerWindow.cs 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. #if UNITY_EDITOR
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using UnityEditor;
  6. using UnityEditor.IMGUI.Controls;
  7. using UnityEngine.InputSystem.LowLevel;
  8. using UnityEngine.InputSystem.Utilities;
  9. ////TODO: allow selecting events and saving out only the selected ones
  10. ////TODO: add the ability for the debugger to just generate input on the device according to the controls it finds; good for testing
  11. ////TODO: add commands to event trace (also clickable)
  12. ////TODO: add diff-to-previous-event ability to event window
  13. ////FIXME: the repaint triggered from IInputStateCallbackReceiver somehow comes with a significant delay
  14. ////TODO: Add "Remote:" field in list that also has a button for local devices that allows to mirror them and their input
  15. //// into connected players
  16. ////TODO: this window should help diagnose problems in the event stream (e.g. ignored state events and why they were ignored)
  17. ////TODO: add toggle to that switches to displaying raw control values
  18. ////TODO: allow adding visualizers (or automatically add them in cases) to control that show value over time (using InputStateHistory)
  19. ////TODO: show default states of controls
  20. ////TODO: provide ability to save and load event traces; also ability to record directly to a file
  21. ////TODO: provide ability to scrub back and forth through history
  22. namespace UnityEngine.InputSystem.Editor
  23. {
  24. // Shows status and activity of a single input device in a separate window.
  25. // Can also be used to alter the state of a device by making up state events.
  26. internal sealed class InputDeviceDebuggerWindow : EditorWindow, ISerializationCallbackReceiver, IDisposable
  27. {
  28. // ATM the debugger window is super slow and repaints are very expensive. So keep the total
  29. // number of events we can fit at a relatively low size until we have fixed that problem.
  30. private const int kDefaultEventTraceSizeInKB = 512;
  31. private const int kMaxEventsPerTrace = 1024;
  32. internal static InlinedArray<Action<InputDevice>> s_OnToolbarGUIActions;
  33. public static event Action<InputDevice> onToolbarGUI
  34. {
  35. add => s_OnToolbarGUIActions.Append(value);
  36. remove => s_OnToolbarGUIActions.Remove(value);
  37. }
  38. public static void CreateOrShowExisting(InputDevice device)
  39. {
  40. if (device == null)
  41. throw new ArgumentNullException(nameof(device));
  42. // See if we have an existing window for the device and if so pop it
  43. // in front.
  44. if (s_OpenDebuggerWindows != null)
  45. {
  46. for (var i = 0; i < s_OpenDebuggerWindows.Count; ++i)
  47. {
  48. var existingWindow = s_OpenDebuggerWindows[i];
  49. if (existingWindow.m_DeviceId == device.deviceId)
  50. {
  51. existingWindow.Show();
  52. existingWindow.Focus();
  53. return;
  54. }
  55. }
  56. }
  57. // No, so create a new one.
  58. var window = CreateInstance<InputDeviceDebuggerWindow>();
  59. window.InitializeWith(device);
  60. window.minSize = new Vector2(270, 300);
  61. window.Show();
  62. window.titleContent = new GUIContent(device.name);
  63. }
  64. internal void OnDestroy()
  65. {
  66. if (m_Device != null)
  67. {
  68. RemoveFromList();
  69. InputSystem.onDeviceChange -= OnDeviceChange;
  70. InputState.onChange -= OnDeviceStateChange;
  71. InputSystem.onSettingsChange -= NeedControlValueRefresh;
  72. Application.focusChanged -= OnApplicationFocusChange;
  73. EditorApplication.playModeStateChanged += OnPlayModeChange;
  74. }
  75. m_EventTrace?.Dispose();
  76. m_EventTrace = null;
  77. m_ReplayController?.Dispose();
  78. m_ReplayController = null;
  79. }
  80. public void Dispose()
  81. {
  82. m_EventTrace?.Dispose();
  83. m_ReplayController?.Dispose();
  84. }
  85. internal void OnGUI()
  86. {
  87. // Find device again if we've gone through a domain reload.
  88. if (m_Device == null)
  89. {
  90. m_Device = InputSystem.GetDeviceById(m_DeviceId);
  91. if (m_Device == null)
  92. {
  93. EditorGUILayout.HelpBox(Styles.notFoundHelpText, MessageType.Warning);
  94. return;
  95. }
  96. InitializeWith(m_Device);
  97. }
  98. ////FIXME: with ExpandHeight(false), editor still expands height for some reason....
  99. EditorGUILayout.BeginVertical("OL Box", GUILayout.Height(170));// GUILayout.ExpandHeight(false));
  100. EditorGUILayout.LabelField("Name", m_Device.name);
  101. EditorGUILayout.LabelField("Layout", m_Device.layout);
  102. EditorGUILayout.LabelField("Type", m_Device.GetType().Name);
  103. if (!string.IsNullOrEmpty(m_Device.description.interfaceName))
  104. EditorGUILayout.LabelField("Interface", m_Device.description.interfaceName);
  105. if (!string.IsNullOrEmpty(m_Device.description.product))
  106. EditorGUILayout.LabelField("Product", m_Device.description.product);
  107. if (!string.IsNullOrEmpty(m_Device.description.manufacturer))
  108. EditorGUILayout.LabelField("Manufacturer", m_Device.description.manufacturer);
  109. if (!string.IsNullOrEmpty(m_Device.description.serial))
  110. EditorGUILayout.LabelField("Serial Number", m_Device.description.serial);
  111. EditorGUILayout.LabelField("Device ID", m_DeviceIdString);
  112. if (!string.IsNullOrEmpty(m_DeviceUsagesString))
  113. EditorGUILayout.LabelField("Usages", m_DeviceUsagesString);
  114. if (!string.IsNullOrEmpty(m_DeviceFlagsString))
  115. EditorGUILayout.LabelField("Flags", m_DeviceFlagsString);
  116. if (m_Device is Keyboard)
  117. EditorGUILayout.LabelField("Keyboard Layout", ((Keyboard)m_Device).keyboardLayout);
  118. EditorGUILayout.EndVertical();
  119. DrawControlTree();
  120. DrawEventList();
  121. }
  122. private void DrawControlTree()
  123. {
  124. var label = m_InputUpdateTypeShownInControlTree == InputUpdateType.Editor
  125. ? Contents.editorStateContent
  126. : Contents.playerStateContent;
  127. GUILayout.BeginHorizontal(EditorStyles.toolbar);
  128. GUILayout.Label(label, GUILayout.MinWidth(100), GUILayout.ExpandWidth(true));
  129. GUILayout.FlexibleSpace();
  130. // Allow plugins to add toolbar buttons.
  131. for (var i = 0; i < s_OnToolbarGUIActions.length; ++i)
  132. s_OnToolbarGUIActions[i](m_Device);
  133. if (GUILayout.Button(Contents.stateContent, EditorStyles.toolbarButton))
  134. {
  135. var window = CreateInstance<InputStateWindow>();
  136. window.InitializeWithControl(m_Device);
  137. window.Show();
  138. }
  139. GUILayout.EndHorizontal();
  140. if (m_NeedControlValueRefresh)
  141. {
  142. RefreshControlTreeValues();
  143. m_NeedControlValueRefresh = false;
  144. }
  145. if (m_Device.disabledInFrontend)
  146. EditorGUILayout.HelpBox("Device is DISABLED. Control values will not receive updates. "
  147. + "To force-enable the device, you can right-click it in the input debugger and use 'Enable Device'.", MessageType.Info);
  148. var rect = EditorGUILayout.GetControlRect(GUILayout.ExpandHeight(true));
  149. m_ControlTree.OnGUI(rect);
  150. }
  151. private void DrawEventList()
  152. {
  153. GUILayout.BeginHorizontal(EditorStyles.toolbar);
  154. GUILayout.Label("Events", GUILayout.MinWidth(100), GUILayout.ExpandWidth(true));
  155. GUILayout.FlexibleSpace();
  156. if (m_ReplayController != null && !m_ReplayController.finished)
  157. EditorGUILayout.LabelField("Playing...", EditorStyles.miniLabel);
  158. // Text field to determine size of event trace.
  159. var currentTraceSizeInKb = m_EventTrace.allocatedSizeInBytes / 1024;
  160. var oldSizeText = currentTraceSizeInKb + " KB";
  161. var newSizeText = EditorGUILayout.DelayedTextField(oldSizeText, Styles.toolbarTextField, GUILayout.Width(75));
  162. if (oldSizeText != newSizeText && StringHelpers.FromNicifiedMemorySize(newSizeText, out var newSizeInBytes, defaultMultiplier: 1024))
  163. m_EventTrace.Resize(newSizeInBytes);
  164. // Button to clear event trace.
  165. if (GUILayout.Button(Contents.clearContent, Styles.toolbarButton))
  166. {
  167. m_EventTrace.Clear();
  168. m_EventTree.Reload();
  169. }
  170. // Button to disable event tracing.
  171. // NOTE: We force-disable event tracing while a replay is in progress.
  172. using (new EditorGUI.DisabledScope(m_ReplayController != null && !m_ReplayController.finished))
  173. {
  174. var eventTraceDisabledNow = GUILayout.Toggle(!m_EventTraceDisabled, Contents.pauseContent, Styles.toolbarButton);
  175. if (eventTraceDisabledNow != m_EventTraceDisabled)
  176. {
  177. m_EventTraceDisabled = eventTraceDisabledNow;
  178. if (eventTraceDisabledNow)
  179. m_EventTrace.Disable();
  180. else
  181. m_EventTrace.Enable();
  182. }
  183. }
  184. // Button to toggle recording of frame markers.
  185. m_EventTrace.recordFrameMarkers =
  186. GUILayout.Toggle(m_EventTrace.recordFrameMarkers, Contents.recordFramesContent, Styles.toolbarButton);
  187. // Button to save event trace to file.
  188. if (GUILayout.Button(Contents.saveContent, Styles.toolbarButton))
  189. {
  190. var defaultName = m_Device?.displayName + ".inputtrace";
  191. var fileName = EditorUtility.SaveFilePanel("Choose where to save event trace", string.Empty, defaultName, "inputtrace");
  192. if (!string.IsNullOrEmpty(fileName))
  193. m_EventTrace.WriteTo(fileName);
  194. }
  195. // Button to load event trace from file.
  196. if (GUILayout.Button(Contents.loadContent, Styles.toolbarButton))
  197. {
  198. var fileName = EditorUtility.OpenFilePanel("Choose event trace to load", string.Empty, "inputtrace");
  199. if (!string.IsNullOrEmpty(fileName))
  200. {
  201. // If replay is in progress, stop it.
  202. if (m_ReplayController != null)
  203. {
  204. m_ReplayController.Dispose();
  205. m_ReplayController = null;
  206. }
  207. // Make sure event trace isn't recording while we're playing.
  208. m_EventTrace.Disable();
  209. m_EventTraceDisabled = true;
  210. m_EventTrace.ReadFrom(fileName);
  211. m_EventTree.Reload();
  212. m_ReplayController = m_EventTrace.Replay()
  213. .PlayAllFramesOneByOne()
  214. .OnFinished(() =>
  215. {
  216. m_ReplayController.Dispose();
  217. m_ReplayController = null;
  218. Repaint();
  219. });
  220. }
  221. }
  222. GUILayout.EndHorizontal();
  223. if (m_ReloadEventTree)
  224. {
  225. m_ReloadEventTree = false;
  226. m_EventTree.Reload();
  227. }
  228. var rect = EditorGUILayout.GetControlRect(GUILayout.ExpandHeight(true));
  229. m_EventTree.OnGUI(rect);
  230. }
  231. ////FIXME: some of the state in here doesn't get refreshed when it's changed on the device
  232. private void InitializeWith(InputDevice device)
  233. {
  234. m_Device = device;
  235. m_DeviceId = device.deviceId;
  236. m_DeviceIdString = device.deviceId.ToString();
  237. m_DeviceUsagesString = string.Join(", ", device.usages.Select(x => x.ToString()).ToArray());
  238. UpdateDeviceFlags();
  239. // Set up event trace. The default trace size of 512kb fits a ton of events and will
  240. // likely bog down the UI if we try to display that many events. Instead, come up
  241. // with a more reasonable sized based on the state size of the device.
  242. if (m_EventTrace == null)
  243. {
  244. var deviceStateSize = (int)device.stateBlock.alignedSizeInBytes;
  245. var traceSizeInBytes = (kDefaultEventTraceSizeInKB * 1024).AlignToMultipleOf(deviceStateSize);
  246. if (traceSizeInBytes / deviceStateSize > kMaxEventsPerTrace)
  247. traceSizeInBytes = kMaxEventsPerTrace * deviceStateSize;
  248. m_EventTrace =
  249. new InputEventTrace(traceSizeInBytes)
  250. {
  251. deviceId = device.deviceId
  252. };
  253. }
  254. m_EventTrace.onEvent += _ => m_ReloadEventTree = true;
  255. if (!m_EventTraceDisabled)
  256. m_EventTrace.Enable();
  257. // Set up event tree.
  258. m_EventTree = InputEventTreeView.Create(m_Device, m_EventTrace, ref m_EventTreeState, ref m_EventTreeHeaderState);
  259. // Set up control tree.
  260. m_ControlTree = InputControlTreeView.Create(m_Device, 1, ref m_ControlTreeState, ref m_ControlTreeHeaderState);
  261. m_ControlTree.Reload();
  262. m_ControlTree.ExpandAll();
  263. AddToList();
  264. InputSystem.onSettingsChange += NeedControlValueRefresh;
  265. InputSystem.onDeviceChange += OnDeviceChange;
  266. InputState.onChange += OnDeviceStateChange;
  267. Application.focusChanged += OnApplicationFocusChange;
  268. EditorApplication.playModeStateChanged += OnPlayModeChange;
  269. }
  270. private void UpdateDeviceFlags()
  271. {
  272. var flags = new List<string>();
  273. if (m_Device.native)
  274. flags.Add("Native");
  275. if (m_Device.remote)
  276. flags.Add("Remote");
  277. if (m_Device.updateBeforeRender)
  278. flags.Add("UpdateBeforeRender");
  279. if (m_Device.hasStateCallbacks)
  280. flags.Add("HasStateCallbacks");
  281. if (m_Device.hasEventMerger)
  282. flags.Add("HasEventMerger");
  283. if (m_Device.hasEventPreProcessor)
  284. flags.Add("HasEventPreProcessor");
  285. if (m_Device.disabledInFrontend)
  286. flags.Add("DisabledInFrontend");
  287. if (m_Device.disabledInRuntime)
  288. flags.Add("DisabledInRuntime");
  289. if (m_Device.disabledWhileInBackground)
  290. flags.Add("DisabledWhileInBackground");
  291. m_DeviceFlags = m_Device.m_DeviceFlags;
  292. m_DeviceFlagsString = string.Join(", ", flags.ToArray());
  293. }
  294. private void RefreshControlTreeValues()
  295. {
  296. m_InputUpdateTypeShownInControlTree = DetermineUpdateTypeToShow(m_Device);
  297. var currentUpdateType = InputState.currentUpdateType;
  298. InputStateBuffers.SwitchTo(InputSystem.s_Manager.m_StateBuffers, m_InputUpdateTypeShownInControlTree);
  299. m_ControlTree.RefreshControlValues();
  300. InputStateBuffers.SwitchTo(InputSystem.s_Manager.m_StateBuffers, currentUpdateType);
  301. }
  302. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "device", Justification = "Keep this for future implementation")]
  303. internal static InputUpdateType DetermineUpdateTypeToShow(InputDevice device)
  304. {
  305. if (EditorApplication.isPlaying)
  306. {
  307. // In play mode, while playing, we show player state. Period.
  308. switch (InputSystem.settings.updateMode)
  309. {
  310. case InputSettings.UpdateMode.ProcessEventsManually:
  311. return InputUpdateType.Manual;
  312. case InputSettings.UpdateMode.ProcessEventsInFixedUpdate:
  313. return InputUpdateType.Fixed;
  314. default:
  315. return InputUpdateType.Dynamic;
  316. }
  317. }
  318. // Outside of play mode, always show editor state.
  319. return InputUpdateType.Editor;
  320. }
  321. // We will lose our device on domain reload and then look it back up the first
  322. // time we hit a repaint after a reload. By that time, the input system should have
  323. // fully come back to life as well.
  324. private InputDevice m_Device;
  325. private string m_DeviceIdString;
  326. private string m_DeviceUsagesString;
  327. private string m_DeviceFlagsString;
  328. private InputDevice.DeviceFlags m_DeviceFlags;
  329. private InputControlTreeView m_ControlTree;
  330. private InputEventTreeView m_EventTree;
  331. private bool m_NeedControlValueRefresh;
  332. private bool m_ReloadEventTree;
  333. private InputEventTrace.ReplayController m_ReplayController;
  334. private InputEventTrace m_EventTrace;
  335. private InputUpdateType m_InputUpdateTypeShownInControlTree;
  336. [SerializeField] private int m_DeviceId = InputDevice.InvalidDeviceId;
  337. [SerializeField] private TreeViewState m_ControlTreeState;
  338. [SerializeField] private TreeViewState m_EventTreeState;
  339. [SerializeField] private MultiColumnHeaderState m_ControlTreeHeaderState;
  340. [SerializeField] private MultiColumnHeaderState m_EventTreeHeaderState;
  341. [SerializeField] private bool m_EventTraceDisabled;
  342. private static List<InputDeviceDebuggerWindow> s_OpenDebuggerWindows;
  343. private void AddToList()
  344. {
  345. if (s_OpenDebuggerWindows == null)
  346. s_OpenDebuggerWindows = new List<InputDeviceDebuggerWindow>();
  347. if (!s_OpenDebuggerWindows.Contains(this))
  348. s_OpenDebuggerWindows.Add(this);
  349. }
  350. private void RemoveFromList()
  351. {
  352. s_OpenDebuggerWindows?.Remove(this);
  353. }
  354. private void NeedControlValueRefresh()
  355. {
  356. m_NeedControlValueRefresh = true;
  357. Repaint();
  358. }
  359. private void OnPlayModeChange(PlayModeStateChange change)
  360. {
  361. if (change == PlayModeStateChange.EnteredPlayMode || change == PlayModeStateChange.EnteredEditMode)
  362. NeedControlValueRefresh();
  363. }
  364. private void OnApplicationFocusChange(bool focus)
  365. {
  366. NeedControlValueRefresh();
  367. }
  368. private void OnDeviceChange(InputDevice device, InputDeviceChange change)
  369. {
  370. if (device.deviceId != m_DeviceId)
  371. return;
  372. if (change == InputDeviceChange.Removed)
  373. {
  374. Close();
  375. }
  376. else
  377. {
  378. if (m_DeviceFlags != device.m_DeviceFlags)
  379. UpdateDeviceFlags();
  380. Repaint();
  381. }
  382. }
  383. private void OnDeviceStateChange(InputDevice device, InputEventPtr eventPtr)
  384. {
  385. if (device == m_Device)
  386. NeedControlValueRefresh();
  387. }
  388. private static class Styles
  389. {
  390. public static string notFoundHelpText = "Device could not be found.";
  391. public static GUIStyle toolbarTextField;
  392. public static GUIStyle toolbarButton;
  393. static Styles()
  394. {
  395. toolbarTextField = new GUIStyle(EditorStyles.toolbarTextField);
  396. toolbarTextField.alignment = TextAnchor.MiddleRight;
  397. toolbarButton = new GUIStyle(EditorStyles.toolbarButton);
  398. toolbarButton.alignment = TextAnchor.MiddleCenter;
  399. }
  400. }
  401. private static class Contents
  402. {
  403. public static GUIContent clearContent = new GUIContent("Clear");
  404. public static GUIContent pauseContent = new GUIContent("Pause");
  405. public static GUIContent saveContent = new GUIContent("Save");
  406. public static GUIContent loadContent = new GUIContent("Load");
  407. public static GUIContent recordFramesContent = new GUIContent("Record Frames");
  408. public static GUIContent stateContent = new GUIContent("State");
  409. public static GUIContent editorStateContent = new GUIContent("Controls (Editor State)");
  410. public static GUIContent playerStateContent = new GUIContent("Controls (Player State)");
  411. }
  412. void ISerializationCallbackReceiver.OnBeforeSerialize()
  413. {
  414. }
  415. void ISerializationCallbackReceiver.OnAfterDeserialize()
  416. {
  417. AddToList();
  418. }
  419. }
  420. }
  421. #endif // UNITY_EDITOR