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.

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