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.

2172 lines
81KB

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