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. static int watchReturnKey(void * userdata, SDL_Event * event);
  12. @interface GameChatKeyboardHandler ()
  13. @property (nonatomic) BOOL wasChatMessageSent;
  14. @end
  15. @implementation GameChatKeyboardHandler
  16. + (void)sendKeyEventWithKeyCode:(SDL_KeyCode)keyCode
  17. {
  18. SDL_Event keyEvent;
  19. keyEvent.key = (SDL_KeyboardEvent){
  20. .type = SDL_KEYDOWN,
  21. .state = SDL_PRESSED,
  22. .keysym.sym = keyCode,
  23. };
  24. SDL_PushEvent(&keyEvent);
  25. }
  26. - (instancetype)init {
  27. self = [super init];
  28. __auto_type notificationCenter = NSNotificationCenter.defaultCenter;
  29. [notificationCenter addObserver:self selector:@selector(textDidBeginEditing:) name:UITextFieldTextDidBeginEditingNotification object:nil];
  30. [notificationCenter addObserver:self selector:@selector(textDidEndEditing:) name:UITextFieldTextDidEndEditingNotification object:nil];
  31. return self;
  32. }
  33. #pragma mark - Notifications
  34. - (void)textDidBeginEditing:(NSNotification *)n {
  35. self.wasChatMessageSent = NO;
  36. // watch for pressing Return to ignore sending Escape key after keyboard is closed
  37. SDL_AddEventWatch(watchReturnKey, (__bridge void *)self);
  38. }
  39. - (void)textDidEndEditing:(NSNotification *)n {
  40. // discard chat message
  41. if(!self.wasChatMessageSent)
  42. [[self class] sendKeyEventWithKeyCode: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. }