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.

2282 lines
86KB

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