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.

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