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.

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