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.

2879 lines
108KB

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