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.

2586 lines
98KB

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