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.

2705 lines
102KB

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