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.

2428 lines
92KB

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