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

2997 lines
116KB

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