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.

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