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.

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