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.

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