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.

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