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.

2123 lines
80KB

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