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.

2099 lines
78KB

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