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.

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