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.

2143 lines
81KB

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