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.

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