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.

2320 lines
87KB

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