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.

2486 lines
95KB

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