godot_content_view.mm 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  1. /**************************************************************************/
  2. /* godot_content_view.mm */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "godot_content_view.h"
  31. #include "display_server_macos.h"
  32. #include "key_mapping_macos.h"
  33. #include "main/main.h"
  34. @implementation GodotContentLayerDelegate
  35. - (id)init {
  36. self = [super init];
  37. window_id = DisplayServer::INVALID_WINDOW_ID;
  38. need_redraw = false;
  39. return self;
  40. }
  41. - (void)setWindowID:(DisplayServerMacOS::WindowID)wid {
  42. window_id = wid;
  43. }
  44. - (void)setNeedRedraw:(bool)redraw {
  45. need_redraw = redraw;
  46. }
  47. - (void)displayLayer:(CALayer *)layer {
  48. DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
  49. if (OS::get_singleton()->get_main_loop() && ds->get_is_resizing() && need_redraw) {
  50. Main::force_redraw();
  51. if (!Main::is_iterating()) { // Avoid cyclic loop.
  52. Main::iteration();
  53. }
  54. need_redraw = false;
  55. }
  56. }
  57. @end
  58. @implementation GodotContentView
  59. - (void)setFrameSize:(NSSize)newSize {
  60. DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
  61. if (ds && ds->has_window(window_id)) {
  62. DisplayServerMacOS::WindowData &wd = ds->get_window(window_id);
  63. NSRect frameRect = [wd.window_object frame];
  64. if (wd.fs_transition || wd.initial_size) {
  65. self.layerContentsPlacement = NSViewLayerContentsPlacementScaleAxesIndependently;
  66. wd.initial_size = false;
  67. } else {
  68. bool left = (wd.last_frame_rect.origin.x != frameRect.origin.x);
  69. bool bottom = (wd.last_frame_rect.origin.y != frameRect.origin.y);
  70. bool right = (wd.last_frame_rect.origin.x + wd.last_frame_rect.size.width != frameRect.origin.x + frameRect.size.width);
  71. bool top = (wd.last_frame_rect.origin.y + wd.last_frame_rect.size.height != frameRect.origin.y + frameRect.size.height);
  72. if (left && top) {
  73. self.layerContentsPlacement = NSViewLayerContentsPlacementBottomRight;
  74. } else if (left && bottom) {
  75. self.layerContentsPlacement = NSViewLayerContentsPlacementTopRight;
  76. } else if (left) {
  77. self.layerContentsPlacement = NSViewLayerContentsPlacementRight;
  78. } else if (right && top) {
  79. self.layerContentsPlacement = NSViewLayerContentsPlacementBottomLeft;
  80. } else if (right && bottom) {
  81. self.layerContentsPlacement = NSViewLayerContentsPlacementTopLeft;
  82. } else if (right) {
  83. self.layerContentsPlacement = NSViewLayerContentsPlacementLeft;
  84. }
  85. }
  86. wd.last_frame_rect = frameRect;
  87. }
  88. [super setFrameSize:newSize];
  89. [layer_delegate setNeedRedraw:true];
  90. [self.layer setNeedsDisplay]; // Force "drawRect" call.
  91. }
  92. - (void)updateLayerDelegate {
  93. self.layer.delegate = layer_delegate;
  94. self.layer.autoresizingMask = kCALayerHeightSizable | kCALayerWidthSizable;
  95. self.layer.needsDisplayOnBoundsChange = YES;
  96. }
  97. - (id)init {
  98. self = [super init];
  99. layer_delegate = [[GodotContentLayerDelegate alloc] init];
  100. window_id = DisplayServer::INVALID_WINDOW_ID;
  101. tracking_area = nil;
  102. ime_input_event_in_progress = false;
  103. mouse_down_control = false;
  104. ignore_momentum_scroll = false;
  105. last_pen_inverted = false;
  106. [self updateTrackingAreas];
  107. self.layerContentsRedrawPolicy = NSViewLayerContentsRedrawDuringViewResize;
  108. self.layerContentsPlacement = NSViewLayerContentsPlacementTopLeft;
  109. [self registerForDraggedTypes:[NSArray arrayWithObject:NSPasteboardTypeFileURL]];
  110. marked_text = [[NSMutableAttributedString alloc] init];
  111. return self;
  112. }
  113. - (void)setWindowID:(DisplayServerMacOS::WindowID)wid {
  114. window_id = wid;
  115. [layer_delegate setWindowID:window_id];
  116. }
  117. // MARK: Backing Layer
  118. - (CALayer *)makeBackingLayer {
  119. return [[CAMetalLayer class] layer];
  120. }
  121. - (BOOL)wantsUpdateLayer {
  122. return YES;
  123. }
  124. - (BOOL)isOpaque {
  125. return YES;
  126. }
  127. // MARK: IME
  128. - (BOOL)hasMarkedText {
  129. return (marked_text.length > 0);
  130. }
  131. - (NSRange)markedRange {
  132. return NSMakeRange(0, marked_text.length);
  133. }
  134. - (NSRange)selectedRange {
  135. static const NSRange kEmptyRange = { NSNotFound, 0 };
  136. return kEmptyRange;
  137. }
  138. - (void)setMarkedText:(id)aString selectedRange:(NSRange)selectedRange replacementRange:(NSRange)replacementRange {
  139. if ([aString isKindOfClass:[NSAttributedString class]]) {
  140. marked_text = [[NSMutableAttributedString alloc] initWithAttributedString:aString];
  141. } else {
  142. marked_text = [[NSMutableAttributedString alloc] initWithString:aString];
  143. }
  144. if (marked_text.length == 0) {
  145. [self unmarkText];
  146. return;
  147. }
  148. DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
  149. if (!ds || !ds->has_window(window_id)) {
  150. return;
  151. }
  152. DisplayServerMacOS::WindowData &wd = ds->get_window(window_id);
  153. if (wd.im_active) {
  154. ime_input_event_in_progress = true;
  155. ds->pop_last_key_event();
  156. ds->update_im_text(Point2i(selectedRange.location, selectedRange.length), String::utf8([[marked_text mutableString] UTF8String]));
  157. }
  158. }
  159. - (void)doCommandBySelector:(SEL)aSelector {
  160. [self tryToPerform:aSelector with:self];
  161. }
  162. - (void)unmarkText {
  163. if (ime_input_event_in_progress) {
  164. ime_suppress_next_keyup = true;
  165. }
  166. ime_input_event_in_progress = false;
  167. [[marked_text mutableString] setString:@""];
  168. DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
  169. if (!ds || !ds->has_window(window_id)) {
  170. return;
  171. }
  172. DisplayServerMacOS::WindowData &wd = ds->get_window(window_id);
  173. if (wd.im_active) {
  174. ds->update_im_text(Point2i(), String());
  175. }
  176. }
  177. - (NSArray *)validAttributesForMarkedText {
  178. return [NSArray array];
  179. }
  180. - (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange {
  181. return nil;
  182. }
  183. - (NSUInteger)characterIndexForPoint:(NSPoint)aPoint {
  184. return 0;
  185. }
  186. - (NSRect)firstRectForCharacterRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange {
  187. DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
  188. if (!ds || !ds->has_window(window_id)) {
  189. return NSMakeRect(0, 0, 0, 0);
  190. }
  191. DisplayServerMacOS::WindowData &wd = ds->get_window(window_id);
  192. const NSRect content_rect = [wd.window_view frame];
  193. const float scale = ds->screen_get_max_scale();
  194. NSRect point_in_window_rect = NSMakeRect(wd.im_position.x / scale, content_rect.size.height - (wd.im_position.y / scale) - 1, 0, 0);
  195. NSPoint point_on_screen = [wd.window_object convertRectToScreen:point_in_window_rect].origin;
  196. return NSMakeRect(point_on_screen.x, point_on_screen.y, 0, 0);
  197. }
  198. - (void)cancelComposition {
  199. [self unmarkText];
  200. [[NSTextInputContext currentInputContext] discardMarkedText];
  201. }
  202. - (void)insertText:(id)aString {
  203. [self insertText:aString replacementRange:NSMakeRange(0, 0)];
  204. }
  205. - (void)insertText:(id)aString replacementRange:(NSRange)replacementRange {
  206. NSString *characters;
  207. if ([aString isKindOfClass:[NSAttributedString class]]) {
  208. characters = [aString string];
  209. } else {
  210. characters = (NSString *)aString;
  211. }
  212. NSCharacterSet *ctrl_chars = [NSCharacterSet controlCharacterSet];
  213. NSCharacterSet *wsnl_chars = [NSCharacterSet whitespaceAndNewlineCharacterSet];
  214. if ([characters rangeOfCharacterFromSet:ctrl_chars].length && [characters rangeOfCharacterFromSet:wsnl_chars].length == 0) {
  215. [[NSTextInputContext currentInputContext] discardMarkedText];
  216. [self cancelComposition];
  217. return;
  218. }
  219. DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
  220. if (!ds || !ds->has_window(window_id)) {
  221. [self cancelComposition];
  222. return;
  223. }
  224. Char16String text;
  225. text.resize([characters length] + 1);
  226. [characters getCharacters:(unichar *)text.ptrw() range:NSMakeRange(0, [characters length])];
  227. String u32text;
  228. u32text.parse_utf16(text.ptr(), text.length());
  229. for (int i = 0; i < u32text.length(); i++) {
  230. const char32_t codepoint = u32text[i];
  231. if ((codepoint & 0xFF00) == 0xF700) {
  232. continue;
  233. }
  234. DisplayServerMacOS::KeyEvent ke;
  235. ke.window_id = window_id;
  236. ke.macos_state = 0;
  237. ke.pressed = true;
  238. ke.echo = false;
  239. ke.raw = false; // IME input event.
  240. ke.keycode = Key::NONE;
  241. ke.physical_keycode = Key::NONE;
  242. ke.key_label = Key::NONE;
  243. ke.unicode = fix_unicode(codepoint);
  244. ds->push_to_key_event_buffer(ke);
  245. }
  246. [self cancelComposition];
  247. }
  248. // MARK: Drag and drop
  249. - (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender {
  250. return NSDragOperationCopy;
  251. }
  252. - (NSDragOperation)draggingUpdated:(id<NSDraggingInfo>)sender {
  253. return NSDragOperationCopy;
  254. }
  255. - (BOOL)performDragOperation:(id<NSDraggingInfo>)sender {
  256. DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
  257. if (!ds || !ds->has_window(window_id)) {
  258. return NO;
  259. }
  260. DisplayServerMacOS::WindowData &wd = ds->get_window(window_id);
  261. if (wd.drop_files_callback.is_valid()) {
  262. Vector<String> files;
  263. NSPasteboard *pboard = [sender draggingPasteboard];
  264. NSArray *items = pboard.pasteboardItems;
  265. for (NSPasteboardItem *item in items) {
  266. NSString *url = [item stringForType:NSPasteboardTypeFileURL];
  267. NSString *file = [NSURL URLWithString:url].path;
  268. files.push_back(String::utf8([file UTF8String]));
  269. }
  270. wd.drop_files_callback.call(files);
  271. }
  272. return NO;
  273. }
  274. // MARK: Focus
  275. - (BOOL)canBecomeKeyView {
  276. DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
  277. if (!ds || !ds->has_window(window_id)) {
  278. return YES;
  279. }
  280. DisplayServerMacOS::WindowData &wd = ds->get_window(window_id);
  281. return !wd.no_focus;
  282. }
  283. - (BOOL)acceptsFirstResponder {
  284. return YES;
  285. }
  286. // MARK: Mouse
  287. - (void)cursorUpdate:(NSEvent *)event {
  288. DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
  289. if (!ds) {
  290. return;
  291. }
  292. ds->cursor_update_shape();
  293. }
  294. - (void)processMouseEvent:(NSEvent *)event index:(MouseButton)index pressed:(bool)pressed outofstream:(bool)outofstream {
  295. DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
  296. if (!ds || !ds->has_window(window_id)) {
  297. return;
  298. }
  299. DisplayServerMacOS::WindowData &wd = ds->get_window(window_id);
  300. BitField<MouseButtonMask> last_button_state = ds->mouse_get_button_state();
  301. MouseButtonMask mask = mouse_button_to_mask(index);
  302. if (pressed) {
  303. last_button_state.set_flag(mask);
  304. } else {
  305. last_button_state.clear_flag(mask);
  306. }
  307. ds->mouse_set_button_state(last_button_state);
  308. Ref<InputEventMouseButton> mb;
  309. mb.instantiate();
  310. mb->set_window_id(window_id);
  311. if (outofstream) {
  312. ds->update_mouse_pos(wd, [wd.window_object mouseLocationOutsideOfEventStream]);
  313. } else {
  314. ds->update_mouse_pos(wd, [event locationInWindow]);
  315. }
  316. ds->get_key_modifier_state([event modifierFlags], mb);
  317. mb->set_button_index(index);
  318. mb->set_pressed(pressed);
  319. mb->set_position(wd.mouse_pos);
  320. mb->set_global_position(wd.mouse_pos);
  321. mb->set_button_mask(last_button_state);
  322. if (!outofstream && index == MouseButton::LEFT && pressed) {
  323. mb->set_double_click([event clickCount] == 2);
  324. }
  325. Input::get_singleton()->parse_input_event(mb);
  326. }
  327. - (void)mouseDown:(NSEvent *)event {
  328. if (([event modifierFlags] & NSEventModifierFlagControl)) {
  329. mouse_down_control = true;
  330. [self processMouseEvent:event index:MouseButton::RIGHT pressed:true outofstream:false];
  331. } else {
  332. mouse_down_control = false;
  333. [self processMouseEvent:event index:MouseButton::LEFT pressed:true outofstream:false];
  334. }
  335. }
  336. - (void)mouseDragged:(NSEvent *)event {
  337. [self mouseMoved:event];
  338. }
  339. - (void)mouseUp:(NSEvent *)event {
  340. if (mouse_down_control) {
  341. [self processMouseEvent:event index:MouseButton::RIGHT pressed:false outofstream:false];
  342. } else {
  343. [self processMouseEvent:event index:MouseButton::LEFT pressed:false outofstream:false];
  344. }
  345. }
  346. - (void)mouseMoved:(NSEvent *)event {
  347. DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
  348. if (!ds || !ds->has_window(window_id)) {
  349. return;
  350. }
  351. DisplayServerMacOS::WindowData &wd = ds->get_window(window_id);
  352. NSPoint delta = NSMakePoint([event deltaX], [event deltaY]);
  353. NSPoint mpos = [event locationInWindow];
  354. if (ds->update_mouse_wrap(wd, delta, mpos, [event timestamp])) {
  355. return;
  356. }
  357. Ref<InputEventMouseMotion> mm;
  358. mm.instantiate();
  359. mm->set_window_id(window_id);
  360. mm->set_button_mask(ds->mouse_get_button_state());
  361. ds->update_mouse_pos(wd, mpos);
  362. mm->set_position(wd.mouse_pos);
  363. mm->set_pressure([event pressure]);
  364. NSEventSubtype subtype = [event subtype];
  365. if (subtype == NSEventSubtypeTabletPoint) {
  366. const NSPoint p = [event tilt];
  367. mm->set_tilt(Vector2(p.x, -p.y));
  368. mm->set_pen_inverted(last_pen_inverted);
  369. } else if (subtype == NSEventSubtypeTabletProximity) {
  370. // Check if using the eraser end of pen only on proximity event.
  371. last_pen_inverted = [event pointingDeviceType] == NSPointingDeviceTypeEraser;
  372. mm->set_pen_inverted(last_pen_inverted);
  373. }
  374. mm->set_global_position(wd.mouse_pos);
  375. mm->set_velocity(Input::get_singleton()->get_last_mouse_velocity());
  376. mm->set_screen_velocity(mm->get_velocity());
  377. const Vector2i relativeMotion = Vector2i(delta.x, delta.y) * ds->screen_get_max_scale();
  378. mm->set_relative(relativeMotion);
  379. mm->set_relative_screen_position(relativeMotion);
  380. ds->get_key_modifier_state([event modifierFlags], mm);
  381. Input::get_singleton()->parse_input_event(mm);
  382. }
  383. - (void)rightMouseDown:(NSEvent *)event {
  384. [self processMouseEvent:event index:MouseButton::RIGHT pressed:true outofstream:false];
  385. }
  386. - (void)rightMouseDragged:(NSEvent *)event {
  387. [self mouseMoved:event];
  388. }
  389. - (void)rightMouseUp:(NSEvent *)event {
  390. [self processMouseEvent:event index:MouseButton::RIGHT pressed:false outofstream:false];
  391. }
  392. - (void)otherMouseDown:(NSEvent *)event {
  393. if ((int)[event buttonNumber] == 2) {
  394. [self processMouseEvent:event index:MouseButton::MIDDLE pressed:true outofstream:false];
  395. } else if ((int)[event buttonNumber] == 3) {
  396. [self processMouseEvent:event index:MouseButton::MB_XBUTTON1 pressed:true outofstream:false];
  397. } else if ((int)[event buttonNumber] == 4) {
  398. [self processMouseEvent:event index:MouseButton::MB_XBUTTON2 pressed:true outofstream:false];
  399. } else {
  400. return;
  401. }
  402. }
  403. - (void)otherMouseDragged:(NSEvent *)event {
  404. [self mouseMoved:event];
  405. }
  406. - (void)otherMouseUp:(NSEvent *)event {
  407. if ((int)[event buttonNumber] == 2) {
  408. [self processMouseEvent:event index:MouseButton::MIDDLE pressed:false outofstream:false];
  409. } else if ((int)[event buttonNumber] == 3) {
  410. [self processMouseEvent:event index:MouseButton::MB_XBUTTON1 pressed:false outofstream:false];
  411. } else if ((int)[event buttonNumber] == 4) {
  412. [self processMouseEvent:event index:MouseButton::MB_XBUTTON2 pressed:false outofstream:false];
  413. } else {
  414. return;
  415. }
  416. }
  417. - (void)swipeWithEvent:(NSEvent *)event {
  418. // Swipe gesture on Trackpad/Magic Mouse, or physical back/forward mouse buttons.
  419. if ([event phase] == NSEventPhaseEnded || [event phase] == NSEventPhaseChanged) {
  420. if (Math::is_equal_approx([event deltaX], 1.0)) {
  421. // Swipe left (back).
  422. [self processMouseEvent:event index:MouseButton::MB_XBUTTON1 pressed:true outofstream:true];
  423. [self processMouseEvent:event index:MouseButton::MB_XBUTTON1 pressed:false outofstream:true];
  424. } else if (Math::is_equal_approx([event deltaX], -1.0)) {
  425. // Swipe right (forward).
  426. [self processMouseEvent:event index:MouseButton::MB_XBUTTON2 pressed:true outofstream:true];
  427. [self processMouseEvent:event index:MouseButton::MB_XBUTTON2 pressed:false outofstream:true];
  428. }
  429. }
  430. }
  431. - (void)mouseExited:(NSEvent *)event {
  432. DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
  433. if (!ds || !ds->has_window(window_id)) {
  434. return;
  435. }
  436. if (ds->mouse_get_mode() != DisplayServer::MOUSE_MODE_CAPTURED) {
  437. ds->mouse_exit_window(window_id);
  438. }
  439. }
  440. - (void)mouseEntered:(NSEvent *)event {
  441. DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
  442. if (!ds || !ds->has_window(window_id)) {
  443. return;
  444. }
  445. if (ds->mouse_get_mode() != DisplayServer::MOUSE_MODE_CAPTURED) {
  446. ds->mouse_enter_window(window_id);
  447. }
  448. ds->cursor_update_shape();
  449. }
  450. - (void)magnifyWithEvent:(NSEvent *)event {
  451. DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
  452. if (!ds || !ds->has_window(window_id)) {
  453. return;
  454. }
  455. DisplayServerMacOS::WindowData &wd = ds->get_window(window_id);
  456. Ref<InputEventMagnifyGesture> ev;
  457. ev.instantiate();
  458. ev->set_window_id(window_id);
  459. ds->get_key_modifier_state([event modifierFlags], ev);
  460. ds->update_mouse_pos(wd, [event locationInWindow]);
  461. ev->set_position(wd.mouse_pos);
  462. ev->set_factor([event magnification] + 1.0);
  463. Input::get_singleton()->parse_input_event(ev);
  464. }
  465. - (void)updateTrackingAreas {
  466. if (tracking_area != nil) {
  467. [self removeTrackingArea:tracking_area];
  468. }
  469. NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited | NSTrackingActiveInKeyWindow | NSTrackingCursorUpdate | NSTrackingInVisibleRect;
  470. tracking_area = [[NSTrackingArea alloc] initWithRect:[self bounds] options:options owner:self userInfo:nil];
  471. [self addTrackingArea:tracking_area];
  472. [super updateTrackingAreas];
  473. }
  474. // MARK: Keyboard
  475. - (void)keyDown:(NSEvent *)event {
  476. DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
  477. if (!ds || !ds->has_window(window_id)) {
  478. return;
  479. }
  480. DisplayServerMacOS::WindowData &wd = ds->get_window(window_id);
  481. ignore_momentum_scroll = true;
  482. // Ignore all input if IME input is in progress.
  483. if (!ime_input_event_in_progress) {
  484. NSString *characters = [event characters];
  485. NSUInteger length = [characters length];
  486. if (!wd.im_active && length > 0 && keycode_has_unicode(KeyMappingMacOS::remap_key([event keyCode], [event modifierFlags], true))) {
  487. // Fallback unicode character handler used if IME is not active.
  488. Char16String text;
  489. text.resize([characters length] + 1);
  490. [characters getCharacters:(unichar *)text.ptrw() range:NSMakeRange(0, [characters length])];
  491. String u32text;
  492. u32text.parse_utf16(text.ptr(), text.length());
  493. DisplayServerMacOS::KeyEvent ke;
  494. ke.window_id = window_id;
  495. ke.macos_state = [event modifierFlags];
  496. ke.pressed = true;
  497. ke.echo = [event isARepeat];
  498. ke.keycode = KeyMappingMacOS::remap_key([event keyCode], [event modifierFlags], false);
  499. ke.physical_keycode = KeyMappingMacOS::translate_key([event keyCode]);
  500. ke.key_label = KeyMappingMacOS::remap_key([event keyCode], [event modifierFlags], true);
  501. ke.raw = true;
  502. if (u32text.is_empty()) {
  503. ke.unicode = 0;
  504. ds->push_to_key_event_buffer(ke);
  505. }
  506. for (int i = 0; i < u32text.length(); i++) {
  507. const char32_t codepoint = u32text[i];
  508. ke.unicode = fix_unicode(codepoint);
  509. ds->push_to_key_event_buffer(ke);
  510. }
  511. } else {
  512. DisplayServerMacOS::KeyEvent ke;
  513. ke.window_id = window_id;
  514. ke.macos_state = [event modifierFlags];
  515. ke.pressed = true;
  516. ke.echo = [event isARepeat];
  517. ke.keycode = KeyMappingMacOS::remap_key([event keyCode], [event modifierFlags], false);
  518. ke.physical_keycode = KeyMappingMacOS::translate_key([event keyCode]);
  519. ke.key_label = KeyMappingMacOS::remap_key([event keyCode], [event modifierFlags], true);
  520. ke.unicode = 0;
  521. ke.location = KeyMappingMacOS::translate_location([event keyCode]);
  522. ke.raw = false;
  523. ds->push_to_key_event_buffer(ke);
  524. }
  525. }
  526. // Pass events to IME handler
  527. if (wd.im_active) {
  528. [self interpretKeyEvents:[NSArray arrayWithObject:event]];
  529. }
  530. }
  531. - (void)flagsChanged:(NSEvent *)event {
  532. DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
  533. if (!ds || !ds->has_window(window_id)) {
  534. return;
  535. }
  536. ignore_momentum_scroll = true;
  537. DisplayServerMacOS::KeyEvent ke;
  538. ke.window_id = window_id;
  539. ke.echo = false;
  540. ke.raw = true;
  541. int key = [event keyCode];
  542. int mod = [event modifierFlags];
  543. if (key == 0x36 || key == 0x37) {
  544. if (mod & NSEventModifierFlagCommand) {
  545. mod &= ~NSEventModifierFlagCommand;
  546. ke.pressed = true;
  547. } else {
  548. ke.pressed = false;
  549. }
  550. } else if (key == 0x38 || key == 0x3c) {
  551. if (mod & NSEventModifierFlagShift) {
  552. mod &= ~NSEventModifierFlagShift;
  553. ke.pressed = true;
  554. } else {
  555. ke.pressed = false;
  556. }
  557. } else if (key == 0x3a || key == 0x3d) {
  558. if (mod & NSEventModifierFlagOption) {
  559. mod &= ~NSEventModifierFlagOption;
  560. ke.pressed = true;
  561. } else {
  562. ke.pressed = false;
  563. }
  564. } else if (key == 0x3b || key == 0x3e) {
  565. if (mod & NSEventModifierFlagControl) {
  566. mod &= ~NSEventModifierFlagControl;
  567. ke.pressed = true;
  568. } else {
  569. ke.pressed = false;
  570. }
  571. } else {
  572. return;
  573. }
  574. ke.macos_state = mod;
  575. ke.keycode = KeyMappingMacOS::remap_key(key, mod, false);
  576. ke.physical_keycode = KeyMappingMacOS::translate_key(key);
  577. ke.key_label = KeyMappingMacOS::remap_key(key, mod, true);
  578. ke.unicode = 0;
  579. ke.location = KeyMappingMacOS::translate_location(key);
  580. ds->push_to_key_event_buffer(ke);
  581. }
  582. - (void)keyUp:(NSEvent *)event {
  583. DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
  584. if (!ds || !ds->has_window(window_id)) {
  585. return;
  586. }
  587. // Ignore all input if IME input is in progress.
  588. if (ime_suppress_next_keyup) {
  589. ime_suppress_next_keyup = false;
  590. return;
  591. }
  592. if (!ime_input_event_in_progress) {
  593. DisplayServerMacOS::KeyEvent ke;
  594. ke.window_id = window_id;
  595. ke.macos_state = [event modifierFlags];
  596. ke.pressed = false;
  597. ke.echo = [event isARepeat];
  598. ke.keycode = KeyMappingMacOS::remap_key([event keyCode], [event modifierFlags], false);
  599. ke.physical_keycode = KeyMappingMacOS::translate_key([event keyCode]);
  600. ke.key_label = KeyMappingMacOS::remap_key([event keyCode], [event modifierFlags], true);
  601. ke.unicode = 0;
  602. ke.location = KeyMappingMacOS::translate_location([event keyCode]);
  603. ke.raw = true;
  604. ds->push_to_key_event_buffer(ke);
  605. }
  606. }
  607. // MARK: Scroll and pan
  608. - (void)processScrollEvent:(NSEvent *)event button:(MouseButton)button factor:(double)factor {
  609. DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
  610. if (!ds || !ds->has_window(window_id)) {
  611. return;
  612. }
  613. DisplayServerMacOS::WindowData &wd = ds->get_window(window_id);
  614. MouseButtonMask mask = mouse_button_to_mask(button);
  615. BitField<MouseButtonMask> last_button_state = ds->mouse_get_button_state();
  616. Ref<InputEventMouseButton> sc;
  617. sc.instantiate();
  618. sc->set_window_id(window_id);
  619. ds->get_key_modifier_state([event modifierFlags], sc);
  620. sc->set_button_index(button);
  621. sc->set_factor(factor);
  622. sc->set_pressed(true);
  623. sc->set_position(wd.mouse_pos);
  624. sc->set_global_position(wd.mouse_pos);
  625. last_button_state.set_flag(mask);
  626. sc->set_button_mask(last_button_state);
  627. ds->mouse_set_button_state(last_button_state);
  628. Input::get_singleton()->parse_input_event(sc);
  629. sc.instantiate();
  630. sc->set_window_id(window_id);
  631. sc->set_button_index(button);
  632. sc->set_factor(factor);
  633. sc->set_pressed(false);
  634. sc->set_position(wd.mouse_pos);
  635. sc->set_global_position(wd.mouse_pos);
  636. last_button_state.clear_flag(mask);
  637. sc->set_button_mask(last_button_state);
  638. ds->mouse_set_button_state(last_button_state);
  639. Input::get_singleton()->parse_input_event(sc);
  640. }
  641. - (void)processPanEvent:(NSEvent *)event dx:(double)dx dy:(double)dy {
  642. DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
  643. if (!ds || !ds->has_window(window_id)) {
  644. return;
  645. }
  646. DisplayServerMacOS::WindowData &wd = ds->get_window(window_id);
  647. Ref<InputEventPanGesture> pg;
  648. pg.instantiate();
  649. pg->set_window_id(window_id);
  650. ds->get_key_modifier_state([event modifierFlags], pg);
  651. pg->set_position(wd.mouse_pos);
  652. pg->set_delta(Vector2(-dx, -dy));
  653. Input::get_singleton()->parse_input_event(pg);
  654. }
  655. - (void)scrollWheel:(NSEvent *)event {
  656. DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
  657. if (!ds || !ds->has_window(window_id)) {
  658. return;
  659. }
  660. DisplayServerMacOS::WindowData &wd = ds->get_window(window_id);
  661. ds->update_mouse_pos(wd, [event locationInWindow]);
  662. double delta_x = [event scrollingDeltaX];
  663. double delta_y = [event scrollingDeltaY];
  664. if ([event hasPreciseScrollingDeltas]) {
  665. delta_x *= 0.03;
  666. delta_y *= 0.03;
  667. }
  668. if ([event momentumPhase] != NSEventPhaseNone) {
  669. if (ignore_momentum_scroll) {
  670. return;
  671. }
  672. } else {
  673. ignore_momentum_scroll = false;
  674. }
  675. if ([event phase] != NSEventPhaseNone || [event momentumPhase] != NSEventPhaseNone) {
  676. [self processPanEvent:event dx:delta_x dy:delta_y];
  677. } else {
  678. if (fabs(delta_x)) {
  679. [self processScrollEvent:event button:(0 > delta_x ? MouseButton::WHEEL_RIGHT : MouseButton::WHEEL_LEFT) factor:fabs(delta_x * 0.3)];
  680. }
  681. if (fabs(delta_y)) {
  682. [self processScrollEvent:event button:(0 < delta_y ? MouseButton::WHEEL_UP : MouseButton::WHEEL_DOWN) factor:fabs(delta_y * 0.3)];
  683. }
  684. }
  685. }
  686. @end