The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2569 lines
96KB

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