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.

2394 lines
90KB

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