TextEvent.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System;
  2. using System.Runtime.InteropServices;
  3. using UnityEngine.InputSystem.Utilities;
  4. namespace UnityEngine.InputSystem.LowLevel
  5. {
  6. /// <summary>
  7. /// A single character text input event.
  8. /// </summary>
  9. /// <remarks>
  10. /// Text input does not fit the control-based input model well and thus is
  11. /// represented as its own form of input. A device that is capable of receiving
  12. /// text input (such as <see cref="Keyboard"/>) receives text input events
  13. /// and should implement <see cref="ITextInputReceiver"/> in order for the
  14. /// input system to be able to relay these events to the device.
  15. /// </remarks>
  16. [StructLayout(LayoutKind.Explicit, Size = InputEvent.kBaseEventSize + 4)]
  17. public struct TextEvent : IInputEventTypeInfo
  18. {
  19. public const int Type = 0x54455854;
  20. [FieldOffset(0)]
  21. public InputEvent baseEvent;
  22. /// <summary>
  23. /// Character in UTF-32 encoding.
  24. /// </summary>
  25. [FieldOffset(InputEvent.kBaseEventSize)]
  26. public int character;
  27. public FourCC typeStatic => Type;
  28. public static unsafe TextEvent* From(InputEventPtr eventPtr)
  29. {
  30. if (!eventPtr.valid)
  31. throw new ArgumentNullException(nameof(eventPtr));
  32. if (!eventPtr.IsA<TextEvent>())
  33. throw new InvalidCastException(string.Format("Cannot cast event with type '{0}' into TextEvent",
  34. eventPtr.type));
  35. return (TextEvent*)eventPtr.data;
  36. }
  37. public static TextEvent Create(int deviceId, char character, double time = -1)
  38. {
  39. ////TODO: detect and throw when if character is surrogate
  40. var inputEvent = new TextEvent
  41. {
  42. baseEvent = new InputEvent(Type, InputEvent.kBaseEventSize + 4, deviceId, time),
  43. character = character
  44. };
  45. return inputEvent;
  46. }
  47. public static TextEvent Create(int deviceId, int character, double time = -1)
  48. {
  49. var inputEvent = new TextEvent
  50. {
  51. baseEvent = new InputEvent(Type, InputEvent.kBaseEventSize + 4, deviceId, time),
  52. character = character
  53. };
  54. return inputEvent;
  55. }
  56. }
  57. }