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.

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