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.

2822 lines
110KB

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