GameChatKeyboardHandler.m 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * GameChatKeyboardHandler.m, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #import "GameChatKeyboardHandler.h"
  11. #include <SDL_events.h>
  12. static int watchReturnKey(void * userdata, SDL_Event * event);
  13. static void sendKeyEvent(SDL_KeyCode keyCode)
  14. {
  15. SDL_Event keyEvent;
  16. keyEvent.key = (SDL_KeyboardEvent){
  17. .type = SDL_KEYDOWN,
  18. .keysym.sym = keyCode,
  19. };
  20. SDL_PushEvent(&keyEvent);
  21. }
  22. @interface GameChatKeyboardHandler ()
  23. @property (nonatomic) BOOL wasChatMessageSent;
  24. @end
  25. @implementation GameChatKeyboardHandler
  26. - (void)triggerInput {
  27. __auto_type notificationCenter = NSNotificationCenter.defaultCenter;
  28. [notificationCenter addObserver:self selector:@selector(textDidBeginEditing:) name:UITextFieldTextDidBeginEditingNotification object:nil];
  29. [notificationCenter addObserver:self selector:@selector(textDidEndEditing:) name:UITextFieldTextDidEndEditingNotification object:nil];
  30. self.wasChatMessageSent = NO;
  31. sendKeyEvent(SDLK_TAB);
  32. }
  33. #pragma mark - Notifications
  34. - (void)textDidBeginEditing:(NSNotification *)n {
  35. // watch for pressing Return to ignore sending Escape key after keyboard is closed
  36. SDL_AddEventWatch(watchReturnKey, (__bridge void *)self);
  37. }
  38. - (void)textDidEndEditing:(NSNotification *)n {
  39. [NSNotificationCenter.defaultCenter removeObserver:self];
  40. // discard chat message
  41. if(!self.wasChatMessageSent)
  42. sendKeyEvent(SDLK_ESCAPE);
  43. }
  44. @end
  45. static int watchReturnKey(void * userdata, SDL_Event * event)
  46. {
  47. if(event->type == SDL_KEYDOWN && event->key.keysym.scancode == SDL_SCANCODE_RETURN)
  48. {
  49. __auto_type self = (__bridge GameChatKeyboardHandler *)userdata;
  50. self.wasChatMessageSent = YES;
  51. SDL_DelEventWatch(watchReturnKey, userdata);
  52. }
  53. return 1;
  54. }