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.

2715 lines
102KB

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