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.

2181 lines
83KB

  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 Timer
  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), lastRepaintTime (Time::getMillisecondCounter())
  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] & NSWindowStyleMaskFullScreen) != 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] & NSEventModifierFlagCommand) != 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] & NSEventModifierFlagCommand) != 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 repaint (const Rectangle<int>& area) 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. // In 10.11 changes were made to the way the OS handles repaint regions, and it seems that it can
  741. // no longer be trusted to coalesce all the regions, or to even remember them all without losing
  742. // a few when there's a lot of activity.
  743. // As a work around for this, we use a RectangleList to do our own coalescing of regions before
  744. // asynchronously asking the OS to repaint them.
  745. deferredRepaints.add ((float) area.getX(), (float) ([view frame].size.height - area.getBottom()),
  746. (float) area.getWidth(), (float) area.getHeight());
  747. // already a timer running -> stop
  748. if (isTimerRunning()) return;
  749. const uint32 now = Time::getMillisecondCounter();
  750. uint32 msSinceLastRepaint =
  751. (lastRepaintTime >= now ? now - lastRepaintTime
  752. : (std::numeric_limits<uint32>::max() - lastRepaintTime) + now);
  753. static uint32 minimumRepaintInterval = 1000 / 30; // 30fps
  754. // When windows are being resized, artificially throttling high-frequency repaints helps
  755. // to stop the event queue getting clogged, and keeps everything working smoothly.
  756. // For some reason Logic also needs this throttling to recored parameter events correctly.
  757. if (shouldThrottle
  758. && msSinceLastRepaint < minimumRepaintInterval)
  759. {
  760. startTimer (static_cast<int> (minimumRepaintInterval - msSinceLastRepaint));
  761. return;
  762. }
  763. setNeedsDisplayRectangles();
  764. }
  765. void timerCallback() override
  766. {
  767. setNeedsDisplayRectangles();
  768. stopTimer();
  769. }
  770. void setNeedsDisplayRectangles()
  771. {
  772. for (const Rectangle<float>* i = deferredRepaints.begin(), *e = deferredRepaints.end(); i != e; ++i)
  773. [view setNeedsDisplayInRect: makeNSRect (*i)];
  774. lastRepaintTime = Time::getMillisecondCounter();
  775. deferredRepaints.clear();
  776. };
  777. void invokePaint (LowLevelGraphicsContext& context)
  778. {
  779. handlePaint (context);
  780. }
  781. void performAnyPendingRepaintsNow() override
  782. {
  783. [view displayIfNeeded];
  784. }
  785. static bool areAnyWindowsInLiveResize() noexcept
  786. {
  787. for (NSWindow* w in [NSApp windows])
  788. if ([w inLiveResize])
  789. return true;
  790. return false;
  791. }
  792. //==============================================================================
  793. bool sendModalInputAttemptIfBlocked()
  794. {
  795. if (Component* modal = Component::getCurrentlyModalComponent())
  796. {
  797. if (insideToFrontCall == 0
  798. && (! getComponent().isParentOf (modal))
  799. && getComponent().isCurrentlyBlockedByAnotherModalComponent())
  800. {
  801. modal->inputAttemptWhenModal();
  802. return true;
  803. }
  804. }
  805. return false;
  806. }
  807. bool canBecomeKeyWindow()
  808. {
  809. return (getStyleFlags() & juce::ComponentPeer::windowIgnoresKeyPresses) == 0;
  810. }
  811. bool canBecomeMainWindow()
  812. {
  813. return dynamic_cast<ResizableWindow*> (&component) != nullptr;
  814. }
  815. bool worksWhenModal() const
  816. {
  817. // In plugins, the host could put our plugin window inside a modal window, so this
  818. // allows us to successfully open other popups. Feels like there could be edge-case
  819. // problems caused by this, so let us know if you spot any issues..
  820. return ! JUCEApplication::isStandaloneApp();
  821. }
  822. void becomeKeyWindow()
  823. {
  824. handleBroughtToFront();
  825. grabFocus();
  826. }
  827. bool windowShouldClose()
  828. {
  829. if (! isValidPeer (this))
  830. return YES;
  831. handleUserClosingWindow();
  832. return NO;
  833. }
  834. void redirectMovedOrResized()
  835. {
  836. updateFullscreenStatus();
  837. handleMovedOrResized();
  838. }
  839. void viewMovedToWindow()
  840. {
  841. if (isSharedWindow)
  842. window = [view window];
  843. }
  844. void liveResizingStart()
  845. {
  846. if (constrainer != nullptr)
  847. {
  848. constrainer->resizeStart();
  849. isFirstLiveResize = true;
  850. }
  851. }
  852. void liveResizingEnd()
  853. {
  854. if (constrainer != nullptr)
  855. constrainer->resizeEnd();
  856. }
  857. NSRect constrainRect (NSRect r)
  858. {
  859. if (constrainer != nullptr && ! isKioskMode())
  860. {
  861. const float scale = getComponent().getDesktopScaleFactor();
  862. Rectangle<int> pos = ScalingHelpers::unscaledScreenPosToScaled (scale, convertToRectInt (flippedScreenRect (r)));
  863. Rectangle<int> original = ScalingHelpers::unscaledScreenPosToScaled (scale, convertToRectInt (flippedScreenRect ([window frame])));
  864. const Rectangle<int> screenBounds (Desktop::getInstance().getDisplays().getTotalBounds (true));
  865. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  866. const bool inLiveResize = [window inLiveResize];
  867. #else
  868. const bool inLiveResize = [window respondsToSelector: @selector (inLiveResize)]
  869. && [window performSelector: @selector (inLiveResize)];
  870. #endif
  871. if (! inLiveResize || isFirstLiveResize)
  872. {
  873. isFirstLiveResize = false;
  874. isStretchingTop = (pos.getY() != original.getY() && pos.getBottom() == original.getBottom());
  875. isStretchingLeft = (pos.getX() != original.getX() && pos.getRight() == original.getRight());
  876. isStretchingBottom = (pos.getY() == original.getY() && pos.getBottom() != original.getBottom());
  877. isStretchingRight = (pos.getX() == original.getX() && pos.getRight() != original.getRight());
  878. }
  879. constrainer->checkBounds (pos, original, screenBounds,
  880. isStretchingTop, isStretchingLeft, isStretchingBottom, isStretchingRight);
  881. pos = ScalingHelpers::scaledScreenPosToUnscaled (scale, pos);
  882. r = flippedScreenRect (makeNSRect (pos));
  883. }
  884. return r;
  885. }
  886. static void showArrowCursorIfNeeded()
  887. {
  888. Desktop& desktop = Desktop::getInstance();
  889. MouseInputSource mouse = desktop.getMainMouseSource();
  890. if (mouse.getComponentUnderMouse() == nullptr
  891. && desktop.findComponentAt (mouse.getScreenPosition().roundToInt()) == nullptr)
  892. {
  893. [[NSCursor arrowCursor] set];
  894. }
  895. }
  896. static void updateModifiers (NSEvent* e)
  897. {
  898. updateModifiers ([e modifierFlags]);
  899. }
  900. static void updateModifiers (const NSUInteger flags)
  901. {
  902. int m = 0;
  903. if ((flags & NSEventModifierFlagShift) != 0) m |= ModifierKeys::shiftModifier;
  904. if ((flags & NSEventModifierFlagControl) != 0) m |= ModifierKeys::ctrlModifier;
  905. if ((flags & NSEventModifierFlagOption) != 0) m |= ModifierKeys::altModifier;
  906. if ((flags & NSEventModifierFlagCommand) != 0) m |= ModifierKeys::commandModifier;
  907. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  908. }
  909. static void updateKeysDown (NSEvent* ev, bool isKeyDown)
  910. {
  911. updateModifiers (ev);
  912. int keyCode = getKeyCodeFromEvent (ev);
  913. if (keyCode != 0)
  914. {
  915. if (isKeyDown)
  916. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  917. else
  918. keysCurrentlyDown.removeFirstMatchingValue (keyCode);
  919. }
  920. }
  921. static int getKeyCodeFromEvent (NSEvent* ev)
  922. {
  923. // Unfortunately, charactersIgnoringModifiers does not ignore the shift key.
  924. // Using [ev keyCode] is not a solution either as this will,
  925. // for example, return VK_KEY_Y if the key is pressed which
  926. // is typically located at the Y key position on a QWERTY
  927. // keyboard. However, on international keyboards this might not
  928. // be the key labeled Y (for example, on German keyboards this key
  929. // has a Z label). Therefore, we need to query the current keyboard
  930. // layout to figure out what character the key would have produced
  931. // if the shift key was not pressed
  932. String unmodified;
  933. #if JUCE_SUPPORT_CARBON
  934. if (TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource())
  935. {
  936. CFDataRef layoutData = (CFDataRef) TISGetInputSourceProperty (currentKeyboard,
  937. kTISPropertyUnicodeKeyLayoutData);
  938. if (layoutData != nullptr)
  939. {
  940. if (const UCKeyboardLayout* layoutPtr = (const UCKeyboardLayout*) CFDataGetBytePtr (layoutData))
  941. {
  942. UInt32 keysDown = 0;
  943. UniChar buffer[4];
  944. UniCharCount actual;
  945. if (UCKeyTranslate (layoutPtr, [ev keyCode], kUCKeyActionDown, 0, LMGetKbdType(),
  946. kUCKeyTranslateNoDeadKeysBit, &keysDown, sizeof (buffer) / sizeof (UniChar),
  947. &actual, buffer) == 0)
  948. unmodified = String (CharPointer_UTF16 (reinterpret_cast<CharPointer_UTF16::CharType*> (buffer)), 4);
  949. }
  950. }
  951. CFRelease (currentKeyboard);
  952. }
  953. // did the above layout conversion fail
  954. if (unmodified.isEmpty())
  955. #endif
  956. {
  957. unmodified = nsStringToJuce ([ev charactersIgnoringModifiers]);
  958. }
  959. int keyCode = unmodified[0];
  960. if (keyCode == 0x19) // (backwards-tab)
  961. keyCode = '\t';
  962. else if (keyCode == 0x03) // (enter)
  963. keyCode = '\r';
  964. else
  965. keyCode = (int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  966. if (([ev modifierFlags] & NSEventModifierFlagNumericPad) != 0)
  967. {
  968. const int numPadConversions[] = { '0', KeyPress::numberPad0, '1', KeyPress::numberPad1,
  969. '2', KeyPress::numberPad2, '3', KeyPress::numberPad3,
  970. '4', KeyPress::numberPad4, '5', KeyPress::numberPad5,
  971. '6', KeyPress::numberPad6, '7', KeyPress::numberPad7,
  972. '8', KeyPress::numberPad8, '9', KeyPress::numberPad9,
  973. '+', KeyPress::numberPadAdd, '-', KeyPress::numberPadSubtract,
  974. '*', KeyPress::numberPadMultiply, '/', KeyPress::numberPadDivide,
  975. '.', KeyPress::numberPadDecimalPoint,
  976. ',', KeyPress::numberPadDecimalPoint, // (to deal with non-english kbds)
  977. '=', KeyPress::numberPadEquals };
  978. for (int i = 0; i < numElementsInArray (numPadConversions); i += 2)
  979. if (keyCode == numPadConversions [i])
  980. keyCode = numPadConversions [i + 1];
  981. }
  982. return keyCode;
  983. }
  984. static int64 getMouseTime (NSEvent* e) noexcept
  985. {
  986. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  987. + (int64) ([e timestamp] * 1000.0);
  988. }
  989. static float getMousePressure (NSEvent* e) noexcept
  990. {
  991. @try
  992. {
  993. if (e.type != NSEventTypeMouseEntered && e.type != NSEventTypeMouseExited)
  994. return (float) e.pressure;
  995. }
  996. @catch (NSException* e) {}
  997. @finally {}
  998. return 0.0f;
  999. }
  1000. static Point<float> getMousePos (NSEvent* e, NSView* view)
  1001. {
  1002. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  1003. return Point<float> ((float) p.x, (float) ([view frame].size.height - p.y));
  1004. }
  1005. static int getModifierForButtonNumber (const NSInteger num)
  1006. {
  1007. return num == 0 ? ModifierKeys::leftButtonModifier
  1008. : (num == 1 ? ModifierKeys::rightButtonModifier
  1009. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  1010. }
  1011. static unsigned int getNSWindowStyleMask (const int flags) noexcept
  1012. {
  1013. unsigned int style = (flags & windowHasTitleBar) != 0 ? NSWindowStyleMaskTitled
  1014. : NSWindowStyleMaskBorderless;
  1015. if ((flags & windowHasMinimiseButton) != 0) style |= NSWindowStyleMaskMiniaturizable;
  1016. if ((flags & windowHasCloseButton) != 0) style |= NSWindowStyleMaskClosable;
  1017. if ((flags & windowIsResizable) != 0) style |= NSWindowStyleMaskResizable;
  1018. return style;
  1019. }
  1020. static NSArray* getSupportedDragTypes()
  1021. {
  1022. return [NSArray arrayWithObjects: NSFilenamesPboardType, NSFilesPromisePboardType, NSStringPboardType, nil];
  1023. }
  1024. BOOL sendDragCallback (const int type, id <NSDraggingInfo> sender)
  1025. {
  1026. NSPasteboard* pasteboard = [sender draggingPasteboard];
  1027. NSString* contentType = [pasteboard availableTypeFromArray: getSupportedDragTypes()];
  1028. if (contentType == nil)
  1029. return false;
  1030. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  1031. ComponentPeer::DragInfo dragInfo;
  1032. dragInfo.position.setXY ((int) p.x, (int) ([view frame].size.height - p.y));
  1033. if (contentType == NSStringPboardType)
  1034. dragInfo.text = nsStringToJuce ([pasteboard stringForType: NSStringPboardType]);
  1035. else
  1036. dragInfo.files = getDroppedFiles (pasteboard, contentType);
  1037. if (! dragInfo.isEmpty())
  1038. {
  1039. switch (type)
  1040. {
  1041. case 0: return handleDragMove (dragInfo);
  1042. case 1: return handleDragExit (dragInfo);
  1043. case 2: return handleDragDrop (dragInfo);
  1044. default: jassertfalse; break;
  1045. }
  1046. }
  1047. return false;
  1048. }
  1049. StringArray getDroppedFiles (NSPasteboard* pasteboard, NSString* contentType)
  1050. {
  1051. StringArray files;
  1052. NSString* iTunesPasteboardType = nsStringLiteral ("CorePasteboardFlavorType 0x6974756E"); // 'itun'
  1053. if (contentType == NSFilesPromisePboardType
  1054. && [[pasteboard types] containsObject: iTunesPasteboardType])
  1055. {
  1056. id list = [pasteboard propertyListForType: iTunesPasteboardType];
  1057. if ([list isKindOfClass: [NSDictionary class]])
  1058. {
  1059. NSDictionary* iTunesDictionary = (NSDictionary*) list;
  1060. NSArray* tracks = [iTunesDictionary valueForKey: nsStringLiteral ("Tracks")];
  1061. NSEnumerator* enumerator = [tracks objectEnumerator];
  1062. NSDictionary* track;
  1063. while ((track = [enumerator nextObject]) != nil)
  1064. {
  1065. NSURL* url = [NSURL URLWithString: [track valueForKey: nsStringLiteral ("Location")]];
  1066. if ([url isFileURL])
  1067. files.add (nsStringToJuce ([url path]));
  1068. }
  1069. }
  1070. }
  1071. else
  1072. {
  1073. id list = [pasteboard propertyListForType: NSFilenamesPboardType];
  1074. if ([list isKindOfClass: [NSArray class]])
  1075. {
  1076. NSArray* items = (NSArray*) [pasteboard propertyListForType: NSFilenamesPboardType];
  1077. for (unsigned int i = 0; i < [items count]; ++i)
  1078. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  1079. }
  1080. }
  1081. return files;
  1082. }
  1083. //==============================================================================
  1084. void viewFocusGain()
  1085. {
  1086. if (currentlyFocusedPeer != this)
  1087. {
  1088. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  1089. currentlyFocusedPeer->handleFocusLoss();
  1090. currentlyFocusedPeer = this;
  1091. handleFocusGain();
  1092. }
  1093. }
  1094. void viewFocusLoss()
  1095. {
  1096. if (currentlyFocusedPeer == this)
  1097. {
  1098. currentlyFocusedPeer = nullptr;
  1099. handleFocusLoss();
  1100. }
  1101. }
  1102. bool isFocused() const override
  1103. {
  1104. return (isSharedWindow || ! JUCEApplication::isStandaloneApp())
  1105. ? this == currentlyFocusedPeer
  1106. : [window isKeyWindow];
  1107. }
  1108. void grabFocus() override
  1109. {
  1110. if (window != nil)
  1111. {
  1112. [window makeKeyWindow];
  1113. [window makeFirstResponder: view];
  1114. viewFocusGain();
  1115. }
  1116. }
  1117. void textInputRequired (Point<int>, TextInputTarget&) override {}
  1118. //==============================================================================
  1119. NSWindow* window;
  1120. NSView* view;
  1121. bool isSharedWindow, fullScreen;
  1122. bool usingCoreGraphics, isZooming, isFirstLiveResize, textWasInserted;
  1123. bool isStretchingTop, isStretchingLeft, isStretchingBottom, isStretchingRight;
  1124. String stringBeingComposed;
  1125. NSNotificationCenter* notificationCenter;
  1126. RectangleList<float> deferredRepaints;
  1127. uint32 lastRepaintTime;
  1128. static ModifierKeys currentModifiers;
  1129. static ComponentPeer* currentlyFocusedPeer;
  1130. static Array<int> keysCurrentlyDown;
  1131. static int insideToFrontCall;
  1132. private:
  1133. static NSView* createViewInstance();
  1134. static NSWindow* createWindowInstance();
  1135. static void setOwner (id viewOrWindow, NSViewComponentPeer* newOwner)
  1136. {
  1137. object_setInstanceVariable (viewOrWindow, "owner", newOwner);
  1138. }
  1139. void getClipRects (RectangleList<int>& clip, const Point<int> offset, const int clipW, const int clipH)
  1140. {
  1141. const NSRect* rects = nullptr;
  1142. NSInteger numRects = 0;
  1143. [view getRectsBeingDrawn: &rects count: &numRects];
  1144. const Rectangle<int> clipBounds (clipW, clipH);
  1145. const CGFloat viewH = [view frame].size.height;
  1146. clip.ensureStorageAllocated ((int) numRects);
  1147. for (int i = 0; i < numRects; ++i)
  1148. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + offset.x,
  1149. roundToInt (viewH - (rects[i].origin.y + rects[i].size.height)) + offset.y,
  1150. roundToInt (rects[i].size.width),
  1151. roundToInt (rects[i].size.height))));
  1152. }
  1153. static void appFocusChanged()
  1154. {
  1155. keysCurrentlyDown.clear();
  1156. if (isValidPeer (currentlyFocusedPeer))
  1157. {
  1158. if (Process::isForegroundProcess())
  1159. {
  1160. currentlyFocusedPeer->handleFocusGain();
  1161. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  1162. }
  1163. else
  1164. {
  1165. currentlyFocusedPeer->handleFocusLoss();
  1166. }
  1167. }
  1168. }
  1169. static bool checkEventBlockedByModalComps (NSEvent* e)
  1170. {
  1171. if (Component::getNumCurrentlyModalComponents() == 0)
  1172. return false;
  1173. NSWindow* const w = [e window];
  1174. if (w == nil || [w worksWhenModal])
  1175. return false;
  1176. bool isKey = false, isInputAttempt = false;
  1177. switch ([e type])
  1178. {
  1179. case NSEventTypeKeyDown:
  1180. case NSEventTypeKeyUp:
  1181. isKey = isInputAttempt = true;
  1182. break;
  1183. case NSEventTypeLeftMouseDown:
  1184. case NSEventTypeRightMouseDown:
  1185. case NSEventTypeOtherMouseDown:
  1186. isInputAttempt = true;
  1187. break;
  1188. case NSEventTypeLeftMouseDragged:
  1189. case NSEventTypeRightMouseDragged:
  1190. case NSEventTypeLeftMouseUp:
  1191. case NSEventTypeRightMouseUp:
  1192. case NSEventTypeOtherMouseUp:
  1193. case NSEventTypeOtherMouseDragged:
  1194. if (Desktop::getInstance().getDraggingMouseSource(0) != nullptr)
  1195. return false;
  1196. break;
  1197. case NSEventTypeMouseMoved:
  1198. case NSEventTypeMouseEntered:
  1199. case NSEventTypeMouseExited:
  1200. case NSEventTypeCursorUpdate:
  1201. case NSEventTypeScrollWheel:
  1202. case NSEventTypeTabletPoint:
  1203. case NSEventTypeTabletProximity:
  1204. break;
  1205. default:
  1206. return false;
  1207. }
  1208. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  1209. {
  1210. if (NSViewComponentPeer* peer = dynamic_cast<NSViewComponentPeer*> (ComponentPeer::getPeer (i)))
  1211. {
  1212. if ([peer->view window] == w)
  1213. {
  1214. if (isKey)
  1215. {
  1216. if (peer->view == [w firstResponder])
  1217. return false;
  1218. }
  1219. else
  1220. {
  1221. if (peer->isSharedWindow
  1222. ? NSPointInRect ([peer->view convertPoint: [e locationInWindow] fromView: nil], [peer->view bounds])
  1223. : NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height)))
  1224. return false;
  1225. }
  1226. }
  1227. }
  1228. }
  1229. if (isInputAttempt)
  1230. {
  1231. if (! [NSApp isActive])
  1232. [NSApp activateIgnoringOtherApps: YES];
  1233. if (Component* const modal = Component::getCurrentlyModalComponent())
  1234. modal->inputAttemptWhenModal();
  1235. }
  1236. return true;
  1237. }
  1238. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentPeer)
  1239. };
  1240. int NSViewComponentPeer::insideToFrontCall = 0;
  1241. //==============================================================================
  1242. struct JuceNSViewClass : public ObjCClass<NSView>
  1243. {
  1244. JuceNSViewClass() : ObjCClass<NSView> ("JUCEView_")
  1245. {
  1246. addIvar<NSViewComponentPeer*> ("owner");
  1247. addMethod (@selector (isOpaque), isOpaque, "c@:");
  1248. addMethod (@selector (drawRect:), drawRect, "v@:", @encode (NSRect));
  1249. addMethod (@selector (mouseDown:), mouseDown, "v@:@");
  1250. addMethod (@selector (asyncMouseDown:), asyncMouseDown, "v@:@");
  1251. addMethod (@selector (mouseUp:), mouseUp, "v@:@");
  1252. addMethod (@selector (asyncMouseUp:), asyncMouseUp, "v@:@");
  1253. addMethod (@selector (mouseDragged:), mouseDragged, "v@:@");
  1254. addMethod (@selector (mouseMoved:), mouseMoved, "v@:@");
  1255. addMethod (@selector (mouseEntered:), mouseEntered, "v@:@");
  1256. addMethod (@selector (mouseExited:), mouseExited, "v@:@");
  1257. addMethod (@selector (rightMouseDown:), mouseDown, "v@:@");
  1258. addMethod (@selector (rightMouseDragged:), mouseDragged, "v@:@");
  1259. addMethod (@selector (rightMouseUp:), mouseUp, "v@:@");
  1260. addMethod (@selector (otherMouseDown:), mouseDown, "v@:@");
  1261. addMethod (@selector (otherMouseDragged:), mouseDragged, "v@:@");
  1262. addMethod (@selector (otherMouseUp:), mouseUp, "v@:@");
  1263. addMethod (@selector (scrollWheel:), scrollWheel, "v@:@");
  1264. addMethod (@selector (magnifyWithEvent:), magnify, "v@:@");
  1265. addMethod (@selector (acceptsFirstMouse:), acceptsFirstMouse, "c@:@");
  1266. addMethod (@selector (frameChanged:), frameChanged, "v@:@");
  1267. addMethod (@selector (wantsDefaultClipping:), wantsDefaultClipping, "c@:");
  1268. addMethod (@selector (worksWhenModal), worksWhenModal, "c@:");
  1269. addMethod (@selector (viewDidMoveToWindow), viewDidMoveToWindow, "v@:");
  1270. addMethod (@selector (keyDown:), keyDown, "v@:@");
  1271. addMethod (@selector (keyUp:), keyUp, "v@:@");
  1272. addMethod (@selector (insertText:), insertText, "v@:@");
  1273. addMethod (@selector (doCommandBySelector:), doCommandBySelector, "v@::");
  1274. addMethod (@selector (setMarkedText:selectedRange:), setMarkedText, "v@:@", @encode (NSRange));
  1275. addMethod (@selector (unmarkText), unmarkText, "v@:");
  1276. addMethod (@selector (hasMarkedText), hasMarkedText, "c@:");
  1277. addMethod (@selector (conversationIdentifier), conversationIdentifier, "l@:");
  1278. addMethod (@selector (attributedSubstringFromRange:), attributedSubstringFromRange, "@@:", @encode (NSRange));
  1279. addMethod (@selector (markedRange), markedRange, @encode (NSRange), "@:");
  1280. addMethod (@selector (selectedRange), selectedRange, @encode (NSRange), "@:");
  1281. addMethod (@selector (firstRectForCharacterRange:), firstRectForCharacterRange, @encode (NSRect), "@:", @encode (NSRange));
  1282. addMethod (@selector (validAttributesForMarkedText), validAttributesForMarkedText, "@@:");
  1283. addMethod (@selector (flagsChanged:), flagsChanged, "v@:@");
  1284. addMethod (@selector (becomeFirstResponder), becomeFirstResponder, "c@:");
  1285. addMethod (@selector (resignFirstResponder), resignFirstResponder, "c@:");
  1286. addMethod (@selector (acceptsFirstResponder), acceptsFirstResponder, "c@:");
  1287. addMethod (@selector (draggingEntered:), draggingEntered, @encode (NSDragOperation), "@:@");
  1288. addMethod (@selector (draggingUpdated:), draggingUpdated, @encode (NSDragOperation), "@:@");
  1289. addMethod (@selector (draggingEnded:), draggingEnded, "v@:@");
  1290. addMethod (@selector (draggingExited:), draggingExited, "v@:@");
  1291. addMethod (@selector (prepareForDragOperation:), prepareForDragOperation, "c@:@");
  1292. addMethod (@selector (performDragOperation:), performDragOperation, "c@:@");
  1293. addMethod (@selector (concludeDragOperation:), concludeDragOperation, "v@:@");
  1294. addMethod (@selector (paste:), paste, "v@:@");
  1295. addMethod (@selector (copy:), copy, "v@:@");
  1296. addMethod (@selector (cut:), cut, "v@:@");
  1297. addMethod (@selector (viewWillMoveToWindow:), willMoveToWindow, "v@:@");
  1298. addProtocol (@protocol (NSTextInput));
  1299. registerClass();
  1300. }
  1301. private:
  1302. static NSViewComponentPeer* getOwner (id self)
  1303. {
  1304. return getIvar<NSViewComponentPeer*> (self, "owner");
  1305. }
  1306. static void mouseDown (id self, SEL s, NSEvent* ev)
  1307. {
  1308. if (JUCEApplicationBase::isStandaloneApp())
  1309. asyncMouseDown (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 (asyncMouseDown:)
  1315. withObject: ev
  1316. waitUntilDone: NO];
  1317. }
  1318. static void mouseUp (id self, SEL s, NSEvent* ev)
  1319. {
  1320. if (JUCEApplicationBase::isStandaloneApp())
  1321. asyncMouseUp (self, s, ev);
  1322. else
  1323. // In some host situations, the host will stop modal loops from working
  1324. // correctly if they're called from a mouse event, so we'll trigger
  1325. // the event asynchronously..
  1326. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  1327. withObject: ev
  1328. waitUntilDone: NO];
  1329. }
  1330. static void asyncMouseDown (id self, SEL, NSEvent* ev) { if (NSViewComponentPeer* p = getOwner (self)) p->redirectMouseDown (ev); }
  1331. static void asyncMouseUp (id self, SEL, NSEvent* ev) { if (NSViewComponentPeer* p = getOwner (self)) p->redirectMouseUp (ev); }
  1332. static void mouseDragged (id self, SEL, NSEvent* ev) { if (NSViewComponentPeer* p = getOwner (self)) p->redirectMouseDrag (ev); }
  1333. static void mouseMoved (id self, SEL, NSEvent* ev) { if (NSViewComponentPeer* p = getOwner (self)) p->redirectMouseMove (ev); }
  1334. static void mouseEntered (id self, SEL, NSEvent* ev) { if (NSViewComponentPeer* p = getOwner (self)) p->redirectMouseEnter (ev); }
  1335. static void mouseExited (id self, SEL, NSEvent* ev) { if (NSViewComponentPeer* p = getOwner (self)) p->redirectMouseExit (ev); }
  1336. static void scrollWheel (id self, SEL, NSEvent* ev) { if (NSViewComponentPeer* p = getOwner (self)) p->redirectMouseWheel (ev); }
  1337. static void magnify (id self, SEL, NSEvent* ev) { if (NSViewComponentPeer* p = getOwner (self)) p->redirectMagnify (ev); }
  1338. static void copy (id self, SEL, NSObject* s) { if (NSViewComponentPeer* p = getOwner (self)) p->redirectCopy (s); }
  1339. static void paste (id self, SEL, NSObject* s) { if (NSViewComponentPeer* p = getOwner (self)) p->redirectPaste (s); }
  1340. static void cut (id self, SEL, NSObject* s) { if (NSViewComponentPeer* p = getOwner (self)) p->redirectCut (s); }
  1341. static void willMoveToWindow (id self, SEL, NSWindow* window)
  1342. {
  1343. if (NSViewComponentPeer* p = getOwner (self)) p->redirectWillMoveToWindow (window);
  1344. }
  1345. static BOOL acceptsFirstMouse (id, SEL, NSEvent*) { return YES; }
  1346. static BOOL wantsDefaultClipping (id, SEL) { return YES; } // (this is the default, but may want to customise it in future)
  1347. static BOOL worksWhenModal (id self, SEL) { if (NSViewComponentPeer* p = getOwner (self)) return p->worksWhenModal(); return NO; };
  1348. static void drawRect (id self, SEL, NSRect r) { if (NSViewComponentPeer* p = getOwner (self)) p->drawRect (r); }
  1349. static void frameChanged (id self, SEL, NSNotification*) { if (NSViewComponentPeer* p = getOwner (self)) p->redirectMovedOrResized(); }
  1350. static void viewDidMoveToWindow (id self, SEL) { if (NSViewComponentPeer* p = getOwner (self)) p->viewMovedToWindow(); }
  1351. static BOOL isOpaque (id self, SEL)
  1352. {
  1353. NSViewComponentPeer* const owner = getOwner (self);
  1354. return owner == nullptr || owner->getComponent().isOpaque();
  1355. }
  1356. //==============================================================================
  1357. static void keyDown (id self, SEL, NSEvent* ev)
  1358. {
  1359. if (NSViewComponentPeer* const owner = getOwner (self))
  1360. {
  1361. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  1362. owner->textWasInserted = false;
  1363. if (target != nullptr)
  1364. [(NSView*) self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  1365. else
  1366. owner->stringBeingComposed.clear();
  1367. if ((! owner->textWasInserted) && (owner == nullptr || ! owner->redirectKeyDown (ev)))
  1368. {
  1369. objc_super s = { self, [NSView class] };
  1370. getMsgSendSuperFn() (&s, @selector (keyDown:), ev);
  1371. }
  1372. }
  1373. }
  1374. static void keyUp (id self, SEL, NSEvent* ev)
  1375. {
  1376. NSViewComponentPeer* const owner = getOwner (self);
  1377. if (owner == nullptr || ! owner->redirectKeyUp (ev))
  1378. {
  1379. objc_super s = { self, [NSView class] };
  1380. getMsgSendSuperFn() (&s, @selector (keyUp:), ev);
  1381. }
  1382. }
  1383. //==============================================================================
  1384. static void insertText (id self, SEL, id aString)
  1385. {
  1386. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  1387. if (NSViewComponentPeer* const owner = getOwner (self))
  1388. {
  1389. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  1390. if ([newText length] > 0)
  1391. {
  1392. if (TextInputTarget* const target = owner->findCurrentTextInputTarget())
  1393. {
  1394. target->insertTextAtCaret (nsStringToJuce (newText));
  1395. owner->textWasInserted = true;
  1396. }
  1397. }
  1398. owner->stringBeingComposed.clear();
  1399. }
  1400. }
  1401. static void doCommandBySelector (id, SEL, SEL) {}
  1402. static void setMarkedText (id self, SEL, id aString, NSRange)
  1403. {
  1404. if (NSViewComponentPeer* const owner = getOwner (self))
  1405. {
  1406. owner->stringBeingComposed = nsStringToJuce ([aString isKindOfClass: [NSAttributedString class]]
  1407. ? [aString string] : aString);
  1408. if (TextInputTarget* const target = owner->findCurrentTextInputTarget())
  1409. {
  1410. const Range<int> currentHighlight (target->getHighlightedRegion());
  1411. target->insertTextAtCaret (owner->stringBeingComposed);
  1412. target->setHighlightedRegion (currentHighlight.withLength (owner->stringBeingComposed.length()));
  1413. owner->textWasInserted = true;
  1414. }
  1415. }
  1416. }
  1417. static void unmarkText (id self, SEL)
  1418. {
  1419. if (NSViewComponentPeer* const owner = getOwner (self))
  1420. {
  1421. if (owner->stringBeingComposed.isNotEmpty())
  1422. {
  1423. if (TextInputTarget* const target = owner->findCurrentTextInputTarget())
  1424. {
  1425. target->insertTextAtCaret (owner->stringBeingComposed);
  1426. owner->textWasInserted = true;
  1427. }
  1428. owner->stringBeingComposed.clear();
  1429. }
  1430. }
  1431. }
  1432. static BOOL hasMarkedText (id self, SEL)
  1433. {
  1434. NSViewComponentPeer* const owner = getOwner (self);
  1435. return owner != nullptr && owner->stringBeingComposed.isNotEmpty();
  1436. }
  1437. static long conversationIdentifier (id self, SEL)
  1438. {
  1439. return (long) (pointer_sized_int) self;
  1440. }
  1441. static NSAttributedString* attributedSubstringFromRange (id self, SEL, NSRange theRange)
  1442. {
  1443. if (NSViewComponentPeer* const owner = getOwner (self))
  1444. {
  1445. if (TextInputTarget* const target = owner->findCurrentTextInputTarget())
  1446. {
  1447. const Range<int> r ((int) theRange.location,
  1448. (int) (theRange.location + theRange.length));
  1449. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  1450. }
  1451. }
  1452. return nil;
  1453. }
  1454. static NSRange markedRange (id self, SEL)
  1455. {
  1456. if (NSViewComponentPeer* const owner = getOwner (self))
  1457. if (owner->stringBeingComposed.isNotEmpty())
  1458. return NSMakeRange (0, (NSUInteger) owner->stringBeingComposed.length());
  1459. return NSMakeRange (NSNotFound, 0);
  1460. }
  1461. static NSRange selectedRange (id self, SEL)
  1462. {
  1463. if (NSViewComponentPeer* const owner = getOwner (self))
  1464. {
  1465. if (TextInputTarget* const target = owner->findCurrentTextInputTarget())
  1466. {
  1467. const Range<int> highlight (target->getHighlightedRegion());
  1468. if (! highlight.isEmpty())
  1469. return NSMakeRange ((NSUInteger) highlight.getStart(),
  1470. (NSUInteger) highlight.getLength());
  1471. }
  1472. }
  1473. return NSMakeRange (NSNotFound, 0);
  1474. }
  1475. static NSRect firstRectForCharacterRange (id self, SEL, NSRange)
  1476. {
  1477. if (NSViewComponentPeer* const owner = getOwner (self))
  1478. if (Component* const comp = dynamic_cast<Component*> (owner->findCurrentTextInputTarget()))
  1479. return flippedScreenRect (makeNSRect (comp->getScreenBounds()));
  1480. return NSZeroRect;
  1481. }
  1482. static NSUInteger characterIndexForPoint (id, SEL, NSPoint) { return NSNotFound; }
  1483. static NSArray* validAttributesForMarkedText (id, SEL) { return [NSArray array]; }
  1484. //==============================================================================
  1485. static void flagsChanged (id self, SEL, NSEvent* ev)
  1486. {
  1487. if (NSViewComponentPeer* const owner = getOwner (self))
  1488. owner->redirectModKeyChange (ev);
  1489. }
  1490. static BOOL becomeFirstResponder (id self, SEL)
  1491. {
  1492. if (NSViewComponentPeer* const owner = getOwner (self))
  1493. owner->viewFocusGain();
  1494. return YES;
  1495. }
  1496. static BOOL resignFirstResponder (id self, SEL)
  1497. {
  1498. if (NSViewComponentPeer* const owner = getOwner (self))
  1499. owner->viewFocusLoss();
  1500. return YES;
  1501. }
  1502. static BOOL acceptsFirstResponder (id self, SEL)
  1503. {
  1504. NSViewComponentPeer* const owner = getOwner (self);
  1505. return owner != nullptr && owner->canBecomeKeyWindow();
  1506. }
  1507. //==============================================================================
  1508. static NSDragOperation draggingEntered (id self, SEL s, id<NSDraggingInfo> sender)
  1509. {
  1510. return draggingUpdated (self, s, sender);
  1511. }
  1512. static NSDragOperation draggingUpdated (id self, SEL, id<NSDraggingInfo> sender)
  1513. {
  1514. if (NSViewComponentPeer* const owner = getOwner (self))
  1515. if (owner->sendDragCallback (0, sender))
  1516. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  1517. return NSDragOperationNone;
  1518. }
  1519. static void draggingEnded (id self, SEL s, id<NSDraggingInfo> sender)
  1520. {
  1521. draggingExited (self, s, sender);
  1522. }
  1523. static void draggingExited (id self, SEL, id<NSDraggingInfo> sender)
  1524. {
  1525. if (NSViewComponentPeer* const owner = getOwner (self))
  1526. owner->sendDragCallback (1, sender);
  1527. }
  1528. static BOOL prepareForDragOperation (id, SEL, id<NSDraggingInfo>)
  1529. {
  1530. return YES;
  1531. }
  1532. static BOOL performDragOperation (id self, SEL, id<NSDraggingInfo> sender)
  1533. {
  1534. NSViewComponentPeer* const owner = getOwner (self);
  1535. return owner != nullptr && owner->sendDragCallback (2, sender);
  1536. }
  1537. static void concludeDragOperation (id, SEL, id<NSDraggingInfo>) {}
  1538. };
  1539. //==============================================================================
  1540. struct JuceNSWindowClass : public ObjCClass<NSWindow>
  1541. {
  1542. JuceNSWindowClass() : ObjCClass<NSWindow> ("JUCEWindow_")
  1543. {
  1544. addIvar<NSViewComponentPeer*> ("owner");
  1545. addMethod (@selector (canBecomeKeyWindow), canBecomeKeyWindow, "c@:");
  1546. addMethod (@selector (canBecomeMainWindow), canBecomeMainWindow, "c@:");
  1547. addMethod (@selector (becomeKeyWindow), becomeKeyWindow, "v@:");
  1548. addMethod (@selector (windowShouldClose:), windowShouldClose, "c@:@");
  1549. addMethod (@selector (constrainFrameRect:toScreen:), constrainFrameRect, @encode (NSRect), "@:", @encode (NSRect), "@");
  1550. addMethod (@selector (windowWillResize:toSize:), windowWillResize, @encode (NSSize), "@:@", @encode (NSSize));
  1551. addMethod (@selector (windowDidExitFullScreen:), windowDidExitFullScreen, "v@:@");
  1552. addMethod (@selector (zoom:), zoom, "v@:@");
  1553. addMethod (@selector (windowWillMove:), windowWillMove, "v@:@");
  1554. addMethod (@selector (windowWillStartLiveResize:), windowWillStartLiveResize, "v@:@");
  1555. addMethod (@selector (windowDidEndLiveResize:), windowDidEndLiveResize, "v@:@");
  1556. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  1557. addProtocol (@protocol (NSWindowDelegate));
  1558. #endif
  1559. registerClass();
  1560. }
  1561. private:
  1562. static NSViewComponentPeer* getOwner (id self)
  1563. {
  1564. return getIvar<NSViewComponentPeer*> (self, "owner");
  1565. }
  1566. //==============================================================================
  1567. static BOOL canBecomeKeyWindow (id self, SEL)
  1568. {
  1569. NSViewComponentPeer* const owner = getOwner (self);
  1570. return owner != nullptr
  1571. && owner->canBecomeKeyWindow()
  1572. && ! owner->sendModalInputAttemptIfBlocked();
  1573. }
  1574. static BOOL canBecomeMainWindow (id self, SEL)
  1575. {
  1576. NSViewComponentPeer* const owner = getOwner (self);
  1577. return owner != nullptr
  1578. && owner->canBecomeMainWindow()
  1579. && ! owner->sendModalInputAttemptIfBlocked();
  1580. }
  1581. static void becomeKeyWindow (id self, SEL)
  1582. {
  1583. sendSuperclassMessage (self, @selector (becomeKeyWindow));
  1584. if (NSViewComponentPeer* const owner = getOwner (self))
  1585. owner->becomeKeyWindow();
  1586. }
  1587. static BOOL windowShouldClose (id self, SEL, id /*window*/)
  1588. {
  1589. NSViewComponentPeer* const owner = getOwner (self);
  1590. return owner == nullptr || owner->windowShouldClose();
  1591. }
  1592. static NSRect constrainFrameRect (id self, SEL, NSRect frameRect, NSScreen*)
  1593. {
  1594. if (NSViewComponentPeer* const owner = getOwner (self))
  1595. frameRect = owner->constrainRect (frameRect);
  1596. return frameRect;
  1597. }
  1598. static NSSize windowWillResize (id self, SEL, NSWindow*, NSSize proposedFrameSize)
  1599. {
  1600. NSViewComponentPeer* const owner = getOwner (self);
  1601. if (owner == nullptr || owner->isZooming)
  1602. return proposedFrameSize;
  1603. NSRect frameRect = [(NSWindow*) self frame];
  1604. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  1605. frameRect.size = proposedFrameSize;
  1606. frameRect = owner->constrainRect (frameRect);
  1607. if (owner->hasNativeTitleBar())
  1608. owner->sendModalInputAttemptIfBlocked();
  1609. return frameRect.size;
  1610. }
  1611. static void windowDidExitFullScreen (id, SEL, NSNotification*)
  1612. {
  1613. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  1614. [NSApp setPresentationOptions: NSApplicationPresentationDefault];
  1615. #endif
  1616. }
  1617. static void zoom (id self, SEL, id sender)
  1618. {
  1619. if (NSViewComponentPeer* const owner = getOwner (self))
  1620. {
  1621. owner->isZooming = true;
  1622. objc_super s = { self, [NSWindow class] };
  1623. getMsgSendSuperFn() (&s, @selector (zoom:), sender);
  1624. owner->isZooming = false;
  1625. owner->redirectMovedOrResized();
  1626. }
  1627. }
  1628. static void windowWillMove (id self, SEL, NSNotification*)
  1629. {
  1630. if (NSViewComponentPeer* const owner = getOwner (self))
  1631. if (owner->hasNativeTitleBar())
  1632. owner->sendModalInputAttemptIfBlocked();
  1633. }
  1634. static void windowWillStartLiveResize (id self, SEL, NSNotification*)
  1635. {
  1636. if (NSViewComponentPeer* const owner = getOwner (self))
  1637. owner->liveResizingStart();
  1638. }
  1639. static void windowDidEndLiveResize (id self, SEL, NSNotification*)
  1640. {
  1641. if (NSViewComponentPeer* const owner = getOwner (self))
  1642. owner->liveResizingEnd();
  1643. }
  1644. };
  1645. NSView* NSViewComponentPeer::createViewInstance()
  1646. {
  1647. static JuceNSViewClass cls;
  1648. return cls.createInstance();
  1649. }
  1650. NSWindow* NSViewComponentPeer::createWindowInstance()
  1651. {
  1652. static JuceNSWindowClass cls;
  1653. return cls.createInstance();
  1654. }
  1655. //==============================================================================
  1656. ModifierKeys NSViewComponentPeer::currentModifiers;
  1657. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = nullptr;
  1658. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  1659. //==============================================================================
  1660. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  1661. {
  1662. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  1663. return true;
  1664. if (keyCode >= 'A' && keyCode <= 'Z'
  1665. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  1666. return true;
  1667. if (keyCode >= 'a' && keyCode <= 'z'
  1668. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  1669. return true;
  1670. return false;
  1671. }
  1672. ModifierKeys ModifierKeys::getCurrentModifiersRealtime() noexcept
  1673. {
  1674. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  1675. if ([NSEvent respondsToSelector: @selector (modifierFlags)])
  1676. NSViewComponentPeer::updateModifiers ((NSUInteger) [NSEvent modifierFlags]);
  1677. #endif
  1678. return NSViewComponentPeer::currentModifiers;
  1679. }
  1680. void ModifierKeys::updateCurrentModifiers() noexcept
  1681. {
  1682. currentModifiers = NSViewComponentPeer::currentModifiers;
  1683. }
  1684. //==============================================================================
  1685. bool MouseInputSource::SourceList::addSource()
  1686. {
  1687. if (sources.size() == 0)
  1688. {
  1689. addSource (0, true);
  1690. return true;
  1691. }
  1692. return false;
  1693. }
  1694. //==============================================================================
  1695. void Desktop::setKioskComponent (Component* kioskComp, bool shouldBeEnabled, bool allowMenusAndBars)
  1696. {
  1697. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  1698. NSViewComponentPeer* const peer = dynamic_cast<NSViewComponentPeer*> (kioskComp->getPeer());
  1699. jassert (peer != nullptr); // (this should have been checked by the caller)
  1700. #if defined (MAC_OS_X_VERSION_10_7) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
  1701. if (peer->hasNativeTitleBar()
  1702. && [peer->window respondsToSelector: @selector (toggleFullScreen:)])
  1703. {
  1704. if (shouldBeEnabled && ! allowMenusAndBars)
  1705. [NSApp setPresentationOptions: NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar];
  1706. [peer->window performSelector: @selector (toggleFullScreen:) withObject: nil];
  1707. }
  1708. else
  1709. #endif
  1710. {
  1711. if (shouldBeEnabled)
  1712. {
  1713. if (peer->hasNativeTitleBar())
  1714. [peer->window setStyleMask: NSWindowStyleMaskBorderless];
  1715. [NSApp setPresentationOptions: (allowMenusAndBars ? (NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)
  1716. : (NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar))];
  1717. kioskComp->setBounds (Desktop::getInstance().getDisplays().getMainDisplay().totalArea);
  1718. peer->becomeKeyWindow();
  1719. }
  1720. else
  1721. {
  1722. if (peer->hasNativeTitleBar())
  1723. {
  1724. [peer->window setStyleMask: (NSViewComponentPeer::getNSWindowStyleMask (peer->getStyleFlags()))];
  1725. peer->setTitle (peer->getComponent().getName()); // required to force the OS to update the title
  1726. }
  1727. [NSApp setPresentationOptions: NSApplicationPresentationDefault];
  1728. }
  1729. }
  1730. #elif JUCE_SUPPORT_CARBON
  1731. if (shouldBeEnabled)
  1732. {
  1733. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  1734. kioskComp->setBounds (Desktop::getInstance().getDisplays().getMainDisplay().totalArea);
  1735. }
  1736. else
  1737. {
  1738. SetSystemUIMode (kUIModeNormal, 0);
  1739. }
  1740. #else
  1741. ignoreUnused (kioskComp, shouldBeEnabled, allowMenusAndBars);
  1742. // If you're targeting OSes earlier than 10.6 and want to use this feature,
  1743. // you'll need to enable JUCE_SUPPORT_CARBON.
  1744. jassertfalse;
  1745. #endif
  1746. }
  1747. void Desktop::allowedOrientationsChanged() {}
  1748. //==============================================================================
  1749. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  1750. {
  1751. return new NSViewComponentPeer (*this, styleFlags, (NSView*) windowToAttachTo);
  1752. }
  1753. //==============================================================================
  1754. const int KeyPress::spaceKey = ' ';
  1755. const int KeyPress::returnKey = 0x0d;
  1756. const int KeyPress::escapeKey = 0x1b;
  1757. const int KeyPress::backspaceKey = 0x7f;
  1758. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  1759. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  1760. const int KeyPress::upKey = NSUpArrowFunctionKey;
  1761. const int KeyPress::downKey = NSDownArrowFunctionKey;
  1762. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  1763. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  1764. const int KeyPress::endKey = NSEndFunctionKey;
  1765. const int KeyPress::homeKey = NSHomeFunctionKey;
  1766. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  1767. const int KeyPress::insertKey = -1;
  1768. const int KeyPress::tabKey = 9;
  1769. const int KeyPress::F1Key = NSF1FunctionKey;
  1770. const int KeyPress::F2Key = NSF2FunctionKey;
  1771. const int KeyPress::F3Key = NSF3FunctionKey;
  1772. const int KeyPress::F4Key = NSF4FunctionKey;
  1773. const int KeyPress::F5Key = NSF5FunctionKey;
  1774. const int KeyPress::F6Key = NSF6FunctionKey;
  1775. const int KeyPress::F7Key = NSF7FunctionKey;
  1776. const int KeyPress::F8Key = NSF8FunctionKey;
  1777. const int KeyPress::F9Key = NSF9FunctionKey;
  1778. const int KeyPress::F10Key = NSF10FunctionKey;
  1779. const int KeyPress::F11Key = NSF11FunctionKey;
  1780. const int KeyPress::F12Key = NSF12FunctionKey;
  1781. const int KeyPress::F13Key = NSF13FunctionKey;
  1782. const int KeyPress::F14Key = NSF14FunctionKey;
  1783. const int KeyPress::F15Key = NSF15FunctionKey;
  1784. const int KeyPress::F16Key = NSF16FunctionKey;
  1785. const int KeyPress::numberPad0 = 0x30020;
  1786. const int KeyPress::numberPad1 = 0x30021;
  1787. const int KeyPress::numberPad2 = 0x30022;
  1788. const int KeyPress::numberPad3 = 0x30023;
  1789. const int KeyPress::numberPad4 = 0x30024;
  1790. const int KeyPress::numberPad5 = 0x30025;
  1791. const int KeyPress::numberPad6 = 0x30026;
  1792. const int KeyPress::numberPad7 = 0x30027;
  1793. const int KeyPress::numberPad8 = 0x30028;
  1794. const int KeyPress::numberPad9 = 0x30029;
  1795. const int KeyPress::numberPadAdd = 0x3002a;
  1796. const int KeyPress::numberPadSubtract = 0x3002b;
  1797. const int KeyPress::numberPadMultiply = 0x3002c;
  1798. const int KeyPress::numberPadDivide = 0x3002d;
  1799. const int KeyPress::numberPadSeparator = 0x3002e;
  1800. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  1801. const int KeyPress::numberPadEquals = 0x30030;
  1802. const int KeyPress::numberPadDelete = 0x30031;
  1803. const int KeyPress::playKey = 0x30000;
  1804. const int KeyPress::stopKey = 0x30001;
  1805. const int KeyPress::fastForwardKey = 0x30002;
  1806. const int KeyPress::rewindKey = 0x30003;