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.

2239 lines
84KB

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