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.

2706 lines
101KB

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