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.

2245 lines
84KB

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