The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2651 lines
99KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 6 End-User License
  8. Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
  9. End User License Agreement: www.juce.com/juce-6-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. @interface NSEvent (DeviceDelta)
  19. - (float)deviceDeltaX;
  20. - (float)deviceDeltaY;
  21. @end
  22. //==============================================================================
  23. namespace juce
  24. {
  25. typedef void (*AppFocusChangeCallback)();
  26. extern AppFocusChangeCallback appFocusChangeCallback;
  27. typedef bool (*CheckEventBlockedByModalComps) (NSEvent*);
  28. extern CheckEventBlockedByModalComps isEventBlockedByModalComps;
  29. }
  30. namespace juce
  31. {
  32. //==============================================================================
  33. static constexpr int translateVirtualToAsciiKeyCode (int keyCode) noexcept
  34. {
  35. switch (keyCode)
  36. {
  37. // The virtual keycodes are from HIToolbox/Events.h
  38. case 0x00: return 'A';
  39. case 0x01: return 'S';
  40. case 0x02: return 'D';
  41. case 0x03: return 'F';
  42. case 0x04: return 'H';
  43. case 0x05: return 'G';
  44. case 0x06: return 'Z';
  45. case 0x07: return 'X';
  46. case 0x08: return 'C';
  47. case 0x09: return 'V';
  48. case 0x0B: return 'B';
  49. case 0x0C: return 'Q';
  50. case 0x0D: return 'W';
  51. case 0x0E: return 'E';
  52. case 0x0F: return 'R';
  53. case 0x10: return 'Y';
  54. case 0x11: return 'T';
  55. case 0x12: return '1';
  56. case 0x13: return '2';
  57. case 0x14: return '3';
  58. case 0x15: return '4';
  59. case 0x16: return '6';
  60. case 0x17: return '5';
  61. case 0x18: return '='; // kVK_ANSI_Equal
  62. case 0x19: return '9';
  63. case 0x1A: return '7';
  64. case 0x1B: return '-'; // kVK_ANSI_Minus
  65. case 0x1C: return '8';
  66. case 0x1D: return '0';
  67. case 0x1E: return ']'; // kVK_ANSI_RightBracket
  68. case 0x1F: return 'O';
  69. case 0x20: return 'U';
  70. case 0x21: return '['; // kVK_ANSI_LeftBracket
  71. case 0x22: return 'I';
  72. case 0x23: return 'P';
  73. case 0x25: return 'L';
  74. case 0x26: return 'J';
  75. case 0x27: return '"'; // kVK_ANSI_Quote
  76. case 0x28: return 'K';
  77. case 0x29: return ';'; // kVK_ANSI_Semicolon
  78. case 0x2A: return '\\'; // kVK_ANSI_Backslash
  79. case 0x2B: return ','; // kVK_ANSI_Comma
  80. case 0x2C: return '/'; // kVK_ANSI_Slash
  81. case 0x2D: return 'N';
  82. case 0x2E: return 'M';
  83. case 0x2F: return '.'; // kVK_ANSI_Period
  84. case 0x32: return '`'; // kVK_ANSI_Grave
  85. default: return keyCode;
  86. }
  87. }
  88. constexpr int extendedKeyModifier = 0x30000;
  89. //==============================================================================
  90. class NSViewComponentPeer : public ComponentPeer,
  91. private Timer
  92. {
  93. public:
  94. NSViewComponentPeer (Component& comp, const int windowStyleFlags, NSView* viewToAttachTo)
  95. : ComponentPeer (comp, windowStyleFlags),
  96. safeComponent (&comp),
  97. isSharedWindow (viewToAttachTo != nil),
  98. lastRepaintTime (Time::getMillisecondCounter())
  99. {
  100. appFocusChangeCallback = appFocusChanged;
  101. isEventBlockedByModalComps = checkEventBlockedByModalComps;
  102. auto r = makeNSRect (component.getLocalBounds());
  103. view = [createViewInstance() initWithFrame: r];
  104. setOwner (view, this);
  105. [view registerForDraggedTypes: getSupportedDragTypes()];
  106. const auto options = NSTrackingMouseEnteredAndExited
  107. | NSTrackingMouseMoved
  108. | NSTrackingEnabledDuringMouseDrag
  109. | NSTrackingActiveAlways
  110. | NSTrackingInVisibleRect;
  111. [view addTrackingArea: [[NSTrackingArea alloc] initWithRect: r
  112. options: options
  113. owner: view
  114. userInfo: nil]];
  115. notificationCenter = [NSNotificationCenter defaultCenter];
  116. [notificationCenter addObserver: view
  117. selector: frameChangedSelector
  118. name: NSViewFrameDidChangeNotification
  119. object: view];
  120. [view setPostsFrameChangedNotifications: YES];
  121. #if USE_COREGRAPHICS_RENDERING && JUCE_COREGRAPHICS_DRAW_ASYNC
  122. if (! getComponentAsyncLayerBackedViewDisabled (component))
  123. {
  124. if (@available (macOS 10.8, *))
  125. {
  126. [view setWantsLayer: YES];
  127. [[view layer] setDrawsAsynchronously: YES];
  128. }
  129. }
  130. #endif
  131. if (isSharedWindow)
  132. {
  133. window = [viewToAttachTo window];
  134. [viewToAttachTo addSubview: view];
  135. }
  136. else
  137. {
  138. r.origin.x = (CGFloat) component.getX();
  139. r.origin.y = (CGFloat) component.getY();
  140. r = flippedScreenRect (r);
  141. window = [createWindowInstance() initWithContentRect: r
  142. styleMask: getNSWindowStyleMask (windowStyleFlags)
  143. backing: NSBackingStoreBuffered
  144. defer: YES];
  145. setOwner (window, this);
  146. if (@available (macOS 10.10, *))
  147. [window setAccessibilityElement: YES];
  148. [window orderOut: nil];
  149. [window setDelegate: (id<NSWindowDelegate>) window];
  150. [window setOpaque: component.isOpaque()];
  151. if (! [window isOpaque])
  152. [window setBackgroundColor: [NSColor clearColor]];
  153. if (@available (macOS 10.9, *))
  154. [view setAppearance: [NSAppearance appearanceNamed: NSAppearanceNameAqua]];
  155. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  156. if (component.isAlwaysOnTop())
  157. setAlwaysOnTop (true);
  158. [window setContentView: view];
  159. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  160. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  161. [window setReleasedWhenClosed: YES];
  162. [window retain];
  163. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  164. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  165. if ((windowStyleFlags & windowHasMaximiseButton) == windowHasMaximiseButton)
  166. [window setCollectionBehavior: NSWindowCollectionBehaviorFullScreenPrimary];
  167. [window setRestorable: NO];
  168. #if defined (MAC_OS_X_VERSION_10_12) && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_12)
  169. if (@available (macOS 10.12, *))
  170. [window setTabbingMode: NSWindowTabbingModeDisallowed];
  171. #endif
  172. [notificationCenter addObserver: view
  173. selector: frameChangedSelector
  174. name: NSWindowDidMoveNotification
  175. object: window];
  176. [notificationCenter addObserver: view
  177. selector: frameChangedSelector
  178. name: NSWindowDidMiniaturizeNotification
  179. object: window];
  180. [notificationCenter addObserver: view
  181. selector: @selector (windowWillMiniaturize:)
  182. name: NSWindowWillMiniaturizeNotification
  183. object: window];
  184. [notificationCenter addObserver: view
  185. selector: @selector (windowDidDeminiaturize:)
  186. name: NSWindowDidDeminiaturizeNotification
  187. object: window];
  188. }
  189. auto alpha = component.getAlpha();
  190. if (alpha < 1.0f)
  191. setAlpha (alpha);
  192. setTitle (component.getName());
  193. getNativeRealtimeModifiers = []
  194. {
  195. if ([NSEvent respondsToSelector: @selector (modifierFlags)])
  196. NSViewComponentPeer::updateModifiers ([NSEvent modifierFlags]);
  197. return ModifierKeys::currentModifiers;
  198. };
  199. }
  200. ~NSViewComponentPeer() override
  201. {
  202. [notificationCenter removeObserver: view];
  203. setOwner (view, nullptr);
  204. if ([view superview] != nil)
  205. {
  206. redirectWillMoveToWindow (nullptr);
  207. [view removeFromSuperview];
  208. }
  209. if (! isSharedWindow)
  210. {
  211. setOwner (window, nullptr);
  212. [window setContentView: nil];
  213. [window close];
  214. [window release];
  215. }
  216. [view release];
  217. }
  218. //==============================================================================
  219. void* getNativeHandle() const override { return view; }
  220. void setVisible (bool shouldBeVisible) override
  221. {
  222. if (isSharedWindow)
  223. {
  224. if (shouldBeVisible)
  225. [view setHidden: false];
  226. else if ([window firstResponder] != view || ([window firstResponder] == view && [window makeFirstResponder: nil]))
  227. [view setHidden: true];
  228. }
  229. else
  230. {
  231. if (shouldBeVisible)
  232. {
  233. ++insideToFrontCall;
  234. [window orderFront: nil];
  235. --insideToFrontCall;
  236. handleBroughtToFront();
  237. }
  238. else
  239. {
  240. [window orderOut: nil];
  241. }
  242. }
  243. }
  244. void setTitle (const String& title) override
  245. {
  246. JUCE_AUTORELEASEPOOL
  247. {
  248. if (! isSharedWindow)
  249. [window setTitle: juceStringToNS (title)];
  250. }
  251. }
  252. bool setDocumentEditedStatus (bool edited) override
  253. {
  254. if (! hasNativeTitleBar())
  255. return false;
  256. [window setDocumentEdited: edited];
  257. return true;
  258. }
  259. void setRepresentedFile (const File& file) override
  260. {
  261. if (! isSharedWindow)
  262. {
  263. [window setRepresentedFilename: juceStringToNS (file != File()
  264. ? file.getFullPathName()
  265. : String())];
  266. windowRepresentsFile = (file != File());
  267. }
  268. }
  269. void setBounds (const Rectangle<int>& newBounds, bool) override
  270. {
  271. auto r = makeNSRect (newBounds);
  272. auto oldViewSize = [view frame].size;
  273. if (isSharedWindow)
  274. {
  275. [view setFrame: r];
  276. }
  277. else
  278. {
  279. // Repaint behaviour of setFrame seemed to change in 10.11, and the drawing became synchronous,
  280. // causing performance issues. But sending an async update causes flickering in older versions,
  281. // hence this version check to use the old behaviour on pre 10.11 machines
  282. static bool isPre10_11 = SystemStats::getOperatingSystemType() <= SystemStats::MacOSX_10_10;
  283. [window setFrame: [window frameRectForContentRect: flippedScreenRect (r)]
  284. display: isPre10_11];
  285. }
  286. if (oldViewSize.width != r.size.width || oldViewSize.height != r.size.height)
  287. [view setNeedsDisplay: true];
  288. }
  289. Rectangle<int> getBounds (const bool global) const
  290. {
  291. auto r = [view frame];
  292. NSWindow* viewWindow = [view window];
  293. if (global && viewWindow != nil)
  294. {
  295. r = [[view superview] convertRect: r toView: nil];
  296. r = [viewWindow convertRectToScreen: r];
  297. r = flippedScreenRect (r);
  298. }
  299. return convertToRectInt (r);
  300. }
  301. Rectangle<int> getBounds() const override
  302. {
  303. return getBounds (! isSharedWindow);
  304. }
  305. Point<float> localToGlobal (Point<float> relativePosition) override
  306. {
  307. return relativePosition + getBounds (true).getPosition().toFloat();
  308. }
  309. using ComponentPeer::localToGlobal;
  310. Point<float> globalToLocal (Point<float> screenPosition) override
  311. {
  312. return screenPosition - getBounds (true).getPosition().toFloat();
  313. }
  314. using ComponentPeer::globalToLocal;
  315. void setAlpha (float newAlpha) override
  316. {
  317. if (isSharedWindow)
  318. [view setAlphaValue: (CGFloat) newAlpha];
  319. else
  320. [window setAlphaValue: (CGFloat) newAlpha];
  321. }
  322. void setMinimised (bool shouldBeMinimised) override
  323. {
  324. if (! isSharedWindow)
  325. {
  326. if (shouldBeMinimised)
  327. [window miniaturize: nil];
  328. else
  329. [window deminiaturize: nil];
  330. }
  331. }
  332. bool isMinimised() const override
  333. {
  334. return [window isMiniaturized];
  335. }
  336. void setFullScreen (bool shouldBeFullScreen) override
  337. {
  338. if (! isSharedWindow)
  339. {
  340. if (isMinimised())
  341. setMinimised (false);
  342. if (hasNativeTitleBar())
  343. {
  344. if (shouldBeFullScreen != isFullScreen())
  345. [window toggleFullScreen: nil];
  346. }
  347. else
  348. {
  349. [window zoom: nil];
  350. }
  351. }
  352. }
  353. bool isFullScreen() const override
  354. {
  355. return ([window styleMask] & NSWindowStyleMaskFullScreen) != 0;
  356. }
  357. bool isKioskMode() const override
  358. {
  359. return isFullScreen() && ComponentPeer::isKioskMode();
  360. }
  361. static bool isWindowAtPoint (NSWindow* w, NSPoint screenPoint)
  362. {
  363. if ([NSWindow respondsToSelector: @selector (windowNumberAtPoint:belowWindowWithWindowNumber:)])
  364. return [NSWindow windowNumberAtPoint: screenPoint belowWindowWithWindowNumber: 0] == [w windowNumber];
  365. return true;
  366. }
  367. bool contains (Point<int> localPos, bool trueIfInAChildWindow) const override
  368. {
  369. NSRect viewFrame = [view frame];
  370. if (! (isPositiveAndBelow (localPos.getX(), viewFrame.size.width)
  371. && isPositiveAndBelow (localPos.getY(), viewFrame.size.height)))
  372. return false;
  373. if (! SystemStats::isRunningInAppExtensionSandbox())
  374. {
  375. if (NSWindow* const viewWindow = [view window])
  376. {
  377. NSRect windowFrame = [viewWindow frame];
  378. NSPoint windowPoint = [view convertPoint: NSMakePoint (localPos.x, localPos.y) toView: nil];
  379. NSPoint screenPoint = NSMakePoint (windowFrame.origin.x + windowPoint.x,
  380. windowFrame.origin.y + windowPoint.y);
  381. if (! isWindowAtPoint (viewWindow, screenPoint))
  382. return false;
  383. }
  384. }
  385. NSView* v = [view hitTest: NSMakePoint (viewFrame.origin.x + localPos.getX(),
  386. viewFrame.origin.y + localPos.getY())];
  387. return trueIfInAChildWindow ? (v != nil)
  388. : (v == view);
  389. }
  390. BorderSize<int> getFrameSize() const override
  391. {
  392. BorderSize<int> b;
  393. if (! isSharedWindow)
  394. {
  395. NSRect v = [view convertRect: [view frame] toView: nil];
  396. NSRect w = [window frame];
  397. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  398. b.setBottom ((int) v.origin.y);
  399. b.setLeft ((int) v.origin.x);
  400. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  401. }
  402. return b;
  403. }
  404. bool hasNativeTitleBar() const
  405. {
  406. return (getStyleFlags() & windowHasTitleBar) != 0;
  407. }
  408. bool setAlwaysOnTop (bool alwaysOnTop) override
  409. {
  410. if (! isSharedWindow)
  411. {
  412. [window setLevel: alwaysOnTop ? ((getStyleFlags() & windowIsTemporary) != 0 ? NSPopUpMenuWindowLevel
  413. : NSFloatingWindowLevel)
  414. : NSNormalWindowLevel];
  415. isAlwaysOnTop = alwaysOnTop;
  416. }
  417. return true;
  418. }
  419. void toFront (bool makeActiveWindow) override
  420. {
  421. if (isSharedWindow)
  422. {
  423. NSView* superview = [view superview];
  424. NSMutableArray* subviews = [NSMutableArray arrayWithArray: [superview subviews]];
  425. const auto isFrontmost = [[subviews lastObject] isEqual: view];
  426. if (! isFrontmost)
  427. {
  428. [view retain];
  429. [subviews removeObject: view];
  430. [subviews addObject: view];
  431. [superview setSubviews: subviews];
  432. [view release];
  433. }
  434. }
  435. if (window != nil && component.isVisible())
  436. {
  437. ++insideToFrontCall;
  438. if (makeActiveWindow)
  439. [window makeKeyAndOrderFront: nil];
  440. else
  441. [window orderFront: nil];
  442. if (insideToFrontCall <= 1)
  443. {
  444. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  445. handleBroughtToFront();
  446. }
  447. --insideToFrontCall;
  448. }
  449. }
  450. void toBehind (ComponentPeer* other) override
  451. {
  452. if (auto* otherPeer = dynamic_cast<NSViewComponentPeer*> (other))
  453. {
  454. if (isSharedWindow)
  455. {
  456. NSView* superview = [view superview];
  457. NSMutableArray* subviews = [NSMutableArray arrayWithArray: [superview subviews]];
  458. const auto otherViewIndex = [subviews indexOfObject: otherPeer->view];
  459. if (otherViewIndex == NSNotFound)
  460. return;
  461. const auto isBehind = [subviews indexOfObject: view] < otherViewIndex;
  462. if (! isBehind)
  463. {
  464. [view retain];
  465. [subviews removeObject: view];
  466. [subviews insertObject: view
  467. atIndex: otherViewIndex];
  468. [superview setSubviews: subviews];
  469. [view release];
  470. }
  471. }
  472. else if (component.isVisible())
  473. {
  474. [window orderWindow: NSWindowBelow
  475. relativeTo: [otherPeer->window windowNumber]];
  476. }
  477. }
  478. else
  479. {
  480. jassertfalse; // wrong type of window?
  481. }
  482. }
  483. void setIcon (const Image& newIcon) override
  484. {
  485. if (! isSharedWindow)
  486. {
  487. // need to set a dummy represented file here to show the file icon (which we then set to the new icon)
  488. if (! windowRepresentsFile)
  489. [window setRepresentedFilename: juceStringToNS (" ")]; // can't just use an empty string for some reason...
  490. auto img = NSUniquePtr<NSImage> { imageToNSImage (ScaledImage (newIcon)) };
  491. [[window standardWindowButton: NSWindowDocumentIconButton] setImage: img.get()];
  492. }
  493. }
  494. StringArray getAvailableRenderingEngines() override
  495. {
  496. StringArray s ("Software Renderer");
  497. #if USE_COREGRAPHICS_RENDERING
  498. s.add ("CoreGraphics Renderer");
  499. #endif
  500. return s;
  501. }
  502. int getCurrentRenderingEngine() const override
  503. {
  504. return usingCoreGraphics ? 1 : 0;
  505. }
  506. void setCurrentRenderingEngine (int index) override
  507. {
  508. #if USE_COREGRAPHICS_RENDERING
  509. if (usingCoreGraphics != (index > 0))
  510. {
  511. usingCoreGraphics = index > 0;
  512. [view setNeedsDisplay: true];
  513. }
  514. #else
  515. ignoreUnused (index);
  516. #endif
  517. }
  518. void redirectMouseDown (NSEvent* ev)
  519. {
  520. if (! Process::isForegroundProcess())
  521. Process::makeForegroundProcess();
  522. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  523. sendMouseEvent (ev);
  524. }
  525. void redirectMouseUp (NSEvent* ev)
  526. {
  527. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  528. sendMouseEvent (ev);
  529. showArrowCursorIfNeeded();
  530. }
  531. void redirectMouseDrag (NSEvent* ev)
  532. {
  533. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  534. sendMouseEvent (ev);
  535. }
  536. void redirectMouseMove (NSEvent* ev)
  537. {
  538. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons();
  539. NSPoint windowPos = [ev locationInWindow];
  540. NSPoint screenPos = [[ev window] convertRectToScreen: NSMakeRect (windowPos.x, windowPos.y, 1.0f, 1.0f)].origin;
  541. if (isWindowAtPoint ([ev window], screenPos))
  542. sendMouseEvent (ev);
  543. else
  544. // moved into another window which overlaps this one, so trigger an exit
  545. handleMouseEvent (MouseInputSource::InputSourceType::mouse, MouseInputSource::offscreenMousePos, ModifierKeys::currentModifiers,
  546. getMousePressure (ev), MouseInputSource::invalidOrientation, getMouseTime (ev));
  547. showArrowCursorIfNeeded();
  548. }
  549. void redirectMouseEnter (NSEvent* ev)
  550. {
  551. sendMouseEnterExit (ev);
  552. }
  553. void redirectMouseExit (NSEvent* ev)
  554. {
  555. sendMouseEnterExit (ev);
  556. }
  557. static float checkDeviceDeltaReturnValue (float v) noexcept
  558. {
  559. // (deviceDeltaX can fail and return NaN, so need to sanity-check the result)
  560. v *= 0.5f / 256.0f;
  561. return (v > -1000.0f && v < 1000.0f) ? v : 0.0f;
  562. }
  563. void redirectMouseWheel (NSEvent* ev)
  564. {
  565. updateModifiers (ev);
  566. MouseWheelDetails wheel;
  567. wheel.deltaX = 0;
  568. wheel.deltaY = 0;
  569. wheel.isReversed = false;
  570. wheel.isSmooth = false;
  571. wheel.isInertial = false;
  572. @try
  573. {
  574. if ([ev respondsToSelector: @selector (isDirectionInvertedFromDevice)])
  575. wheel.isReversed = [ev isDirectionInvertedFromDevice];
  576. wheel.isInertial = ([ev momentumPhase] != NSEventPhaseNone);
  577. if ([ev respondsToSelector: @selector (hasPreciseScrollingDeltas)])
  578. {
  579. if ([ev hasPreciseScrollingDeltas])
  580. {
  581. const float scale = 0.5f / 256.0f;
  582. wheel.deltaX = scale * (float) [ev scrollingDeltaX];
  583. wheel.deltaY = scale * (float) [ev scrollingDeltaY];
  584. wheel.isSmooth = true;
  585. }
  586. }
  587. else if ([ev respondsToSelector: @selector (deviceDeltaX)])
  588. {
  589. wheel.deltaX = checkDeviceDeltaReturnValue ([ev deviceDeltaX]);
  590. wheel.deltaY = checkDeviceDeltaReturnValue ([ev deviceDeltaY]);
  591. }
  592. }
  593. @catch (...)
  594. {}
  595. if (wheel.deltaX == 0.0f && wheel.deltaY == 0.0f)
  596. {
  597. const float scale = 10.0f / 256.0f;
  598. wheel.deltaX = scale * (float) [ev deltaX];
  599. wheel.deltaY = scale * (float) [ev deltaY];
  600. }
  601. handleMouseWheel (MouseInputSource::InputSourceType::mouse, getMousePos (ev, view), getMouseTime (ev), wheel);
  602. }
  603. void redirectMagnify (NSEvent* ev)
  604. {
  605. const float invScale = 1.0f - (float) [ev magnification];
  606. if (invScale > 0.0f)
  607. handleMagnifyGesture (MouseInputSource::InputSourceType::mouse, getMousePos (ev, view), getMouseTime (ev), 1.0f / invScale);
  608. }
  609. void redirectCopy (NSObject*) { handleKeyPress (KeyPress ('c', ModifierKeys (ModifierKeys::commandModifier), 'c')); }
  610. void redirectPaste (NSObject*) { handleKeyPress (KeyPress ('v', ModifierKeys (ModifierKeys::commandModifier), 'v')); }
  611. void redirectCut (NSObject*) { handleKeyPress (KeyPress ('x', ModifierKeys (ModifierKeys::commandModifier), 'x')); }
  612. void redirectSelectAll (NSObject*) { handleKeyPress (KeyPress ('a', ModifierKeys (ModifierKeys::commandModifier), 'a')); }
  613. void redirectWillMoveToWindow (NSWindow* newWindow)
  614. {
  615. if (auto* currentWindow = [view window])
  616. {
  617. [notificationCenter removeObserver: view
  618. name: NSWindowDidMoveNotification
  619. object: currentWindow];
  620. [notificationCenter removeObserver: view
  621. name: NSWindowWillMiniaturizeNotification
  622. object: currentWindow];
  623. #if JUCE_COREGRAPHICS_DRAW_ASYNC
  624. [notificationCenter removeObserver: view
  625. name: NSWindowDidBecomeKeyNotification
  626. object: currentWindow];
  627. #endif
  628. }
  629. if (isSharedWindow && [view window] == window && newWindow == nullptr)
  630. {
  631. if (auto* comp = safeComponent.get())
  632. comp->setVisible (false);
  633. }
  634. }
  635. void sendMouseEvent (NSEvent* ev)
  636. {
  637. updateModifiers (ev);
  638. handleMouseEvent (MouseInputSource::InputSourceType::mouse, getMousePos (ev, view), ModifierKeys::currentModifiers,
  639. getMousePressure (ev), MouseInputSource::invalidOrientation, getMouseTime (ev));
  640. }
  641. bool handleKeyEvent (NSEvent* ev, bool isKeyDown)
  642. {
  643. auto unicode = nsStringToJuce ([ev characters]);
  644. auto keyCode = getKeyCodeFromEvent (ev);
  645. #if JUCE_DEBUG_KEYCODES
  646. DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  647. auto unmodified = nsStringToJuce ([ev charactersIgnoringModifiers]);
  648. DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  649. #endif
  650. if (keyCode != 0 || unicode.isNotEmpty())
  651. {
  652. if (isKeyDown)
  653. {
  654. bool used = false;
  655. for (auto u = unicode.getCharPointer(); ! u.isEmpty();)
  656. {
  657. auto textCharacter = u.getAndAdvance();
  658. switch (keyCode)
  659. {
  660. case NSLeftArrowFunctionKey:
  661. case NSRightArrowFunctionKey:
  662. case NSUpArrowFunctionKey:
  663. case NSDownArrowFunctionKey:
  664. case NSPageUpFunctionKey:
  665. case NSPageDownFunctionKey:
  666. case NSEndFunctionKey:
  667. case NSHomeFunctionKey:
  668. case NSDeleteFunctionKey:
  669. textCharacter = 0;
  670. break; // (these all seem to generate unwanted garbage unicode strings)
  671. default:
  672. if (([ev modifierFlags] & NSEventModifierFlagCommand) != 0
  673. || (keyCode >= NSF1FunctionKey && keyCode <= NSF35FunctionKey))
  674. textCharacter = 0;
  675. break;
  676. }
  677. used = handleKeyUpOrDown (true) || used;
  678. used = handleKeyPress (keyCode, textCharacter) || used;
  679. }
  680. return used;
  681. }
  682. if (handleKeyUpOrDown (false))
  683. return true;
  684. }
  685. return false;
  686. }
  687. bool redirectKeyDown (NSEvent* ev)
  688. {
  689. // (need to retain this in case a modal loop runs in handleKeyEvent and
  690. // our event object gets lost)
  691. const NSUniquePtr<NSEvent> r ([ev retain]);
  692. updateKeysDown (ev, true);
  693. bool used = handleKeyEvent (ev, true);
  694. if (([ev modifierFlags] & NSEventModifierFlagCommand) != 0)
  695. {
  696. // for command keys, the key-up event is thrown away, so simulate one..
  697. updateKeysDown (ev, false);
  698. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  699. }
  700. // (If we're running modally, don't allow unused keystrokes to be passed
  701. // along to other blocked views..)
  702. if (Component::getCurrentlyModalComponent() != nullptr)
  703. used = true;
  704. return used;
  705. }
  706. bool redirectKeyUp (NSEvent* ev)
  707. {
  708. updateKeysDown (ev, false);
  709. return handleKeyEvent (ev, false)
  710. || Component::getCurrentlyModalComponent() != nullptr;
  711. }
  712. void redirectModKeyChange (NSEvent* ev)
  713. {
  714. // (need to retain this in case a modal loop runs and our event object gets lost)
  715. const NSUniquePtr<NSEvent> r ([ev retain]);
  716. keysCurrentlyDown.clear();
  717. handleKeyUpOrDown (true);
  718. updateModifiers (ev);
  719. handleModifierKeysChange();
  720. }
  721. //==============================================================================
  722. void drawRect (NSRect r)
  723. {
  724. if (r.size.width < 1.0f || r.size.height < 1.0f)
  725. return;
  726. auto cg = []
  727. {
  728. if (@available (macOS 10.10, *))
  729. return (CGContextRef) [[NSGraphicsContext currentContext] CGContext];
  730. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
  731. return (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  732. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  733. }();
  734. if (! component.isOpaque())
  735. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  736. float displayScale = 1.0f;
  737. NSScreen* screen = [[view window] screen];
  738. if ([screen respondsToSelector: @selector (backingScaleFactor)])
  739. displayScale = (float) screen.backingScaleFactor;
  740. auto invalidateTransparentWindowShadow = [this]
  741. {
  742. // transparent NSWindows with a drop-shadow need to redraw their shadow when the content
  743. // changes to avoid stale shadows being drawn behind the window
  744. if (! isSharedWindow && ! [window isOpaque] && [window hasShadow])
  745. [window invalidateShadow];
  746. };
  747. #if USE_COREGRAPHICS_RENDERING && JUCE_COREGRAPHICS_RENDER_WITH_MULTIPLE_PAINT_CALLS
  748. // This option invokes a separate paint call for each rectangle of the clip region.
  749. // It's a long story, but this is a basically a workaround for a CGContext not having
  750. // a way of finding whether a rectangle falls within its clip region
  751. if (usingCoreGraphics)
  752. {
  753. const NSRect* rects = nullptr;
  754. NSInteger numRects = 0;
  755. [view getRectsBeingDrawn: &rects count: &numRects];
  756. if (numRects > 1)
  757. {
  758. for (int i = 0; i < numRects; ++i)
  759. {
  760. NSRect rect = rects[i];
  761. CGContextSaveGState (cg);
  762. CGContextClipToRect (cg, CGRectMake (rect.origin.x, rect.origin.y, rect.size.width, rect.size.height));
  763. drawRectWithContext (cg, rect, displayScale);
  764. CGContextRestoreGState (cg);
  765. }
  766. invalidateTransparentWindowShadow();
  767. return;
  768. }
  769. }
  770. #endif
  771. drawRectWithContext (cg, r, displayScale);
  772. invalidateTransparentWindowShadow();
  773. }
  774. void drawRectWithContext (CGContextRef cg, NSRect r, float displayScale)
  775. {
  776. #if USE_COREGRAPHICS_RENDERING
  777. if (usingCoreGraphics)
  778. {
  779. const auto height = getComponent().getHeight();
  780. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, height));
  781. CoreGraphicsContext context (cg, (float) height);
  782. handlePaint (context);
  783. }
  784. else
  785. #endif
  786. {
  787. const Point<int> offset (-roundToInt (r.origin.x), -roundToInt (r.origin.y));
  788. auto clipW = (int) (r.size.width + 0.5f);
  789. auto clipH = (int) (r.size.height + 0.5f);
  790. RectangleList<int> clip;
  791. getClipRects (clip, offset, clipW, clipH);
  792. if (! clip.isEmpty())
  793. {
  794. Image temp (component.isOpaque() ? Image::RGB : Image::ARGB,
  795. roundToInt (clipW * displayScale),
  796. roundToInt (clipH * displayScale),
  797. ! component.isOpaque());
  798. {
  799. auto intScale = roundToInt (displayScale);
  800. if (intScale != 1)
  801. clip.scaleAll (intScale);
  802. auto context = component.getLookAndFeel()
  803. .createGraphicsContext (temp, offset * intScale, clip);
  804. if (intScale != 1)
  805. context->addTransform (AffineTransform::scale (displayScale));
  806. handlePaint (*context);
  807. }
  808. detail::ColorSpacePtr colourSpace { CGColorSpaceCreateWithName (kCGColorSpaceSRGB) };
  809. CGImageRef image = juce_createCoreGraphicsImage (temp, colourSpace.get());
  810. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, r.origin.x, r.origin.y + clipH));
  811. CGContextDrawImage (cg, CGRectMake (0.0f, 0.0f, clipW, clipH), image);
  812. CGImageRelease (image);
  813. }
  814. }
  815. }
  816. void repaint (const Rectangle<int>& area) override
  817. {
  818. // In 10.11 changes were made to the way the OS handles repaint regions, and it seems that it can
  819. // no longer be trusted to coalesce all the regions, or to even remember them all without losing
  820. // a few when there's a lot of activity.
  821. // As a work around for this, we use a RectangleList to do our own coalescing of regions before
  822. // asynchronously asking the OS to repaint them.
  823. deferredRepaints.add ((float) area.getX(), (float) area.getY(),
  824. (float) area.getWidth(), (float) area.getHeight());
  825. if (isTimerRunning())
  826. return;
  827. auto now = Time::getMillisecondCounter();
  828. auto msSinceLastRepaint = (lastRepaintTime >= now) ? now - lastRepaintTime
  829. : (std::numeric_limits<uint32>::max() - lastRepaintTime) + now;
  830. static uint32 minimumRepaintInterval = 1000 / 30; // 30fps
  831. // When windows are being resized, artificially throttling high-frequency repaints helps
  832. // to stop the event queue getting clogged, and keeps everything working smoothly.
  833. // For some reason Logic also needs this throttling to record parameter events correctly.
  834. if (msSinceLastRepaint < minimumRepaintInterval && shouldThrottleRepaint())
  835. {
  836. startTimer (static_cast<int> (minimumRepaintInterval - msSinceLastRepaint));
  837. return;
  838. }
  839. setNeedsDisplayRectangles();
  840. }
  841. static bool shouldThrottleRepaint()
  842. {
  843. return areAnyWindowsInLiveResize() || ! JUCEApplication::isStandaloneApp();
  844. }
  845. void timerCallback() override
  846. {
  847. setNeedsDisplayRectangles();
  848. stopTimer();
  849. }
  850. void setNeedsDisplayRectangles()
  851. {
  852. for (auto& i : deferredRepaints)
  853. [view setNeedsDisplayInRect: makeNSRect (i)];
  854. lastRepaintTime = Time::getMillisecondCounter();
  855. deferredRepaints.clear();
  856. }
  857. void performAnyPendingRepaintsNow() override
  858. {
  859. [view displayIfNeeded];
  860. }
  861. static bool areAnyWindowsInLiveResize() noexcept
  862. {
  863. for (NSWindow* w in [NSApp windows])
  864. if ([w inLiveResize])
  865. return true;
  866. return false;
  867. }
  868. //==============================================================================
  869. bool isBlockedByModalComponent()
  870. {
  871. if (auto* modal = Component::getCurrentlyModalComponent())
  872. {
  873. if (insideToFrontCall == 0
  874. && (! getComponent().isParentOf (modal))
  875. && getComponent().isCurrentlyBlockedByAnotherModalComponent())
  876. {
  877. return true;
  878. }
  879. }
  880. return false;
  881. }
  882. void sendModalInputAttemptIfBlocked()
  883. {
  884. if (isBlockedByModalComponent())
  885. if (auto* modal = Component::getCurrentlyModalComponent())
  886. if (auto* otherPeer = modal->getPeer())
  887. if ((otherPeer->getStyleFlags() & ComponentPeer::windowIsTemporary) != 0)
  888. modal->inputAttemptWhenModal();
  889. }
  890. bool canBecomeKeyWindow()
  891. {
  892. return component.isVisible() && (getStyleFlags() & ComponentPeer::windowIgnoresKeyPresses) == 0;
  893. }
  894. bool canBecomeMainWindow()
  895. {
  896. return component.isVisible() && dynamic_cast<ResizableWindow*> (&component) != nullptr;
  897. }
  898. bool worksWhenModal() const
  899. {
  900. // In plugins, the host could put our plugin window inside a modal window, so this
  901. // allows us to successfully open other popups. Feels like there could be edge-case
  902. // problems caused by this, so let us know if you spot any issues..
  903. return ! JUCEApplication::isStandaloneApp();
  904. }
  905. void becomeKeyWindow()
  906. {
  907. handleBroughtToFront();
  908. grabFocus();
  909. }
  910. void resignKeyWindow()
  911. {
  912. viewFocusLoss();
  913. }
  914. bool windowShouldClose()
  915. {
  916. if (! isValidPeer (this))
  917. return YES;
  918. handleUserClosingWindow();
  919. return NO;
  920. }
  921. void redirectMovedOrResized()
  922. {
  923. handleMovedOrResized();
  924. }
  925. void viewMovedToWindow()
  926. {
  927. if (isSharedWindow)
  928. {
  929. auto newWindow = [view window];
  930. bool shouldSetVisible = (window == nullptr && newWindow != nullptr);
  931. window = newWindow;
  932. if (shouldSetVisible)
  933. getComponent().setVisible (true);
  934. }
  935. if (auto* currentWindow = [view window])
  936. {
  937. [notificationCenter addObserver: view
  938. selector: dismissModalsSelector
  939. name: NSWindowDidMoveNotification
  940. object: currentWindow];
  941. [notificationCenter addObserver: view
  942. selector: dismissModalsSelector
  943. name: NSWindowWillMiniaturizeNotification
  944. object: currentWindow];
  945. [notificationCenter addObserver: view
  946. selector: becomeKeySelector
  947. name: NSWindowDidBecomeKeyNotification
  948. object: currentWindow];
  949. [notificationCenter addObserver: view
  950. selector: resignKeySelector
  951. name: NSWindowDidResignKeyNotification
  952. object: currentWindow];
  953. }
  954. }
  955. void dismissModals()
  956. {
  957. if (hasNativeTitleBar() || isSharedWindow)
  958. sendModalInputAttemptIfBlocked();
  959. }
  960. void becomeKey()
  961. {
  962. component.repaint();
  963. }
  964. void resignKey()
  965. {
  966. viewFocusLoss();
  967. sendModalInputAttemptIfBlocked();
  968. }
  969. void liveResizingStart()
  970. {
  971. if (constrainer == nullptr)
  972. return;
  973. constrainer->resizeStart();
  974. isFirstLiveResize = true;
  975. setFullScreenSizeConstraints (*constrainer);
  976. }
  977. void liveResizingEnd()
  978. {
  979. if (constrainer != nullptr)
  980. constrainer->resizeEnd();
  981. }
  982. NSRect constrainRect (const NSRect r)
  983. {
  984. if (constrainer == nullptr || isKioskMode() || isFullScreen())
  985. return r;
  986. const auto scale = getComponent().getDesktopScaleFactor();
  987. auto pos = ScalingHelpers::unscaledScreenPosToScaled (scale, convertToRectInt (flippedScreenRect (r)));
  988. const auto original = ScalingHelpers::unscaledScreenPosToScaled (scale, convertToRectInt (flippedScreenRect ([window frame])));
  989. const auto screenBounds = Desktop::getInstance().getDisplays().getTotalBounds (true);
  990. const bool inLiveResize = [window inLiveResize];
  991. if (! inLiveResize || isFirstLiveResize)
  992. {
  993. isFirstLiveResize = false;
  994. isStretchingTop = (pos.getY() != original.getY() && pos.getBottom() == original.getBottom());
  995. isStretchingLeft = (pos.getX() != original.getX() && pos.getRight() == original.getRight());
  996. isStretchingBottom = (pos.getY() == original.getY() && pos.getBottom() != original.getBottom());
  997. isStretchingRight = (pos.getX() == original.getX() && pos.getRight() != original.getRight());
  998. }
  999. constrainer->checkBounds (pos, original, screenBounds,
  1000. isStretchingTop, isStretchingLeft, isStretchingBottom, isStretchingRight);
  1001. return flippedScreenRect (makeNSRect (ScalingHelpers::scaledScreenPosToUnscaled (scale, pos)));
  1002. }
  1003. static void showArrowCursorIfNeeded()
  1004. {
  1005. auto& desktop = Desktop::getInstance();
  1006. auto mouse = desktop.getMainMouseSource();
  1007. if (mouse.getComponentUnderMouse() == nullptr
  1008. && desktop.findComponentAt (mouse.getScreenPosition().roundToInt()) == nullptr)
  1009. {
  1010. [[NSCursor arrowCursor] set];
  1011. }
  1012. }
  1013. static void updateModifiers (NSEvent* e)
  1014. {
  1015. updateModifiers ([e modifierFlags]);
  1016. }
  1017. static void updateModifiers (const NSUInteger flags)
  1018. {
  1019. int m = 0;
  1020. if ((flags & NSEventModifierFlagShift) != 0) m |= ModifierKeys::shiftModifier;
  1021. if ((flags & NSEventModifierFlagControl) != 0) m |= ModifierKeys::ctrlModifier;
  1022. if ((flags & NSEventModifierFlagOption) != 0) m |= ModifierKeys::altModifier;
  1023. if ((flags & NSEventModifierFlagCommand) != 0) m |= ModifierKeys::commandModifier;
  1024. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withOnlyMouseButtons().withFlags (m);
  1025. }
  1026. static void updateKeysDown (NSEvent* ev, bool isKeyDown)
  1027. {
  1028. updateModifiers (ev);
  1029. if (auto keyCode = getKeyCodeFromEvent (ev))
  1030. {
  1031. if (isKeyDown)
  1032. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  1033. else
  1034. keysCurrentlyDown.removeFirstMatchingValue (keyCode);
  1035. }
  1036. }
  1037. static int getKeyCodeFromEvent (NSEvent* ev)
  1038. {
  1039. // Unfortunately, charactersIgnoringModifiers does not ignore the shift key.
  1040. // Using [ev keyCode] is not a solution either as this will,
  1041. // for example, return VK_KEY_Y if the key is pressed which
  1042. // is typically located at the Y key position on a QWERTY
  1043. // keyboard. However, on international keyboards this might not
  1044. // be the key labeled Y (for example, on German keyboards this key
  1045. // has a Z label). Therefore, we need to query the current keyboard
  1046. // layout to figure out what character the key would have produced
  1047. // if the shift key was not pressed
  1048. String unmodified;
  1049. #if JUCE_SUPPORT_CARBON
  1050. if (auto currentKeyboard = CFUniquePtr<TISInputSourceRef> (TISCopyCurrentKeyboardInputSource()))
  1051. {
  1052. if (auto layoutData = (CFDataRef) TISGetInputSourceProperty (currentKeyboard,
  1053. kTISPropertyUnicodeKeyLayoutData))
  1054. {
  1055. if (auto* layoutPtr = (const UCKeyboardLayout*) CFDataGetBytePtr (layoutData))
  1056. {
  1057. UInt32 keysDown = 0;
  1058. UniChar buffer[4];
  1059. UniCharCount actual;
  1060. if (UCKeyTranslate (layoutPtr, [ev keyCode], kUCKeyActionDown, 0, LMGetKbdType(),
  1061. kUCKeyTranslateNoDeadKeysBit, &keysDown, sizeof (buffer) / sizeof (UniChar),
  1062. &actual, buffer) == 0)
  1063. unmodified = String (CharPointer_UTF16 (reinterpret_cast<CharPointer_UTF16::CharType*> (buffer)), 4);
  1064. }
  1065. }
  1066. }
  1067. // did the above layout conversion fail
  1068. if (unmodified.isEmpty())
  1069. #endif
  1070. {
  1071. unmodified = nsStringToJuce ([ev charactersIgnoringModifiers]);
  1072. }
  1073. auto keyCode = (int) unmodified[0];
  1074. if (keyCode == 0x19) // (backwards-tab)
  1075. keyCode = '\t';
  1076. else if (keyCode == 0x03) // (enter)
  1077. keyCode = '\r';
  1078. else
  1079. keyCode = (int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  1080. // The purpose of the keyCode is to provide information about non-printing characters to facilitate
  1081. // keyboard control over the application.
  1082. //
  1083. // So when keyCode is decoded as a printing character outside the ASCII range we need to replace it.
  1084. // This holds when the keyCode is larger than 0xff and not part one of the two MacOS specific
  1085. // non-printing ranges.
  1086. if (keyCode > 0xff
  1087. && ! (keyCode >= NSUpArrowFunctionKey && keyCode <= NSModeSwitchFunctionKey)
  1088. && ! (keyCode >= extendedKeyModifier))
  1089. {
  1090. keyCode = translateVirtualToAsciiKeyCode ([ev keyCode]);
  1091. }
  1092. if (([ev modifierFlags] & NSEventModifierFlagNumericPad) != 0)
  1093. {
  1094. const int numPadConversions[] = { '0', KeyPress::numberPad0, '1', KeyPress::numberPad1,
  1095. '2', KeyPress::numberPad2, '3', KeyPress::numberPad3,
  1096. '4', KeyPress::numberPad4, '5', KeyPress::numberPad5,
  1097. '6', KeyPress::numberPad6, '7', KeyPress::numberPad7,
  1098. '8', KeyPress::numberPad8, '9', KeyPress::numberPad9,
  1099. '+', KeyPress::numberPadAdd, '-', KeyPress::numberPadSubtract,
  1100. '*', KeyPress::numberPadMultiply, '/', KeyPress::numberPadDivide,
  1101. '.', KeyPress::numberPadDecimalPoint,
  1102. ',', KeyPress::numberPadDecimalPoint, // (to deal with non-english kbds)
  1103. '=', KeyPress::numberPadEquals };
  1104. for (int i = 0; i < numElementsInArray (numPadConversions); i += 2)
  1105. if (keyCode == numPadConversions [i])
  1106. keyCode = numPadConversions [i + 1];
  1107. }
  1108. return keyCode;
  1109. }
  1110. static int64 getMouseTime (NSEvent* e) noexcept
  1111. {
  1112. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  1113. + (int64) ([e timestamp] * 1000.0);
  1114. }
  1115. static float getMousePressure (NSEvent* e) noexcept
  1116. {
  1117. @try
  1118. {
  1119. if (e.type != NSEventTypeMouseEntered && e.type != NSEventTypeMouseExited)
  1120. return (float) e.pressure;
  1121. }
  1122. @catch (NSException* e) {}
  1123. @finally {}
  1124. return 0.0f;
  1125. }
  1126. static Point<float> getMousePos (NSEvent* e, NSView* view)
  1127. {
  1128. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  1129. return { (float) p.x, (float) p.y };
  1130. }
  1131. static int getModifierForButtonNumber (const NSInteger num)
  1132. {
  1133. return num == 0 ? ModifierKeys::leftButtonModifier
  1134. : (num == 1 ? ModifierKeys::rightButtonModifier
  1135. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  1136. }
  1137. static unsigned int getNSWindowStyleMask (const int flags) noexcept
  1138. {
  1139. unsigned int style = (flags & windowHasTitleBar) != 0 ? NSWindowStyleMaskTitled
  1140. : NSWindowStyleMaskBorderless;
  1141. if ((flags & windowHasMinimiseButton) != 0) style |= NSWindowStyleMaskMiniaturizable;
  1142. if ((flags & windowHasCloseButton) != 0) style |= NSWindowStyleMaskClosable;
  1143. if ((flags & windowIsResizable) != 0) style |= NSWindowStyleMaskResizable;
  1144. return style;
  1145. }
  1146. static NSArray* getSupportedDragTypes()
  1147. {
  1148. const auto type = []
  1149. {
  1150. #if defined (MAC_OS_X_VERSION_10_13) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_13
  1151. if (@available (macOS 10.13, *))
  1152. return NSPasteboardTypeFileURL;
  1153. #endif
  1154. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
  1155. return (NSString*) kUTTypeFileURL;
  1156. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  1157. }();
  1158. return [NSArray arrayWithObjects: type, (NSString*) kPasteboardTypeFileURLPromise, NSPasteboardTypeString, nil];
  1159. }
  1160. BOOL sendDragCallback (const int type, id <NSDraggingInfo> sender)
  1161. {
  1162. NSPasteboard* pasteboard = [sender draggingPasteboard];
  1163. NSString* contentType = [pasteboard availableTypeFromArray: getSupportedDragTypes()];
  1164. if (contentType == nil)
  1165. return false;
  1166. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  1167. ComponentPeer::DragInfo dragInfo;
  1168. dragInfo.position.setXY ((int) p.x, (int) p.y);
  1169. if (contentType == NSPasteboardTypeString)
  1170. dragInfo.text = nsStringToJuce ([pasteboard stringForType: NSPasteboardTypeString]);
  1171. else
  1172. dragInfo.files = getDroppedFiles (pasteboard, contentType);
  1173. if (! dragInfo.isEmpty())
  1174. {
  1175. switch (type)
  1176. {
  1177. case 0: return handleDragMove (dragInfo);
  1178. case 1: return handleDragExit (dragInfo);
  1179. case 2: return handleDragDrop (dragInfo);
  1180. default: jassertfalse; break;
  1181. }
  1182. }
  1183. return false;
  1184. }
  1185. StringArray getDroppedFiles (NSPasteboard* pasteboard, NSString* contentType)
  1186. {
  1187. StringArray files;
  1188. NSString* iTunesPasteboardType = nsStringLiteral ("CorePasteboardFlavorType 0x6974756E"); // 'itun'
  1189. if ([contentType isEqualToString: (NSString*) kPasteboardTypeFileURLPromise]
  1190. && [[pasteboard types] containsObject: iTunesPasteboardType])
  1191. {
  1192. id list = [pasteboard propertyListForType: iTunesPasteboardType];
  1193. if ([list isKindOfClass: [NSDictionary class]])
  1194. {
  1195. NSDictionary* iTunesDictionary = (NSDictionary*) list;
  1196. NSArray* tracks = [iTunesDictionary valueForKey: nsStringLiteral ("Tracks")];
  1197. NSEnumerator* enumerator = [tracks objectEnumerator];
  1198. NSDictionary* track;
  1199. while ((track = [enumerator nextObject]) != nil)
  1200. {
  1201. if (id value = [track valueForKey: nsStringLiteral ("Location")])
  1202. {
  1203. NSURL* url = [NSURL URLWithString: value];
  1204. if ([url isFileURL])
  1205. files.add (nsStringToJuce ([url path]));
  1206. }
  1207. }
  1208. }
  1209. }
  1210. else
  1211. {
  1212. NSArray* items = [pasteboard readObjectsForClasses:@[[NSURL class]] options: nil];
  1213. for (unsigned int i = 0; i < [items count]; ++i)
  1214. {
  1215. NSURL* url = [items objectAtIndex: i];
  1216. if ([url isFileURL])
  1217. files.add (nsStringToJuce ([url path]));
  1218. }
  1219. }
  1220. return files;
  1221. }
  1222. //==============================================================================
  1223. void viewFocusGain()
  1224. {
  1225. if (currentlyFocusedPeer != this)
  1226. {
  1227. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  1228. currentlyFocusedPeer->handleFocusLoss();
  1229. currentlyFocusedPeer = this;
  1230. handleFocusGain();
  1231. }
  1232. }
  1233. void viewFocusLoss()
  1234. {
  1235. if (currentlyFocusedPeer == this)
  1236. {
  1237. currentlyFocusedPeer = nullptr;
  1238. handleFocusLoss();
  1239. }
  1240. }
  1241. bool isFocused() const override
  1242. {
  1243. return (isSharedWindow || ! JUCEApplication::isStandaloneApp())
  1244. ? this == currentlyFocusedPeer
  1245. : [window isKeyWindow];
  1246. }
  1247. void grabFocus() override
  1248. {
  1249. if (window != nil && [window canBecomeKeyWindow])
  1250. {
  1251. [window makeKeyWindow];
  1252. [window makeFirstResponder: view];
  1253. viewFocusGain();
  1254. }
  1255. }
  1256. void textInputRequired (Point<int>, TextInputTarget&) override {}
  1257. void dismissPendingTextInput() override
  1258. {
  1259. stringBeingComposed.clear();
  1260. const auto* inputContext = [NSTextInputContext currentInputContext];
  1261. if (inputContext != nil)
  1262. [inputContext discardMarkedText];
  1263. }
  1264. void resetWindowPresentation()
  1265. {
  1266. if (hasNativeTitleBar())
  1267. {
  1268. [window setStyleMask: (NSViewComponentPeer::getNSWindowStyleMask (getStyleFlags()))];
  1269. setTitle (getComponent().getName()); // required to force the OS to update the title
  1270. }
  1271. [NSApp setPresentationOptions: NSApplicationPresentationDefault];
  1272. }
  1273. void setHasChangedSinceSaved (bool b) override
  1274. {
  1275. if (! isSharedWindow)
  1276. [window setDocumentEdited: b];
  1277. }
  1278. //==============================================================================
  1279. NSWindow* window = nil;
  1280. NSView* view = nil;
  1281. WeakReference<Component> safeComponent;
  1282. bool isSharedWindow = false;
  1283. #if USE_COREGRAPHICS_RENDERING
  1284. bool usingCoreGraphics = true;
  1285. #else
  1286. bool usingCoreGraphics = false;
  1287. #endif
  1288. bool isZooming = false, isFirstLiveResize = false, textWasInserted = false;
  1289. bool isStretchingTop = false, isStretchingLeft = false, isStretchingBottom = false, isStretchingRight = false;
  1290. bool windowRepresentsFile = false;
  1291. bool isAlwaysOnTop = false, wasAlwaysOnTop = false;
  1292. String stringBeingComposed;
  1293. NSNotificationCenter* notificationCenter = nil;
  1294. RectangleList<float> deferredRepaints;
  1295. uint32 lastRepaintTime;
  1296. static ComponentPeer* currentlyFocusedPeer;
  1297. static Array<int> keysCurrentlyDown;
  1298. static int insideToFrontCall;
  1299. static const SEL dismissModalsSelector;
  1300. static const SEL frameChangedSelector;
  1301. static const SEL asyncMouseDownSelector;
  1302. static const SEL asyncMouseUpSelector;
  1303. static const SEL becomeKeySelector;
  1304. static const SEL resignKeySelector;
  1305. private:
  1306. static NSView* createViewInstance();
  1307. static NSWindow* createWindowInstance();
  1308. void sendMouseEnterExit (NSEvent* ev)
  1309. {
  1310. if (auto* area = [ev trackingArea])
  1311. if (! [[view trackingAreas] containsObject: area])
  1312. return;
  1313. sendMouseEvent (ev);
  1314. }
  1315. static void setOwner (id viewOrWindow, NSViewComponentPeer* newOwner)
  1316. {
  1317. object_setInstanceVariable (viewOrWindow, "owner", newOwner);
  1318. }
  1319. void getClipRects (RectangleList<int>& clip, Point<int> offset, int clipW, int clipH)
  1320. {
  1321. const NSRect* rects = nullptr;
  1322. NSInteger numRects = 0;
  1323. [view getRectsBeingDrawn: &rects count: &numRects];
  1324. const Rectangle<int> clipBounds (clipW, clipH);
  1325. clip.ensureStorageAllocated ((int) numRects);
  1326. for (int i = 0; i < numRects; ++i)
  1327. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + offset.x,
  1328. roundToInt (rects[i].origin.y) + offset.y,
  1329. roundToInt (rects[i].size.width),
  1330. roundToInt (rects[i].size.height))));
  1331. }
  1332. static void appFocusChanged()
  1333. {
  1334. keysCurrentlyDown.clear();
  1335. if (isValidPeer (currentlyFocusedPeer))
  1336. {
  1337. if (Process::isForegroundProcess())
  1338. {
  1339. currentlyFocusedPeer->handleFocusGain();
  1340. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  1341. }
  1342. else
  1343. {
  1344. currentlyFocusedPeer->handleFocusLoss();
  1345. }
  1346. }
  1347. }
  1348. static bool checkEventBlockedByModalComps (NSEvent* e)
  1349. {
  1350. if (Component::getNumCurrentlyModalComponents() == 0)
  1351. return false;
  1352. NSWindow* const w = [e window];
  1353. if (w == nil || [w worksWhenModal])
  1354. return false;
  1355. bool isKey = false, isInputAttempt = false;
  1356. switch ([e type])
  1357. {
  1358. case NSEventTypeKeyDown:
  1359. case NSEventTypeKeyUp:
  1360. isKey = isInputAttempt = true;
  1361. break;
  1362. case NSEventTypeLeftMouseDown:
  1363. case NSEventTypeRightMouseDown:
  1364. case NSEventTypeOtherMouseDown:
  1365. isInputAttempt = true;
  1366. break;
  1367. case NSEventTypeLeftMouseDragged:
  1368. case NSEventTypeRightMouseDragged:
  1369. case NSEventTypeLeftMouseUp:
  1370. case NSEventTypeRightMouseUp:
  1371. case NSEventTypeOtherMouseUp:
  1372. case NSEventTypeOtherMouseDragged:
  1373. if (Desktop::getInstance().getDraggingMouseSource(0) != nullptr)
  1374. return false;
  1375. break;
  1376. case NSEventTypeMouseMoved:
  1377. case NSEventTypeMouseEntered:
  1378. case NSEventTypeMouseExited:
  1379. case NSEventTypeCursorUpdate:
  1380. case NSEventTypeScrollWheel:
  1381. case NSEventTypeTabletPoint:
  1382. case NSEventTypeTabletProximity:
  1383. break;
  1384. case NSEventTypeFlagsChanged:
  1385. case NSEventTypeAppKitDefined:
  1386. case NSEventTypeSystemDefined:
  1387. case NSEventTypeApplicationDefined:
  1388. case NSEventTypePeriodic:
  1389. case NSEventTypeGesture:
  1390. case NSEventTypeMagnify:
  1391. case NSEventTypeSwipe:
  1392. case NSEventTypeRotate:
  1393. case NSEventTypeBeginGesture:
  1394. case NSEventTypeEndGesture:
  1395. case NSEventTypeQuickLook:
  1396. #if JUCE_64BIT
  1397. case NSEventTypeSmartMagnify:
  1398. case NSEventTypePressure:
  1399. #endif
  1400. #if defined (MAC_OS_X_VERSION_10_12) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_12
  1401. #if JUCE_64BIT
  1402. case NSEventTypeDirectTouch:
  1403. #endif
  1404. #if defined (MAC_OS_X_VERSION_10_15) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_15
  1405. case NSEventTypeChangeMode:
  1406. #endif
  1407. #endif
  1408. default:
  1409. return false;
  1410. }
  1411. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  1412. {
  1413. if (auto* peer = dynamic_cast<NSViewComponentPeer*> (ComponentPeer::getPeer (i)))
  1414. {
  1415. if ([peer->view window] == w)
  1416. {
  1417. if (isKey)
  1418. {
  1419. if (peer->view == [w firstResponder])
  1420. return false;
  1421. }
  1422. else
  1423. {
  1424. if (peer->isSharedWindow
  1425. ? NSPointInRect ([peer->view convertPoint: [e locationInWindow] fromView: nil], [peer->view bounds])
  1426. : NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height)))
  1427. return false;
  1428. }
  1429. }
  1430. }
  1431. }
  1432. if (isInputAttempt)
  1433. {
  1434. if (! [NSApp isActive])
  1435. [NSApp activateIgnoringOtherApps: YES];
  1436. if (auto* modal = Component::getCurrentlyModalComponent())
  1437. modal->inputAttemptWhenModal();
  1438. }
  1439. return true;
  1440. }
  1441. void setFullScreenSizeConstraints (const ComponentBoundsConstrainer& c)
  1442. {
  1443. const auto minSize = NSMakeSize (static_cast<float> (c.getMinimumWidth()),
  1444. 0.0f);
  1445. [window setMinFullScreenContentSize: minSize];
  1446. [window setMaxFullScreenContentSize: NSMakeSize (100000, 100000)];
  1447. }
  1448. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentPeer)
  1449. };
  1450. int NSViewComponentPeer::insideToFrontCall = 0;
  1451. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wundeclared-selector")
  1452. const SEL NSViewComponentPeer::dismissModalsSelector = @selector (dismissModals);
  1453. const SEL NSViewComponentPeer::frameChangedSelector = @selector (frameChanged:);
  1454. const SEL NSViewComponentPeer::asyncMouseDownSelector = @selector (asyncMouseDown:);
  1455. const SEL NSViewComponentPeer::asyncMouseUpSelector = @selector (asyncMouseUp:);
  1456. const SEL NSViewComponentPeer::becomeKeySelector = @selector (becomeKey:);
  1457. const SEL NSViewComponentPeer::resignKeySelector = @selector (resignKey:);
  1458. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  1459. //==============================================================================
  1460. template <typename Base>
  1461. struct NSViewComponentPeerWrapper : public Base
  1462. {
  1463. explicit NSViewComponentPeerWrapper (const char* baseName)
  1464. : Base (baseName)
  1465. {
  1466. Base::template addIvar<NSViewComponentPeer*> ("owner");
  1467. }
  1468. static NSViewComponentPeer* getOwner (id self)
  1469. {
  1470. return getIvar<NSViewComponentPeer*> (self, "owner");
  1471. }
  1472. static id getAccessibleChild (id self)
  1473. {
  1474. if (auto* owner = getOwner (self))
  1475. if (auto* handler = owner->getComponent().getAccessibilityHandler())
  1476. return (id) handler->getNativeImplementation();
  1477. return nil;
  1478. }
  1479. };
  1480. struct JuceNSViewClass : public NSViewComponentPeerWrapper<ObjCClass<NSView>>
  1481. {
  1482. JuceNSViewClass() : NSViewComponentPeerWrapper ("JUCEView_")
  1483. {
  1484. addMethod (@selector (isOpaque), isOpaque);
  1485. addMethod (@selector (drawRect:), drawRect);
  1486. addMethod (@selector (mouseDown:), mouseDown);
  1487. addMethod (@selector (mouseUp:), mouseUp);
  1488. addMethod (@selector (mouseDragged:), mouseDragged);
  1489. addMethod (@selector (mouseMoved:), mouseMoved);
  1490. addMethod (@selector (mouseEntered:), mouseEntered);
  1491. addMethod (@selector (mouseExited:), mouseExited);
  1492. addMethod (@selector (rightMouseDown:), mouseDown);
  1493. addMethod (@selector (rightMouseDragged:), mouseDragged);
  1494. addMethod (@selector (rightMouseUp:), mouseUp);
  1495. addMethod (@selector (otherMouseDown:), mouseDown);
  1496. addMethod (@selector (otherMouseDragged:), mouseDragged);
  1497. addMethod (@selector (otherMouseUp:), mouseUp);
  1498. addMethod (@selector (scrollWheel:), scrollWheel);
  1499. addMethod (@selector (magnifyWithEvent:), magnify);
  1500. addMethod (@selector (acceptsFirstMouse:), acceptsFirstMouse);
  1501. addMethod (@selector (windowWillMiniaturize:), windowWillMiniaturize);
  1502. addMethod (@selector (windowDidDeminiaturize:), windowDidDeminiaturize);
  1503. addMethod (@selector (wantsDefaultClipping), wantsDefaultClipping);
  1504. addMethod (@selector (worksWhenModal), worksWhenModal);
  1505. addMethod (@selector (viewDidMoveToWindow), viewDidMoveToWindow);
  1506. addMethod (@selector (viewWillDraw), viewWillDraw);
  1507. addMethod (@selector (keyDown:), keyDown);
  1508. addMethod (@selector (keyUp:), keyUp);
  1509. addMethod (@selector (insertText:), insertText);
  1510. addMethod (@selector (doCommandBySelector:), doCommandBySelector);
  1511. addMethod (@selector (setMarkedText:selectedRange:), setMarkedText);
  1512. addMethod (@selector (unmarkText), unmarkText);
  1513. addMethod (@selector (hasMarkedText), hasMarkedText);
  1514. addMethod (@selector (conversationIdentifier), conversationIdentifier);
  1515. addMethod (@selector (attributedSubstringFromRange:), attributedSubstringFromRange);
  1516. addMethod (@selector (markedRange), markedRange);
  1517. addMethod (@selector (selectedRange), selectedRange);
  1518. addMethod (@selector (firstRectForCharacterRange:), firstRectForCharacterRange);
  1519. addMethod (@selector (characterIndexForPoint:), characterIndexForPoint);
  1520. addMethod (@selector (validAttributesForMarkedText), validAttributesForMarkedText);
  1521. addMethod (@selector (flagsChanged:), flagsChanged);
  1522. addMethod (@selector (becomeFirstResponder), becomeFirstResponder);
  1523. addMethod (@selector (resignFirstResponder), resignFirstResponder);
  1524. addMethod (@selector (acceptsFirstResponder), acceptsFirstResponder);
  1525. addMethod (@selector (draggingEntered:), draggingEntered);
  1526. addMethod (@selector (draggingUpdated:), draggingUpdated);
  1527. addMethod (@selector (draggingEnded:), draggingEnded);
  1528. addMethod (@selector (draggingExited:), draggingExited);
  1529. addMethod (@selector (prepareForDragOperation:), prepareForDragOperation);
  1530. addMethod (@selector (performDragOperation:), performDragOperation);
  1531. addMethod (@selector (concludeDragOperation:), concludeDragOperation);
  1532. addMethod (@selector (paste:), paste);
  1533. addMethod (@selector (copy:), copy);
  1534. addMethod (@selector (cut:), cut);
  1535. addMethod (@selector (selectAll:), selectAll);
  1536. addMethod (@selector (viewWillMoveToWindow:), willMoveToWindow);
  1537. addMethod (@selector (isAccessibilityElement), getIsAccessibilityElement);
  1538. addMethod (@selector (accessibilityChildren), getAccessibilityChildren);
  1539. addMethod (@selector (accessibilityHitTest:), accessibilityHitTest);
  1540. addMethod (@selector (accessibilityFocusedUIElement), getAccessibilityFocusedUIElement);
  1541. // deprecated methods required for backwards compatibility
  1542. addMethod (@selector (accessibilityIsIgnored), getAccessibilityIsIgnored);
  1543. addMethod (@selector (accessibilityAttributeValue:), getAccessibilityAttributeValue);
  1544. addMethod (@selector (isFlipped), isFlipped);
  1545. addMethod (NSViewComponentPeer::dismissModalsSelector, dismissModals);
  1546. addMethod (NSViewComponentPeer::asyncMouseDownSelector, asyncMouseDown);
  1547. addMethod (NSViewComponentPeer::asyncMouseUpSelector, asyncMouseUp);
  1548. addMethod (NSViewComponentPeer::frameChangedSelector, frameChanged);
  1549. addMethod (NSViewComponentPeer::becomeKeySelector, becomeKey);
  1550. addMethod (NSViewComponentPeer::resignKeySelector, resignKey);
  1551. addMethod (@selector (performKeyEquivalent:), performKeyEquivalent);
  1552. addProtocol (@protocol (NSTextInput));
  1553. registerClass();
  1554. }
  1555. private:
  1556. static void mouseDown (id self, SEL s, NSEvent* ev)
  1557. {
  1558. if (JUCEApplicationBase::isStandaloneApp())
  1559. {
  1560. asyncMouseDown (self, s, ev);
  1561. }
  1562. else
  1563. {
  1564. // In some host situations, the host will stop modal loops from working
  1565. // correctly if they're called from a mouse event, so we'll trigger
  1566. // the event asynchronously..
  1567. [self performSelectorOnMainThread: NSViewComponentPeer::asyncMouseDownSelector
  1568. withObject: ev
  1569. waitUntilDone: NO];
  1570. }
  1571. }
  1572. static void mouseUp (id self, SEL s, NSEvent* ev)
  1573. {
  1574. if (JUCEApplicationBase::isStandaloneApp())
  1575. {
  1576. asyncMouseUp (self, s, ev);
  1577. }
  1578. else
  1579. {
  1580. // In some host situations, the host will stop modal loops from working
  1581. // correctly if they're called from a mouse event, so we'll trigger
  1582. // the event asynchronously..
  1583. [self performSelectorOnMainThread: NSViewComponentPeer::asyncMouseUpSelector
  1584. withObject: ev
  1585. waitUntilDone: NO];
  1586. }
  1587. }
  1588. static void asyncMouseDown (id self, SEL, NSEvent* ev) { callOnOwner (self, &NSViewComponentPeer::redirectMouseDown, ev); }
  1589. static void asyncMouseUp (id self, SEL, NSEvent* ev) { callOnOwner (self, &NSViewComponentPeer::redirectMouseUp, ev); }
  1590. static void mouseDragged (id self, SEL, NSEvent* ev) { callOnOwner (self, &NSViewComponentPeer::redirectMouseDrag, ev); }
  1591. static void mouseMoved (id self, SEL, NSEvent* ev) { callOnOwner (self, &NSViewComponentPeer::redirectMouseMove, ev); }
  1592. static void mouseEntered (id self, SEL, NSEvent* ev) { callOnOwner (self, &NSViewComponentPeer::redirectMouseEnter, ev); }
  1593. static void mouseExited (id self, SEL, NSEvent* ev) { callOnOwner (self, &NSViewComponentPeer::redirectMouseExit, ev); }
  1594. static void scrollWheel (id self, SEL, NSEvent* ev) { callOnOwner (self, &NSViewComponentPeer::redirectMouseWheel, ev); }
  1595. static void magnify (id self, SEL, NSEvent* ev) { callOnOwner (self, &NSViewComponentPeer::redirectMagnify, ev); }
  1596. static void copy (id self, SEL, NSObject* s) { callOnOwner (self, &NSViewComponentPeer::redirectCopy, s); }
  1597. static void paste (id self, SEL, NSObject* s) { callOnOwner (self, &NSViewComponentPeer::redirectPaste, s); }
  1598. static void cut (id self, SEL, NSObject* s) { callOnOwner (self, &NSViewComponentPeer::redirectCut, s); }
  1599. static void selectAll (id self, SEL, NSObject* s) { callOnOwner (self, &NSViewComponentPeer::redirectSelectAll, s); }
  1600. static void willMoveToWindow (id self, SEL, NSWindow* w) { callOnOwner (self, &NSViewComponentPeer::redirectWillMoveToWindow, w); }
  1601. static BOOL acceptsFirstMouse (id, SEL, NSEvent*) { return YES; }
  1602. static BOOL wantsDefaultClipping (id, SEL) { return YES; } // (this is the default, but may want to customise it in future)
  1603. static BOOL worksWhenModal (id self, SEL) { if (auto* p = getOwner (self)) return p->worksWhenModal(); return NO; }
  1604. static void drawRect (id self, SEL, NSRect r) { callOnOwner (self, &NSViewComponentPeer::drawRect, r); }
  1605. static void frameChanged (id self, SEL, NSNotification*) { callOnOwner (self, &NSViewComponentPeer::redirectMovedOrResized); }
  1606. static void viewDidMoveToWindow (id self, SEL) { callOnOwner (self, &NSViewComponentPeer::viewMovedToWindow); }
  1607. static void dismissModals (id self, SEL) { callOnOwner (self, &NSViewComponentPeer::dismissModals); }
  1608. static void becomeKey (id self, SEL) { callOnOwner (self, &NSViewComponentPeer::becomeKey); }
  1609. static void resignKey (id self, SEL) { callOnOwner (self, &NSViewComponentPeer::resignKey); }
  1610. static BOOL isFlipped (id, SEL) { return true; }
  1611. static void viewWillDraw (id self, SEL)
  1612. {
  1613. // Without setting contentsFormat macOS Big Sur will always set the invalid area
  1614. // to be the entire frame.
  1615. #if defined (MAC_OS_X_VERSION_10_12) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_12
  1616. if (@available (macOS 10.12, *))
  1617. {
  1618. CALayer* layer = ((NSView*) self).layer;
  1619. layer.contentsFormat = kCAContentsFormatRGBA8Uint;
  1620. }
  1621. #endif
  1622. sendSuperclassMessage<void> (self, @selector (viewWillDraw));
  1623. }
  1624. static void windowWillMiniaturize (id self, SEL, NSNotification*)
  1625. {
  1626. if (auto* p = getOwner (self))
  1627. {
  1628. if (p->isAlwaysOnTop)
  1629. {
  1630. // there is a bug when restoring minimised always on top windows so we need
  1631. // to remove this behaviour before minimising and restore it afterwards
  1632. p->setAlwaysOnTop (false);
  1633. p->wasAlwaysOnTop = true;
  1634. }
  1635. }
  1636. }
  1637. static void windowDidDeminiaturize (id self, SEL, NSNotification*)
  1638. {
  1639. if (auto* p = getOwner (self))
  1640. {
  1641. if (p->wasAlwaysOnTop)
  1642. p->setAlwaysOnTop (true);
  1643. p->redirectMovedOrResized();
  1644. }
  1645. }
  1646. static BOOL isOpaque (id self, SEL)
  1647. {
  1648. auto* owner = getOwner (self);
  1649. return owner == nullptr || owner->getComponent().isOpaque();
  1650. }
  1651. //==============================================================================
  1652. static void keyDown (id self, SEL, NSEvent* ev)
  1653. {
  1654. if (auto* owner = getOwner (self))
  1655. {
  1656. auto* target = owner->findCurrentTextInputTarget();
  1657. owner->textWasInserted = false;
  1658. if (target != nullptr)
  1659. [(NSView*) self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  1660. else
  1661. owner->stringBeingComposed.clear();
  1662. if (! (owner->textWasInserted || owner->redirectKeyDown (ev)))
  1663. sendSuperclassMessage<void> (self, @selector (keyDown:), ev);
  1664. }
  1665. }
  1666. static void keyUp (id self, SEL, NSEvent* ev)
  1667. {
  1668. auto* owner = getOwner (self);
  1669. if (! owner->redirectKeyUp (ev))
  1670. sendSuperclassMessage<void> (self, @selector (keyUp:), ev);
  1671. }
  1672. //==============================================================================
  1673. static void insertText (id self, SEL, id aString)
  1674. {
  1675. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  1676. if (auto* owner = getOwner (self))
  1677. {
  1678. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  1679. if ([newText length] > 0)
  1680. {
  1681. if (auto* target = owner->findCurrentTextInputTarget())
  1682. {
  1683. target->insertTextAtCaret (nsStringToJuce (newText));
  1684. owner->textWasInserted = true;
  1685. }
  1686. }
  1687. owner->stringBeingComposed.clear();
  1688. }
  1689. }
  1690. static void doCommandBySelector (id, SEL, SEL) {}
  1691. static void setMarkedText (id self, SEL, id aString, NSRange)
  1692. {
  1693. if (auto* owner = getOwner (self))
  1694. {
  1695. owner->stringBeingComposed = nsStringToJuce ([aString isKindOfClass: [NSAttributedString class]]
  1696. ? [aString string] : aString);
  1697. if (auto* target = owner->findCurrentTextInputTarget())
  1698. {
  1699. auto currentHighlight = target->getHighlightedRegion();
  1700. target->insertTextAtCaret (owner->stringBeingComposed);
  1701. target->setHighlightedRegion (currentHighlight.withLength (owner->stringBeingComposed.length()));
  1702. owner->textWasInserted = true;
  1703. }
  1704. }
  1705. }
  1706. static void unmarkText (id self, SEL)
  1707. {
  1708. if (auto* owner = getOwner (self))
  1709. {
  1710. if (owner->stringBeingComposed.isNotEmpty())
  1711. {
  1712. if (auto* target = owner->findCurrentTextInputTarget())
  1713. {
  1714. target->insertTextAtCaret (owner->stringBeingComposed);
  1715. owner->textWasInserted = true;
  1716. }
  1717. owner->stringBeingComposed.clear();
  1718. }
  1719. }
  1720. }
  1721. static BOOL hasMarkedText (id self, SEL)
  1722. {
  1723. auto* owner = getOwner (self);
  1724. return owner != nullptr && owner->stringBeingComposed.isNotEmpty();
  1725. }
  1726. static long conversationIdentifier (id self, SEL)
  1727. {
  1728. return (long) (pointer_sized_int) self;
  1729. }
  1730. static NSAttributedString* attributedSubstringFromRange (id self, SEL, NSRange theRange)
  1731. {
  1732. if (auto* owner = getOwner (self))
  1733. {
  1734. if (auto* target = owner->findCurrentTextInputTarget())
  1735. {
  1736. Range<int> r ((int) theRange.location,
  1737. (int) (theRange.location + theRange.length));
  1738. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  1739. }
  1740. }
  1741. return nil;
  1742. }
  1743. static NSRange markedRange (id self, SEL)
  1744. {
  1745. if (auto* owner = getOwner (self))
  1746. if (owner->stringBeingComposed.isNotEmpty())
  1747. return NSMakeRange (0, (NSUInteger) owner->stringBeingComposed.length());
  1748. return NSMakeRange (NSNotFound, 0);
  1749. }
  1750. static NSRange selectedRange (id self, SEL)
  1751. {
  1752. if (auto* owner = getOwner (self))
  1753. {
  1754. if (auto* target = owner->findCurrentTextInputTarget())
  1755. {
  1756. auto highlight = target->getHighlightedRegion();
  1757. if (! highlight.isEmpty())
  1758. return NSMakeRange ((NSUInteger) highlight.getStart(),
  1759. (NSUInteger) highlight.getLength());
  1760. }
  1761. }
  1762. return NSMakeRange (NSNotFound, 0);
  1763. }
  1764. static NSRect firstRectForCharacterRange (id self, SEL, NSRange)
  1765. {
  1766. if (auto* owner = getOwner (self))
  1767. if (auto* comp = dynamic_cast<Component*> (owner->findCurrentTextInputTarget()))
  1768. return flippedScreenRect (makeNSRect (comp->getScreenBounds()));
  1769. return NSZeroRect;
  1770. }
  1771. static NSUInteger characterIndexForPoint (id, SEL, NSPoint) { return NSNotFound; }
  1772. static NSArray* validAttributesForMarkedText (id, SEL) { return [NSArray array]; }
  1773. //==============================================================================
  1774. static void flagsChanged (id self, SEL, NSEvent* ev)
  1775. {
  1776. callOnOwner (self, &NSViewComponentPeer::redirectModKeyChange, ev);
  1777. }
  1778. static BOOL becomeFirstResponder (id self, SEL)
  1779. {
  1780. callOnOwner (self, &NSViewComponentPeer::viewFocusGain);
  1781. return YES;
  1782. }
  1783. static BOOL resignFirstResponder (id self, SEL)
  1784. {
  1785. callOnOwner (self, &NSViewComponentPeer::viewFocusLoss);
  1786. return YES;
  1787. }
  1788. static BOOL acceptsFirstResponder (id self, SEL)
  1789. {
  1790. auto* owner = getOwner (self);
  1791. return owner != nullptr && owner->canBecomeKeyWindow();
  1792. }
  1793. //==============================================================================
  1794. static NSDragOperation draggingEntered (id self, SEL s, id<NSDraggingInfo> sender)
  1795. {
  1796. return draggingUpdated (self, s, sender);
  1797. }
  1798. static NSDragOperation draggingUpdated (id self, SEL, id<NSDraggingInfo> sender)
  1799. {
  1800. if (auto* owner = getOwner (self))
  1801. if (owner->sendDragCallback (0, sender))
  1802. return NSDragOperationGeneric;
  1803. return NSDragOperationNone;
  1804. }
  1805. static void draggingEnded (id self, SEL s, id<NSDraggingInfo> sender)
  1806. {
  1807. draggingExited (self, s, sender);
  1808. }
  1809. static void draggingExited (id self, SEL, id<NSDraggingInfo> sender)
  1810. {
  1811. callOnOwner (self, &NSViewComponentPeer::sendDragCallback, 1, sender);
  1812. }
  1813. static BOOL prepareForDragOperation (id, SEL, id<NSDraggingInfo>)
  1814. {
  1815. return YES;
  1816. }
  1817. static BOOL performDragOperation (id self, SEL, id<NSDraggingInfo> sender)
  1818. {
  1819. auto* owner = getOwner (self);
  1820. return owner != nullptr && owner->sendDragCallback (2, sender);
  1821. }
  1822. static void concludeDragOperation (id, SEL, id<NSDraggingInfo>) {}
  1823. //==============================================================================
  1824. static BOOL getIsAccessibilityElement (id, SEL)
  1825. {
  1826. return NO;
  1827. }
  1828. static NSArray* getAccessibilityChildren (id self, SEL)
  1829. {
  1830. return NSAccessibilityUnignoredChildrenForOnlyChild (getAccessibleChild (self));
  1831. }
  1832. static id accessibilityHitTest (id self, SEL, NSPoint point)
  1833. {
  1834. return [getAccessibleChild (self) accessibilityHitTest: point];
  1835. }
  1836. static id getAccessibilityFocusedUIElement (id self, SEL)
  1837. {
  1838. return [getAccessibleChild (self) accessibilityFocusedUIElement];
  1839. }
  1840. static BOOL getAccessibilityIsIgnored (id, SEL)
  1841. {
  1842. return YES;
  1843. }
  1844. static id getAccessibilityAttributeValue (id self, SEL, NSString* attribute)
  1845. {
  1846. if ([attribute isEqualToString: NSAccessibilityChildrenAttribute])
  1847. return getAccessibilityChildren (self, {});
  1848. return sendSuperclassMessage<id> (self, @selector (accessibilityAttributeValue:), attribute);
  1849. }
  1850. static bool tryPassingKeyEventToPeer (NSEvent* e)
  1851. {
  1852. if ([e type] != NSEventTypeKeyDown && [e type] != NSEventTypeKeyUp)
  1853. return false;
  1854. if (auto* focused = Component::getCurrentlyFocusedComponent())
  1855. {
  1856. if (auto* peer = dynamic_cast<NSViewComponentPeer*> (focused->getPeer()))
  1857. {
  1858. return [e type] == NSEventTypeKeyDown ? peer->redirectKeyDown (e)
  1859. : peer->redirectKeyUp (e);
  1860. }
  1861. }
  1862. return false;
  1863. }
  1864. static BOOL performKeyEquivalent (id self, SEL s, NSEvent* event)
  1865. {
  1866. // We try passing shortcut keys to the currently focused component first.
  1867. // If the component doesn't want the event, we'll fall back to the superclass
  1868. // implementation, which will pass the event to the main menu.
  1869. if (tryPassingKeyEventToPeer (event))
  1870. return YES;
  1871. return sendSuperclassMessage<BOOL> (self, s, event);
  1872. }
  1873. template <typename Func, typename... Args>
  1874. static void callOnOwner (id self, Func&& func, Args&&... args)
  1875. {
  1876. if (auto* owner = getOwner (self))
  1877. (owner->*func) (std::forward<Args> (args)...);
  1878. }
  1879. };
  1880. //==============================================================================
  1881. struct JuceNSWindowClass : public NSViewComponentPeerWrapper<ObjCClass<NSWindow>>
  1882. {
  1883. JuceNSWindowClass() : NSViewComponentPeerWrapper ("JUCEWindow_")
  1884. {
  1885. addMethod (@selector (canBecomeKeyWindow), canBecomeKeyWindow);
  1886. addMethod (@selector (canBecomeMainWindow), canBecomeMainWindow);
  1887. addMethod (@selector (becomeKeyWindow), becomeKeyWindow);
  1888. addMethod (@selector (resignKeyWindow), resignKeyWindow);
  1889. addMethod (@selector (windowShouldClose:), windowShouldClose);
  1890. addMethod (@selector (constrainFrameRect:toScreen:), constrainFrameRect);
  1891. addMethod (@selector (windowWillResize:toSize:), windowWillResize);
  1892. addMethod (@selector (windowDidExitFullScreen:), windowDidExitFullScreen);
  1893. addMethod (@selector (windowWillEnterFullScreen:), windowWillEnterFullScreen);
  1894. addMethod (@selector (windowWillStartLiveResize:), windowWillStartLiveResize);
  1895. addMethod (@selector (windowDidEndLiveResize:), windowDidEndLiveResize);
  1896. addMethod (@selector (window:shouldPopUpDocumentPathMenu:), shouldPopUpPathMenu);
  1897. addMethod (@selector (isFlipped), isFlipped);
  1898. addMethod (@selector (windowWillUseStandardFrame:defaultFrame:), windowWillUseStandardFrame);
  1899. addMethod (@selector (windowShouldZoom:toFrame:), windowShouldZoomToFrame);
  1900. addMethod (@selector (accessibilityTitle), getAccessibilityTitle);
  1901. addMethod (@selector (accessibilityLabel), getAccessibilityLabel);
  1902. addMethod (@selector (accessibilityTopLevelUIElement), getAccessibilityWindow);
  1903. addMethod (@selector (accessibilityWindow), getAccessibilityWindow);
  1904. addMethod (@selector (accessibilityRole), getAccessibilityRole);
  1905. addMethod (@selector (accessibilitySubrole), getAccessibilitySubrole);
  1906. addMethod (@selector (window:shouldDragDocumentWithEvent:from:withPasteboard:), shouldAllowIconDrag);
  1907. addProtocol (@protocol (NSWindowDelegate));
  1908. registerClass();
  1909. }
  1910. private:
  1911. //==============================================================================
  1912. static BOOL isFlipped (id, SEL) { return true; }
  1913. static NSRect windowWillUseStandardFrame (id self, SEL, NSWindow*, NSRect)
  1914. {
  1915. if (auto* owner = getOwner (self))
  1916. {
  1917. if (auto* constrainer = owner->getConstrainer())
  1918. {
  1919. return flippedScreenRect (makeNSRect (owner->getFrameSize().addedTo (owner->getComponent().getScreenBounds()
  1920. .withWidth (constrainer->getMaximumWidth())
  1921. .withHeight (constrainer->getMaximumHeight()))));
  1922. }
  1923. }
  1924. return makeNSRect (Rectangle<int> (10000, 10000));
  1925. }
  1926. static BOOL windowShouldZoomToFrame (id, SEL, NSWindow* window, NSRect frame)
  1927. {
  1928. return convertToRectFloat ([window frame]).withZeroOrigin() != convertToRectFloat (frame).withZeroOrigin();
  1929. }
  1930. static BOOL canBecomeKeyWindow (id self, SEL)
  1931. {
  1932. auto* owner = getOwner (self);
  1933. return owner != nullptr
  1934. && owner->canBecomeKeyWindow()
  1935. && ! owner->isBlockedByModalComponent();
  1936. }
  1937. static BOOL canBecomeMainWindow (id self, SEL)
  1938. {
  1939. auto* owner = getOwner (self);
  1940. return owner != nullptr
  1941. && owner->canBecomeMainWindow()
  1942. && ! owner->isBlockedByModalComponent();
  1943. }
  1944. static void becomeKeyWindow (id self, SEL)
  1945. {
  1946. sendSuperclassMessage<void> (self, @selector (becomeKeyWindow));
  1947. if (auto* owner = getOwner (self))
  1948. {
  1949. if (owner->canBecomeKeyWindow())
  1950. {
  1951. owner->becomeKeyWindow();
  1952. return;
  1953. }
  1954. // this fixes a bug causing hidden windows to sometimes become visible when the app regains focus
  1955. if (! owner->getComponent().isVisible())
  1956. [(NSWindow*) self orderOut: nil];
  1957. }
  1958. }
  1959. static void resignKeyWindow (id self, SEL)
  1960. {
  1961. sendSuperclassMessage<void> (self, @selector (resignKeyWindow));
  1962. if (auto* owner = getOwner (self))
  1963. owner->resignKeyWindow();
  1964. }
  1965. static BOOL windowShouldClose (id self, SEL, id /*window*/)
  1966. {
  1967. auto* owner = getOwner (self);
  1968. return owner == nullptr || owner->windowShouldClose();
  1969. }
  1970. static NSRect constrainFrameRect (id self, SEL, NSRect frameRect, NSScreen* screen)
  1971. {
  1972. if (auto* owner = getOwner (self))
  1973. {
  1974. frameRect = sendSuperclassMessage<NSRect, NSRect, NSScreen*> (self, @selector (constrainFrameRect:toScreen:),
  1975. frameRect, screen);
  1976. frameRect = owner->constrainRect (frameRect);
  1977. }
  1978. return frameRect;
  1979. }
  1980. static NSSize windowWillResize (id self, SEL, NSWindow*, NSSize proposedFrameSize)
  1981. {
  1982. auto* owner = getOwner (self);
  1983. if (owner == nullptr || owner->isZooming)
  1984. return proposedFrameSize;
  1985. NSRect frameRect = flippedScreenRect ([(NSWindow*) self frame]);
  1986. frameRect.size = proposedFrameSize;
  1987. frameRect = owner->constrainRect (flippedScreenRect (frameRect));
  1988. owner->dismissModals();
  1989. return frameRect.size;
  1990. }
  1991. static void windowDidExitFullScreen (id self, SEL, NSNotification*)
  1992. {
  1993. if (auto* owner = getOwner (self))
  1994. owner->resetWindowPresentation();
  1995. }
  1996. static void windowWillEnterFullScreen (id self, SEL, NSNotification*)
  1997. {
  1998. if (SystemStats::getOperatingSystemType() <= SystemStats::MacOSX_10_9)
  1999. return;
  2000. if (auto* owner = getOwner (self))
  2001. if (owner->hasNativeTitleBar() && (owner->getStyleFlags() & ComponentPeer::windowIsResizable) == 0)
  2002. [owner->window setStyleMask: NSWindowStyleMaskBorderless];
  2003. }
  2004. static void windowWillStartLiveResize (id self, SEL, NSNotification*)
  2005. {
  2006. if (auto* owner = getOwner (self))
  2007. owner->liveResizingStart();
  2008. }
  2009. static void windowDidEndLiveResize (id self, SEL, NSNotification*)
  2010. {
  2011. if (auto* owner = getOwner (self))
  2012. owner->liveResizingEnd();
  2013. }
  2014. static bool shouldPopUpPathMenu (id self, SEL, id /*window*/, NSMenu*)
  2015. {
  2016. if (auto* owner = getOwner (self))
  2017. return owner->windowRepresentsFile;
  2018. return false;
  2019. }
  2020. static bool shouldAllowIconDrag (id self, SEL, id /*window*/, NSEvent*, NSPoint, NSPasteboard*)
  2021. {
  2022. if (auto* owner = getOwner (self))
  2023. return owner->windowRepresentsFile;
  2024. return false;
  2025. }
  2026. static NSString* getAccessibilityTitle (id self, SEL)
  2027. {
  2028. return [self title];
  2029. }
  2030. static NSString* getAccessibilityLabel (id self, SEL)
  2031. {
  2032. return [getAccessibleChild (self) accessibilityLabel];
  2033. }
  2034. static id getAccessibilityWindow (id self, SEL)
  2035. {
  2036. return self;
  2037. }
  2038. static NSAccessibilityRole getAccessibilityRole (id, SEL)
  2039. {
  2040. return NSAccessibilityWindowRole;
  2041. }
  2042. static NSAccessibilityRole getAccessibilitySubrole (id self, SEL)
  2043. {
  2044. if (@available (macOS 10.10, *))
  2045. return [getAccessibleChild (self) accessibilitySubrole];
  2046. return nil;
  2047. }
  2048. };
  2049. NSView* NSViewComponentPeer::createViewInstance()
  2050. {
  2051. static JuceNSViewClass cls;
  2052. return cls.createInstance();
  2053. }
  2054. NSWindow* NSViewComponentPeer::createWindowInstance()
  2055. {
  2056. static JuceNSWindowClass cls;
  2057. return cls.createInstance();
  2058. }
  2059. //==============================================================================
  2060. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = nullptr;
  2061. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  2062. //==============================================================================
  2063. bool KeyPress::isKeyCurrentlyDown (int keyCode)
  2064. {
  2065. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  2066. return true;
  2067. if (keyCode >= 'A' && keyCode <= 'Z'
  2068. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  2069. return true;
  2070. if (keyCode >= 'a' && keyCode <= 'z'
  2071. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  2072. return true;
  2073. return false;
  2074. }
  2075. //==============================================================================
  2076. bool MouseInputSource::SourceList::addSource()
  2077. {
  2078. if (sources.size() == 0)
  2079. {
  2080. addSource (0, MouseInputSource::InputSourceType::mouse);
  2081. return true;
  2082. }
  2083. return false;
  2084. }
  2085. bool MouseInputSource::SourceList::canUseTouch()
  2086. {
  2087. return false;
  2088. }
  2089. //==============================================================================
  2090. void Desktop::setKioskComponent (Component* kioskComp, bool shouldBeEnabled, bool allowMenusAndBars)
  2091. {
  2092. auto* peer = dynamic_cast<NSViewComponentPeer*> (kioskComp->getPeer());
  2093. jassert (peer != nullptr); // (this should have been checked by the caller)
  2094. if (peer->hasNativeTitleBar())
  2095. {
  2096. if (shouldBeEnabled && ! allowMenusAndBars)
  2097. [NSApp setPresentationOptions: NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar];
  2098. else if (! shouldBeEnabled)
  2099. [NSApp setPresentationOptions: NSApplicationPresentationDefault];
  2100. [peer->window toggleFullScreen: nil];
  2101. }
  2102. else
  2103. {
  2104. if (shouldBeEnabled)
  2105. {
  2106. [NSApp setPresentationOptions: (allowMenusAndBars ? (NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)
  2107. : (NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar))];
  2108. kioskComp->setBounds (getDisplays().getDisplayForRect (kioskComp->getScreenBounds())->totalArea);
  2109. peer->becomeKeyWindow();
  2110. }
  2111. else
  2112. {
  2113. peer->resetWindowPresentation();
  2114. }
  2115. }
  2116. }
  2117. void Desktop::allowedOrientationsChanged() {}
  2118. //==============================================================================
  2119. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  2120. {
  2121. return new NSViewComponentPeer (*this, styleFlags, (NSView*) windowToAttachTo);
  2122. }
  2123. //==============================================================================
  2124. const int KeyPress::spaceKey = ' ';
  2125. const int KeyPress::returnKey = 0x0d;
  2126. const int KeyPress::escapeKey = 0x1b;
  2127. const int KeyPress::backspaceKey = 0x7f;
  2128. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  2129. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  2130. const int KeyPress::upKey = NSUpArrowFunctionKey;
  2131. const int KeyPress::downKey = NSDownArrowFunctionKey;
  2132. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  2133. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  2134. const int KeyPress::endKey = NSEndFunctionKey;
  2135. const int KeyPress::homeKey = NSHomeFunctionKey;
  2136. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  2137. const int KeyPress::insertKey = -1;
  2138. const int KeyPress::tabKey = 9;
  2139. const int KeyPress::F1Key = NSF1FunctionKey;
  2140. const int KeyPress::F2Key = NSF2FunctionKey;
  2141. const int KeyPress::F3Key = NSF3FunctionKey;
  2142. const int KeyPress::F4Key = NSF4FunctionKey;
  2143. const int KeyPress::F5Key = NSF5FunctionKey;
  2144. const int KeyPress::F6Key = NSF6FunctionKey;
  2145. const int KeyPress::F7Key = NSF7FunctionKey;
  2146. const int KeyPress::F8Key = NSF8FunctionKey;
  2147. const int KeyPress::F9Key = NSF9FunctionKey;
  2148. const int KeyPress::F10Key = NSF10FunctionKey;
  2149. const int KeyPress::F11Key = NSF11FunctionKey;
  2150. const int KeyPress::F12Key = NSF12FunctionKey;
  2151. const int KeyPress::F13Key = NSF13FunctionKey;
  2152. const int KeyPress::F14Key = NSF14FunctionKey;
  2153. const int KeyPress::F15Key = NSF15FunctionKey;
  2154. const int KeyPress::F16Key = NSF16FunctionKey;
  2155. const int KeyPress::F17Key = NSF17FunctionKey;
  2156. const int KeyPress::F18Key = NSF18FunctionKey;
  2157. const int KeyPress::F19Key = NSF19FunctionKey;
  2158. const int KeyPress::F20Key = NSF20FunctionKey;
  2159. const int KeyPress::F21Key = NSF21FunctionKey;
  2160. const int KeyPress::F22Key = NSF22FunctionKey;
  2161. const int KeyPress::F23Key = NSF23FunctionKey;
  2162. const int KeyPress::F24Key = NSF24FunctionKey;
  2163. const int KeyPress::F25Key = NSF25FunctionKey;
  2164. const int KeyPress::F26Key = NSF26FunctionKey;
  2165. const int KeyPress::F27Key = NSF27FunctionKey;
  2166. const int KeyPress::F28Key = NSF28FunctionKey;
  2167. const int KeyPress::F29Key = NSF29FunctionKey;
  2168. const int KeyPress::F30Key = NSF30FunctionKey;
  2169. const int KeyPress::F31Key = NSF31FunctionKey;
  2170. const int KeyPress::F32Key = NSF32FunctionKey;
  2171. const int KeyPress::F33Key = NSF33FunctionKey;
  2172. const int KeyPress::F34Key = NSF34FunctionKey;
  2173. const int KeyPress::F35Key = NSF35FunctionKey;
  2174. const int KeyPress::numberPad0 = extendedKeyModifier + 0x20;
  2175. const int KeyPress::numberPad1 = extendedKeyModifier + 0x21;
  2176. const int KeyPress::numberPad2 = extendedKeyModifier + 0x22;
  2177. const int KeyPress::numberPad3 = extendedKeyModifier + 0x23;
  2178. const int KeyPress::numberPad4 = extendedKeyModifier + 0x24;
  2179. const int KeyPress::numberPad5 = extendedKeyModifier + 0x25;
  2180. const int KeyPress::numberPad6 = extendedKeyModifier + 0x26;
  2181. const int KeyPress::numberPad7 = extendedKeyModifier + 0x27;
  2182. const int KeyPress::numberPad8 = extendedKeyModifier + 0x28;
  2183. const int KeyPress::numberPad9 = extendedKeyModifier + 0x29;
  2184. const int KeyPress::numberPadAdd = extendedKeyModifier + 0x2a;
  2185. const int KeyPress::numberPadSubtract = extendedKeyModifier + 0x2b;
  2186. const int KeyPress::numberPadMultiply = extendedKeyModifier + 0x2c;
  2187. const int KeyPress::numberPadDivide = extendedKeyModifier + 0x2d;
  2188. const int KeyPress::numberPadSeparator = extendedKeyModifier + 0x2e;
  2189. const int KeyPress::numberPadDecimalPoint = extendedKeyModifier + 0x2f;
  2190. const int KeyPress::numberPadEquals = extendedKeyModifier + 0x30;
  2191. const int KeyPress::numberPadDelete = extendedKeyModifier + 0x31;
  2192. const int KeyPress::playKey = extendedKeyModifier + 0x00;
  2193. const int KeyPress::stopKey = extendedKeyModifier + 0x01;
  2194. const int KeyPress::fastForwardKey = extendedKeyModifier + 0x02;
  2195. const int KeyPress::rewindKey = extendedKeyModifier + 0x03;
  2196. } // namespace juce