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.

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