Audio plugin host https://kx.studio/carla
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.

2202 lines
83KB

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