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.

2300 lines
87KB

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