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.

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