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.

2764 lines
104KB

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