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.

2273 lines
85KB

  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 sendModalInputAttemptIfBlocked()
  813. {
  814. if (auto* modal = Component::getCurrentlyModalComponent())
  815. {
  816. if (insideToFrontCall == 0
  817. && (! getComponent().isParentOf (modal))
  818. && getComponent().isCurrentlyBlockedByAnotherModalComponent())
  819. {
  820. modal->inputAttemptWhenModal();
  821. return true;
  822. }
  823. }
  824. return false;
  825. }
  826. bool canBecomeKeyWindow()
  827. {
  828. return (getStyleFlags() & juce::ComponentPeer::windowIgnoresKeyPresses) == 0;
  829. }
  830. bool canBecomeMainWindow()
  831. {
  832. return dynamic_cast<ResizableWindow*> (&component) != nullptr;
  833. }
  834. bool worksWhenModal() const
  835. {
  836. // In plugins, the host could put our plugin window inside a modal window, so this
  837. // allows us to successfully open other popups. Feels like there could be edge-case
  838. // problems caused by this, so let us know if you spot any issues..
  839. return ! JUCEApplication::isStandaloneApp();
  840. }
  841. void becomeKeyWindow()
  842. {
  843. handleBroughtToFront();
  844. grabFocus();
  845. }
  846. bool windowShouldClose()
  847. {
  848. if (! isValidPeer (this))
  849. return YES;
  850. handleUserClosingWindow();
  851. return NO;
  852. }
  853. void redirectMovedOrResized()
  854. {
  855. updateFullscreenStatus();
  856. handleMovedOrResized();
  857. }
  858. void viewMovedToWindow()
  859. {
  860. if (isSharedWindow)
  861. {
  862. auto newWindow = [view window];
  863. bool shouldSetVisible = (window == nullptr && newWindow != nullptr);
  864. window = newWindow;
  865. if (shouldSetVisible)
  866. getComponent().setVisible (true);
  867. }
  868. }
  869. void liveResizingStart()
  870. {
  871. if (constrainer != nullptr)
  872. {
  873. constrainer->resizeStart();
  874. isFirstLiveResize = true;
  875. }
  876. }
  877. void liveResizingEnd()
  878. {
  879. if (constrainer != nullptr)
  880. constrainer->resizeEnd();
  881. }
  882. NSRect constrainRect (NSRect r)
  883. {
  884. if (constrainer != nullptr && ! isKioskMode())
  885. {
  886. auto scale = getComponent().getDesktopScaleFactor();
  887. auto pos = ScalingHelpers::unscaledScreenPosToScaled (scale, convertToRectInt (flippedScreenRect (r)));
  888. auto original = ScalingHelpers::unscaledScreenPosToScaled (scale, convertToRectInt (flippedScreenRect ([window frame])));
  889. auto screenBounds = Desktop::getInstance().getDisplays().getTotalBounds (true);
  890. const bool inLiveResize = [window inLiveResize];
  891. if (! inLiveResize || isFirstLiveResize)
  892. {
  893. isFirstLiveResize = false;
  894. isStretchingTop = (pos.getY() != original.getY() && pos.getBottom() == original.getBottom());
  895. isStretchingLeft = (pos.getX() != original.getX() && pos.getRight() == original.getRight());
  896. isStretchingBottom = (pos.getY() == original.getY() && pos.getBottom() != original.getBottom());
  897. isStretchingRight = (pos.getX() == original.getX() && pos.getRight() != original.getRight());
  898. }
  899. constrainer->checkBounds (pos, original, screenBounds,
  900. isStretchingTop, isStretchingLeft, isStretchingBottom, isStretchingRight);
  901. pos = ScalingHelpers::scaledScreenPosToUnscaled (scale, pos);
  902. r = flippedScreenRect (makeNSRect (pos));
  903. }
  904. return r;
  905. }
  906. static void showArrowCursorIfNeeded()
  907. {
  908. auto& desktop = Desktop::getInstance();
  909. auto mouse = desktop.getMainMouseSource();
  910. if (mouse.getComponentUnderMouse() == nullptr
  911. && desktop.findComponentAt (mouse.getScreenPosition().roundToInt()) == nullptr)
  912. {
  913. [[NSCursor arrowCursor] set];
  914. }
  915. }
  916. static void updateModifiers (NSEvent* e)
  917. {
  918. updateModifiers ([e modifierFlags]);
  919. }
  920. static void updateModifiers (const NSUInteger flags)
  921. {
  922. int m = 0;
  923. if ((flags & NSEventModifierFlagShift) != 0) m |= ModifierKeys::shiftModifier;
  924. if ((flags & NSEventModifierFlagControl) != 0) m |= ModifierKeys::ctrlModifier;
  925. if ((flags & NSEventModifierFlagOption) != 0) m |= ModifierKeys::altModifier;
  926. if ((flags & NSEventModifierFlagCommand) != 0) m |= ModifierKeys::commandModifier;
  927. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withOnlyMouseButtons().withFlags (m);
  928. }
  929. static void updateKeysDown (NSEvent* ev, bool isKeyDown)
  930. {
  931. updateModifiers (ev);
  932. if (auto keyCode = getKeyCodeFromEvent (ev))
  933. {
  934. if (isKeyDown)
  935. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  936. else
  937. keysCurrentlyDown.removeFirstMatchingValue (keyCode);
  938. }
  939. }
  940. static int getKeyCodeFromEvent (NSEvent* ev)
  941. {
  942. // Unfortunately, charactersIgnoringModifiers does not ignore the shift key.
  943. // Using [ev keyCode] is not a solution either as this will,
  944. // for example, return VK_KEY_Y if the key is pressed which
  945. // is typically located at the Y key position on a QWERTY
  946. // keyboard. However, on international keyboards this might not
  947. // be the key labeled Y (for example, on German keyboards this key
  948. // has a Z label). Therefore, we need to query the current keyboard
  949. // layout to figure out what character the key would have produced
  950. // if the shift key was not pressed
  951. String unmodified;
  952. #if JUCE_SUPPORT_CARBON
  953. if (TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource())
  954. {
  955. if (auto layoutData = (CFDataRef) TISGetInputSourceProperty (currentKeyboard,
  956. kTISPropertyUnicodeKeyLayoutData))
  957. {
  958. if (auto* layoutPtr = (const UCKeyboardLayout*) CFDataGetBytePtr (layoutData))
  959. {
  960. UInt32 keysDown = 0;
  961. UniChar buffer[4];
  962. UniCharCount actual;
  963. if (UCKeyTranslate (layoutPtr, [ev keyCode], kUCKeyActionDown, 0, LMGetKbdType(),
  964. kUCKeyTranslateNoDeadKeysBit, &keysDown, sizeof (buffer) / sizeof (UniChar),
  965. &actual, buffer) == 0)
  966. unmodified = String (CharPointer_UTF16 (reinterpret_cast<CharPointer_UTF16::CharType*> (buffer)), 4);
  967. }
  968. }
  969. CFRelease (currentKeyboard);
  970. }
  971. // did the above layout conversion fail
  972. if (unmodified.isEmpty())
  973. #endif
  974. {
  975. unmodified = nsStringToJuce ([ev charactersIgnoringModifiers]);
  976. }
  977. auto keyCode = (int) unmodified[0];
  978. if (keyCode == 0x19) // (backwards-tab)
  979. keyCode = '\t';
  980. else if (keyCode == 0x03) // (enter)
  981. keyCode = '\r';
  982. else
  983. keyCode = (int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  984. if (([ev modifierFlags] & NSEventModifierFlagNumericPad) != 0)
  985. {
  986. const int numPadConversions[] = { '0', KeyPress::numberPad0, '1', KeyPress::numberPad1,
  987. '2', KeyPress::numberPad2, '3', KeyPress::numberPad3,
  988. '4', KeyPress::numberPad4, '5', KeyPress::numberPad5,
  989. '6', KeyPress::numberPad6, '7', KeyPress::numberPad7,
  990. '8', KeyPress::numberPad8, '9', KeyPress::numberPad9,
  991. '+', KeyPress::numberPadAdd, '-', KeyPress::numberPadSubtract,
  992. '*', KeyPress::numberPadMultiply, '/', KeyPress::numberPadDivide,
  993. '.', KeyPress::numberPadDecimalPoint,
  994. ',', KeyPress::numberPadDecimalPoint, // (to deal with non-english kbds)
  995. '=', KeyPress::numberPadEquals };
  996. for (int i = 0; i < numElementsInArray (numPadConversions); i += 2)
  997. if (keyCode == numPadConversions [i])
  998. keyCode = numPadConversions [i + 1];
  999. }
  1000. return keyCode;
  1001. }
  1002. static int64 getMouseTime (NSEvent* e) noexcept
  1003. {
  1004. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  1005. + (int64) ([e timestamp] * 1000.0);
  1006. }
  1007. static float getMousePressure (NSEvent* e) noexcept
  1008. {
  1009. @try
  1010. {
  1011. if (e.type != NSEventTypeMouseEntered && e.type != NSEventTypeMouseExited)
  1012. return (float) e.pressure;
  1013. }
  1014. @catch (NSException* e) {}
  1015. @finally {}
  1016. return 0.0f;
  1017. }
  1018. static Point<float> getMousePos (NSEvent* e, NSView* view)
  1019. {
  1020. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  1021. return { (float) p.x, (float) ([view frame].size.height - p.y) };
  1022. }
  1023. static int getModifierForButtonNumber (const NSInteger num)
  1024. {
  1025. return num == 0 ? ModifierKeys::leftButtonModifier
  1026. : (num == 1 ? ModifierKeys::rightButtonModifier
  1027. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  1028. }
  1029. static unsigned int getNSWindowStyleMask (const int flags) noexcept
  1030. {
  1031. unsigned int style = (flags & windowHasTitleBar) != 0 ? NSWindowStyleMaskTitled
  1032. : NSWindowStyleMaskBorderless;
  1033. if ((flags & windowHasMinimiseButton) != 0) style |= NSWindowStyleMaskMiniaturizable;
  1034. if ((flags & windowHasCloseButton) != 0) style |= NSWindowStyleMaskClosable;
  1035. if ((flags & windowIsResizable) != 0) style |= NSWindowStyleMaskResizable;
  1036. return style;
  1037. }
  1038. static NSArray* getSupportedDragTypes()
  1039. {
  1040. return [NSArray arrayWithObjects: (NSString*) kUTTypeFileURL, (NSString*) kPasteboardTypeFileURLPromise, NSPasteboardTypeString, nil];
  1041. }
  1042. BOOL sendDragCallback (const int type, id <NSDraggingInfo> sender)
  1043. {
  1044. NSPasteboard* pasteboard = [sender draggingPasteboard];
  1045. NSString* contentType = [pasteboard availableTypeFromArray: getSupportedDragTypes()];
  1046. if (contentType == nil)
  1047. return false;
  1048. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  1049. ComponentPeer::DragInfo dragInfo;
  1050. dragInfo.position.setXY ((int) p.x, (int) ([view frame].size.height - p.y));
  1051. if (contentType == NSPasteboardTypeString)
  1052. dragInfo.text = nsStringToJuce ([pasteboard stringForType: NSPasteboardTypeString]);
  1053. else
  1054. dragInfo.files = getDroppedFiles (pasteboard, contentType);
  1055. if (! dragInfo.isEmpty())
  1056. {
  1057. switch (type)
  1058. {
  1059. case 0: return handleDragMove (dragInfo);
  1060. case 1: return handleDragExit (dragInfo);
  1061. case 2: return handleDragDrop (dragInfo);
  1062. default: jassertfalse; break;
  1063. }
  1064. }
  1065. return false;
  1066. }
  1067. StringArray getDroppedFiles (NSPasteboard* pasteboard, NSString* contentType)
  1068. {
  1069. StringArray files;
  1070. NSString* iTunesPasteboardType = nsStringLiteral ("CorePasteboardFlavorType 0x6974756E"); // 'itun'
  1071. if ([contentType isEqualToString: (NSString*) kPasteboardTypeFileURLPromise]
  1072. && [[pasteboard types] containsObject: iTunesPasteboardType])
  1073. {
  1074. id list = [pasteboard propertyListForType: iTunesPasteboardType];
  1075. if ([list isKindOfClass: [NSDictionary class]])
  1076. {
  1077. NSDictionary* iTunesDictionary = (NSDictionary*) list;
  1078. NSArray* tracks = [iTunesDictionary valueForKey: nsStringLiteral ("Tracks")];
  1079. NSEnumerator* enumerator = [tracks objectEnumerator];
  1080. NSDictionary* track;
  1081. while ((track = [enumerator nextObject]) != nil)
  1082. {
  1083. if (id value = [track valueForKey: nsStringLiteral ("Location")])
  1084. {
  1085. NSURL* url = [NSURL URLWithString: value];
  1086. if ([url isFileURL])
  1087. files.add (nsStringToJuce ([url path]));
  1088. }
  1089. }
  1090. }
  1091. }
  1092. else
  1093. {
  1094. NSArray* items = [pasteboard readObjectsForClasses:@[[NSURL class]] options: nil];
  1095. for (unsigned int i = 0; i < [items count]; ++i)
  1096. {
  1097. NSURL* url = [items objectAtIndex: i];
  1098. if ([url isFileURL])
  1099. files.add (nsStringToJuce ([url path]));
  1100. }
  1101. }
  1102. return files;
  1103. }
  1104. //==============================================================================
  1105. void viewFocusGain()
  1106. {
  1107. if (currentlyFocusedPeer != this)
  1108. {
  1109. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  1110. currentlyFocusedPeer->handleFocusLoss();
  1111. currentlyFocusedPeer = this;
  1112. handleFocusGain();
  1113. }
  1114. }
  1115. void viewFocusLoss()
  1116. {
  1117. if (currentlyFocusedPeer == this)
  1118. {
  1119. currentlyFocusedPeer = nullptr;
  1120. handleFocusLoss();
  1121. }
  1122. }
  1123. bool isFocused() const override
  1124. {
  1125. return (isSharedWindow || ! JUCEApplication::isStandaloneApp())
  1126. ? this == currentlyFocusedPeer
  1127. : [window isKeyWindow];
  1128. }
  1129. void grabFocus() override
  1130. {
  1131. if (window != nil)
  1132. {
  1133. [window makeKeyWindow];
  1134. [window makeFirstResponder: view];
  1135. viewFocusGain();
  1136. }
  1137. }
  1138. void textInputRequired (Point<int>, TextInputTarget&) override {}
  1139. void resetWindowPresentation()
  1140. {
  1141. if (hasNativeTitleBar())
  1142. {
  1143. [window setStyleMask: (NSViewComponentPeer::getNSWindowStyleMask (getStyleFlags()))];
  1144. setTitle (getComponent().getName()); // required to force the OS to update the title
  1145. }
  1146. [NSApp setPresentationOptions: NSApplicationPresentationDefault];
  1147. }
  1148. //==============================================================================
  1149. NSWindow* window = nil;
  1150. NSView* view = nil;
  1151. WeakReference<Component> safeComponent;
  1152. bool isSharedWindow = false, fullScreen = false;
  1153. bool isWindowInKioskMode = false;
  1154. #if USE_COREGRAPHICS_RENDERING
  1155. bool usingCoreGraphics = true;
  1156. #else
  1157. bool usingCoreGraphics = false;
  1158. #endif
  1159. bool isZooming = false, isFirstLiveResize = false, textWasInserted = false;
  1160. bool isStretchingTop = false, isStretchingLeft = false, isStretchingBottom = false, isStretchingRight = false;
  1161. bool windowRepresentsFile = false;
  1162. bool isAlwaysOnTop = false, wasAlwaysOnTop = false;
  1163. String stringBeingComposed;
  1164. NSNotificationCenter* notificationCenter = nil;
  1165. RectangleList<float> deferredRepaints;
  1166. uint32 lastRepaintTime;
  1167. static ComponentPeer* currentlyFocusedPeer;
  1168. static Array<int> keysCurrentlyDown;
  1169. static int insideToFrontCall;
  1170. private:
  1171. static NSView* createViewInstance();
  1172. static NSWindow* createWindowInstance();
  1173. static void setOwner (id viewOrWindow, NSViewComponentPeer* newOwner)
  1174. {
  1175. object_setInstanceVariable (viewOrWindow, "owner", newOwner);
  1176. }
  1177. void getClipRects (RectangleList<int>& clip, Point<int> offset, int clipW, int clipH)
  1178. {
  1179. const NSRect* rects = nullptr;
  1180. NSInteger numRects = 0;
  1181. [view getRectsBeingDrawn: &rects count: &numRects];
  1182. const Rectangle<int> clipBounds (clipW, clipH);
  1183. auto viewH = [view frame].size.height;
  1184. clip.ensureStorageAllocated ((int) numRects);
  1185. for (int i = 0; i < numRects; ++i)
  1186. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + offset.x,
  1187. roundToInt (viewH - (rects[i].origin.y + rects[i].size.height)) + offset.y,
  1188. roundToInt (rects[i].size.width),
  1189. roundToInt (rects[i].size.height))));
  1190. }
  1191. static void appFocusChanged()
  1192. {
  1193. keysCurrentlyDown.clear();
  1194. if (isValidPeer (currentlyFocusedPeer))
  1195. {
  1196. if (Process::isForegroundProcess())
  1197. {
  1198. currentlyFocusedPeer->handleFocusGain();
  1199. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  1200. }
  1201. else
  1202. {
  1203. currentlyFocusedPeer->handleFocusLoss();
  1204. }
  1205. }
  1206. }
  1207. static bool checkEventBlockedByModalComps (NSEvent* e)
  1208. {
  1209. if (Component::getNumCurrentlyModalComponents() == 0)
  1210. return false;
  1211. NSWindow* const w = [e window];
  1212. if (w == nil || [w worksWhenModal])
  1213. return false;
  1214. bool isKey = false, isInputAttempt = false;
  1215. switch ([e type])
  1216. {
  1217. case NSEventTypeKeyDown:
  1218. case NSEventTypeKeyUp:
  1219. isKey = isInputAttempt = true;
  1220. break;
  1221. case NSEventTypeLeftMouseDown:
  1222. case NSEventTypeRightMouseDown:
  1223. case NSEventTypeOtherMouseDown:
  1224. isInputAttempt = true;
  1225. break;
  1226. case NSEventTypeLeftMouseDragged:
  1227. case NSEventTypeRightMouseDragged:
  1228. case NSEventTypeLeftMouseUp:
  1229. case NSEventTypeRightMouseUp:
  1230. case NSEventTypeOtherMouseUp:
  1231. case NSEventTypeOtherMouseDragged:
  1232. if (Desktop::getInstance().getDraggingMouseSource(0) != nullptr)
  1233. return false;
  1234. break;
  1235. case NSEventTypeMouseMoved:
  1236. case NSEventTypeMouseEntered:
  1237. case NSEventTypeMouseExited:
  1238. case NSEventTypeCursorUpdate:
  1239. case NSEventTypeScrollWheel:
  1240. case NSEventTypeTabletPoint:
  1241. case NSEventTypeTabletProximity:
  1242. break;
  1243. default:
  1244. return false;
  1245. }
  1246. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  1247. {
  1248. if (auto* peer = dynamic_cast<NSViewComponentPeer*> (ComponentPeer::getPeer (i)))
  1249. {
  1250. if ([peer->view window] == w)
  1251. {
  1252. if (isKey)
  1253. {
  1254. if (peer->view == [w firstResponder])
  1255. return false;
  1256. }
  1257. else
  1258. {
  1259. if (peer->isSharedWindow
  1260. ? NSPointInRect ([peer->view convertPoint: [e locationInWindow] fromView: nil], [peer->view bounds])
  1261. : NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height)))
  1262. return false;
  1263. }
  1264. }
  1265. }
  1266. }
  1267. if (isInputAttempt)
  1268. {
  1269. if (! [NSApp isActive])
  1270. [NSApp activateIgnoringOtherApps: YES];
  1271. if (auto* modal = Component::getCurrentlyModalComponent())
  1272. modal->inputAttemptWhenModal();
  1273. }
  1274. return true;
  1275. }
  1276. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentPeer)
  1277. };
  1278. int NSViewComponentPeer::insideToFrontCall = 0;
  1279. //==============================================================================
  1280. struct JuceNSViewClass : public ObjCClass<NSView>
  1281. {
  1282. JuceNSViewClass() : ObjCClass<NSView> ("JUCEView_")
  1283. {
  1284. addIvar<NSViewComponentPeer*> ("owner");
  1285. addMethod (@selector (isOpaque), isOpaque, "c@:");
  1286. addMethod (@selector (drawRect:), drawRect, "v@:", @encode (NSRect));
  1287. addMethod (@selector (mouseDown:), mouseDown, "v@:@");
  1288. addMethod (@selector (asyncMouseDown:), asyncMouseDown, "v@:@");
  1289. addMethod (@selector (mouseUp:), mouseUp, "v@:@");
  1290. addMethod (@selector (asyncMouseUp:), asyncMouseUp, "v@:@");
  1291. addMethod (@selector (mouseDragged:), mouseDragged, "v@:@");
  1292. addMethod (@selector (mouseMoved:), mouseMoved, "v@:@");
  1293. addMethod (@selector (mouseEntered:), mouseEntered, "v@:@");
  1294. addMethod (@selector (mouseExited:), mouseExited, "v@:@");
  1295. addMethod (@selector (rightMouseDown:), mouseDown, "v@:@");
  1296. addMethod (@selector (rightMouseDragged:), mouseDragged, "v@:@");
  1297. addMethod (@selector (rightMouseUp:), mouseUp, "v@:@");
  1298. addMethod (@selector (otherMouseDown:), mouseDown, "v@:@");
  1299. addMethod (@selector (otherMouseDragged:), mouseDragged, "v@:@");
  1300. addMethod (@selector (otherMouseUp:), mouseUp, "v@:@");
  1301. addMethod (@selector (scrollWheel:), scrollWheel, "v@:@");
  1302. addMethod (@selector (magnifyWithEvent:), magnify, "v@:@");
  1303. addMethod (@selector (acceptsFirstMouse:), acceptsFirstMouse, "c@:@");
  1304. addMethod (@selector (frameChanged:), frameChanged, "v@:@");
  1305. addMethod (@selector (windowWillMiniaturize:), windowWillMiniaturize, "v@:@");
  1306. addMethod (@selector (windowDidDeminiaturize:), windowDidDeminiaturize, "v@:@");
  1307. addMethod (@selector (wantsDefaultClipping:), wantsDefaultClipping, "c@:");
  1308. addMethod (@selector (worksWhenModal), worksWhenModal, "c@:");
  1309. addMethod (@selector (viewDidMoveToWindow), viewDidMoveToWindow, "v@:");
  1310. addMethod (@selector (keyDown:), keyDown, "v@:@");
  1311. addMethod (@selector (keyUp:), keyUp, "v@:@");
  1312. addMethod (@selector (insertText:), insertText, "v@:@");
  1313. addMethod (@selector (doCommandBySelector:), doCommandBySelector, "v@::");
  1314. addMethod (@selector (setMarkedText:selectedRange:), setMarkedText, "v@:@", @encode (NSRange));
  1315. addMethod (@selector (unmarkText), unmarkText, "v@:");
  1316. addMethod (@selector (hasMarkedText), hasMarkedText, "c@:");
  1317. addMethod (@selector (conversationIdentifier), conversationIdentifier, "l@:");
  1318. addMethod (@selector (attributedSubstringFromRange:), attributedSubstringFromRange, "@@:", @encode (NSRange));
  1319. addMethod (@selector (markedRange), markedRange, @encode (NSRange), "@:");
  1320. addMethod (@selector (selectedRange), selectedRange, @encode (NSRange), "@:");
  1321. addMethod (@selector (firstRectForCharacterRange:), firstRectForCharacterRange, @encode (NSRect), "@:", @encode (NSRange));
  1322. addMethod (@selector (characterIndexForPoint:), characterIndexForPoint, "L@:", @encode (NSPoint));
  1323. addMethod (@selector (validAttributesForMarkedText), validAttributesForMarkedText, "@@:");
  1324. addMethod (@selector (flagsChanged:), flagsChanged, "v@:@");
  1325. addMethod (@selector (becomeFirstResponder), becomeFirstResponder, "c@:");
  1326. addMethod (@selector (resignFirstResponder), resignFirstResponder, "c@:");
  1327. addMethod (@selector (acceptsFirstResponder), acceptsFirstResponder, "c@:");
  1328. addMethod (@selector (draggingEntered:), draggingEntered, @encode (NSDragOperation), "@:@");
  1329. addMethod (@selector (draggingUpdated:), draggingUpdated, @encode (NSDragOperation), "@:@");
  1330. addMethod (@selector (draggingEnded:), draggingEnded, "v@:@");
  1331. addMethod (@selector (draggingExited:), draggingExited, "v@:@");
  1332. addMethod (@selector (prepareForDragOperation:), prepareForDragOperation, "c@:@");
  1333. addMethod (@selector (performDragOperation:), performDragOperation, "c@:@");
  1334. addMethod (@selector (concludeDragOperation:), concludeDragOperation, "v@:@");
  1335. addMethod (@selector (paste:), paste, "v@:@");
  1336. addMethod (@selector (copy:), copy, "v@:@");
  1337. addMethod (@selector (cut:), cut, "v@:@");
  1338. addMethod (@selector (viewWillMoveToWindow:), willMoveToWindow, "v@:@");
  1339. addProtocol (@protocol (NSTextInput));
  1340. registerClass();
  1341. }
  1342. private:
  1343. static NSViewComponentPeer* getOwner (id self)
  1344. {
  1345. return getIvar<NSViewComponentPeer*> (self, "owner");
  1346. }
  1347. static void mouseDown (id self, SEL s, NSEvent* ev)
  1348. {
  1349. if (JUCEApplicationBase::isStandaloneApp())
  1350. asyncMouseDown (self, s, ev);
  1351. else
  1352. // In some host situations, the host will stop modal loops from working
  1353. // correctly if they're called from a mouse event, so we'll trigger
  1354. // the event asynchronously..
  1355. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  1356. withObject: ev
  1357. waitUntilDone: NO];
  1358. }
  1359. static void mouseUp (id self, SEL s, NSEvent* ev)
  1360. {
  1361. if (JUCEApplicationBase::isStandaloneApp())
  1362. asyncMouseUp (self, s, ev);
  1363. else
  1364. // In some host situations, the host will stop modal loops from working
  1365. // correctly if they're called from a mouse event, so we'll trigger
  1366. // the event asynchronously..
  1367. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  1368. withObject: ev
  1369. waitUntilDone: NO];
  1370. }
  1371. static void asyncMouseDown (id self, SEL, NSEvent* ev) { if (auto* p = getOwner (self)) p->redirectMouseDown (ev); }
  1372. static void asyncMouseUp (id self, SEL, NSEvent* ev) { if (auto* p = getOwner (self)) p->redirectMouseUp (ev); }
  1373. static void mouseDragged (id self, SEL, NSEvent* ev) { if (auto* p = getOwner (self)) p->redirectMouseDrag (ev); }
  1374. static void mouseMoved (id self, SEL, NSEvent* ev) { if (auto* p = getOwner (self)) p->redirectMouseMove (ev); }
  1375. static void mouseEntered (id self, SEL, NSEvent* ev) { if (auto* p = getOwner (self)) p->redirectMouseEnter (ev); }
  1376. static void mouseExited (id self, SEL, NSEvent* ev) { if (auto* p = getOwner (self)) p->redirectMouseExit (ev); }
  1377. static void scrollWheel (id self, SEL, NSEvent* ev) { if (auto* p = getOwner (self)) p->redirectMouseWheel (ev); }
  1378. static void magnify (id self, SEL, NSEvent* ev) { if (auto* p = getOwner (self)) p->redirectMagnify (ev); }
  1379. static void copy (id self, SEL, NSObject* s) { if (auto* p = getOwner (self)) p->redirectCopy (s); }
  1380. static void paste (id self, SEL, NSObject* s) { if (auto* p = getOwner (self)) p->redirectPaste (s); }
  1381. static void cut (id self, SEL, NSObject* s) { if (auto* p = getOwner (self)) p->redirectCut (s); }
  1382. static void willMoveToWindow (id self, SEL, NSWindow* w) { if (auto* p = getOwner (self)) p->redirectWillMoveToWindow (w); }
  1383. static BOOL acceptsFirstMouse (id, SEL, NSEvent*) { return YES; }
  1384. static BOOL wantsDefaultClipping (id, SEL) { return YES; } // (this is the default, but may want to customise it in future)
  1385. static BOOL worksWhenModal (id self, SEL) { if (auto* p = getOwner (self)) return p->worksWhenModal(); return NO; }
  1386. static void drawRect (id self, SEL, NSRect r) { if (auto* p = getOwner (self)) p->drawRect (r); }
  1387. static void frameChanged (id self, SEL, NSNotification*) { if (auto* p = getOwner (self)) p->redirectMovedOrResized(); }
  1388. static void viewDidMoveToWindow (id self, SEL) { if (auto* p = getOwner (self)) p->viewMovedToWindow(); }
  1389. static void windowWillMiniaturize (id self, SEL, NSNotification*)
  1390. {
  1391. if (auto* p = getOwner (self))
  1392. {
  1393. if (p->isAlwaysOnTop)
  1394. {
  1395. // there is a bug when restoring minimised always on top windows so we need
  1396. // to remove this behaviour before minimising and restore it afterwards
  1397. p->setAlwaysOnTop (false);
  1398. p->wasAlwaysOnTop = true;
  1399. }
  1400. }
  1401. }
  1402. static void windowDidDeminiaturize (id self, SEL, NSNotification*)
  1403. {
  1404. if (auto* p = getOwner (self))
  1405. {
  1406. if (p->wasAlwaysOnTop)
  1407. p->setAlwaysOnTop (true);
  1408. p->redirectMovedOrResized();
  1409. }
  1410. }
  1411. static BOOL isOpaque (id self, SEL)
  1412. {
  1413. auto* owner = getOwner (self);
  1414. return owner == nullptr || owner->getComponent().isOpaque();
  1415. }
  1416. //==============================================================================
  1417. static void keyDown (id self, SEL, NSEvent* ev)
  1418. {
  1419. if (auto* owner = getOwner (self))
  1420. {
  1421. auto* target = owner->findCurrentTextInputTarget();
  1422. owner->textWasInserted = false;
  1423. if (target != nullptr)
  1424. [(NSView*) self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  1425. else
  1426. owner->stringBeingComposed.clear();
  1427. if (! (owner->textWasInserted || owner->redirectKeyDown (ev)))
  1428. {
  1429. objc_super s = { self, [NSView class] };
  1430. getMsgSendSuperFn() (&s, @selector (keyDown:), ev);
  1431. }
  1432. }
  1433. }
  1434. static void keyUp (id self, SEL, NSEvent* ev)
  1435. {
  1436. auto* owner = getOwner (self);
  1437. if (owner == nullptr || ! owner->redirectKeyUp (ev))
  1438. {
  1439. objc_super s = { self, [NSView class] };
  1440. getMsgSendSuperFn() (&s, @selector (keyUp:), ev);
  1441. }
  1442. }
  1443. //==============================================================================
  1444. static void insertText (id self, SEL, id aString)
  1445. {
  1446. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  1447. if (auto* owner = getOwner (self))
  1448. {
  1449. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  1450. if ([newText length] > 0)
  1451. {
  1452. if (auto* target = owner->findCurrentTextInputTarget())
  1453. {
  1454. target->insertTextAtCaret (nsStringToJuce (newText));
  1455. owner->textWasInserted = true;
  1456. }
  1457. }
  1458. owner->stringBeingComposed.clear();
  1459. }
  1460. }
  1461. static void doCommandBySelector (id, SEL, SEL) {}
  1462. static void setMarkedText (id self, SEL, id aString, NSRange)
  1463. {
  1464. if (auto* owner = getOwner (self))
  1465. {
  1466. owner->stringBeingComposed = nsStringToJuce ([aString isKindOfClass: [NSAttributedString class]]
  1467. ? [aString string] : aString);
  1468. if (auto* target = owner->findCurrentTextInputTarget())
  1469. {
  1470. auto currentHighlight = target->getHighlightedRegion();
  1471. target->insertTextAtCaret (owner->stringBeingComposed);
  1472. target->setHighlightedRegion (currentHighlight.withLength (owner->stringBeingComposed.length()));
  1473. owner->textWasInserted = true;
  1474. }
  1475. }
  1476. }
  1477. static void unmarkText (id self, SEL)
  1478. {
  1479. if (auto* owner = getOwner (self))
  1480. {
  1481. if (owner->stringBeingComposed.isNotEmpty())
  1482. {
  1483. if (auto* target = owner->findCurrentTextInputTarget())
  1484. {
  1485. target->insertTextAtCaret (owner->stringBeingComposed);
  1486. owner->textWasInserted = true;
  1487. }
  1488. owner->stringBeingComposed.clear();
  1489. }
  1490. }
  1491. }
  1492. static BOOL hasMarkedText (id self, SEL)
  1493. {
  1494. auto* owner = getOwner (self);
  1495. return owner != nullptr && owner->stringBeingComposed.isNotEmpty();
  1496. }
  1497. static long conversationIdentifier (id self, SEL)
  1498. {
  1499. return (long) (pointer_sized_int) self;
  1500. }
  1501. static NSAttributedString* attributedSubstringFromRange (id self, SEL, NSRange theRange)
  1502. {
  1503. if (auto* owner = getOwner (self))
  1504. {
  1505. if (auto* target = owner->findCurrentTextInputTarget())
  1506. {
  1507. Range<int> r ((int) theRange.location,
  1508. (int) (theRange.location + theRange.length));
  1509. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  1510. }
  1511. }
  1512. return nil;
  1513. }
  1514. static NSRange markedRange (id self, SEL)
  1515. {
  1516. if (auto* owner = getOwner (self))
  1517. if (owner->stringBeingComposed.isNotEmpty())
  1518. return NSMakeRange (0, (NSUInteger) owner->stringBeingComposed.length());
  1519. return NSMakeRange (NSNotFound, 0);
  1520. }
  1521. static NSRange selectedRange (id self, SEL)
  1522. {
  1523. if (auto* owner = getOwner (self))
  1524. {
  1525. if (auto* target = owner->findCurrentTextInputTarget())
  1526. {
  1527. auto highlight = target->getHighlightedRegion();
  1528. if (! highlight.isEmpty())
  1529. return NSMakeRange ((NSUInteger) highlight.getStart(),
  1530. (NSUInteger) highlight.getLength());
  1531. }
  1532. }
  1533. return NSMakeRange (NSNotFound, 0);
  1534. }
  1535. static NSRect firstRectForCharacterRange (id self, SEL, NSRange)
  1536. {
  1537. if (auto* owner = getOwner (self))
  1538. if (auto* comp = dynamic_cast<Component*> (owner->findCurrentTextInputTarget()))
  1539. return flippedScreenRect (makeNSRect (comp->getScreenBounds()));
  1540. return NSZeroRect;
  1541. }
  1542. static NSUInteger characterIndexForPoint (id, SEL, NSPoint) { return NSNotFound; }
  1543. static NSArray* validAttributesForMarkedText (id, SEL) { return [NSArray array]; }
  1544. //==============================================================================
  1545. static void flagsChanged (id self, SEL, NSEvent* ev)
  1546. {
  1547. if (auto* owner = getOwner (self))
  1548. owner->redirectModKeyChange (ev);
  1549. }
  1550. static BOOL becomeFirstResponder (id self, SEL)
  1551. {
  1552. if (auto* owner = getOwner (self))
  1553. owner->viewFocusGain();
  1554. return YES;
  1555. }
  1556. static BOOL resignFirstResponder (id self, SEL)
  1557. {
  1558. if (auto* owner = getOwner (self))
  1559. owner->viewFocusLoss();
  1560. return YES;
  1561. }
  1562. static BOOL acceptsFirstResponder (id self, SEL)
  1563. {
  1564. auto* owner = getOwner (self);
  1565. return owner != nullptr && owner->canBecomeKeyWindow();
  1566. }
  1567. //==============================================================================
  1568. static NSDragOperation draggingEntered (id self, SEL s, id<NSDraggingInfo> sender)
  1569. {
  1570. return draggingUpdated (self, s, sender);
  1571. }
  1572. static NSDragOperation draggingUpdated (id self, SEL, id<NSDraggingInfo> sender)
  1573. {
  1574. if (auto* owner = getOwner (self))
  1575. if (owner->sendDragCallback (0, sender))
  1576. return NSDragOperationGeneric;
  1577. return NSDragOperationNone;
  1578. }
  1579. static void draggingEnded (id self, SEL s, id<NSDraggingInfo> sender)
  1580. {
  1581. draggingExited (self, s, sender);
  1582. }
  1583. static void draggingExited (id self, SEL, id<NSDraggingInfo> sender)
  1584. {
  1585. if (auto* owner = getOwner (self))
  1586. owner->sendDragCallback (1, sender);
  1587. }
  1588. static BOOL prepareForDragOperation (id, SEL, id<NSDraggingInfo>)
  1589. {
  1590. return YES;
  1591. }
  1592. static BOOL performDragOperation (id self, SEL, id<NSDraggingInfo> sender)
  1593. {
  1594. auto* owner = getOwner (self);
  1595. return owner != nullptr && owner->sendDragCallback (2, sender);
  1596. }
  1597. static void concludeDragOperation (id, SEL, id<NSDraggingInfo>) {}
  1598. };
  1599. //==============================================================================
  1600. struct JuceNSWindowClass : public ObjCClass<NSWindow>
  1601. {
  1602. JuceNSWindowClass() : ObjCClass<NSWindow> ("JUCEWindow_")
  1603. {
  1604. addIvar<NSViewComponentPeer*> ("owner");
  1605. addMethod (@selector (canBecomeKeyWindow), canBecomeKeyWindow, "c@:");
  1606. addMethod (@selector (canBecomeMainWindow), canBecomeMainWindow, "c@:");
  1607. addMethod (@selector (becomeKeyWindow), becomeKeyWindow, "v@:");
  1608. addMethod (@selector (windowShouldClose:), windowShouldClose, "c@:@");
  1609. addMethod (@selector (constrainFrameRect:toScreen:), constrainFrameRect, @encode (NSRect), "@:", @encode (NSRect), "@");
  1610. addMethod (@selector (windowWillResize:toSize:), windowWillResize, @encode (NSSize), "@:@", @encode (NSSize));
  1611. addMethod (@selector (windowDidExitFullScreen:), windowDidExitFullScreen, "v@:@");
  1612. addMethod (@selector (windowWillEnterFullScreen:), windowWillEnterFullScreen, "v@:@");
  1613. addMethod (@selector (zoom:), zoom, "v@:@");
  1614. addMethod (@selector (windowWillMove:), windowWillMove, "v@:@");
  1615. addMethod (@selector (windowWillStartLiveResize:), windowWillStartLiveResize, "v@:@");
  1616. addMethod (@selector (windowDidEndLiveResize:), windowDidEndLiveResize, "v@:@");
  1617. addMethod (@selector (window:shouldPopUpDocumentPathMenu:), shouldPopUpPathMenu, "B@:@", @encode (NSMenu*));
  1618. addMethod (@selector (window:shouldDragDocumentWithEvent:from:withPasteboard:),
  1619. shouldAllowIconDrag, "B@:@", @encode (NSEvent*), @encode (NSPoint), @encode (NSPasteboard*));
  1620. addProtocol (@protocol (NSWindowDelegate));
  1621. registerClass();
  1622. }
  1623. private:
  1624. static NSViewComponentPeer* getOwner (id self)
  1625. {
  1626. return getIvar<NSViewComponentPeer*> (self, "owner");
  1627. }
  1628. //==============================================================================
  1629. static BOOL canBecomeKeyWindow (id self, SEL)
  1630. {
  1631. auto* owner = getOwner (self);
  1632. return owner != nullptr
  1633. && owner->canBecomeKeyWindow()
  1634. && ! owner->sendModalInputAttemptIfBlocked();
  1635. }
  1636. static BOOL canBecomeMainWindow (id self, SEL)
  1637. {
  1638. auto* owner = getOwner (self);
  1639. return owner != nullptr
  1640. && owner->canBecomeMainWindow()
  1641. && ! owner->sendModalInputAttemptIfBlocked();
  1642. }
  1643. static void becomeKeyWindow (id self, SEL)
  1644. {
  1645. sendSuperclassMessage (self, @selector (becomeKeyWindow));
  1646. if (auto* owner = getOwner (self))
  1647. owner->becomeKeyWindow();
  1648. }
  1649. static BOOL windowShouldClose (id self, SEL, id /*window*/)
  1650. {
  1651. auto* owner = getOwner (self);
  1652. return owner == nullptr || owner->windowShouldClose();
  1653. }
  1654. static NSRect constrainFrameRect (id self, SEL, NSRect frameRect, NSScreen*)
  1655. {
  1656. if (auto* owner = getOwner (self))
  1657. frameRect = owner->constrainRect (frameRect);
  1658. return frameRect;
  1659. }
  1660. static NSSize windowWillResize (id self, SEL, NSWindow*, NSSize proposedFrameSize)
  1661. {
  1662. auto* owner = getOwner (self);
  1663. if (owner == nullptr || owner->isZooming)
  1664. return proposedFrameSize;
  1665. NSRect frameRect = [(NSWindow*) self frame];
  1666. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  1667. frameRect.size = proposedFrameSize;
  1668. frameRect = owner->constrainRect (frameRect);
  1669. if (owner->hasNativeTitleBar())
  1670. owner->sendModalInputAttemptIfBlocked();
  1671. return frameRect.size;
  1672. }
  1673. static void windowDidExitFullScreen (id self, SEL, NSNotification*)
  1674. {
  1675. if (auto* owner = getOwner (self))
  1676. owner->resetWindowPresentation();
  1677. }
  1678. static void windowWillEnterFullScreen (id self, SEL, NSNotification*)
  1679. {
  1680. if (SystemStats::getOperatingSystemType() <= SystemStats::MacOSX_10_9)
  1681. return;
  1682. if (auto* owner = getOwner (self))
  1683. if (owner->hasNativeTitleBar() && (owner->getStyleFlags() & ComponentPeer::windowIsResizable) == 0)
  1684. [owner->window setStyleMask: NSWindowStyleMaskBorderless];
  1685. }
  1686. static void zoom (id self, SEL, id sender)
  1687. {
  1688. if (auto* owner = getOwner (self))
  1689. {
  1690. owner->isZooming = true;
  1691. objc_super s = { self, [NSWindow class] };
  1692. getMsgSendSuperFn() (&s, @selector (zoom:), sender);
  1693. owner->isZooming = false;
  1694. owner->redirectMovedOrResized();
  1695. }
  1696. }
  1697. static void windowWillMove (id self, SEL, NSNotification*)
  1698. {
  1699. if (auto* owner = getOwner (self))
  1700. if (owner->hasNativeTitleBar())
  1701. owner->sendModalInputAttemptIfBlocked();
  1702. }
  1703. static void windowWillStartLiveResize (id self, SEL, NSNotification*)
  1704. {
  1705. if (auto* owner = getOwner (self))
  1706. owner->liveResizingStart();
  1707. }
  1708. static void windowDidEndLiveResize (id self, SEL, NSNotification*)
  1709. {
  1710. if (auto* owner = getOwner (self))
  1711. owner->liveResizingEnd();
  1712. }
  1713. static bool shouldPopUpPathMenu (id self, SEL, id /*window*/, NSMenu*)
  1714. {
  1715. if (auto* owner = getOwner (self))
  1716. return owner->windowRepresentsFile;
  1717. return false;
  1718. }
  1719. static bool shouldAllowIconDrag (id self, SEL, id /*window*/, NSEvent*, NSPoint, NSPasteboard*)
  1720. {
  1721. if (auto* owner = getOwner (self))
  1722. return owner->windowRepresentsFile;
  1723. return false;
  1724. }
  1725. };
  1726. NSView* NSViewComponentPeer::createViewInstance()
  1727. {
  1728. static JuceNSViewClass cls;
  1729. return cls.createInstance();
  1730. }
  1731. NSWindow* NSViewComponentPeer::createWindowInstance()
  1732. {
  1733. static JuceNSWindowClass cls;
  1734. return cls.createInstance();
  1735. }
  1736. //==============================================================================
  1737. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = nullptr;
  1738. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  1739. //==============================================================================
  1740. bool KeyPress::isKeyCurrentlyDown (int keyCode)
  1741. {
  1742. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  1743. return true;
  1744. if (keyCode >= 'A' && keyCode <= 'Z'
  1745. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  1746. return true;
  1747. if (keyCode >= 'a' && keyCode <= 'z'
  1748. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  1749. return true;
  1750. return false;
  1751. }
  1752. //==============================================================================
  1753. bool MouseInputSource::SourceList::addSource()
  1754. {
  1755. if (sources.size() == 0)
  1756. {
  1757. addSource (0, MouseInputSource::InputSourceType::mouse);
  1758. return true;
  1759. }
  1760. return false;
  1761. }
  1762. bool MouseInputSource::SourceList::canUseTouch()
  1763. {
  1764. return false;
  1765. }
  1766. //==============================================================================
  1767. void Desktop::setKioskComponent (Component* kioskComp, bool shouldBeEnabled, bool allowMenusAndBars)
  1768. {
  1769. auto* peer = dynamic_cast<NSViewComponentPeer*> (kioskComp->getPeer());
  1770. jassert (peer != nullptr); // (this should have been checked by the caller)
  1771. if (peer->hasNativeTitleBar()
  1772. && [peer->window respondsToSelector: @selector (toggleFullScreen:)])
  1773. {
  1774. if (shouldBeEnabled && ! allowMenusAndBars)
  1775. [NSApp setPresentationOptions: NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar];
  1776. else if (! shouldBeEnabled)
  1777. [NSApp setPresentationOptions: NSApplicationPresentationDefault];
  1778. [peer->window performSelector: @selector (toggleFullScreen:) withObject: nil];
  1779. }
  1780. else
  1781. {
  1782. if (shouldBeEnabled)
  1783. {
  1784. if (peer->hasNativeTitleBar())
  1785. [peer->window setStyleMask: NSWindowStyleMaskBorderless];
  1786. [NSApp setPresentationOptions: (allowMenusAndBars ? (NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)
  1787. : (NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar))];
  1788. kioskComp->setBounds (Desktop::getInstance().getDisplays().getMainDisplay().totalArea);
  1789. peer->becomeKeyWindow();
  1790. }
  1791. else
  1792. {
  1793. peer->resetWindowPresentation();
  1794. }
  1795. }
  1796. }
  1797. void Desktop::allowedOrientationsChanged() {}
  1798. //==============================================================================
  1799. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  1800. {
  1801. return new NSViewComponentPeer (*this, styleFlags, (NSView*) windowToAttachTo);
  1802. }
  1803. //==============================================================================
  1804. const int KeyPress::spaceKey = ' ';
  1805. const int KeyPress::returnKey = 0x0d;
  1806. const int KeyPress::escapeKey = 0x1b;
  1807. const int KeyPress::backspaceKey = 0x7f;
  1808. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  1809. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  1810. const int KeyPress::upKey = NSUpArrowFunctionKey;
  1811. const int KeyPress::downKey = NSDownArrowFunctionKey;
  1812. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  1813. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  1814. const int KeyPress::endKey = NSEndFunctionKey;
  1815. const int KeyPress::homeKey = NSHomeFunctionKey;
  1816. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  1817. const int KeyPress::insertKey = -1;
  1818. const int KeyPress::tabKey = 9;
  1819. const int KeyPress::F1Key = NSF1FunctionKey;
  1820. const int KeyPress::F2Key = NSF2FunctionKey;
  1821. const int KeyPress::F3Key = NSF3FunctionKey;
  1822. const int KeyPress::F4Key = NSF4FunctionKey;
  1823. const int KeyPress::F5Key = NSF5FunctionKey;
  1824. const int KeyPress::F6Key = NSF6FunctionKey;
  1825. const int KeyPress::F7Key = NSF7FunctionKey;
  1826. const int KeyPress::F8Key = NSF8FunctionKey;
  1827. const int KeyPress::F9Key = NSF9FunctionKey;
  1828. const int KeyPress::F10Key = NSF10FunctionKey;
  1829. const int KeyPress::F11Key = NSF11FunctionKey;
  1830. const int KeyPress::F12Key = NSF12FunctionKey;
  1831. const int KeyPress::F13Key = NSF13FunctionKey;
  1832. const int KeyPress::F14Key = NSF14FunctionKey;
  1833. const int KeyPress::F15Key = NSF15FunctionKey;
  1834. const int KeyPress::F16Key = NSF16FunctionKey;
  1835. const int KeyPress::F17Key = NSF17FunctionKey;
  1836. const int KeyPress::F18Key = NSF18FunctionKey;
  1837. const int KeyPress::F19Key = NSF19FunctionKey;
  1838. const int KeyPress::F20Key = NSF20FunctionKey;
  1839. const int KeyPress::F21Key = NSF21FunctionKey;
  1840. const int KeyPress::F22Key = NSF22FunctionKey;
  1841. const int KeyPress::F23Key = NSF23FunctionKey;
  1842. const int KeyPress::F24Key = NSF24FunctionKey;
  1843. const int KeyPress::F25Key = NSF25FunctionKey;
  1844. const int KeyPress::F26Key = NSF26FunctionKey;
  1845. const int KeyPress::F27Key = NSF27FunctionKey;
  1846. const int KeyPress::F28Key = NSF28FunctionKey;
  1847. const int KeyPress::F29Key = NSF29FunctionKey;
  1848. const int KeyPress::F30Key = NSF30FunctionKey;
  1849. const int KeyPress::F31Key = NSF31FunctionKey;
  1850. const int KeyPress::F32Key = NSF32FunctionKey;
  1851. const int KeyPress::F33Key = NSF33FunctionKey;
  1852. const int KeyPress::F34Key = NSF34FunctionKey;
  1853. const int KeyPress::F35Key = NSF35FunctionKey;
  1854. const int KeyPress::numberPad0 = 0x30020;
  1855. const int KeyPress::numberPad1 = 0x30021;
  1856. const int KeyPress::numberPad2 = 0x30022;
  1857. const int KeyPress::numberPad3 = 0x30023;
  1858. const int KeyPress::numberPad4 = 0x30024;
  1859. const int KeyPress::numberPad5 = 0x30025;
  1860. const int KeyPress::numberPad6 = 0x30026;
  1861. const int KeyPress::numberPad7 = 0x30027;
  1862. const int KeyPress::numberPad8 = 0x30028;
  1863. const int KeyPress::numberPad9 = 0x30029;
  1864. const int KeyPress::numberPadAdd = 0x3002a;
  1865. const int KeyPress::numberPadSubtract = 0x3002b;
  1866. const int KeyPress::numberPadMultiply = 0x3002c;
  1867. const int KeyPress::numberPadDivide = 0x3002d;
  1868. const int KeyPress::numberPadSeparator = 0x3002e;
  1869. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  1870. const int KeyPress::numberPadEquals = 0x30030;
  1871. const int KeyPress::numberPadDelete = 0x30031;
  1872. const int KeyPress::playKey = 0x30000;
  1873. const int KeyPress::stopKey = 0x30001;
  1874. const int KeyPress::fastForwardKey = 0x30002;
  1875. const int KeyPress::rewindKey = 0x30003;
  1876. } // namespace juce