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.

2884 lines
108KB

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