Audio plugin host https://kx.studio/carla
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.

2323 lines
87KB

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