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.

2244 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] CGContext];
  658. if (! component.isOpaque())
  659. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  660. float displayScale = 1.0f;
  661. NSScreen* screen = [[view window] screen];
  662. if ([screen respondsToSelector: @selector (backingScaleFactor)])
  663. displayScale = (float) screen.backingScaleFactor;
  664. #if USE_COREGRAPHICS_RENDERING && JUCE_COREGRAPHICS_RENDER_WITH_MULTIPLE_PAINT_CALLS
  665. // This option invokes a separate paint call for each rectangle of the clip region.
  666. // It's a long story, but this is a basically a workaround for a CGContext not having
  667. // a way of finding whether a rectangle falls within its clip region
  668. if (usingCoreGraphics)
  669. {
  670. const NSRect* rects = nullptr;
  671. NSInteger numRects = 0;
  672. [view getRectsBeingDrawn: &rects count: &numRects];
  673. if (numRects > 1)
  674. {
  675. for (int i = 0; i < numRects; ++i)
  676. {
  677. NSRect rect = rects[i];
  678. CGContextSaveGState (cg);
  679. CGContextClipToRect (cg, CGRectMake (rect.origin.x, rect.origin.y, rect.size.width, rect.size.height));
  680. drawRect (cg, rect, displayScale);
  681. CGContextRestoreGState (cg);
  682. }
  683. return;
  684. }
  685. }
  686. #endif
  687. drawRect (cg, r, displayScale);
  688. }
  689. void drawRect (CGContextRef cg, NSRect r, float displayScale)
  690. {
  691. #if USE_COREGRAPHICS_RENDERING
  692. if (usingCoreGraphics)
  693. {
  694. CoreGraphicsContext context (cg, (float) [view frame].size.height, displayScale);
  695. invokePaint (context);
  696. }
  697. else
  698. #endif
  699. {
  700. const Point<int> offset (-roundToInt (r.origin.x),
  701. -roundToInt ([view frame].size.height - (r.origin.y + r.size.height)));
  702. auto clipW = (int) (r.size.width + 0.5f);
  703. auto clipH = (int) (r.size.height + 0.5f);
  704. RectangleList<int> clip;
  705. getClipRects (clip, offset, clipW, clipH);
  706. if (! clip.isEmpty())
  707. {
  708. Image temp (component.isOpaque() ? Image::RGB : Image::ARGB,
  709. roundToInt (clipW * displayScale),
  710. roundToInt (clipH * displayScale),
  711. ! component.isOpaque());
  712. {
  713. auto intScale = roundToInt (displayScale);
  714. if (intScale != 1)
  715. clip.scaleAll (intScale);
  716. auto context = component.getLookAndFeel()
  717. .createGraphicsContext (temp, offset * intScale, clip);
  718. if (intScale != 1)
  719. context->addTransform (AffineTransform::scale (displayScale));
  720. invokePaint (*context);
  721. }
  722. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  723. CGImageRef image = juce_createCoreGraphicsImage (temp, colourSpace, false);
  724. CGColorSpaceRelease (colourSpace);
  725. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, clipW, clipH), image);
  726. CGImageRelease (image);
  727. }
  728. }
  729. }
  730. void repaint (const Rectangle<int>& area) override
  731. {
  732. // In 10.11 changes were made to the way the OS handles repaint regions, and it seems that it can
  733. // no longer be trusted to coalesce all the regions, or to even remember them all without losing
  734. // a few when there's a lot of activity.
  735. // As a work around for this, we use a RectangleList to do our own coalescing of regions before
  736. // asynchronously asking the OS to repaint them.
  737. deferredRepaints.add ((float) area.getX(), (float) ([view frame].size.height - area.getBottom()),
  738. (float) area.getWidth(), (float) area.getHeight());
  739. if (isTimerRunning())
  740. return;
  741. auto now = Time::getMillisecondCounter();
  742. auto msSinceLastRepaint = (lastRepaintTime >= now) ? now - lastRepaintTime
  743. : (std::numeric_limits<uint32>::max() - lastRepaintTime) + now;
  744. static uint32 minimumRepaintInterval = 1000 / 30; // 30fps
  745. // When windows are being resized, artificially throttling high-frequency repaints helps
  746. // to stop the event queue getting clogged, and keeps everything working smoothly.
  747. // For some reason Logic also needs this throttling to recored parameter events correctly.
  748. if (msSinceLastRepaint < minimumRepaintInterval && shouldThrottleRepaint())
  749. {
  750. startTimer (static_cast<int> (minimumRepaintInterval - msSinceLastRepaint));
  751. return;
  752. }
  753. setNeedsDisplayRectangles();
  754. }
  755. static bool shouldThrottleRepaint()
  756. {
  757. return areAnyWindowsInLiveResize() || ! JUCEApplication::isStandaloneApp();
  758. }
  759. void timerCallback() override
  760. {
  761. setNeedsDisplayRectangles();
  762. stopTimer();
  763. }
  764. void setNeedsDisplayRectangles()
  765. {
  766. for (auto& i : deferredRepaints)
  767. [view setNeedsDisplayInRect: makeNSRect (i)];
  768. lastRepaintTime = Time::getMillisecondCounter();
  769. deferredRepaints.clear();
  770. }
  771. void invokePaint (LowLevelGraphicsContext& context)
  772. {
  773. handlePaint (context);
  774. }
  775. void performAnyPendingRepaintsNow() override
  776. {
  777. [view displayIfNeeded];
  778. }
  779. static bool areAnyWindowsInLiveResize() noexcept
  780. {
  781. for (NSWindow* w in [NSApp windows])
  782. if ([w inLiveResize])
  783. return true;
  784. return false;
  785. }
  786. //==============================================================================
  787. bool sendModalInputAttemptIfBlocked()
  788. {
  789. if (auto* modal = Component::getCurrentlyModalComponent())
  790. {
  791. if (insideToFrontCall == 0
  792. && (! getComponent().isParentOf (modal))
  793. && getComponent().isCurrentlyBlockedByAnotherModalComponent())
  794. {
  795. modal->inputAttemptWhenModal();
  796. return true;
  797. }
  798. }
  799. return false;
  800. }
  801. bool canBecomeKeyWindow()
  802. {
  803. return (getStyleFlags() & juce::ComponentPeer::windowIgnoresKeyPresses) == 0;
  804. }
  805. bool canBecomeMainWindow()
  806. {
  807. return dynamic_cast<ResizableWindow*> (&component) != nullptr;
  808. }
  809. bool worksWhenModal() const
  810. {
  811. // In plugins, the host could put our plugin window inside a modal window, so this
  812. // allows us to successfully open other popups. Feels like there could be edge-case
  813. // problems caused by this, so let us know if you spot any issues..
  814. return ! JUCEApplication::isStandaloneApp();
  815. }
  816. void becomeKeyWindow()
  817. {
  818. handleBroughtToFront();
  819. grabFocus();
  820. }
  821. bool windowShouldClose()
  822. {
  823. if (! isValidPeer (this))
  824. return YES;
  825. handleUserClosingWindow();
  826. return NO;
  827. }
  828. void redirectMovedOrResized()
  829. {
  830. updateFullscreenStatus();
  831. handleMovedOrResized();
  832. }
  833. void viewMovedToWindow()
  834. {
  835. if (isSharedWindow)
  836. {
  837. auto newWindow = [view window];
  838. bool shouldSetVisible = (window == nullptr && newWindow != nullptr);
  839. window = newWindow;
  840. if (shouldSetVisible)
  841. getComponent().setVisible (true);
  842. }
  843. }
  844. void liveResizingStart()
  845. {
  846. if (constrainer != nullptr)
  847. {
  848. constrainer->resizeStart();
  849. isFirstLiveResize = true;
  850. }
  851. }
  852. void liveResizingEnd()
  853. {
  854. if (constrainer != nullptr)
  855. constrainer->resizeEnd();
  856. }
  857. NSRect constrainRect (NSRect r)
  858. {
  859. if (constrainer != nullptr && ! isKioskMode())
  860. {
  861. auto scale = getComponent().getDesktopScaleFactor();
  862. auto pos = ScalingHelpers::unscaledScreenPosToScaled (scale, convertToRectInt (flippedScreenRect (r)));
  863. auto original = ScalingHelpers::unscaledScreenPosToScaled (scale, convertToRectInt (flippedScreenRect ([window frame])));
  864. auto screenBounds = Desktop::getInstance().getDisplays().getTotalBounds (true);
  865. const bool inLiveResize = [window inLiveResize];
  866. if (! inLiveResize || isFirstLiveResize)
  867. {
  868. isFirstLiveResize = false;
  869. isStretchingTop = (pos.getY() != original.getY() && pos.getBottom() == original.getBottom());
  870. isStretchingLeft = (pos.getX() != original.getX() && pos.getRight() == original.getRight());
  871. isStretchingBottom = (pos.getY() == original.getY() && pos.getBottom() != original.getBottom());
  872. isStretchingRight = (pos.getX() == original.getX() && pos.getRight() != original.getRight());
  873. }
  874. constrainer->checkBounds (pos, original, screenBounds,
  875. isStretchingTop, isStretchingLeft, isStretchingBottom, isStretchingRight);
  876. pos = ScalingHelpers::scaledScreenPosToUnscaled (scale, pos);
  877. r = flippedScreenRect (makeNSRect (pos));
  878. }
  879. return r;
  880. }
  881. static void showArrowCursorIfNeeded()
  882. {
  883. auto& desktop = Desktop::getInstance();
  884. auto mouse = desktop.getMainMouseSource();
  885. if (mouse.getComponentUnderMouse() == nullptr
  886. && desktop.findComponentAt (mouse.getScreenPosition().roundToInt()) == nullptr)
  887. {
  888. [[NSCursor arrowCursor] set];
  889. }
  890. }
  891. static void updateModifiers (NSEvent* e)
  892. {
  893. updateModifiers ([e modifierFlags]);
  894. }
  895. static void updateModifiers (const NSUInteger flags)
  896. {
  897. int m = 0;
  898. if ((flags & NSEventModifierFlagShift) != 0) m |= ModifierKeys::shiftModifier;
  899. if ((flags & NSEventModifierFlagControl) != 0) m |= ModifierKeys::ctrlModifier;
  900. if ((flags & NSEventModifierFlagOption) != 0) m |= ModifierKeys::altModifier;
  901. if ((flags & NSEventModifierFlagCommand) != 0) m |= ModifierKeys::commandModifier;
  902. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withOnlyMouseButtons().withFlags (m);
  903. }
  904. static void updateKeysDown (NSEvent* ev, bool isKeyDown)
  905. {
  906. updateModifiers (ev);
  907. if (auto keyCode = getKeyCodeFromEvent (ev))
  908. {
  909. if (isKeyDown)
  910. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  911. else
  912. keysCurrentlyDown.removeFirstMatchingValue (keyCode);
  913. }
  914. }
  915. static int getKeyCodeFromEvent (NSEvent* ev)
  916. {
  917. // Unfortunately, charactersIgnoringModifiers does not ignore the shift key.
  918. // Using [ev keyCode] is not a solution either as this will,
  919. // for example, return VK_KEY_Y if the key is pressed which
  920. // is typically located at the Y key position on a QWERTY
  921. // keyboard. However, on international keyboards this might not
  922. // be the key labeled Y (for example, on German keyboards this key
  923. // has a Z label). Therefore, we need to query the current keyboard
  924. // layout to figure out what character the key would have produced
  925. // if the shift key was not pressed
  926. String unmodified;
  927. #if JUCE_SUPPORT_CARBON
  928. if (TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource())
  929. {
  930. if (auto layoutData = (CFDataRef) TISGetInputSourceProperty (currentKeyboard,
  931. kTISPropertyUnicodeKeyLayoutData))
  932. {
  933. if (auto* layoutPtr = (const UCKeyboardLayout*) CFDataGetBytePtr (layoutData))
  934. {
  935. UInt32 keysDown = 0;
  936. UniChar buffer[4];
  937. UniCharCount actual;
  938. if (UCKeyTranslate (layoutPtr, [ev keyCode], kUCKeyActionDown, 0, LMGetKbdType(),
  939. kUCKeyTranslateNoDeadKeysBit, &keysDown, sizeof (buffer) / sizeof (UniChar),
  940. &actual, buffer) == 0)
  941. unmodified = String (CharPointer_UTF16 (reinterpret_cast<CharPointer_UTF16::CharType*> (buffer)), 4);
  942. }
  943. }
  944. CFRelease (currentKeyboard);
  945. }
  946. // did the above layout conversion fail
  947. if (unmodified.isEmpty())
  948. #endif
  949. {
  950. unmodified = nsStringToJuce ([ev charactersIgnoringModifiers]);
  951. }
  952. auto keyCode = (int) unmodified[0];
  953. if (keyCode == 0x19) // (backwards-tab)
  954. keyCode = '\t';
  955. else if (keyCode == 0x03) // (enter)
  956. keyCode = '\r';
  957. else
  958. keyCode = (int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  959. if (([ev modifierFlags] & NSEventModifierFlagNumericPad) != 0)
  960. {
  961. const int numPadConversions[] = { '0', KeyPress::numberPad0, '1', KeyPress::numberPad1,
  962. '2', KeyPress::numberPad2, '3', KeyPress::numberPad3,
  963. '4', KeyPress::numberPad4, '5', KeyPress::numberPad5,
  964. '6', KeyPress::numberPad6, '7', KeyPress::numberPad7,
  965. '8', KeyPress::numberPad8, '9', KeyPress::numberPad9,
  966. '+', KeyPress::numberPadAdd, '-', KeyPress::numberPadSubtract,
  967. '*', KeyPress::numberPadMultiply, '/', KeyPress::numberPadDivide,
  968. '.', KeyPress::numberPadDecimalPoint,
  969. ',', KeyPress::numberPadDecimalPoint, // (to deal with non-english kbds)
  970. '=', KeyPress::numberPadEquals };
  971. for (int i = 0; i < numElementsInArray (numPadConversions); i += 2)
  972. if (keyCode == numPadConversions [i])
  973. keyCode = numPadConversions [i + 1];
  974. }
  975. return keyCode;
  976. }
  977. static int64 getMouseTime (NSEvent* e) noexcept
  978. {
  979. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  980. + (int64) ([e timestamp] * 1000.0);
  981. }
  982. static float getMousePressure (NSEvent* e) noexcept
  983. {
  984. @try
  985. {
  986. if (e.type != NSEventTypeMouseEntered && e.type != NSEventTypeMouseExited)
  987. return (float) e.pressure;
  988. }
  989. @catch (NSException* e) {}
  990. @finally {}
  991. return 0.0f;
  992. }
  993. static Point<float> getMousePos (NSEvent* e, NSView* view)
  994. {
  995. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  996. return { (float) p.x, (float) ([view frame].size.height - p.y) };
  997. }
  998. static int getModifierForButtonNumber (const NSInteger num)
  999. {
  1000. return num == 0 ? ModifierKeys::leftButtonModifier
  1001. : (num == 1 ? ModifierKeys::rightButtonModifier
  1002. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  1003. }
  1004. static unsigned int getNSWindowStyleMask (const int flags) noexcept
  1005. {
  1006. unsigned int style = (flags & windowHasTitleBar) != 0 ? NSWindowStyleMaskTitled
  1007. : NSWindowStyleMaskBorderless;
  1008. if ((flags & windowHasMinimiseButton) != 0) style |= NSWindowStyleMaskMiniaturizable;
  1009. if ((flags & windowHasCloseButton) != 0) style |= NSWindowStyleMaskClosable;
  1010. if ((flags & windowIsResizable) != 0) style |= NSWindowStyleMaskResizable;
  1011. return style;
  1012. }
  1013. static NSArray* getSupportedDragTypes()
  1014. {
  1015. return [NSArray arrayWithObjects: (NSString*) kUTTypeFileURL, (NSString*) kPasteboardTypeFileURLPromise, NSPasteboardTypeString, nil];
  1016. }
  1017. BOOL sendDragCallback (const int type, id <NSDraggingInfo> sender)
  1018. {
  1019. NSPasteboard* pasteboard = [sender draggingPasteboard];
  1020. NSString* contentType = [pasteboard availableTypeFromArray: getSupportedDragTypes()];
  1021. if (contentType == nil)
  1022. return false;
  1023. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  1024. ComponentPeer::DragInfo dragInfo;
  1025. dragInfo.position.setXY ((int) p.x, (int) ([view frame].size.height - p.y));
  1026. if (contentType == NSPasteboardTypeString)
  1027. dragInfo.text = nsStringToJuce ([pasteboard stringForType: NSPasteboardTypeString]);
  1028. else
  1029. dragInfo.files = getDroppedFiles (pasteboard, contentType);
  1030. if (! dragInfo.isEmpty())
  1031. {
  1032. switch (type)
  1033. {
  1034. case 0: return handleDragMove (dragInfo);
  1035. case 1: return handleDragExit (dragInfo);
  1036. case 2: return handleDragDrop (dragInfo);
  1037. default: jassertfalse; break;
  1038. }
  1039. }
  1040. return false;
  1041. }
  1042. StringArray getDroppedFiles (NSPasteboard* pasteboard, NSString* contentType)
  1043. {
  1044. StringArray files;
  1045. NSString* iTunesPasteboardType = nsStringLiteral ("CorePasteboardFlavorType 0x6974756E"); // 'itun'
  1046. if ([contentType isEqualToString: (NSString*) kPasteboardTypeFileURLPromise]
  1047. && [[pasteboard types] containsObject: iTunesPasteboardType])
  1048. {
  1049. id list = [pasteboard propertyListForType: iTunesPasteboardType];
  1050. if ([list isKindOfClass: [NSDictionary class]])
  1051. {
  1052. NSDictionary* iTunesDictionary = (NSDictionary*) list;
  1053. NSArray* tracks = [iTunesDictionary valueForKey: nsStringLiteral ("Tracks")];
  1054. NSEnumerator* enumerator = [tracks objectEnumerator];
  1055. NSDictionary* track;
  1056. while ((track = [enumerator nextObject]) != nil)
  1057. {
  1058. if (id value = [track valueForKey: nsStringLiteral ("Location")])
  1059. {
  1060. NSURL* url = [NSURL URLWithString: value];
  1061. if ([url isFileURL])
  1062. files.add (nsStringToJuce ([url path]));
  1063. }
  1064. }
  1065. }
  1066. }
  1067. else
  1068. {
  1069. NSArray* items = [pasteboard readObjectsForClasses:@[[NSURL class]] options: nil];
  1070. for (unsigned int i = 0; i < [items count]; ++i)
  1071. {
  1072. NSURL* url = [items objectAtIndex: i];
  1073. if ([url isFileURL])
  1074. files.add (nsStringToJuce ([url path]));
  1075. }
  1076. }
  1077. return files;
  1078. }
  1079. //==============================================================================
  1080. void viewFocusGain()
  1081. {
  1082. if (currentlyFocusedPeer != this)
  1083. {
  1084. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  1085. currentlyFocusedPeer->handleFocusLoss();
  1086. currentlyFocusedPeer = this;
  1087. handleFocusGain();
  1088. }
  1089. }
  1090. void viewFocusLoss()
  1091. {
  1092. if (currentlyFocusedPeer == this)
  1093. {
  1094. currentlyFocusedPeer = nullptr;
  1095. handleFocusLoss();
  1096. }
  1097. }
  1098. bool isFocused() const override
  1099. {
  1100. return (isSharedWindow || ! JUCEApplication::isStandaloneApp())
  1101. ? this == currentlyFocusedPeer
  1102. : [window isKeyWindow];
  1103. }
  1104. void grabFocus() override
  1105. {
  1106. if (window != nil)
  1107. {
  1108. [window makeKeyWindow];
  1109. [window makeFirstResponder: view];
  1110. viewFocusGain();
  1111. }
  1112. }
  1113. void textInputRequired (Point<int>, TextInputTarget&) override {}
  1114. void resetWindowPresentation()
  1115. {
  1116. if (hasNativeTitleBar())
  1117. {
  1118. [window setStyleMask: (NSViewComponentPeer::getNSWindowStyleMask (getStyleFlags()))];
  1119. setTitle (getComponent().getName()); // required to force the OS to update the title
  1120. }
  1121. [NSApp setPresentationOptions: NSApplicationPresentationDefault];
  1122. }
  1123. //==============================================================================
  1124. NSWindow* window = nil;
  1125. NSView* view = nil;
  1126. WeakReference<Component> safeComponent;
  1127. bool isSharedWindow = false, fullScreen = false;
  1128. bool isWindowInKioskMode = false;
  1129. #if USE_COREGRAPHICS_RENDERING
  1130. bool usingCoreGraphics = true;
  1131. #else
  1132. bool usingCoreGraphics = false;
  1133. #endif
  1134. bool isZooming = false, isFirstLiveResize = false, textWasInserted = false;
  1135. bool isStretchingTop = false, isStretchingLeft = false, isStretchingBottom = false, isStretchingRight = false;
  1136. bool windowRepresentsFile = false;
  1137. bool isAlwaysOnTop = false, wasAlwaysOnTop = false;
  1138. String stringBeingComposed;
  1139. NSNotificationCenter* notificationCenter = nil;
  1140. RectangleList<float> deferredRepaints;
  1141. uint32 lastRepaintTime;
  1142. static ComponentPeer* currentlyFocusedPeer;
  1143. static Array<int> keysCurrentlyDown;
  1144. static int insideToFrontCall;
  1145. private:
  1146. static NSView* createViewInstance();
  1147. static NSWindow* createWindowInstance();
  1148. static void setOwner (id viewOrWindow, NSViewComponentPeer* newOwner)
  1149. {
  1150. object_setInstanceVariable (viewOrWindow, "owner", newOwner);
  1151. }
  1152. void getClipRects (RectangleList<int>& clip, Point<int> offset, int clipW, int clipH)
  1153. {
  1154. const NSRect* rects = nullptr;
  1155. NSInteger numRects = 0;
  1156. [view getRectsBeingDrawn: &rects count: &numRects];
  1157. const Rectangle<int> clipBounds (clipW, clipH);
  1158. auto viewH = [view frame].size.height;
  1159. clip.ensureStorageAllocated ((int) numRects);
  1160. for (int i = 0; i < numRects; ++i)
  1161. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + offset.x,
  1162. roundToInt (viewH - (rects[i].origin.y + rects[i].size.height)) + offset.y,
  1163. roundToInt (rects[i].size.width),
  1164. roundToInt (rects[i].size.height))));
  1165. }
  1166. static void appFocusChanged()
  1167. {
  1168. keysCurrentlyDown.clear();
  1169. if (isValidPeer (currentlyFocusedPeer))
  1170. {
  1171. if (Process::isForegroundProcess())
  1172. {
  1173. currentlyFocusedPeer->handleFocusGain();
  1174. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  1175. }
  1176. else
  1177. {
  1178. currentlyFocusedPeer->handleFocusLoss();
  1179. }
  1180. }
  1181. }
  1182. static bool checkEventBlockedByModalComps (NSEvent* e)
  1183. {
  1184. if (Component::getNumCurrentlyModalComponents() == 0)
  1185. return false;
  1186. NSWindow* const w = [e window];
  1187. if (w == nil || [w worksWhenModal])
  1188. return false;
  1189. bool isKey = false, isInputAttempt = false;
  1190. switch ([e type])
  1191. {
  1192. case NSEventTypeKeyDown:
  1193. case NSEventTypeKeyUp:
  1194. isKey = isInputAttempt = true;
  1195. break;
  1196. case NSEventTypeLeftMouseDown:
  1197. case NSEventTypeRightMouseDown:
  1198. case NSEventTypeOtherMouseDown:
  1199. isInputAttempt = true;
  1200. break;
  1201. case NSEventTypeLeftMouseDragged:
  1202. case NSEventTypeRightMouseDragged:
  1203. case NSEventTypeLeftMouseUp:
  1204. case NSEventTypeRightMouseUp:
  1205. case NSEventTypeOtherMouseUp:
  1206. case NSEventTypeOtherMouseDragged:
  1207. if (Desktop::getInstance().getDraggingMouseSource(0) != nullptr)
  1208. return false;
  1209. break;
  1210. case NSEventTypeMouseMoved:
  1211. case NSEventTypeMouseEntered:
  1212. case NSEventTypeMouseExited:
  1213. case NSEventTypeCursorUpdate:
  1214. case NSEventTypeScrollWheel:
  1215. case NSEventTypeTabletPoint:
  1216. case NSEventTypeTabletProximity:
  1217. break;
  1218. default:
  1219. return false;
  1220. }
  1221. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  1222. {
  1223. if (auto* peer = dynamic_cast<NSViewComponentPeer*> (ComponentPeer::getPeer (i)))
  1224. {
  1225. if ([peer->view window] == w)
  1226. {
  1227. if (isKey)
  1228. {
  1229. if (peer->view == [w firstResponder])
  1230. return false;
  1231. }
  1232. else
  1233. {
  1234. if (peer->isSharedWindow
  1235. ? NSPointInRect ([peer->view convertPoint: [e locationInWindow] fromView: nil], [peer->view bounds])
  1236. : NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height)))
  1237. return false;
  1238. }
  1239. }
  1240. }
  1241. }
  1242. if (isInputAttempt)
  1243. {
  1244. if (! [NSApp isActive])
  1245. [NSApp activateIgnoringOtherApps: YES];
  1246. if (auto* modal = Component::getCurrentlyModalComponent())
  1247. modal->inputAttemptWhenModal();
  1248. }
  1249. return true;
  1250. }
  1251. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentPeer)
  1252. };
  1253. int NSViewComponentPeer::insideToFrontCall = 0;
  1254. //==============================================================================
  1255. struct JuceNSViewClass : public ObjCClass<NSView>
  1256. {
  1257. JuceNSViewClass() : ObjCClass<NSView> ("JUCEView_")
  1258. {
  1259. addIvar<NSViewComponentPeer*> ("owner");
  1260. addMethod (@selector (isOpaque), isOpaque, "c@:");
  1261. addMethod (@selector (drawRect:), drawRect, "v@:", @encode (NSRect));
  1262. addMethod (@selector (mouseDown:), mouseDown, "v@:@");
  1263. addMethod (@selector (asyncMouseDown:), asyncMouseDown, "v@:@");
  1264. addMethod (@selector (mouseUp:), mouseUp, "v@:@");
  1265. addMethod (@selector (asyncMouseUp:), asyncMouseUp, "v@:@");
  1266. addMethod (@selector (mouseDragged:), mouseDragged, "v@:@");
  1267. addMethod (@selector (mouseMoved:), mouseMoved, "v@:@");
  1268. addMethod (@selector (mouseEntered:), mouseEntered, "v@:@");
  1269. addMethod (@selector (mouseExited:), mouseExited, "v@:@");
  1270. addMethod (@selector (rightMouseDown:), mouseDown, "v@:@");
  1271. addMethod (@selector (rightMouseDragged:), mouseDragged, "v@:@");
  1272. addMethod (@selector (rightMouseUp:), mouseUp, "v@:@");
  1273. addMethod (@selector (otherMouseDown:), mouseDown, "v@:@");
  1274. addMethod (@selector (otherMouseDragged:), mouseDragged, "v@:@");
  1275. addMethod (@selector (otherMouseUp:), mouseUp, "v@:@");
  1276. addMethod (@selector (scrollWheel:), scrollWheel, "v@:@");
  1277. addMethod (@selector (magnifyWithEvent:), magnify, "v@:@");
  1278. addMethod (@selector (acceptsFirstMouse:), acceptsFirstMouse, "c@:@");
  1279. addMethod (@selector (frameChanged:), frameChanged, "v@:@");
  1280. addMethod (@selector (windowWillMiniaturize:), windowWillMiniaturize, "v@:@");
  1281. addMethod (@selector (windowDidDeminiaturize:), windowDidDeminiaturize, "v@:@");
  1282. addMethod (@selector (wantsDefaultClipping:), wantsDefaultClipping, "c@:");
  1283. addMethod (@selector (worksWhenModal), worksWhenModal, "c@:");
  1284. addMethod (@selector (viewDidMoveToWindow), viewDidMoveToWindow, "v@:");
  1285. addMethod (@selector (keyDown:), keyDown, "v@:@");
  1286. addMethod (@selector (keyUp:), keyUp, "v@:@");
  1287. addMethod (@selector (insertText:), insertText, "v@:@");
  1288. addMethod (@selector (doCommandBySelector:), doCommandBySelector, "v@::");
  1289. addMethod (@selector (setMarkedText:selectedRange:), setMarkedText, "v@:@", @encode (NSRange));
  1290. addMethod (@selector (unmarkText), unmarkText, "v@:");
  1291. addMethod (@selector (hasMarkedText), hasMarkedText, "c@:");
  1292. addMethod (@selector (conversationIdentifier), conversationIdentifier, "l@:");
  1293. addMethod (@selector (attributedSubstringFromRange:), attributedSubstringFromRange, "@@:", @encode (NSRange));
  1294. addMethod (@selector (markedRange), markedRange, @encode (NSRange), "@:");
  1295. addMethod (@selector (selectedRange), selectedRange, @encode (NSRange), "@:");
  1296. addMethod (@selector (firstRectForCharacterRange:), firstRectForCharacterRange, @encode (NSRect), "@:", @encode (NSRange));
  1297. addMethod (@selector (characterIndexForPoint:), characterIndexForPoint, "L@:", @encode (NSPoint));
  1298. addMethod (@selector (validAttributesForMarkedText), validAttributesForMarkedText, "@@:");
  1299. addMethod (@selector (flagsChanged:), flagsChanged, "v@:@");
  1300. addMethod (@selector (becomeFirstResponder), becomeFirstResponder, "c@:");
  1301. addMethod (@selector (resignFirstResponder), resignFirstResponder, "c@:");
  1302. addMethod (@selector (acceptsFirstResponder), acceptsFirstResponder, "c@:");
  1303. addMethod (@selector (draggingEntered:), draggingEntered, @encode (NSDragOperation), "@:@");
  1304. addMethod (@selector (draggingUpdated:), draggingUpdated, @encode (NSDragOperation), "@:@");
  1305. addMethod (@selector (draggingEnded:), draggingEnded, "v@:@");
  1306. addMethod (@selector (draggingExited:), draggingExited, "v@:@");
  1307. addMethod (@selector (prepareForDragOperation:), prepareForDragOperation, "c@:@");
  1308. addMethod (@selector (performDragOperation:), performDragOperation, "c@:@");
  1309. addMethod (@selector (concludeDragOperation:), concludeDragOperation, "v@:@");
  1310. addMethod (@selector (paste:), paste, "v@:@");
  1311. addMethod (@selector (copy:), copy, "v@:@");
  1312. addMethod (@selector (cut:), cut, "v@:@");
  1313. addMethod (@selector (viewWillMoveToWindow:), willMoveToWindow, "v@:@");
  1314. addProtocol (@protocol (NSTextInput));
  1315. registerClass();
  1316. }
  1317. private:
  1318. static NSViewComponentPeer* getOwner (id self)
  1319. {
  1320. return getIvar<NSViewComponentPeer*> (self, "owner");
  1321. }
  1322. static void mouseDown (id self, SEL s, NSEvent* ev)
  1323. {
  1324. if (JUCEApplicationBase::isStandaloneApp())
  1325. asyncMouseDown (self, s, ev);
  1326. else
  1327. // In some host situations, the host will stop modal loops from working
  1328. // correctly if they're called from a mouse event, so we'll trigger
  1329. // the event asynchronously..
  1330. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  1331. withObject: ev
  1332. waitUntilDone: NO];
  1333. }
  1334. static void mouseUp (id self, SEL s, NSEvent* ev)
  1335. {
  1336. if (JUCEApplicationBase::isStandaloneApp())
  1337. asyncMouseUp (self, s, ev);
  1338. else
  1339. // In some host situations, the host will stop modal loops from working
  1340. // correctly if they're called from a mouse event, so we'll trigger
  1341. // the event asynchronously..
  1342. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  1343. withObject: ev
  1344. waitUntilDone: NO];
  1345. }
  1346. static void asyncMouseDown (id self, SEL, NSEvent* ev) { if (auto* p = getOwner (self)) p->redirectMouseDown (ev); }
  1347. static void asyncMouseUp (id self, SEL, NSEvent* ev) { if (auto* p = getOwner (self)) p->redirectMouseUp (ev); }
  1348. static void mouseDragged (id self, SEL, NSEvent* ev) { if (auto* p = getOwner (self)) p->redirectMouseDrag (ev); }
  1349. static void mouseMoved (id self, SEL, NSEvent* ev) { if (auto* p = getOwner (self)) p->redirectMouseMove (ev); }
  1350. static void mouseEntered (id self, SEL, NSEvent* ev) { if (auto* p = getOwner (self)) p->redirectMouseEnter (ev); }
  1351. static void mouseExited (id self, SEL, NSEvent* ev) { if (auto* p = getOwner (self)) p->redirectMouseExit (ev); }
  1352. static void scrollWheel (id self, SEL, NSEvent* ev) { if (auto* p = getOwner (self)) p->redirectMouseWheel (ev); }
  1353. static void magnify (id self, SEL, NSEvent* ev) { if (auto* p = getOwner (self)) p->redirectMagnify (ev); }
  1354. static void copy (id self, SEL, NSObject* s) { if (auto* p = getOwner (self)) p->redirectCopy (s); }
  1355. static void paste (id self, SEL, NSObject* s) { if (auto* p = getOwner (self)) p->redirectPaste (s); }
  1356. static void cut (id self, SEL, NSObject* s) { if (auto* p = getOwner (self)) p->redirectCut (s); }
  1357. static void willMoveToWindow (id self, SEL, NSWindow* w) { if (auto* p = getOwner (self)) p->redirectWillMoveToWindow (w); }
  1358. static BOOL acceptsFirstMouse (id, SEL, NSEvent*) { return YES; }
  1359. static BOOL wantsDefaultClipping (id, SEL) { return YES; } // (this is the default, but may want to customise it in future)
  1360. static BOOL worksWhenModal (id self, SEL) { if (auto* p = getOwner (self)) return p->worksWhenModal(); return NO; }
  1361. static void drawRect (id self, SEL, NSRect r) { if (auto* p = getOwner (self)) p->drawRect (r); }
  1362. static void frameChanged (id self, SEL, NSNotification*) { if (auto* p = getOwner (self)) p->redirectMovedOrResized(); }
  1363. static void viewDidMoveToWindow (id self, SEL) { if (auto* p = getOwner (self)) p->viewMovedToWindow(); }
  1364. static void windowWillMiniaturize (id self, SEL, NSNotification*)
  1365. {
  1366. if (auto* p = getOwner (self))
  1367. {
  1368. if (p->isAlwaysOnTop)
  1369. {
  1370. // there is a bug when restoring minimised always on top windows so we need
  1371. // to remove this behaviour before minimising and restore it afterwards
  1372. p->setAlwaysOnTop (false);
  1373. p->wasAlwaysOnTop = true;
  1374. }
  1375. }
  1376. }
  1377. static void windowDidDeminiaturize (id self, SEL, NSNotification*)
  1378. {
  1379. if (auto* p = getOwner (self))
  1380. {
  1381. if (p->wasAlwaysOnTop)
  1382. p->setAlwaysOnTop (true);
  1383. p->redirectMovedOrResized();
  1384. }
  1385. }
  1386. static BOOL isOpaque (id self, SEL)
  1387. {
  1388. auto* owner = getOwner (self);
  1389. return owner == nullptr || owner->getComponent().isOpaque();
  1390. }
  1391. //==============================================================================
  1392. static void keyDown (id self, SEL, NSEvent* ev)
  1393. {
  1394. if (auto* owner = getOwner (self))
  1395. {
  1396. auto* target = owner->findCurrentTextInputTarget();
  1397. owner->textWasInserted = false;
  1398. if (target != nullptr)
  1399. [(NSView*) self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  1400. else
  1401. owner->stringBeingComposed.clear();
  1402. if (! (owner->textWasInserted || owner->redirectKeyDown (ev)))
  1403. {
  1404. objc_super s = { self, [NSView class] };
  1405. getMsgSendSuperFn() (&s, @selector (keyDown:), ev);
  1406. }
  1407. }
  1408. }
  1409. static void keyUp (id self, SEL, NSEvent* ev)
  1410. {
  1411. auto* owner = getOwner (self);
  1412. if (owner == nullptr || ! owner->redirectKeyUp (ev))
  1413. {
  1414. objc_super s = { self, [NSView class] };
  1415. getMsgSendSuperFn() (&s, @selector (keyUp:), ev);
  1416. }
  1417. }
  1418. //==============================================================================
  1419. static void insertText (id self, SEL, id aString)
  1420. {
  1421. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  1422. if (auto* owner = getOwner (self))
  1423. {
  1424. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  1425. if ([newText length] > 0)
  1426. {
  1427. if (auto* target = owner->findCurrentTextInputTarget())
  1428. {
  1429. target->insertTextAtCaret (nsStringToJuce (newText));
  1430. owner->textWasInserted = true;
  1431. }
  1432. }
  1433. owner->stringBeingComposed.clear();
  1434. }
  1435. }
  1436. static void doCommandBySelector (id, SEL, SEL) {}
  1437. static void setMarkedText (id self, SEL, id aString, NSRange)
  1438. {
  1439. if (auto* owner = getOwner (self))
  1440. {
  1441. owner->stringBeingComposed = nsStringToJuce ([aString isKindOfClass: [NSAttributedString class]]
  1442. ? [aString string] : aString);
  1443. if (auto* target = owner->findCurrentTextInputTarget())
  1444. {
  1445. auto currentHighlight = target->getHighlightedRegion();
  1446. target->insertTextAtCaret (owner->stringBeingComposed);
  1447. target->setHighlightedRegion (currentHighlight.withLength (owner->stringBeingComposed.length()));
  1448. owner->textWasInserted = true;
  1449. }
  1450. }
  1451. }
  1452. static void unmarkText (id self, SEL)
  1453. {
  1454. if (auto* owner = getOwner (self))
  1455. {
  1456. if (owner->stringBeingComposed.isNotEmpty())
  1457. {
  1458. if (auto* target = owner->findCurrentTextInputTarget())
  1459. {
  1460. target->insertTextAtCaret (owner->stringBeingComposed);
  1461. owner->textWasInserted = true;
  1462. }
  1463. owner->stringBeingComposed.clear();
  1464. }
  1465. }
  1466. }
  1467. static BOOL hasMarkedText (id self, SEL)
  1468. {
  1469. auto* owner = getOwner (self);
  1470. return owner != nullptr && owner->stringBeingComposed.isNotEmpty();
  1471. }
  1472. static long conversationIdentifier (id self, SEL)
  1473. {
  1474. return (long) (pointer_sized_int) self;
  1475. }
  1476. static NSAttributedString* attributedSubstringFromRange (id self, SEL, NSRange theRange)
  1477. {
  1478. if (auto* owner = getOwner (self))
  1479. {
  1480. if (auto* target = owner->findCurrentTextInputTarget())
  1481. {
  1482. Range<int> r ((int) theRange.location,
  1483. (int) (theRange.location + theRange.length));
  1484. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  1485. }
  1486. }
  1487. return nil;
  1488. }
  1489. static NSRange markedRange (id self, SEL)
  1490. {
  1491. if (auto* owner = getOwner (self))
  1492. if (owner->stringBeingComposed.isNotEmpty())
  1493. return NSMakeRange (0, (NSUInteger) owner->stringBeingComposed.length());
  1494. return NSMakeRange (NSNotFound, 0);
  1495. }
  1496. static NSRange selectedRange (id self, SEL)
  1497. {
  1498. if (auto* owner = getOwner (self))
  1499. {
  1500. if (auto* target = owner->findCurrentTextInputTarget())
  1501. {
  1502. auto highlight = target->getHighlightedRegion();
  1503. if (! highlight.isEmpty())
  1504. return NSMakeRange ((NSUInteger) highlight.getStart(),
  1505. (NSUInteger) highlight.getLength());
  1506. }
  1507. }
  1508. return NSMakeRange (NSNotFound, 0);
  1509. }
  1510. static NSRect firstRectForCharacterRange (id self, SEL, NSRange)
  1511. {
  1512. if (auto* owner = getOwner (self))
  1513. if (auto* comp = dynamic_cast<Component*> (owner->findCurrentTextInputTarget()))
  1514. return flippedScreenRect (makeNSRect (comp->getScreenBounds()));
  1515. return NSZeroRect;
  1516. }
  1517. static NSUInteger characterIndexForPoint (id, SEL, NSPoint) { return NSNotFound; }
  1518. static NSArray* validAttributesForMarkedText (id, SEL) { return [NSArray array]; }
  1519. //==============================================================================
  1520. static void flagsChanged (id self, SEL, NSEvent* ev)
  1521. {
  1522. if (auto* owner = getOwner (self))
  1523. owner->redirectModKeyChange (ev);
  1524. }
  1525. static BOOL becomeFirstResponder (id self, SEL)
  1526. {
  1527. if (auto* owner = getOwner (self))
  1528. owner->viewFocusGain();
  1529. return YES;
  1530. }
  1531. static BOOL resignFirstResponder (id self, SEL)
  1532. {
  1533. if (auto* owner = getOwner (self))
  1534. owner->viewFocusLoss();
  1535. return YES;
  1536. }
  1537. static BOOL acceptsFirstResponder (id self, SEL)
  1538. {
  1539. auto* owner = getOwner (self);
  1540. return owner != nullptr && owner->canBecomeKeyWindow();
  1541. }
  1542. //==============================================================================
  1543. static NSDragOperation draggingEntered (id self, SEL s, id<NSDraggingInfo> sender)
  1544. {
  1545. return draggingUpdated (self, s, sender);
  1546. }
  1547. static NSDragOperation draggingUpdated (id self, SEL, id<NSDraggingInfo> sender)
  1548. {
  1549. if (auto* owner = getOwner (self))
  1550. if (owner->sendDragCallback (0, sender))
  1551. return NSDragOperationGeneric;
  1552. return NSDragOperationNone;
  1553. }
  1554. static void draggingEnded (id self, SEL s, id<NSDraggingInfo> sender)
  1555. {
  1556. draggingExited (self, s, sender);
  1557. }
  1558. static void draggingExited (id self, SEL, id<NSDraggingInfo> sender)
  1559. {
  1560. if (auto* owner = getOwner (self))
  1561. owner->sendDragCallback (1, sender);
  1562. }
  1563. static BOOL prepareForDragOperation (id, SEL, id<NSDraggingInfo>)
  1564. {
  1565. return YES;
  1566. }
  1567. static BOOL performDragOperation (id self, SEL, id<NSDraggingInfo> sender)
  1568. {
  1569. auto* owner = getOwner (self);
  1570. return owner != nullptr && owner->sendDragCallback (2, sender);
  1571. }
  1572. static void concludeDragOperation (id, SEL, id<NSDraggingInfo>) {}
  1573. };
  1574. //==============================================================================
  1575. struct JuceNSWindowClass : public ObjCClass<NSWindow>
  1576. {
  1577. JuceNSWindowClass() : ObjCClass<NSWindow> ("JUCEWindow_")
  1578. {
  1579. addIvar<NSViewComponentPeer*> ("owner");
  1580. addMethod (@selector (canBecomeKeyWindow), canBecomeKeyWindow, "c@:");
  1581. addMethod (@selector (canBecomeMainWindow), canBecomeMainWindow, "c@:");
  1582. addMethod (@selector (becomeKeyWindow), becomeKeyWindow, "v@:");
  1583. addMethod (@selector (windowShouldClose:), windowShouldClose, "c@:@");
  1584. addMethod (@selector (constrainFrameRect:toScreen:), constrainFrameRect, @encode (NSRect), "@:", @encode (NSRect), "@");
  1585. addMethod (@selector (windowWillResize:toSize:), windowWillResize, @encode (NSSize), "@:@", @encode (NSSize));
  1586. addMethod (@selector (windowDidExitFullScreen:), windowDidExitFullScreen, "v@:@");
  1587. addMethod (@selector (windowWillEnterFullScreen:), windowWillEnterFullScreen, "v@:@");
  1588. addMethod (@selector (zoom:), zoom, "v@:@");
  1589. addMethod (@selector (windowWillMove:), windowWillMove, "v@:@");
  1590. addMethod (@selector (windowWillStartLiveResize:), windowWillStartLiveResize, "v@:@");
  1591. addMethod (@selector (windowDidEndLiveResize:), windowDidEndLiveResize, "v@:@");
  1592. addMethod (@selector (window:shouldPopUpDocumentPathMenu:), shouldPopUpPathMenu, "B@:@", @encode (NSMenu*));
  1593. addMethod (@selector (window:shouldDragDocumentWithEvent:from:withPasteboard:),
  1594. shouldAllowIconDrag, "B@:@", @encode (NSEvent*), @encode (NSPoint), @encode (NSPasteboard*));
  1595. addProtocol (@protocol (NSWindowDelegate));
  1596. registerClass();
  1597. }
  1598. private:
  1599. static NSViewComponentPeer* getOwner (id self)
  1600. {
  1601. return getIvar<NSViewComponentPeer*> (self, "owner");
  1602. }
  1603. //==============================================================================
  1604. static BOOL canBecomeKeyWindow (id self, SEL)
  1605. {
  1606. auto* owner = getOwner (self);
  1607. return owner != nullptr
  1608. && owner->canBecomeKeyWindow()
  1609. && ! owner->sendModalInputAttemptIfBlocked();
  1610. }
  1611. static BOOL canBecomeMainWindow (id self, SEL)
  1612. {
  1613. auto* owner = getOwner (self);
  1614. return owner != nullptr
  1615. && owner->canBecomeMainWindow()
  1616. && ! owner->sendModalInputAttemptIfBlocked();
  1617. }
  1618. static void becomeKeyWindow (id self, SEL)
  1619. {
  1620. sendSuperclassMessage (self, @selector (becomeKeyWindow));
  1621. if (auto* owner = getOwner (self))
  1622. owner->becomeKeyWindow();
  1623. }
  1624. static BOOL windowShouldClose (id self, SEL, id /*window*/)
  1625. {
  1626. auto* owner = getOwner (self);
  1627. return owner == nullptr || owner->windowShouldClose();
  1628. }
  1629. static NSRect constrainFrameRect (id self, SEL, NSRect frameRect, NSScreen*)
  1630. {
  1631. if (auto* owner = getOwner (self))
  1632. frameRect = owner->constrainRect (frameRect);
  1633. return frameRect;
  1634. }
  1635. static NSSize windowWillResize (id self, SEL, NSWindow*, NSSize proposedFrameSize)
  1636. {
  1637. auto* owner = getOwner (self);
  1638. if (owner == nullptr || owner->isZooming)
  1639. return proposedFrameSize;
  1640. NSRect frameRect = [(NSWindow*) self frame];
  1641. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  1642. frameRect.size = proposedFrameSize;
  1643. frameRect = owner->constrainRect (frameRect);
  1644. if (owner->hasNativeTitleBar())
  1645. owner->sendModalInputAttemptIfBlocked();
  1646. return frameRect.size;
  1647. }
  1648. static void windowDidExitFullScreen (id self, SEL, NSNotification*)
  1649. {
  1650. if (auto* owner = getOwner (self))
  1651. owner->resetWindowPresentation();
  1652. }
  1653. static void windowWillEnterFullScreen (id self, SEL, NSNotification*)
  1654. {
  1655. if (SystemStats::getOperatingSystemType() <= SystemStats::MacOSX_10_9)
  1656. return;
  1657. if (auto* owner = getOwner (self))
  1658. if (owner->hasNativeTitleBar() && (owner->getStyleFlags() & ComponentPeer::windowIsResizable) == 0)
  1659. [owner->window setStyleMask: NSWindowStyleMaskBorderless];
  1660. }
  1661. static void zoom (id self, SEL, id sender)
  1662. {
  1663. if (auto* owner = getOwner (self))
  1664. {
  1665. owner->isZooming = true;
  1666. objc_super s = { self, [NSWindow class] };
  1667. getMsgSendSuperFn() (&s, @selector (zoom:), sender);
  1668. owner->isZooming = false;
  1669. owner->redirectMovedOrResized();
  1670. }
  1671. }
  1672. static void windowWillMove (id self, SEL, NSNotification*)
  1673. {
  1674. if (auto* owner = getOwner (self))
  1675. if (owner->hasNativeTitleBar())
  1676. owner->sendModalInputAttemptIfBlocked();
  1677. }
  1678. static void windowWillStartLiveResize (id self, SEL, NSNotification*)
  1679. {
  1680. if (auto* owner = getOwner (self))
  1681. owner->liveResizingStart();
  1682. }
  1683. static void windowDidEndLiveResize (id self, SEL, NSNotification*)
  1684. {
  1685. if (auto* owner = getOwner (self))
  1686. owner->liveResizingEnd();
  1687. }
  1688. static bool shouldPopUpPathMenu (id self, SEL, id /*window*/, NSMenu*)
  1689. {
  1690. if (auto* owner = getOwner (self))
  1691. return owner->windowRepresentsFile;
  1692. return false;
  1693. }
  1694. static bool shouldAllowIconDrag (id self, SEL, id /*window*/, NSEvent*, NSPoint, NSPasteboard*)
  1695. {
  1696. if (auto* owner = getOwner (self))
  1697. return owner->windowRepresentsFile;
  1698. return false;
  1699. }
  1700. };
  1701. NSView* NSViewComponentPeer::createViewInstance()
  1702. {
  1703. static JuceNSViewClass cls;
  1704. return cls.createInstance();
  1705. }
  1706. NSWindow* NSViewComponentPeer::createWindowInstance()
  1707. {
  1708. static JuceNSWindowClass cls;
  1709. return cls.createInstance();
  1710. }
  1711. //==============================================================================
  1712. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = nullptr;
  1713. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  1714. //==============================================================================
  1715. bool KeyPress::isKeyCurrentlyDown (int keyCode)
  1716. {
  1717. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  1718. return true;
  1719. if (keyCode >= 'A' && keyCode <= 'Z'
  1720. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  1721. return true;
  1722. if (keyCode >= 'a' && keyCode <= 'z'
  1723. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  1724. return true;
  1725. return false;
  1726. }
  1727. //==============================================================================
  1728. bool MouseInputSource::SourceList::addSource()
  1729. {
  1730. if (sources.size() == 0)
  1731. {
  1732. addSource (0, MouseInputSource::InputSourceType::mouse);
  1733. return true;
  1734. }
  1735. return false;
  1736. }
  1737. bool MouseInputSource::SourceList::canUseTouch()
  1738. {
  1739. return false;
  1740. }
  1741. //==============================================================================
  1742. void Desktop::setKioskComponent (Component* kioskComp, bool shouldBeEnabled, bool allowMenusAndBars)
  1743. {
  1744. auto* peer = dynamic_cast<NSViewComponentPeer*> (kioskComp->getPeer());
  1745. jassert (peer != nullptr); // (this should have been checked by the caller)
  1746. if (peer->hasNativeTitleBar()
  1747. && [peer->window respondsToSelector: @selector (toggleFullScreen:)])
  1748. {
  1749. if (shouldBeEnabled && ! allowMenusAndBars)
  1750. [NSApp setPresentationOptions: NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar];
  1751. else if (! shouldBeEnabled)
  1752. [NSApp setPresentationOptions: NSApplicationPresentationDefault];
  1753. [peer->window performSelector: @selector (toggleFullScreen:) withObject: nil];
  1754. }
  1755. else
  1756. {
  1757. if (shouldBeEnabled)
  1758. {
  1759. if (peer->hasNativeTitleBar())
  1760. [peer->window setStyleMask: NSWindowStyleMaskBorderless];
  1761. [NSApp setPresentationOptions: (allowMenusAndBars ? (NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)
  1762. : (NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar))];
  1763. kioskComp->setBounds (Desktop::getInstance().getDisplays().getMainDisplay().totalArea);
  1764. peer->becomeKeyWindow();
  1765. }
  1766. else
  1767. {
  1768. peer->resetWindowPresentation();
  1769. }
  1770. }
  1771. }
  1772. void Desktop::allowedOrientationsChanged() {}
  1773. //==============================================================================
  1774. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  1775. {
  1776. return new NSViewComponentPeer (*this, styleFlags, (NSView*) windowToAttachTo);
  1777. }
  1778. //==============================================================================
  1779. const int KeyPress::spaceKey = ' ';
  1780. const int KeyPress::returnKey = 0x0d;
  1781. const int KeyPress::escapeKey = 0x1b;
  1782. const int KeyPress::backspaceKey = 0x7f;
  1783. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  1784. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  1785. const int KeyPress::upKey = NSUpArrowFunctionKey;
  1786. const int KeyPress::downKey = NSDownArrowFunctionKey;
  1787. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  1788. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  1789. const int KeyPress::endKey = NSEndFunctionKey;
  1790. const int KeyPress::homeKey = NSHomeFunctionKey;
  1791. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  1792. const int KeyPress::insertKey = -1;
  1793. const int KeyPress::tabKey = 9;
  1794. const int KeyPress::F1Key = NSF1FunctionKey;
  1795. const int KeyPress::F2Key = NSF2FunctionKey;
  1796. const int KeyPress::F3Key = NSF3FunctionKey;
  1797. const int KeyPress::F4Key = NSF4FunctionKey;
  1798. const int KeyPress::F5Key = NSF5FunctionKey;
  1799. const int KeyPress::F6Key = NSF6FunctionKey;
  1800. const int KeyPress::F7Key = NSF7FunctionKey;
  1801. const int KeyPress::F8Key = NSF8FunctionKey;
  1802. const int KeyPress::F9Key = NSF9FunctionKey;
  1803. const int KeyPress::F10Key = NSF10FunctionKey;
  1804. const int KeyPress::F11Key = NSF11FunctionKey;
  1805. const int KeyPress::F12Key = NSF12FunctionKey;
  1806. const int KeyPress::F13Key = NSF13FunctionKey;
  1807. const int KeyPress::F14Key = NSF14FunctionKey;
  1808. const int KeyPress::F15Key = NSF15FunctionKey;
  1809. const int KeyPress::F16Key = NSF16FunctionKey;
  1810. const int KeyPress::F17Key = NSF17FunctionKey;
  1811. const int KeyPress::F18Key = NSF18FunctionKey;
  1812. const int KeyPress::F19Key = NSF19FunctionKey;
  1813. const int KeyPress::F20Key = NSF20FunctionKey;
  1814. const int KeyPress::F21Key = NSF21FunctionKey;
  1815. const int KeyPress::F22Key = NSF22FunctionKey;
  1816. const int KeyPress::F23Key = NSF23FunctionKey;
  1817. const int KeyPress::F24Key = NSF24FunctionKey;
  1818. const int KeyPress::F25Key = NSF25FunctionKey;
  1819. const int KeyPress::F26Key = NSF26FunctionKey;
  1820. const int KeyPress::F27Key = NSF27FunctionKey;
  1821. const int KeyPress::F28Key = NSF28FunctionKey;
  1822. const int KeyPress::F29Key = NSF29FunctionKey;
  1823. const int KeyPress::F30Key = NSF30FunctionKey;
  1824. const int KeyPress::F31Key = NSF31FunctionKey;
  1825. const int KeyPress::F32Key = NSF32FunctionKey;
  1826. const int KeyPress::F33Key = NSF33FunctionKey;
  1827. const int KeyPress::F34Key = NSF34FunctionKey;
  1828. const int KeyPress::F35Key = NSF35FunctionKey;
  1829. const int KeyPress::numberPad0 = 0x30020;
  1830. const int KeyPress::numberPad1 = 0x30021;
  1831. const int KeyPress::numberPad2 = 0x30022;
  1832. const int KeyPress::numberPad3 = 0x30023;
  1833. const int KeyPress::numberPad4 = 0x30024;
  1834. const int KeyPress::numberPad5 = 0x30025;
  1835. const int KeyPress::numberPad6 = 0x30026;
  1836. const int KeyPress::numberPad7 = 0x30027;
  1837. const int KeyPress::numberPad8 = 0x30028;
  1838. const int KeyPress::numberPad9 = 0x30029;
  1839. const int KeyPress::numberPadAdd = 0x3002a;
  1840. const int KeyPress::numberPadSubtract = 0x3002b;
  1841. const int KeyPress::numberPadMultiply = 0x3002c;
  1842. const int KeyPress::numberPadDivide = 0x3002d;
  1843. const int KeyPress::numberPadSeparator = 0x3002e;
  1844. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  1845. const int KeyPress::numberPadEquals = 0x30030;
  1846. const int KeyPress::numberPadDelete = 0x30031;
  1847. const int KeyPress::playKey = 0x30000;
  1848. const int KeyPress::stopKey = 0x30001;
  1849. const int KeyPress::fastForwardKey = 0x30002;
  1850. const int KeyPress::rewindKey = 0x30003;
  1851. } // namespace juce