Audio plugin host https://kx.studio/carla
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.

2095 lines
79KB

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