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.

2485 lines
95KB

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