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.

2746 lines
103KB

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