The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2084 lines
77KB

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