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.

2408 lines
91KB

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