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.

2564 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 defined (MAC_OS_X_VERSION_10_8) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_8) \
  56. && USE_COREGRAPHICS_RENDERING && JUCE_COREGRAPHICS_DRAW_ASYNC
  57. if (! getComponentAsyncLayerBackedViewDisabled (component))
  58. {
  59. [view setWantsLayer: YES];
  60. [[view layer] setDrawsAsynchronously: YES];
  61. }
  62. #endif
  63. if (isSharedWindow)
  64. {
  65. window = [viewToAttachTo window];
  66. [viewToAttachTo addSubview: view];
  67. }
  68. else
  69. {
  70. r.origin.x = (CGFloat) component.getX();
  71. r.origin.y = (CGFloat) component.getY();
  72. r = flippedScreenRect (r);
  73. window = [createWindowInstance() initWithContentRect: r
  74. styleMask: getNSWindowStyleMask (windowStyleFlags)
  75. backing: NSBackingStoreBuffered
  76. defer: YES];
  77. setOwner (window, this);
  78. #if JUCE_OBJC_HAS_AVAILABLE_FEATURE || (defined (MAC_OS_X_VERSION_10_10) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_10)
  79. #if JUCE_OBJC_HAS_AVAILABLE_FEATURE
  80. if (@available (macOS 10.10, *))
  81. #endif
  82. {
  83. [window setAccessibilityElement: YES];
  84. }
  85. #endif
  86. [window orderOut: nil];
  87. [window setDelegate: (id<NSWindowDelegate>) window];
  88. [window setOpaque: component.isOpaque()];
  89. if (! [window isOpaque])
  90. [window setBackgroundColor: [NSColor clearColor]];
  91. #if defined (MAC_OS_X_VERSION_10_9) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_9)
  92. [view setAppearance: [NSAppearance appearanceNamed: NSAppearanceNameAqua]];
  93. #endif
  94. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  95. if (component.isAlwaysOnTop())
  96. setAlwaysOnTop (true);
  97. [window setContentView: view];
  98. [window setAcceptsMouseMovedEvents: YES];
  99. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  100. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  101. [window setReleasedWhenClosed: YES];
  102. [window retain];
  103. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  104. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  105. if ((windowStyleFlags & (windowHasMaximiseButton | windowHasTitleBar)) == (windowHasMaximiseButton | windowHasTitleBar))
  106. [window setCollectionBehavior: NSWindowCollectionBehaviorFullScreenPrimary];
  107. if ([window respondsToSelector: @selector (setRestorable:)])
  108. [window setRestorable: NO];
  109. #if defined (MAC_OS_X_VERSION_10_13) && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_13)
  110. if ([window respondsToSelector: @selector (setTabbingMode:)])
  111. [window setTabbingMode: NSWindowTabbingModeDisallowed];
  112. #endif
  113. [notificationCenter addObserver: view
  114. selector: frameChangedSelector
  115. name: NSWindowDidMoveNotification
  116. object: window];
  117. [notificationCenter addObserver: view
  118. selector: frameChangedSelector
  119. name: NSWindowDidMiniaturizeNotification
  120. object: window];
  121. [notificationCenter addObserver: view
  122. selector: @selector (windowWillMiniaturize:)
  123. name: NSWindowWillMiniaturizeNotification
  124. object: window];
  125. [notificationCenter addObserver: view
  126. selector: @selector (windowDidDeminiaturize:)
  127. name: NSWindowDidDeminiaturizeNotification
  128. object: window];
  129. }
  130. auto alpha = component.getAlpha();
  131. if (alpha < 1.0f)
  132. setAlpha (alpha);
  133. setTitle (component.getName());
  134. getNativeRealtimeModifiers = []
  135. {
  136. if ([NSEvent respondsToSelector: @selector (modifierFlags)])
  137. NSViewComponentPeer::updateModifiers ([NSEvent modifierFlags]);
  138. return ModifierKeys::currentModifiers;
  139. };
  140. }
  141. ~NSViewComponentPeer() override
  142. {
  143. [notificationCenter removeObserver: view];
  144. setOwner (view, nullptr);
  145. if ([view superview] != nil)
  146. {
  147. redirectWillMoveToWindow (nullptr);
  148. [view removeFromSuperview];
  149. }
  150. if (! isSharedWindow)
  151. {
  152. setOwner (window, nullptr);
  153. [window setContentView: nil];
  154. [window close];
  155. [window release];
  156. }
  157. [view release];
  158. }
  159. //==============================================================================
  160. void* getNativeHandle() const override { return view; }
  161. void setVisible (bool shouldBeVisible) override
  162. {
  163. if (isSharedWindow)
  164. {
  165. if (shouldBeVisible)
  166. [view setHidden: false];
  167. else if ([window firstResponder] != view || ([window firstResponder] == view && [window makeFirstResponder: nil]))
  168. [view setHidden: true];
  169. }
  170. else
  171. {
  172. if (shouldBeVisible)
  173. {
  174. ++insideToFrontCall;
  175. [window orderFront: nil];
  176. --insideToFrontCall;
  177. handleBroughtToFront();
  178. }
  179. else
  180. {
  181. [window orderOut: nil];
  182. }
  183. }
  184. }
  185. void setTitle (const String& title) override
  186. {
  187. JUCE_AUTORELEASEPOOL
  188. {
  189. if (! isSharedWindow)
  190. [window setTitle: juceStringToNS (title)];
  191. }
  192. }
  193. bool setDocumentEditedStatus (bool edited) override
  194. {
  195. if (! hasNativeTitleBar())
  196. return false;
  197. [window setDocumentEdited: edited];
  198. return true;
  199. }
  200. void setRepresentedFile (const File& file) override
  201. {
  202. if (! isSharedWindow)
  203. {
  204. [window setRepresentedFilename: juceStringToNS (file != File()
  205. ? file.getFullPathName()
  206. : String())];
  207. windowRepresentsFile = (file != File());
  208. }
  209. }
  210. void setBounds (const Rectangle<int>& newBounds, bool isNowFullScreen) override
  211. {
  212. fullScreen = isNowFullScreen;
  213. auto r = makeNSRect (newBounds);
  214. auto oldViewSize = [view frame].size;
  215. if (isSharedWindow)
  216. {
  217. [view setFrame: r];
  218. }
  219. else
  220. {
  221. // Repaint behaviour of setFrame seemed to change in 10.11, and the drawing became synchronous,
  222. // causing performance issues. But sending an async update causes flickering in older versions,
  223. // hence this version check to use the old behaviour on pre 10.11 machines
  224. static bool isPre10_11 = SystemStats::getOperatingSystemType() <= SystemStats::MacOSX_10_10;
  225. [window setFrame: [window frameRectForContentRect: flippedScreenRect (r)]
  226. display: isPre10_11];
  227. }
  228. if (oldViewSize.width != r.size.width || oldViewSize.height != r.size.height)
  229. [view setNeedsDisplay: true];
  230. }
  231. Rectangle<int> getBounds (const bool global) const
  232. {
  233. auto r = [view frame];
  234. NSWindow* viewWindow = [view window];
  235. if (global && viewWindow != nil)
  236. {
  237. r = [[view superview] convertRect: r toView: nil];
  238. r = [viewWindow convertRectToScreen: r];
  239. r = flippedScreenRect (r);
  240. }
  241. return convertToRectInt (r);
  242. }
  243. Rectangle<int> getBounds() const override
  244. {
  245. return getBounds (! isSharedWindow);
  246. }
  247. Point<float> localToGlobal (Point<float> relativePosition) override
  248. {
  249. return relativePosition + getBounds (true).getPosition().toFloat();
  250. }
  251. using ComponentPeer::localToGlobal;
  252. Point<float> globalToLocal (Point<float> screenPosition) override
  253. {
  254. return screenPosition - getBounds (true).getPosition().toFloat();
  255. }
  256. using ComponentPeer::globalToLocal;
  257. void setAlpha (float newAlpha) override
  258. {
  259. if (isSharedWindow)
  260. [view setAlphaValue: (CGFloat) newAlpha];
  261. else
  262. [window setAlphaValue: (CGFloat) newAlpha];
  263. }
  264. void setMinimised (bool shouldBeMinimised) override
  265. {
  266. if (! isSharedWindow)
  267. {
  268. if (shouldBeMinimised)
  269. [window miniaturize: nil];
  270. else
  271. [window deminiaturize: nil];
  272. }
  273. }
  274. bool isMinimised() const override
  275. {
  276. return [window isMiniaturized];
  277. }
  278. void setFullScreen (bool shouldBeFullScreen) override
  279. {
  280. if (! isSharedWindow)
  281. {
  282. auto r = lastNonFullscreenBounds;
  283. if (isMinimised())
  284. setMinimised (false);
  285. if (fullScreen != shouldBeFullScreen)
  286. {
  287. if (shouldBeFullScreen && hasNativeTitleBar())
  288. {
  289. fullScreen = true;
  290. [window performZoom: nil];
  291. }
  292. else
  293. {
  294. if (shouldBeFullScreen)
  295. r = component.getParentMonitorArea();
  296. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  297. if (r != component.getBounds() && ! r.isEmpty())
  298. setBounds (ScalingHelpers::scaledScreenPosToUnscaled (component, r), shouldBeFullScreen);
  299. }
  300. }
  301. }
  302. }
  303. bool isFullScreen() const override
  304. {
  305. return fullScreen;
  306. }
  307. bool isKioskMode() const override
  308. {
  309. return isWindowInKioskMode || ComponentPeer::isKioskMode();
  310. }
  311. static bool isWindowAtPoint (NSWindow* w, NSPoint screenPoint)
  312. {
  313. if ([NSWindow respondsToSelector: @selector (windowNumberAtPoint:belowWindowWithWindowNumber:)])
  314. return [NSWindow windowNumberAtPoint: screenPoint belowWindowWithWindowNumber: 0] == [w windowNumber];
  315. return true;
  316. }
  317. bool contains (Point<int> localPos, bool trueIfInAChildWindow) const override
  318. {
  319. NSRect viewFrame = [view frame];
  320. if (! (isPositiveAndBelow (localPos.getX(), viewFrame.size.width)
  321. && isPositiveAndBelow (localPos.getY(), viewFrame.size.height)))
  322. return false;
  323. if (! SystemStats::isRunningInAppExtensionSandbox())
  324. {
  325. if (NSWindow* const viewWindow = [view window])
  326. {
  327. NSRect windowFrame = [viewWindow frame];
  328. NSPoint windowPoint = [view convertPoint: NSMakePoint (localPos.x, localPos.y) toView: nil];
  329. NSPoint screenPoint = NSMakePoint (windowFrame.origin.x + windowPoint.x,
  330. windowFrame.origin.y + windowPoint.y);
  331. if (! isWindowAtPoint (viewWindow, screenPoint))
  332. return false;
  333. }
  334. }
  335. NSView* v = [view hitTest: NSMakePoint (viewFrame.origin.x + localPos.getX(),
  336. viewFrame.origin.y + localPos.getY())];
  337. return trueIfInAChildWindow ? (v != nil)
  338. : (v == view);
  339. }
  340. BorderSize<int> getFrameSize() const override
  341. {
  342. BorderSize<int> b;
  343. if (! isSharedWindow)
  344. {
  345. NSRect v = [view convertRect: [view frame] toView: nil];
  346. NSRect w = [window frame];
  347. b.setTop ((int) v.origin.y);
  348. b.setBottom ((int) (w.size.height - (v.origin.y + v.size.height)));
  349. b.setLeft ((int) v.origin.x);
  350. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  351. }
  352. return b;
  353. }
  354. void updateFullscreenStatus()
  355. {
  356. if (hasNativeTitleBar())
  357. {
  358. isWindowInKioskMode = (([window styleMask] & NSWindowStyleMaskFullScreen) != 0);
  359. auto screen = getFrameSize().subtractedFrom (component.getParentMonitorArea());
  360. fullScreen = component.getScreenBounds().expanded (2, 2).contains (screen);
  361. }
  362. else
  363. {
  364. isWindowInKioskMode = false;
  365. }
  366. }
  367. bool hasNativeTitleBar() const
  368. {
  369. return (getStyleFlags() & windowHasTitleBar) != 0;
  370. }
  371. bool setAlwaysOnTop (bool alwaysOnTop) override
  372. {
  373. if (! isSharedWindow)
  374. {
  375. [window setLevel: alwaysOnTop ? ((getStyleFlags() & windowIsTemporary) != 0 ? NSPopUpMenuWindowLevel
  376. : NSFloatingWindowLevel)
  377. : NSNormalWindowLevel];
  378. isAlwaysOnTop = alwaysOnTop;
  379. }
  380. return true;
  381. }
  382. void toFront (bool makeActiveWindow) override
  383. {
  384. if (isSharedWindow)
  385. {
  386. NSView* superview = [view superview];
  387. NSMutableArray* subviews = [NSMutableArray arrayWithArray: [superview subviews]];
  388. const auto isFrontmost = [[subviews lastObject] isEqual: view];
  389. if (! isFrontmost)
  390. {
  391. [view retain];
  392. [subviews removeObject: view];
  393. [subviews addObject: view];
  394. [superview setSubviews: subviews];
  395. [view release];
  396. }
  397. }
  398. if (window != nil && component.isVisible())
  399. {
  400. ++insideToFrontCall;
  401. if (makeActiveWindow)
  402. [window makeKeyAndOrderFront: nil];
  403. else
  404. [window orderFront: nil];
  405. if (insideToFrontCall <= 1)
  406. {
  407. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  408. handleBroughtToFront();
  409. }
  410. --insideToFrontCall;
  411. }
  412. }
  413. void toBehind (ComponentPeer* other) override
  414. {
  415. if (auto* otherPeer = dynamic_cast<NSViewComponentPeer*> (other))
  416. {
  417. if (isSharedWindow)
  418. {
  419. NSView* superview = [view superview];
  420. NSMutableArray* subviews = [NSMutableArray arrayWithArray: [superview subviews]];
  421. const auto otherViewIndex = [subviews indexOfObject: otherPeer->view];
  422. if (otherViewIndex == NSNotFound)
  423. return;
  424. const auto isBehind = [subviews indexOfObject: view] < otherViewIndex;
  425. if (! isBehind)
  426. {
  427. [view retain];
  428. [subviews removeObject: view];
  429. [subviews insertObject: view
  430. atIndex: otherViewIndex];
  431. [superview setSubviews: subviews];
  432. [view release];
  433. }
  434. }
  435. else if (component.isVisible())
  436. {
  437. [window orderWindow: NSWindowBelow
  438. relativeTo: [otherPeer->window windowNumber]];
  439. }
  440. }
  441. else
  442. {
  443. jassertfalse; // wrong type of window?
  444. }
  445. }
  446. void setIcon (const Image& newIcon) override
  447. {
  448. if (! isSharedWindow)
  449. {
  450. // need to set a dummy represented file here to show the file icon (which we then set to the new icon)
  451. if (! windowRepresentsFile)
  452. [window setRepresentedFilename:juceStringToNS (" ")]; // can't just use an empty string for some reason...
  453. [[window standardWindowButton:NSWindowDocumentIconButton] setImage:imageToNSImage (newIcon)];
  454. }
  455. }
  456. StringArray getAvailableRenderingEngines() override
  457. {
  458. StringArray s ("Software Renderer");
  459. #if USE_COREGRAPHICS_RENDERING
  460. s.add ("CoreGraphics Renderer");
  461. #endif
  462. return s;
  463. }
  464. int getCurrentRenderingEngine() const override
  465. {
  466. return usingCoreGraphics ? 1 : 0;
  467. }
  468. void setCurrentRenderingEngine (int index) override
  469. {
  470. #if USE_COREGRAPHICS_RENDERING
  471. if (usingCoreGraphics != (index > 0))
  472. {
  473. usingCoreGraphics = index > 0;
  474. [view setNeedsDisplay: true];
  475. }
  476. #else
  477. ignoreUnused (index);
  478. #endif
  479. }
  480. void redirectMouseDown (NSEvent* ev)
  481. {
  482. if (! Process::isForegroundProcess())
  483. Process::makeForegroundProcess();
  484. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  485. sendMouseEvent (ev);
  486. }
  487. void redirectMouseUp (NSEvent* ev)
  488. {
  489. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  490. sendMouseEvent (ev);
  491. showArrowCursorIfNeeded();
  492. }
  493. void redirectMouseDrag (NSEvent* ev)
  494. {
  495. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  496. sendMouseEvent (ev);
  497. }
  498. void redirectMouseMove (NSEvent* ev)
  499. {
  500. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons();
  501. NSPoint windowPos = [ev locationInWindow];
  502. NSPoint screenPos = [[ev window] convertRectToScreen: NSMakeRect (windowPos.x, windowPos.y, 1.0f, 1.0f)].origin;
  503. if (isWindowAtPoint ([ev window], screenPos))
  504. sendMouseEvent (ev);
  505. else
  506. // moved into another window which overlaps this one, so trigger an exit
  507. handleMouseEvent (MouseInputSource::InputSourceType::mouse, MouseInputSource::offscreenMousePos, ModifierKeys::currentModifiers,
  508. getMousePressure (ev), MouseInputSource::invalidOrientation, getMouseTime (ev));
  509. showArrowCursorIfNeeded();
  510. }
  511. void redirectMouseEnter (NSEvent* ev)
  512. {
  513. if (shouldIgnoreMouseEnterExit (ev))
  514. return;
  515. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  516. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons();
  517. sendMouseEvent (ev);
  518. }
  519. void redirectMouseExit (NSEvent* ev)
  520. {
  521. if (shouldIgnoreMouseEnterExit (ev))
  522. return;
  523. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons();
  524. sendMouseEvent (ev);
  525. }
  526. static float checkDeviceDeltaReturnValue (float v) noexcept
  527. {
  528. // (deviceDeltaX can fail and return NaN, so need to sanity-check the result)
  529. v *= 0.5f / 256.0f;
  530. return (v > -1000.0f && v < 1000.0f) ? v : 0.0f;
  531. }
  532. void redirectMouseWheel (NSEvent* ev)
  533. {
  534. updateModifiers (ev);
  535. MouseWheelDetails wheel;
  536. wheel.deltaX = 0;
  537. wheel.deltaY = 0;
  538. wheel.isReversed = false;
  539. wheel.isSmooth = false;
  540. wheel.isInertial = false;
  541. @try
  542. {
  543. if ([ev respondsToSelector: @selector (isDirectionInvertedFromDevice)])
  544. wheel.isReversed = [ev isDirectionInvertedFromDevice];
  545. wheel.isInertial = ([ev momentumPhase] != NSEventPhaseNone);
  546. if ([ev respondsToSelector: @selector (hasPreciseScrollingDeltas)])
  547. {
  548. if ([ev hasPreciseScrollingDeltas])
  549. {
  550. const float scale = 0.5f / 256.0f;
  551. wheel.deltaX = scale * (float) [ev scrollingDeltaX];
  552. wheel.deltaY = scale * (float) [ev scrollingDeltaY];
  553. wheel.isSmooth = true;
  554. }
  555. }
  556. else if ([ev respondsToSelector: @selector (deviceDeltaX)])
  557. {
  558. wheel.deltaX = checkDeviceDeltaReturnValue ([ev deviceDeltaX]);
  559. wheel.deltaY = checkDeviceDeltaReturnValue ([ev deviceDeltaY]);
  560. }
  561. }
  562. @catch (...)
  563. {}
  564. if (wheel.deltaX == 0.0f && wheel.deltaY == 0.0f)
  565. {
  566. const float scale = 10.0f / 256.0f;
  567. wheel.deltaX = scale * (float) [ev deltaX];
  568. wheel.deltaY = scale * (float) [ev deltaY];
  569. }
  570. handleMouseWheel (MouseInputSource::InputSourceType::mouse, getMousePos (ev, view), getMouseTime (ev), wheel);
  571. }
  572. void redirectMagnify (NSEvent* ev)
  573. {
  574. const float invScale = 1.0f - (float) [ev magnification];
  575. if (invScale > 0.0f)
  576. handleMagnifyGesture (MouseInputSource::InputSourceType::mouse, getMousePos (ev, view), getMouseTime (ev), 1.0f / invScale);
  577. }
  578. void redirectCopy (NSObject*) { handleKeyPress (KeyPress ('c', ModifierKeys (ModifierKeys::commandModifier), 'c')); }
  579. void redirectPaste (NSObject*) { handleKeyPress (KeyPress ('v', ModifierKeys (ModifierKeys::commandModifier), 'v')); }
  580. void redirectCut (NSObject*) { handleKeyPress (KeyPress ('x', ModifierKeys (ModifierKeys::commandModifier), 'x')); }
  581. void redirectSelectAll (NSObject*) { handleKeyPress (KeyPress ('a', ModifierKeys (ModifierKeys::commandModifier), 'a')); }
  582. void redirectWillMoveToWindow (NSWindow* newWindow)
  583. {
  584. if (auto* currentWindow = [view window])
  585. {
  586. [notificationCenter removeObserver: view
  587. name: NSWindowDidMoveNotification
  588. object: currentWindow];
  589. [notificationCenter removeObserver: view
  590. name: NSWindowWillMiniaturizeNotification
  591. object: currentWindow];
  592. #if JUCE_COREGRAPHICS_DRAW_ASYNC
  593. [notificationCenter removeObserver: view
  594. name: NSWindowDidBecomeKeyNotification
  595. object: currentWindow];
  596. #endif
  597. }
  598. if (isSharedWindow && [view window] == window && newWindow == nullptr)
  599. {
  600. if (auto* comp = safeComponent.get())
  601. comp->setVisible (false);
  602. }
  603. }
  604. void sendMouseEvent (NSEvent* ev)
  605. {
  606. updateModifiers (ev);
  607. handleMouseEvent (MouseInputSource::InputSourceType::mouse, getMousePos (ev, view), ModifierKeys::currentModifiers,
  608. getMousePressure (ev), MouseInputSource::invalidOrientation, getMouseTime (ev));
  609. }
  610. bool handleKeyEvent (NSEvent* ev, bool isKeyDown)
  611. {
  612. auto unicode = nsStringToJuce ([ev characters]);
  613. auto keyCode = getKeyCodeFromEvent (ev);
  614. #if JUCE_DEBUG_KEYCODES
  615. DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  616. auto unmodified = nsStringToJuce ([ev charactersIgnoringModifiers]);
  617. DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  618. #endif
  619. if (keyCode != 0 || unicode.isNotEmpty())
  620. {
  621. if (isKeyDown)
  622. {
  623. bool used = false;
  624. for (auto u = unicode.getCharPointer(); ! u.isEmpty();)
  625. {
  626. auto textCharacter = u.getAndAdvance();
  627. switch (keyCode)
  628. {
  629. case NSLeftArrowFunctionKey:
  630. case NSRightArrowFunctionKey:
  631. case NSUpArrowFunctionKey:
  632. case NSDownArrowFunctionKey:
  633. case NSPageUpFunctionKey:
  634. case NSPageDownFunctionKey:
  635. case NSEndFunctionKey:
  636. case NSHomeFunctionKey:
  637. case NSDeleteFunctionKey:
  638. textCharacter = 0;
  639. break; // (these all seem to generate unwanted garbage unicode strings)
  640. default:
  641. if (([ev modifierFlags] & NSEventModifierFlagCommand) != 0
  642. || (keyCode >= NSF1FunctionKey && keyCode <= NSF35FunctionKey))
  643. textCharacter = 0;
  644. break;
  645. }
  646. used = handleKeyUpOrDown (true) || used;
  647. used = handleKeyPress (keyCode, textCharacter) || used;
  648. }
  649. return used;
  650. }
  651. if (handleKeyUpOrDown (false))
  652. return true;
  653. }
  654. return false;
  655. }
  656. bool redirectKeyDown (NSEvent* ev)
  657. {
  658. // (need to retain this in case a modal loop runs in handleKeyEvent and
  659. // our event object gets lost)
  660. const NSUniquePtr<NSEvent> r ([ev retain]);
  661. updateKeysDown (ev, true);
  662. bool used = handleKeyEvent (ev, true);
  663. if (([ev modifierFlags] & NSEventModifierFlagCommand) != 0)
  664. {
  665. // for command keys, the key-up event is thrown away, so simulate one..
  666. updateKeysDown (ev, false);
  667. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  668. }
  669. // (If we're running modally, don't allow unused keystrokes to be passed
  670. // along to other blocked views..)
  671. if (Component::getCurrentlyModalComponent() != nullptr)
  672. used = true;
  673. return used;
  674. }
  675. bool redirectKeyUp (NSEvent* ev)
  676. {
  677. updateKeysDown (ev, false);
  678. return handleKeyEvent (ev, false)
  679. || Component::getCurrentlyModalComponent() != nullptr;
  680. }
  681. void redirectModKeyChange (NSEvent* ev)
  682. {
  683. // (need to retain this in case a modal loop runs and our event object gets lost)
  684. const NSUniquePtr<NSEvent> r ([ev retain]);
  685. keysCurrentlyDown.clear();
  686. handleKeyUpOrDown (true);
  687. updateModifiers (ev);
  688. handleModifierKeysChange();
  689. }
  690. //==============================================================================
  691. void drawRect (NSRect r)
  692. {
  693. if (r.size.width < 1.0f || r.size.height < 1.0f)
  694. return;
  695. auto cg = (CGContextRef) [[NSGraphicsContext currentContext]
  696. #if (defined (MAC_OS_X_VERSION_10_10) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_10)
  697. CGContext];
  698. #else
  699. graphicsPort];
  700. #endif
  701. if (! component.isOpaque())
  702. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  703. float displayScale = 1.0f;
  704. NSScreen* screen = [[view window] screen];
  705. if ([screen respondsToSelector: @selector (backingScaleFactor)])
  706. displayScale = (float) screen.backingScaleFactor;
  707. auto invalidateTransparentWindowShadow = [this]
  708. {
  709. // transparent NSWindows with a drop-shadow need to redraw their shadow when the content
  710. // changes to avoid stale shadows being drawn behind the window
  711. if (! isSharedWindow && ! [window isOpaque] && [window hasShadow])
  712. [window invalidateShadow];
  713. };
  714. #if USE_COREGRAPHICS_RENDERING && JUCE_COREGRAPHICS_RENDER_WITH_MULTIPLE_PAINT_CALLS
  715. // This option invokes a separate paint call for each rectangle of the clip region.
  716. // It's a long story, but this is a basically a workaround for a CGContext not having
  717. // a way of finding whether a rectangle falls within its clip region
  718. if (usingCoreGraphics)
  719. {
  720. const NSRect* rects = nullptr;
  721. NSInteger numRects = 0;
  722. [view getRectsBeingDrawn: &rects count: &numRects];
  723. if (numRects > 1)
  724. {
  725. for (int i = 0; i < numRects; ++i)
  726. {
  727. NSRect rect = rects[i];
  728. CGContextSaveGState (cg);
  729. CGContextClipToRect (cg, CGRectMake (rect.origin.x, rect.origin.y, rect.size.width, rect.size.height));
  730. drawRect (cg, rect, displayScale);
  731. CGContextRestoreGState (cg);
  732. }
  733. invalidateTransparentWindowShadow();
  734. return;
  735. }
  736. }
  737. #endif
  738. drawRect (cg, r, displayScale);
  739. invalidateTransparentWindowShadow();
  740. }
  741. void drawRect (CGContextRef cg, NSRect r, float displayScale)
  742. {
  743. #if USE_COREGRAPHICS_RENDERING
  744. if (usingCoreGraphics)
  745. {
  746. const auto height = getComponent().getHeight();
  747. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, height));
  748. CoreGraphicsContext context (cg, (float) height);
  749. handlePaint (context);
  750. }
  751. else
  752. #endif
  753. {
  754. const Point<int> offset (-roundToInt (r.origin.x), -roundToInt (r.origin.y));
  755. auto clipW = (int) (r.size.width + 0.5f);
  756. auto clipH = (int) (r.size.height + 0.5f);
  757. RectangleList<int> clip;
  758. getClipRects (clip, offset, clipW, clipH);
  759. if (! clip.isEmpty())
  760. {
  761. Image temp (component.isOpaque() ? Image::RGB : Image::ARGB,
  762. roundToInt (clipW * displayScale),
  763. roundToInt (clipH * displayScale),
  764. ! component.isOpaque());
  765. {
  766. auto intScale = roundToInt (displayScale);
  767. if (intScale != 1)
  768. clip.scaleAll (intScale);
  769. auto context = component.getLookAndFeel()
  770. .createGraphicsContext (temp, offset * intScale, clip);
  771. if (intScale != 1)
  772. context->addTransform (AffineTransform::scale (displayScale));
  773. handlePaint (*context);
  774. }
  775. detail::ColorSpacePtr colourSpace { CGColorSpaceCreateWithName (kCGColorSpaceSRGB) };
  776. CGImageRef image = juce_createCoreGraphicsImage (temp, colourSpace.get(), false);
  777. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, r.origin.x, r.origin.y + clipH));
  778. CGContextDrawImage (cg, CGRectMake (0.0f, 0.0f, clipW, clipH), image);
  779. CGImageRelease (image);
  780. }
  781. }
  782. }
  783. void repaint (const Rectangle<int>& area) override
  784. {
  785. // In 10.11 changes were made to the way the OS handles repaint regions, and it seems that it can
  786. // no longer be trusted to coalesce all the regions, or to even remember them all without losing
  787. // a few when there's a lot of activity.
  788. // As a work around for this, we use a RectangleList to do our own coalescing of regions before
  789. // asynchronously asking the OS to repaint them.
  790. deferredRepaints.add ((float) area.getX(), (float) area.getY(),
  791. (float) area.getWidth(), (float) area.getHeight());
  792. if (isTimerRunning())
  793. return;
  794. auto now = Time::getMillisecondCounter();
  795. auto msSinceLastRepaint = (lastRepaintTime >= now) ? now - lastRepaintTime
  796. : (std::numeric_limits<uint32>::max() - lastRepaintTime) + now;
  797. static uint32 minimumRepaintInterval = 1000 / 30; // 30fps
  798. // When windows are being resized, artificially throttling high-frequency repaints helps
  799. // to stop the event queue getting clogged, and keeps everything working smoothly.
  800. // For some reason Logic also needs this throttling to record parameter events correctly.
  801. if (msSinceLastRepaint < minimumRepaintInterval && shouldThrottleRepaint())
  802. {
  803. startTimer (static_cast<int> (minimumRepaintInterval - msSinceLastRepaint));
  804. return;
  805. }
  806. setNeedsDisplayRectangles();
  807. }
  808. static bool shouldThrottleRepaint()
  809. {
  810. return areAnyWindowsInLiveResize() || ! JUCEApplication::isStandaloneApp();
  811. }
  812. void timerCallback() override
  813. {
  814. setNeedsDisplayRectangles();
  815. stopTimer();
  816. }
  817. void setNeedsDisplayRectangles()
  818. {
  819. for (auto& i : deferredRepaints)
  820. [view setNeedsDisplayInRect: makeNSRect (i)];
  821. lastRepaintTime = Time::getMillisecondCounter();
  822. deferredRepaints.clear();
  823. }
  824. void performAnyPendingRepaintsNow() override
  825. {
  826. [view displayIfNeeded];
  827. }
  828. static bool areAnyWindowsInLiveResize() noexcept
  829. {
  830. for (NSWindow* w in [NSApp windows])
  831. if ([w inLiveResize])
  832. return true;
  833. return false;
  834. }
  835. //==============================================================================
  836. bool isBlockedByModalComponent()
  837. {
  838. if (auto* modal = Component::getCurrentlyModalComponent())
  839. {
  840. if (insideToFrontCall == 0
  841. && (! getComponent().isParentOf (modal))
  842. && getComponent().isCurrentlyBlockedByAnotherModalComponent())
  843. {
  844. return true;
  845. }
  846. }
  847. return false;
  848. }
  849. void sendModalInputAttemptIfBlocked()
  850. {
  851. if (isBlockedByModalComponent())
  852. if (auto* modal = Component::getCurrentlyModalComponent())
  853. modal->inputAttemptWhenModal();
  854. }
  855. bool canBecomeKeyWindow()
  856. {
  857. return component.isVisible() && (getStyleFlags() & juce::ComponentPeer::windowIgnoresKeyPresses) == 0;
  858. }
  859. bool canBecomeMainWindow()
  860. {
  861. return component.isVisible() && dynamic_cast<ResizableWindow*> (&component) != nullptr;
  862. }
  863. bool worksWhenModal() const
  864. {
  865. // In plugins, the host could put our plugin window inside a modal window, so this
  866. // allows us to successfully open other popups. Feels like there could be edge-case
  867. // problems caused by this, so let us know if you spot any issues..
  868. return ! JUCEApplication::isStandaloneApp();
  869. }
  870. void becomeKeyWindow()
  871. {
  872. handleBroughtToFront();
  873. grabFocus();
  874. }
  875. void resignKeyWindow()
  876. {
  877. viewFocusLoss();
  878. }
  879. bool windowShouldClose()
  880. {
  881. if (! isValidPeer (this))
  882. return YES;
  883. handleUserClosingWindow();
  884. return NO;
  885. }
  886. void redirectMovedOrResized()
  887. {
  888. updateFullscreenStatus();
  889. handleMovedOrResized();
  890. }
  891. void viewMovedToWindow()
  892. {
  893. if (isSharedWindow)
  894. {
  895. auto newWindow = [view window];
  896. bool shouldSetVisible = (window == nullptr && newWindow != nullptr);
  897. window = newWindow;
  898. if (shouldSetVisible)
  899. getComponent().setVisible (true);
  900. }
  901. if (auto* currentWindow = [view window])
  902. {
  903. [notificationCenter addObserver: view
  904. selector: dismissModalsSelector
  905. name: NSWindowDidMoveNotification
  906. object: currentWindow];
  907. [notificationCenter addObserver: view
  908. selector: dismissModalsSelector
  909. name: NSWindowWillMiniaturizeNotification
  910. object: currentWindow];
  911. #if JUCE_COREGRAPHICS_DRAW_ASYNC
  912. [notificationCenter addObserver: view
  913. selector: becomeKeySelector
  914. name: NSWindowDidBecomeKeyNotification
  915. object: currentWindow];
  916. #endif
  917. }
  918. }
  919. void dismissModals()
  920. {
  921. if (hasNativeTitleBar() || isSharedWindow)
  922. sendModalInputAttemptIfBlocked();
  923. }
  924. void becomeKey()
  925. {
  926. component.repaint();
  927. }
  928. void liveResizingStart()
  929. {
  930. if (constrainer == nullptr)
  931. return;
  932. constrainer->resizeStart();
  933. isFirstLiveResize = true;
  934. setFullScreenSizeConstraints (*constrainer);
  935. }
  936. void liveResizingEnd()
  937. {
  938. if (constrainer != nullptr)
  939. constrainer->resizeEnd();
  940. }
  941. NSRect constrainRect (const NSRect r)
  942. {
  943. if (constrainer == nullptr || isKioskMode())
  944. return r;
  945. const auto scale = getComponent().getDesktopScaleFactor();
  946. auto pos = ScalingHelpers::unscaledScreenPosToScaled (scale, convertToRectInt (flippedScreenRect (r)));
  947. const auto original = ScalingHelpers::unscaledScreenPosToScaled (scale, convertToRectInt (flippedScreenRect ([window frame])));
  948. const auto screenBounds = Desktop::getInstance().getDisplays().getTotalBounds (true);
  949. const bool inLiveResize = [window inLiveResize];
  950. if (! inLiveResize || isFirstLiveResize)
  951. {
  952. isFirstLiveResize = false;
  953. isStretchingTop = (pos.getY() != original.getY() && pos.getBottom() == original.getBottom());
  954. isStretchingLeft = (pos.getX() != original.getX() && pos.getRight() == original.getRight());
  955. isStretchingBottom = (pos.getY() == original.getY() && pos.getBottom() != original.getBottom());
  956. isStretchingRight = (pos.getX() == original.getX() && pos.getRight() != original.getRight());
  957. }
  958. constrainer->checkBounds (pos, original, screenBounds,
  959. isStretchingTop, isStretchingLeft, isStretchingBottom, isStretchingRight);
  960. return flippedScreenRect (makeNSRect (ScalingHelpers::scaledScreenPosToUnscaled (scale, pos)));
  961. }
  962. static void showArrowCursorIfNeeded()
  963. {
  964. auto& desktop = Desktop::getInstance();
  965. auto mouse = desktop.getMainMouseSource();
  966. if (mouse.getComponentUnderMouse() == nullptr
  967. && desktop.findComponentAt (mouse.getScreenPosition().roundToInt()) == nullptr)
  968. {
  969. [[NSCursor arrowCursor] set];
  970. }
  971. }
  972. static void updateModifiers (NSEvent* e)
  973. {
  974. updateModifiers ([e modifierFlags]);
  975. }
  976. static void updateModifiers (const NSUInteger flags)
  977. {
  978. int m = 0;
  979. if ((flags & NSEventModifierFlagShift) != 0) m |= ModifierKeys::shiftModifier;
  980. if ((flags & NSEventModifierFlagControl) != 0) m |= ModifierKeys::ctrlModifier;
  981. if ((flags & NSEventModifierFlagOption) != 0) m |= ModifierKeys::altModifier;
  982. if ((flags & NSEventModifierFlagCommand) != 0) m |= ModifierKeys::commandModifier;
  983. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withOnlyMouseButtons().withFlags (m);
  984. }
  985. static void updateKeysDown (NSEvent* ev, bool isKeyDown)
  986. {
  987. updateModifiers (ev);
  988. if (auto keyCode = getKeyCodeFromEvent (ev))
  989. {
  990. if (isKeyDown)
  991. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  992. else
  993. keysCurrentlyDown.removeFirstMatchingValue (keyCode);
  994. }
  995. }
  996. static int getKeyCodeFromEvent (NSEvent* ev)
  997. {
  998. // Unfortunately, charactersIgnoringModifiers does not ignore the shift key.
  999. // Using [ev keyCode] is not a solution either as this will,
  1000. // for example, return VK_KEY_Y if the key is pressed which
  1001. // is typically located at the Y key position on a QWERTY
  1002. // keyboard. However, on international keyboards this might not
  1003. // be the key labeled Y (for example, on German keyboards this key
  1004. // has a Z label). Therefore, we need to query the current keyboard
  1005. // layout to figure out what character the key would have produced
  1006. // if the shift key was not pressed
  1007. String unmodified;
  1008. #if JUCE_SUPPORT_CARBON
  1009. if (auto currentKeyboard = CFUniquePtr<TISInputSourceRef> (TISCopyCurrentKeyboardInputSource()))
  1010. {
  1011. if (auto layoutData = (CFDataRef) TISGetInputSourceProperty (currentKeyboard,
  1012. kTISPropertyUnicodeKeyLayoutData))
  1013. {
  1014. if (auto* layoutPtr = (const UCKeyboardLayout*) CFDataGetBytePtr (layoutData))
  1015. {
  1016. UInt32 keysDown = 0;
  1017. UniChar buffer[4];
  1018. UniCharCount actual;
  1019. if (UCKeyTranslate (layoutPtr, [ev keyCode], kUCKeyActionDown, 0, LMGetKbdType(),
  1020. kUCKeyTranslateNoDeadKeysBit, &keysDown, sizeof (buffer) / sizeof (UniChar),
  1021. &actual, buffer) == 0)
  1022. unmodified = String (CharPointer_UTF16 (reinterpret_cast<CharPointer_UTF16::CharType*> (buffer)), 4);
  1023. }
  1024. }
  1025. }
  1026. // did the above layout conversion fail
  1027. if (unmodified.isEmpty())
  1028. #endif
  1029. {
  1030. unmodified = nsStringToJuce ([ev charactersIgnoringModifiers]);
  1031. }
  1032. auto keyCode = (int) unmodified[0];
  1033. if (keyCode == 0x19) // (backwards-tab)
  1034. keyCode = '\t';
  1035. else if (keyCode == 0x03) // (enter)
  1036. keyCode = '\r';
  1037. else
  1038. keyCode = (int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  1039. if (([ev modifierFlags] & NSEventModifierFlagNumericPad) != 0)
  1040. {
  1041. const int numPadConversions[] = { '0', KeyPress::numberPad0, '1', KeyPress::numberPad1,
  1042. '2', KeyPress::numberPad2, '3', KeyPress::numberPad3,
  1043. '4', KeyPress::numberPad4, '5', KeyPress::numberPad5,
  1044. '6', KeyPress::numberPad6, '7', KeyPress::numberPad7,
  1045. '8', KeyPress::numberPad8, '9', KeyPress::numberPad9,
  1046. '+', KeyPress::numberPadAdd, '-', KeyPress::numberPadSubtract,
  1047. '*', KeyPress::numberPadMultiply, '/', KeyPress::numberPadDivide,
  1048. '.', KeyPress::numberPadDecimalPoint,
  1049. ',', KeyPress::numberPadDecimalPoint, // (to deal with non-english kbds)
  1050. '=', KeyPress::numberPadEquals };
  1051. for (int i = 0; i < numElementsInArray (numPadConversions); i += 2)
  1052. if (keyCode == numPadConversions [i])
  1053. keyCode = numPadConversions [i + 1];
  1054. }
  1055. return keyCode;
  1056. }
  1057. static int64 getMouseTime (NSEvent* e) noexcept
  1058. {
  1059. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  1060. + (int64) ([e timestamp] * 1000.0);
  1061. }
  1062. static float getMousePressure (NSEvent* e) noexcept
  1063. {
  1064. @try
  1065. {
  1066. if (e.type != NSEventTypeMouseEntered && e.type != NSEventTypeMouseExited)
  1067. return (float) e.pressure;
  1068. }
  1069. @catch (NSException* e) {}
  1070. @finally {}
  1071. return 0.0f;
  1072. }
  1073. static Point<float> getMousePos (NSEvent* e, NSView* view)
  1074. {
  1075. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  1076. return { (float) p.x, (float) p.y };
  1077. }
  1078. static int getModifierForButtonNumber (const NSInteger num)
  1079. {
  1080. return num == 0 ? ModifierKeys::leftButtonModifier
  1081. : (num == 1 ? ModifierKeys::rightButtonModifier
  1082. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  1083. }
  1084. static unsigned int getNSWindowStyleMask (const int flags) noexcept
  1085. {
  1086. unsigned int style = (flags & windowHasTitleBar) != 0 ? NSWindowStyleMaskTitled
  1087. : NSWindowStyleMaskBorderless;
  1088. if ((flags & windowHasMinimiseButton) != 0) style |= NSWindowStyleMaskMiniaturizable;
  1089. if ((flags & windowHasCloseButton) != 0) style |= NSWindowStyleMaskClosable;
  1090. if ((flags & windowIsResizable) != 0) style |= NSWindowStyleMaskResizable;
  1091. return style;
  1092. }
  1093. static NSArray* getSupportedDragTypes()
  1094. {
  1095. const auto type =
  1096. #if defined (MAC_OS_X_VERSION_10_13) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_13
  1097. NSPasteboardTypeFileURL;
  1098. #else
  1099. kUTTypeFileURL;
  1100. #endif
  1101. return [NSArray arrayWithObjects: (NSString*) 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 (NSFoundationVersionNumber > (double) NSFoundationVersionNumber10_11_Max)
  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 self, SEL)
  1770. {
  1771. return ! [self isAccessibilityElement];
  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. return [getAccessibleChild (self) accessibilitySubrole];
  1962. }
  1963. };
  1964. NSView* NSViewComponentPeer::createViewInstance()
  1965. {
  1966. static JuceNSViewClass cls;
  1967. return cls.createInstance();
  1968. }
  1969. NSWindow* NSViewComponentPeer::createWindowInstance()
  1970. {
  1971. static JuceNSWindowClass cls;
  1972. return cls.createInstance();
  1973. }
  1974. //==============================================================================
  1975. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = nullptr;
  1976. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  1977. //==============================================================================
  1978. bool KeyPress::isKeyCurrentlyDown (int keyCode)
  1979. {
  1980. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  1981. return true;
  1982. if (keyCode >= 'A' && keyCode <= 'Z'
  1983. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  1984. return true;
  1985. if (keyCode >= 'a' && keyCode <= 'z'
  1986. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  1987. return true;
  1988. return false;
  1989. }
  1990. //==============================================================================
  1991. bool MouseInputSource::SourceList::addSource()
  1992. {
  1993. if (sources.size() == 0)
  1994. {
  1995. addSource (0, MouseInputSource::InputSourceType::mouse);
  1996. return true;
  1997. }
  1998. return false;
  1999. }
  2000. bool MouseInputSource::SourceList::canUseTouch()
  2001. {
  2002. return false;
  2003. }
  2004. //==============================================================================
  2005. void Desktop::setKioskComponent (Component* kioskComp, bool shouldBeEnabled, bool allowMenusAndBars)
  2006. {
  2007. auto* peer = dynamic_cast<NSViewComponentPeer*> (kioskComp->getPeer());
  2008. jassert (peer != nullptr); // (this should have been checked by the caller)
  2009. if (peer->hasNativeTitleBar()
  2010. && [peer->window respondsToSelector: @selector (toggleFullScreen:)])
  2011. {
  2012. if (shouldBeEnabled && ! allowMenusAndBars)
  2013. [NSApp setPresentationOptions: NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar];
  2014. else if (! shouldBeEnabled)
  2015. [NSApp setPresentationOptions: NSApplicationPresentationDefault];
  2016. [peer->window performSelector: @selector (toggleFullScreen:) withObject: nil];
  2017. }
  2018. else
  2019. {
  2020. if (shouldBeEnabled)
  2021. {
  2022. if (peer->hasNativeTitleBar())
  2023. [peer->window setStyleMask: NSWindowStyleMaskBorderless];
  2024. [NSApp setPresentationOptions: (allowMenusAndBars ? (NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)
  2025. : (NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar))];
  2026. kioskComp->setBounds (getDisplays().getDisplayForRect (kioskComp->getScreenBounds())->totalArea);
  2027. peer->becomeKeyWindow();
  2028. }
  2029. else
  2030. {
  2031. peer->resetWindowPresentation();
  2032. }
  2033. }
  2034. }
  2035. void Desktop::allowedOrientationsChanged() {}
  2036. //==============================================================================
  2037. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  2038. {
  2039. return new NSViewComponentPeer (*this, styleFlags, (NSView*) windowToAttachTo);
  2040. }
  2041. //==============================================================================
  2042. const int KeyPress::spaceKey = ' ';
  2043. const int KeyPress::returnKey = 0x0d;
  2044. const int KeyPress::escapeKey = 0x1b;
  2045. const int KeyPress::backspaceKey = 0x7f;
  2046. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  2047. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  2048. const int KeyPress::upKey = NSUpArrowFunctionKey;
  2049. const int KeyPress::downKey = NSDownArrowFunctionKey;
  2050. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  2051. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  2052. const int KeyPress::endKey = NSEndFunctionKey;
  2053. const int KeyPress::homeKey = NSHomeFunctionKey;
  2054. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  2055. const int KeyPress::insertKey = -1;
  2056. const int KeyPress::tabKey = 9;
  2057. const int KeyPress::F1Key = NSF1FunctionKey;
  2058. const int KeyPress::F2Key = NSF2FunctionKey;
  2059. const int KeyPress::F3Key = NSF3FunctionKey;
  2060. const int KeyPress::F4Key = NSF4FunctionKey;
  2061. const int KeyPress::F5Key = NSF5FunctionKey;
  2062. const int KeyPress::F6Key = NSF6FunctionKey;
  2063. const int KeyPress::F7Key = NSF7FunctionKey;
  2064. const int KeyPress::F8Key = NSF8FunctionKey;
  2065. const int KeyPress::F9Key = NSF9FunctionKey;
  2066. const int KeyPress::F10Key = NSF10FunctionKey;
  2067. const int KeyPress::F11Key = NSF11FunctionKey;
  2068. const int KeyPress::F12Key = NSF12FunctionKey;
  2069. const int KeyPress::F13Key = NSF13FunctionKey;
  2070. const int KeyPress::F14Key = NSF14FunctionKey;
  2071. const int KeyPress::F15Key = NSF15FunctionKey;
  2072. const int KeyPress::F16Key = NSF16FunctionKey;
  2073. const int KeyPress::F17Key = NSF17FunctionKey;
  2074. const int KeyPress::F18Key = NSF18FunctionKey;
  2075. const int KeyPress::F19Key = NSF19FunctionKey;
  2076. const int KeyPress::F20Key = NSF20FunctionKey;
  2077. const int KeyPress::F21Key = NSF21FunctionKey;
  2078. const int KeyPress::F22Key = NSF22FunctionKey;
  2079. const int KeyPress::F23Key = NSF23FunctionKey;
  2080. const int KeyPress::F24Key = NSF24FunctionKey;
  2081. const int KeyPress::F25Key = NSF25FunctionKey;
  2082. const int KeyPress::F26Key = NSF26FunctionKey;
  2083. const int KeyPress::F27Key = NSF27FunctionKey;
  2084. const int KeyPress::F28Key = NSF28FunctionKey;
  2085. const int KeyPress::F29Key = NSF29FunctionKey;
  2086. const int KeyPress::F30Key = NSF30FunctionKey;
  2087. const int KeyPress::F31Key = NSF31FunctionKey;
  2088. const int KeyPress::F32Key = NSF32FunctionKey;
  2089. const int KeyPress::F33Key = NSF33FunctionKey;
  2090. const int KeyPress::F34Key = NSF34FunctionKey;
  2091. const int KeyPress::F35Key = NSF35FunctionKey;
  2092. const int KeyPress::numberPad0 = 0x30020;
  2093. const int KeyPress::numberPad1 = 0x30021;
  2094. const int KeyPress::numberPad2 = 0x30022;
  2095. const int KeyPress::numberPad3 = 0x30023;
  2096. const int KeyPress::numberPad4 = 0x30024;
  2097. const int KeyPress::numberPad5 = 0x30025;
  2098. const int KeyPress::numberPad6 = 0x30026;
  2099. const int KeyPress::numberPad7 = 0x30027;
  2100. const int KeyPress::numberPad8 = 0x30028;
  2101. const int KeyPress::numberPad9 = 0x30029;
  2102. const int KeyPress::numberPadAdd = 0x3002a;
  2103. const int KeyPress::numberPadSubtract = 0x3002b;
  2104. const int KeyPress::numberPadMultiply = 0x3002c;
  2105. const int KeyPress::numberPadDivide = 0x3002d;
  2106. const int KeyPress::numberPadSeparator = 0x3002e;
  2107. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  2108. const int KeyPress::numberPadEquals = 0x30030;
  2109. const int KeyPress::numberPadDelete = 0x30031;
  2110. const int KeyPress::playKey = 0x30000;
  2111. const int KeyPress::stopKey = 0x30001;
  2112. const int KeyPress::fastForwardKey = 0x30002;
  2113. const int KeyPress::rewindKey = 0x30003;
  2114. } // namespace juce