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.

2893 lines
112KB

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