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.

2164 lines
82KB

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