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.

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