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.

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