Audio plugin host https://kx.studio/carla
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.

2861 lines
107KB

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