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.

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