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.

2569 lines
97KB

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