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.

2286 lines
86KB

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