UnityView+Keyboard.mm 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. #import "UnityView.h"
  2. #include "UI/Keyboard.h"
  3. #include <sys/time.h>
  4. #include <map>
  5. #include <vector>
  6. static NSArray* keyboardCommands = nil;
  7. extern "C" int UnityGetAppleTVRemoteAllowExitToMenu();
  8. extern "C" void UnitySetAppleTVRemoteAllowExitToMenu(int val);
  9. @implementation UnityView (Keyboard)
  10. // Keyboard shortcuts don't provide events for key up
  11. // Keyboard shortcut callbacks are called with 0.4 (first time) and 0.1 (following times) seconds interval while pressing the key
  12. // Below we implement key expiration mechanism where key up event is generated if shortcut callback
  13. // is not called for specific key for more than <kKeyTimeoutInSeconds>
  14. typedef std::map<int, double> KeyMap;
  15. static const double kKeyTimeoutInSeconds = 0.5;
  16. static KeyMap& GetKeyMap()
  17. {
  18. static KeyMap s_Map;
  19. return s_Map;
  20. }
  21. static double GetTimeInSeconds()
  22. {
  23. timeval now;
  24. gettimeofday(&now, NULL);
  25. return now.tv_sec + now.tv_usec / 1000000.0;
  26. }
  27. - (void)createKeyboard
  28. {
  29. // only English keyboard layout is supported
  30. NSString* baseLayout = @"1234567890-=qwertyuiop[]asdfghjkl;'\\`zxcvbnm,./!@#$%^&*()_+{}:\"|<>?~ \t\r\b\\";
  31. NSString* numpadLayout = @"1234567890-=*+/.\r";
  32. NSString* upperCaseLetters = @"QWERTYUIOPASDFGHJKLZXCVBNM";
  33. NSString* shortcutCharacters = @"axcv";
  34. size_t sizeOfKeyboardCommands = baseLayout.length + numpadLayout.length + upperCaseLetters.length + 11;
  35. NSMutableArray* commands = [NSMutableArray arrayWithCapacity: sizeOfKeyboardCommands];
  36. void (^addKey)(NSString *keyName, UIKeyModifierFlags modifierFlags) = ^(NSString *keyName, UIKeyModifierFlags modifierFlags)
  37. {
  38. UIKeyCommand* command = [UIKeyCommand keyCommandWithInput: keyName modifierFlags: modifierFlags action: @selector(handleCommand:)];
  39. command.wantsPriorityOverSystemBehavior = YES;
  40. [commands addObject: command];
  41. };
  42. for (NSInteger i = 0; i < baseLayout.length; ++i)
  43. {
  44. NSString* input = [baseLayout substringWithRange: NSMakeRange(i, 1)];
  45. addKey(input, kNilOptions);
  46. }
  47. for (NSInteger i = 0; i < shortcutCharacters.length; ++i)
  48. {
  49. NSString* input = [shortcutCharacters substringWithRange: NSMakeRange(i, 1)];
  50. [commands addObject: [UIKeyCommand keyCommandWithInput: input modifierFlags: UIKeyModifierCommand action: @selector(handleCommand:)]];
  51. }
  52. for (NSInteger i = 0; i < numpadLayout.length; ++i)
  53. {
  54. NSString* input = [numpadLayout substringWithRange: NSMakeRange(i, 1)];
  55. addKey(input, UIKeyModifierNumericPad);
  56. }
  57. for (NSInteger i = 0; i < upperCaseLetters.length; ++i)
  58. {
  59. NSString* input = [upperCaseLetters substringWithRange: NSMakeRange(i, 1)];
  60. addKey(input, UIKeyModifierShift);
  61. }
  62. // pageUp, pageDown
  63. addKey(UIKeyInputPageUp, kNilOptions);
  64. addKey(UIKeyInputPageDown, kNilOptions);
  65. // up, down, left, right, esc
  66. addKey(UIKeyInputUpArrow, kNilOptions);
  67. addKey(UIKeyInputDownArrow, kNilOptions);
  68. addKey(UIKeyInputLeftArrow, kNilOptions);
  69. addKey(UIKeyInputRightArrow, kNilOptions);
  70. addKey(UIKeyInputEscape, kNilOptions);
  71. // caps Lock, shift, control, option, command
  72. addKey(@"", UIKeyModifierAlphaShift);
  73. addKey(@"", UIKeyModifierShift);
  74. addKey(@"", UIKeyModifierControl);
  75. addKey(@"", UIKeyModifierAlternate);
  76. addKey(@"", UIKeyModifierCommand);
  77. keyboardCommands = commands.copy;
  78. }
  79. - (NSArray*)keyCommands
  80. {
  81. //keyCommands take control of buttons over UITextView, that's why need to return nil if text input field is active or we have an external keyboard attached AND a first responder
  82. if ([[KeyboardDelegate Instance] status] == Visible || ([[KeyboardDelegate Instance] hasExternalKeyboard] && [self hasFirstResponderInHeirachy: UnityGetGLView()]))
  83. return nil;
  84. if (keyboardCommands == nil)
  85. {
  86. [self createKeyboard];
  87. }
  88. return keyboardCommands;
  89. }
  90. - (bool)hasFirstResponderInHeirachy:(UIView*)view
  91. {
  92. if (view.isFirstResponder)
  93. return true;
  94. for (UIView* subview in view.subviews)
  95. {
  96. if ([self hasFirstResponderInHeirachy: subview])
  97. return true;
  98. }
  99. return false;
  100. }
  101. - (bool)isValidCodeForButton:(int)code
  102. {
  103. return (code > 0 && code < 128);
  104. }
  105. - (void)handleCommand:(UIKeyCommand *)command
  106. {
  107. NSString* input = command.input;
  108. UIKeyModifierFlags modifierFlags = command.modifierFlags;
  109. char inputChar = ([input length] == 1) ? [input characterAtIndex: 0] : 0;
  110. int code = (int)inputChar; // ASCII code
  111. if (![self isValidCodeForButton: code])
  112. {
  113. code = 0;
  114. }
  115. if ((modifierFlags & UIKeyModifierAlphaShift) != 0)
  116. code = UnityStringToKey("caps lock");
  117. if ((modifierFlags & UIKeyModifierShift) != 0)
  118. code = UnityStringToKey("left shift");
  119. if ((modifierFlags & UIKeyModifierControl) != 0)
  120. code = UnityStringToKey("left ctrl");
  121. if ((modifierFlags & UIKeyModifierAlternate) != 0)
  122. code = UnityStringToKey("left alt");
  123. if ((modifierFlags & UIKeyModifierCommand) != 0)
  124. code = UnityStringToKey("left cmd");
  125. if ((modifierFlags & UIKeyModifierNumericPad) != 0)
  126. {
  127. switch (inputChar)
  128. {
  129. case '0':
  130. code = UnityStringToKey("[0]");
  131. break;
  132. case '1':
  133. code = UnityStringToKey("[1]");
  134. break;
  135. case '2':
  136. code = UnityStringToKey("[2]");
  137. break;
  138. case '3':
  139. code = UnityStringToKey("[3]");
  140. break;
  141. case '4':
  142. code = UnityStringToKey("[4]");
  143. break;
  144. case '5':
  145. code = UnityStringToKey("[5]");
  146. break;
  147. case '6':
  148. code = UnityStringToKey("[6]");
  149. break;
  150. case '7':
  151. code = UnityStringToKey("[7]");
  152. break;
  153. case '8':
  154. code = UnityStringToKey("[8]");
  155. break;
  156. case '9':
  157. code = UnityStringToKey("[9]");
  158. break;
  159. case '-':
  160. code = UnityStringToKey("[-]");
  161. break;
  162. case '=':
  163. code = UnityStringToKey("equals");
  164. break;
  165. case '*':
  166. code = UnityStringToKey("[*]");
  167. break;
  168. case '+':
  169. code = UnityStringToKey("[+]");
  170. break;
  171. case '/':
  172. code = UnityStringToKey("[/]");
  173. break;
  174. case '.':
  175. code = UnityStringToKey("[.]");
  176. break;
  177. case '\r':
  178. code = UnityStringToKey("enter");
  179. break;
  180. default:
  181. break;
  182. }
  183. }
  184. if (input == UIKeyInputUpArrow)
  185. code = UnityStringToKey("up");
  186. else if (input == UIKeyInputDownArrow)
  187. code = UnityStringToKey("down");
  188. else if (input == UIKeyInputRightArrow)
  189. code = UnityStringToKey("right");
  190. else if (input == UIKeyInputLeftArrow)
  191. code = UnityStringToKey("left");
  192. else if (input == UIKeyInputEscape)
  193. code = UnityStringToKey("escape");
  194. else if ([input isEqualToString: @"UIKeyInputPageUp"])
  195. code = UnityStringToKey("page up");
  196. else if ([input isEqualToString: @"UIKeyInputPageDown"])
  197. code = UnityStringToKey("page down");
  198. UnitySendKeyboardCommand(command, code);
  199. KeyMap::iterator item = GetKeyMap().find(code);
  200. if (item == GetKeyMap().end())
  201. {
  202. // New key is down, register it and its time
  203. UnitySetKeyboardKeyState(code, true);
  204. GetKeyMap()[code] = GetTimeInSeconds();
  205. }
  206. else
  207. {
  208. // Still holding the key, update its time
  209. item->second = GetTimeInSeconds();
  210. }
  211. }
  212. - (void)processKeyboard
  213. {
  214. KeyMap& map = GetKeyMap();
  215. if (map.size() == 0)
  216. return;
  217. std::vector<int> keysToUnpress;
  218. double nowTime = GetTimeInSeconds();
  219. for (KeyMap::iterator item = map.begin();
  220. item != map.end();
  221. item++)
  222. {
  223. // Key has expired, register it for key up event
  224. if (nowTime - item->second > kKeyTimeoutInSeconds)
  225. keysToUnpress.push_back(item->first);
  226. }
  227. for (std::vector<int>::iterator item = keysToUnpress.begin();
  228. item != keysToUnpress.end();
  229. item++)
  230. {
  231. map.erase(*item);
  232. UnitySetKeyboardKeyState(*item, false);
  233. }
  234. }
  235. @end