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.

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