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.

2091 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. return (float) e.pressure;
  900. }
  901. static Point<float> getMousePos (NSEvent* e, NSView* view)
  902. {
  903. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  904. return Point<float> ((float) p.x, (float) ([view frame].size.height - p.y));
  905. }
  906. static int getModifierForButtonNumber (const NSInteger num)
  907. {
  908. return num == 0 ? ModifierKeys::leftButtonModifier
  909. : (num == 1 ? ModifierKeys::rightButtonModifier
  910. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  911. }
  912. static unsigned int getNSWindowStyleMask (const int flags) noexcept
  913. {
  914. unsigned int style = (flags & windowHasTitleBar) != 0 ? NSTitledWindowMask
  915. : NSBorderlessWindowMask;
  916. if ((flags & windowHasMinimiseButton) != 0) style |= NSMiniaturizableWindowMask;
  917. if ((flags & windowHasCloseButton) != 0) style |= NSClosableWindowMask;
  918. if ((flags & windowIsResizable) != 0) style |= NSResizableWindowMask;
  919. return style;
  920. }
  921. static NSArray* getSupportedDragTypes()
  922. {
  923. return [NSArray arrayWithObjects: NSFilenamesPboardType, NSFilesPromisePboardType, NSStringPboardType, nil];
  924. }
  925. BOOL sendDragCallback (const int type, id <NSDraggingInfo> sender)
  926. {
  927. NSPasteboard* pasteboard = [sender draggingPasteboard];
  928. NSString* contentType = [pasteboard availableTypeFromArray: getSupportedDragTypes()];
  929. if (contentType == nil)
  930. return false;
  931. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  932. ComponentPeer::DragInfo dragInfo;
  933. dragInfo.position.setXY ((int) p.x, (int) ([view frame].size.height - p.y));
  934. if (contentType == NSStringPboardType)
  935. dragInfo.text = nsStringToJuce ([pasteboard stringForType: NSStringPboardType]);
  936. else
  937. dragInfo.files = getDroppedFiles (pasteboard, contentType);
  938. if (! dragInfo.isEmpty())
  939. {
  940. switch (type)
  941. {
  942. case 0: return handleDragMove (dragInfo);
  943. case 1: return handleDragExit (dragInfo);
  944. case 2: return handleDragDrop (dragInfo);
  945. default: jassertfalse; break;
  946. }
  947. }
  948. return false;
  949. }
  950. StringArray getDroppedFiles (NSPasteboard* pasteboard, NSString* contentType)
  951. {
  952. StringArray files;
  953. NSString* iTunesPasteboardType = nsStringLiteral ("CorePasteboardFlavorType 0x6974756E"); // 'itun'
  954. if (contentType == NSFilesPromisePboardType
  955. && [[pasteboard types] containsObject: iTunesPasteboardType])
  956. {
  957. id list = [pasteboard propertyListForType: iTunesPasteboardType];
  958. if ([list isKindOfClass: [NSDictionary class]])
  959. {
  960. NSDictionary* iTunesDictionary = (NSDictionary*) list;
  961. NSArray* tracks = [iTunesDictionary valueForKey: nsStringLiteral ("Tracks")];
  962. NSEnumerator* enumerator = [tracks objectEnumerator];
  963. NSDictionary* track;
  964. while ((track = [enumerator nextObject]) != nil)
  965. {
  966. NSURL* url = [NSURL URLWithString: [track valueForKey: nsStringLiteral ("Location")]];
  967. if ([url isFileURL])
  968. files.add (nsStringToJuce ([url path]));
  969. }
  970. }
  971. }
  972. else
  973. {
  974. id list = [pasteboard propertyListForType: NSFilenamesPboardType];
  975. if ([list isKindOfClass: [NSArray class]])
  976. {
  977. NSArray* items = (NSArray*) [pasteboard propertyListForType: NSFilenamesPboardType];
  978. for (unsigned int i = 0; i < [items count]; ++i)
  979. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  980. }
  981. }
  982. return files;
  983. }
  984. //==============================================================================
  985. void viewFocusGain()
  986. {
  987. if (currentlyFocusedPeer != this)
  988. {
  989. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  990. currentlyFocusedPeer->handleFocusLoss();
  991. currentlyFocusedPeer = this;
  992. handleFocusGain();
  993. }
  994. }
  995. void viewFocusLoss()
  996. {
  997. if (currentlyFocusedPeer == this)
  998. {
  999. currentlyFocusedPeer = nullptr;
  1000. handleFocusLoss();
  1001. }
  1002. }
  1003. bool isFocused() const override
  1004. {
  1005. return (isSharedWindow || ! JUCEApplication::isStandaloneApp())
  1006. ? this == currentlyFocusedPeer
  1007. : [window isKeyWindow];
  1008. }
  1009. void grabFocus() override
  1010. {
  1011. if (window != nil)
  1012. {
  1013. [window makeKeyWindow];
  1014. [window makeFirstResponder: view];
  1015. viewFocusGain();
  1016. }
  1017. }
  1018. void textInputRequired (Point<int>, TextInputTarget&) override {}
  1019. //==============================================================================
  1020. void repaint (const Rectangle<int>& area) override
  1021. {
  1022. if (insideDrawRect)
  1023. {
  1024. class AsyncRepaintMessage : public CallbackMessage
  1025. {
  1026. public:
  1027. AsyncRepaintMessage (NSViewComponentPeer* const p, const Rectangle<int>& r)
  1028. : peer (p), rect (r)
  1029. {}
  1030. void messageCallback() override
  1031. {
  1032. if (ComponentPeer::isValidPeer (peer))
  1033. peer->repaint (rect);
  1034. }
  1035. private:
  1036. NSViewComponentPeer* const peer;
  1037. const Rectangle<int> rect;
  1038. };
  1039. (new AsyncRepaintMessage (this, area))->post();
  1040. }
  1041. else
  1042. {
  1043. [view setNeedsDisplayInRect: NSMakeRect ((CGFloat) area.getX(), [view frame].size.height - (CGFloat) area.getBottom(),
  1044. (CGFloat) area.getWidth(), (CGFloat) area.getHeight())];
  1045. }
  1046. }
  1047. void performAnyPendingRepaintsNow() override
  1048. {
  1049. [view displayIfNeeded];
  1050. }
  1051. //==============================================================================
  1052. NSWindow* window;
  1053. NSView* view;
  1054. bool isSharedWindow, fullScreen, insideDrawRect;
  1055. bool usingCoreGraphics, isZooming, textWasInserted;
  1056. String stringBeingComposed;
  1057. NSNotificationCenter* notificationCenter;
  1058. static ModifierKeys currentModifiers;
  1059. static ComponentPeer* currentlyFocusedPeer;
  1060. static Array<int> keysCurrentlyDown;
  1061. static int insideToFrontCall;
  1062. private:
  1063. static NSView* createViewInstance();
  1064. static NSWindow* createWindowInstance();
  1065. static void setOwner (id viewOrWindow, NSViewComponentPeer* newOwner)
  1066. {
  1067. object_setInstanceVariable (viewOrWindow, "owner", newOwner);
  1068. }
  1069. void getClipRects (RectangleList<int>& clip, const Point<int> offset, const int clipW, const int clipH)
  1070. {
  1071. const NSRect* rects = nullptr;
  1072. NSInteger numRects = 0;
  1073. [view getRectsBeingDrawn: &rects count: &numRects];
  1074. const Rectangle<int> clipBounds (clipW, clipH);
  1075. const CGFloat viewH = [view frame].size.height;
  1076. clip.ensureStorageAllocated ((int) numRects);
  1077. for (int i = 0; i < numRects; ++i)
  1078. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + offset.x,
  1079. roundToInt (viewH - (rects[i].origin.y + rects[i].size.height)) + offset.y,
  1080. roundToInt (rects[i].size.width),
  1081. roundToInt (rects[i].size.height))));
  1082. }
  1083. static void appFocusChanged()
  1084. {
  1085. keysCurrentlyDown.clear();
  1086. if (isValidPeer (currentlyFocusedPeer))
  1087. {
  1088. if (Process::isForegroundProcess())
  1089. {
  1090. currentlyFocusedPeer->handleFocusGain();
  1091. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  1092. }
  1093. else
  1094. {
  1095. currentlyFocusedPeer->handleFocusLoss();
  1096. }
  1097. }
  1098. }
  1099. static bool checkEventBlockedByModalComps (NSEvent* e)
  1100. {
  1101. if (Component::getNumCurrentlyModalComponents() == 0)
  1102. return false;
  1103. NSWindow* const w = [e window];
  1104. if (w == nil || [w worksWhenModal])
  1105. return false;
  1106. bool isKey = false, isInputAttempt = false;
  1107. switch ([e type])
  1108. {
  1109. case NSKeyDown:
  1110. case NSKeyUp:
  1111. isKey = isInputAttempt = true;
  1112. break;
  1113. case NSLeftMouseDown:
  1114. case NSRightMouseDown:
  1115. case NSOtherMouseDown:
  1116. isInputAttempt = true;
  1117. break;
  1118. case NSLeftMouseDragged:
  1119. case NSRightMouseDragged:
  1120. case NSLeftMouseUp:
  1121. case NSRightMouseUp:
  1122. case NSOtherMouseUp:
  1123. case NSOtherMouseDragged:
  1124. if (Desktop::getInstance().getDraggingMouseSource(0) != nullptr)
  1125. return false;
  1126. break;
  1127. case NSMouseMoved:
  1128. case NSMouseEntered:
  1129. case NSMouseExited:
  1130. case NSCursorUpdate:
  1131. case NSScrollWheel:
  1132. case NSTabletPoint:
  1133. case NSTabletProximity:
  1134. break;
  1135. default:
  1136. return false;
  1137. }
  1138. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  1139. {
  1140. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  1141. NSView* const compView = (NSView*) peer->getNativeHandle();
  1142. if ([compView window] == w)
  1143. {
  1144. if (isKey)
  1145. {
  1146. if (compView == [w firstResponder])
  1147. return false;
  1148. }
  1149. else
  1150. {
  1151. NSViewComponentPeer* nsViewPeer = dynamic_cast<NSViewComponentPeer*> (peer);
  1152. if ((nsViewPeer == nullptr || ! nsViewPeer->isSharedWindow)
  1153. ? NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height))
  1154. : NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil], [compView bounds]))
  1155. return false;
  1156. }
  1157. }
  1158. }
  1159. if (isInputAttempt)
  1160. {
  1161. if (! [NSApp isActive])
  1162. [NSApp activateIgnoringOtherApps: YES];
  1163. if (Component* const modal = Component::getCurrentlyModalComponent())
  1164. modal->inputAttemptWhenModal();
  1165. }
  1166. return true;
  1167. }
  1168. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentPeer)
  1169. };
  1170. int NSViewComponentPeer::insideToFrontCall = 0;
  1171. //==============================================================================
  1172. struct JuceNSViewClass : public ObjCClass <NSView>
  1173. {
  1174. JuceNSViewClass() : ObjCClass <NSView> ("JUCEView_")
  1175. {
  1176. addIvar<NSViewComponentPeer*> ("owner");
  1177. addMethod (@selector (isOpaque), isOpaque, "c@:");
  1178. addMethod (@selector (drawRect:), drawRect, "v@:", @encode (NSRect));
  1179. addMethod (@selector (mouseDown:), mouseDown, "v@:@");
  1180. addMethod (@selector (asyncMouseDown:), asyncMouseDown, "v@:@");
  1181. addMethod (@selector (mouseUp:), mouseUp, "v@:@");
  1182. addMethod (@selector (asyncMouseUp:), asyncMouseUp, "v@:@");
  1183. addMethod (@selector (mouseDragged:), mouseDragged, "v@:@");
  1184. addMethod (@selector (mouseMoved:), mouseMoved, "v@:@");
  1185. addMethod (@selector (mouseEntered:), mouseEntered, "v@:@");
  1186. addMethod (@selector (mouseExited:), mouseExited, "v@:@");
  1187. addMethod (@selector (rightMouseDown:), mouseDown, "v@:@");
  1188. addMethod (@selector (rightMouseDragged:), mouseDragged, "v@:@");
  1189. addMethod (@selector (rightMouseUp:), mouseUp, "v@:@");
  1190. addMethod (@selector (otherMouseDown:), mouseDown, "v@:@");
  1191. addMethod (@selector (otherMouseDragged:), mouseDragged, "v@:@");
  1192. addMethod (@selector (otherMouseUp:), mouseUp, "v@:@");
  1193. addMethod (@selector (scrollWheel:), scrollWheel, "v@:@");
  1194. addMethod (@selector (magnifyWithEvent:), magnify, "v@:@");
  1195. addMethod (@selector (acceptsFirstMouse:), acceptsFirstMouse, "v@:@");
  1196. addMethod (@selector (frameChanged:), frameChanged, "v@:@");
  1197. addMethod (@selector (viewDidMoveToWindow), viewDidMoveToWindow, "v@:");
  1198. addMethod (@selector (keyDown:), keyDown, "v@:@");
  1199. addMethod (@selector (keyUp:), keyUp, "v@:@");
  1200. addMethod (@selector (insertText:), insertText, "v@:@");
  1201. addMethod (@selector (doCommandBySelector:), doCommandBySelector, "v@::");
  1202. addMethod (@selector (setMarkedText:selectedRange:), setMarkedText, "v@:@", @encode (NSRange));
  1203. addMethod (@selector (unmarkText), unmarkText, "v@:");
  1204. addMethod (@selector (hasMarkedText), hasMarkedText, "c@:");
  1205. addMethod (@selector (conversationIdentifier), conversationIdentifier, "l@:");
  1206. addMethod (@selector (attributedSubstringFromRange:), attributedSubstringFromRange, "@@:", @encode (NSRange));
  1207. addMethod (@selector (markedRange), markedRange, @encode (NSRange), "@:");
  1208. addMethod (@selector (selectedRange), selectedRange, @encode (NSRange), "@:");
  1209. addMethod (@selector (firstRectForCharacterRange:), firstRectForCharacterRange, @encode (NSRect), "@:", @encode (NSRange));
  1210. addMethod (@selector (validAttributesForMarkedText), validAttributesForMarkedText, "@@:");
  1211. addMethod (@selector (flagsChanged:), flagsChanged, "v@:@");
  1212. addMethod (@selector (becomeFirstResponder), becomeFirstResponder, "c@:");
  1213. addMethod (@selector (resignFirstResponder), resignFirstResponder, "c@:");
  1214. addMethod (@selector (acceptsFirstResponder), acceptsFirstResponder, "c@:");
  1215. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  1216. addMethod (@selector (performKeyEquivalent:), performKeyEquivalent, "c@:@");
  1217. #endif
  1218. addMethod (@selector (draggingEntered:), draggingEntered, @encode (NSDragOperation), "@:@");
  1219. addMethod (@selector (draggingUpdated:), draggingUpdated, @encode (NSDragOperation), "@:@");
  1220. addMethod (@selector (draggingEnded:), draggingEnded, "v@:@");
  1221. addMethod (@selector (draggingExited:), draggingExited, "v@:@");
  1222. addMethod (@selector (prepareForDragOperation:), prepareForDragOperation, "c@:@");
  1223. addMethod (@selector (performDragOperation:), performDragOperation, "c@:@");
  1224. addMethod (@selector (concludeDragOperation:), concludeDragOperation, "v@:@");
  1225. addProtocol (@protocol (NSTextInput));
  1226. registerClass();
  1227. }
  1228. private:
  1229. static NSViewComponentPeer* getOwner (id self)
  1230. {
  1231. return getIvar<NSViewComponentPeer*> (self, "owner");
  1232. }
  1233. static void mouseDown (id self, SEL s, NSEvent* ev)
  1234. {
  1235. if (JUCEApplicationBase::isStandaloneApp())
  1236. asyncMouseDown (self, s, ev);
  1237. else
  1238. // In some host situations, the host will stop modal loops from working
  1239. // correctly if they're called from a mouse event, so we'll trigger
  1240. // the event asynchronously..
  1241. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  1242. withObject: ev
  1243. waitUntilDone: NO];
  1244. }
  1245. static void mouseUp (id self, SEL s, NSEvent* ev)
  1246. {
  1247. if (JUCEApplicationBase::isStandaloneApp())
  1248. asyncMouseUp (self, s, ev);
  1249. else
  1250. // In some host situations, the host will stop modal loops from working
  1251. // correctly if they're called from a mouse event, so we'll trigger
  1252. // the event asynchronously..
  1253. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  1254. withObject: ev
  1255. waitUntilDone: NO];
  1256. }
  1257. static void asyncMouseDown (id self, SEL, NSEvent* ev) { if (NSViewComponentPeer* const p = getOwner (self)) p->redirectMouseDown (ev); }
  1258. static void asyncMouseUp (id self, SEL, NSEvent* ev) { if (NSViewComponentPeer* const p = getOwner (self)) p->redirectMouseUp (ev); }
  1259. static void mouseDragged (id self, SEL, NSEvent* ev) { if (NSViewComponentPeer* const p = getOwner (self)) p->redirectMouseDrag (ev); }
  1260. static void mouseMoved (id self, SEL, NSEvent* ev) { if (NSViewComponentPeer* const p = getOwner (self)) p->redirectMouseMove (ev); }
  1261. static void mouseEntered (id self, SEL, NSEvent* ev) { if (NSViewComponentPeer* const p = getOwner (self)) p->redirectMouseEnter (ev); }
  1262. static void mouseExited (id self, SEL, NSEvent* ev) { if (NSViewComponentPeer* const p = getOwner (self)) p->redirectMouseExit (ev); }
  1263. static void scrollWheel (id self, SEL, NSEvent* ev) { if (NSViewComponentPeer* const p = getOwner (self)) p->redirectMouseWheel (ev); }
  1264. static void magnify (id self, SEL, NSEvent* ev) { if (NSViewComponentPeer* const p = getOwner (self)) p->redirectMagnify (ev); }
  1265. static BOOL acceptsFirstMouse (id, SEL, NSEvent*) { return YES; }
  1266. static void drawRect (id self, SEL, NSRect r) { if (NSViewComponentPeer* const p = getOwner (self)) p->drawRect (r); }
  1267. static void frameChanged (id self, SEL, NSNotification*) { if (NSViewComponentPeer* const p = getOwner (self)) p->redirectMovedOrResized(); }
  1268. static void viewDidMoveToWindow (id self, SEL) { if (NSViewComponentPeer* const p = getOwner (self)) p->viewMovedToWindow(); }
  1269. static BOOL isOpaque (id self, SEL)
  1270. {
  1271. NSViewComponentPeer* const owner = getOwner (self);
  1272. return owner == nullptr || owner->getComponent().isOpaque();
  1273. }
  1274. //==============================================================================
  1275. static void keyDown (id self, SEL, NSEvent* ev)
  1276. {
  1277. if (NSViewComponentPeer* const owner = getOwner (self))
  1278. {
  1279. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  1280. owner->textWasInserted = false;
  1281. if (target != nullptr)
  1282. [(NSView*) self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  1283. else
  1284. owner->stringBeingComposed.clear();
  1285. if ((! owner->textWasInserted) && (owner == nullptr || ! owner->redirectKeyDown (ev)))
  1286. {
  1287. objc_super s = { self, [NSView class] };
  1288. getMsgSendSuperFn() (&s, @selector (keyDown:), ev);
  1289. }
  1290. }
  1291. }
  1292. static void keyUp (id self, SEL, NSEvent* ev)
  1293. {
  1294. NSViewComponentPeer* const owner = getOwner (self);
  1295. if (owner == nullptr || ! owner->redirectKeyUp (ev))
  1296. {
  1297. objc_super s = { self, [NSView class] };
  1298. getMsgSendSuperFn() (&s, @selector (keyUp:), ev);
  1299. }
  1300. }
  1301. //==============================================================================
  1302. static void insertText (id self, SEL, id aString)
  1303. {
  1304. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  1305. if (NSViewComponentPeer* const owner = getOwner (self))
  1306. {
  1307. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  1308. if ([newText length] > 0)
  1309. {
  1310. if (TextInputTarget* const target = owner->findCurrentTextInputTarget())
  1311. {
  1312. target->insertTextAtCaret (nsStringToJuce (newText));
  1313. owner->textWasInserted = true;
  1314. }
  1315. }
  1316. owner->stringBeingComposed.clear();
  1317. }
  1318. }
  1319. static void doCommandBySelector (id, SEL, SEL) {}
  1320. static void setMarkedText (id self, SEL, id aString, NSRange)
  1321. {
  1322. if (NSViewComponentPeer* const owner = getOwner (self))
  1323. {
  1324. owner->stringBeingComposed = nsStringToJuce ([aString isKindOfClass: [NSAttributedString class]]
  1325. ? [aString string] : aString);
  1326. if (TextInputTarget* const target = owner->findCurrentTextInputTarget())
  1327. {
  1328. const Range<int> currentHighlight (target->getHighlightedRegion());
  1329. target->insertTextAtCaret (owner->stringBeingComposed);
  1330. target->setHighlightedRegion (currentHighlight.withLength (owner->stringBeingComposed.length()));
  1331. owner->textWasInserted = true;
  1332. }
  1333. }
  1334. }
  1335. static void unmarkText (id self, SEL)
  1336. {
  1337. if (NSViewComponentPeer* const owner = getOwner (self))
  1338. {
  1339. if (owner->stringBeingComposed.isNotEmpty())
  1340. {
  1341. if (TextInputTarget* const target = owner->findCurrentTextInputTarget())
  1342. {
  1343. target->insertTextAtCaret (owner->stringBeingComposed);
  1344. owner->textWasInserted = true;
  1345. }
  1346. owner->stringBeingComposed.clear();
  1347. }
  1348. }
  1349. }
  1350. static BOOL hasMarkedText (id self, SEL)
  1351. {
  1352. NSViewComponentPeer* const owner = getOwner (self);
  1353. return owner != nullptr && owner->stringBeingComposed.isNotEmpty();
  1354. }
  1355. static long conversationIdentifier (id self, SEL)
  1356. {
  1357. return (long) (pointer_sized_int) self;
  1358. }
  1359. static NSAttributedString* attributedSubstringFromRange (id self, SEL, NSRange theRange)
  1360. {
  1361. if (NSViewComponentPeer* const owner = getOwner (self))
  1362. {
  1363. if (TextInputTarget* const target = owner->findCurrentTextInputTarget())
  1364. {
  1365. const Range<int> r ((int) theRange.location,
  1366. (int) (theRange.location + theRange.length));
  1367. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  1368. }
  1369. }
  1370. return nil;
  1371. }
  1372. static NSRange markedRange (id self, SEL)
  1373. {
  1374. if (NSViewComponentPeer* const owner = getOwner (self))
  1375. if (owner->stringBeingComposed.isNotEmpty())
  1376. return NSMakeRange (0, (NSUInteger) owner->stringBeingComposed.length());
  1377. return NSMakeRange (NSNotFound, 0);
  1378. }
  1379. static NSRange selectedRange (id self, SEL)
  1380. {
  1381. if (NSViewComponentPeer* const owner = getOwner (self))
  1382. {
  1383. if (TextInputTarget* const target = owner->findCurrentTextInputTarget())
  1384. {
  1385. const Range<int> highlight (target->getHighlightedRegion());
  1386. if (! highlight.isEmpty())
  1387. return NSMakeRange ((NSUInteger) highlight.getStart(),
  1388. (NSUInteger) highlight.getLength());
  1389. }
  1390. }
  1391. return NSMakeRange (NSNotFound, 0);
  1392. }
  1393. static NSRect firstRectForCharacterRange (id self, SEL, NSRange)
  1394. {
  1395. if (NSViewComponentPeer* const owner = getOwner (self))
  1396. if (Component* const comp = dynamic_cast<Component*> (owner->findCurrentTextInputTarget()))
  1397. return flippedScreenRect (makeNSRect (comp->getScreenBounds()));
  1398. return NSZeroRect;
  1399. }
  1400. static NSUInteger characterIndexForPoint (id, SEL, NSPoint) { return NSNotFound; }
  1401. static NSArray* validAttributesForMarkedText (id, SEL) { return [NSArray array]; }
  1402. //==============================================================================
  1403. static void flagsChanged (id self, SEL, NSEvent* ev)
  1404. {
  1405. if (NSViewComponentPeer* const owner = getOwner (self))
  1406. owner->redirectModKeyChange (ev);
  1407. }
  1408. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  1409. static BOOL performKeyEquivalent (id self, SEL, NSEvent* ev)
  1410. {
  1411. if (NSViewComponentPeer* const owner = getOwner (self))
  1412. if (owner->redirectPerformKeyEquivalent (ev))
  1413. return true;
  1414. objc_super s = { self, [NSView class] };
  1415. return getMsgSendSuperFn() (&s, @selector (performKeyEquivalent:), ev) != nil;
  1416. }
  1417. #endif
  1418. static BOOL becomeFirstResponder (id self, SEL)
  1419. {
  1420. if (NSViewComponentPeer* const owner = getOwner (self))
  1421. owner->viewFocusGain();
  1422. return YES;
  1423. }
  1424. static BOOL resignFirstResponder (id self, SEL)
  1425. {
  1426. if (NSViewComponentPeer* const owner = getOwner (self))
  1427. owner->viewFocusLoss();
  1428. return YES;
  1429. }
  1430. static BOOL acceptsFirstResponder (id self, SEL)
  1431. {
  1432. NSViewComponentPeer* const owner = getOwner (self);
  1433. return owner != nullptr && owner->canBecomeKeyWindow();
  1434. }
  1435. //==============================================================================
  1436. static NSDragOperation draggingEntered (id self, SEL s, id <NSDraggingInfo> sender)
  1437. {
  1438. return draggingUpdated (self, s, sender);
  1439. }
  1440. static NSDragOperation draggingUpdated (id self, SEL, id <NSDraggingInfo> sender)
  1441. {
  1442. if (NSViewComponentPeer* const owner = getOwner (self))
  1443. if (owner->sendDragCallback (0, sender))
  1444. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  1445. return NSDragOperationNone;
  1446. }
  1447. static void draggingEnded (id self, SEL s, id <NSDraggingInfo> sender)
  1448. {
  1449. draggingExited (self, s, sender);
  1450. }
  1451. static void draggingExited (id self, SEL, id <NSDraggingInfo> sender)
  1452. {
  1453. if (NSViewComponentPeer* const owner = getOwner (self))
  1454. owner->sendDragCallback (1, sender);
  1455. }
  1456. static BOOL prepareForDragOperation (id, SEL, id <NSDraggingInfo>)
  1457. {
  1458. return YES;
  1459. }
  1460. static BOOL performDragOperation (id self, SEL, id <NSDraggingInfo> sender)
  1461. {
  1462. NSViewComponentPeer* const owner = getOwner (self);
  1463. return owner != nullptr && owner->sendDragCallback (2, sender);
  1464. }
  1465. static void concludeDragOperation (id, SEL, id <NSDraggingInfo>) {}
  1466. };
  1467. //==============================================================================
  1468. struct JuceNSWindowClass : public ObjCClass<NSWindow>
  1469. {
  1470. JuceNSWindowClass() : ObjCClass<NSWindow> ("JUCEWindow_")
  1471. {
  1472. addIvar<NSViewComponentPeer*> ("owner");
  1473. addMethod (@selector (canBecomeKeyWindow), canBecomeKeyWindow, "c@:");
  1474. addMethod (@selector (canBecomeMainWindow), canBecomeMainWindow, "c@:");
  1475. addMethod (@selector (becomeKeyWindow), becomeKeyWindow, "v@:");
  1476. addMethod (@selector (windowShouldClose:), windowShouldClose, "c@:@");
  1477. addMethod (@selector (constrainFrameRect:toScreen:), constrainFrameRect, @encode (NSRect), "@:", @encode (NSRect), "@");
  1478. addMethod (@selector (windowWillResize:toSize:), windowWillResize, @encode (NSSize), "@:@", @encode (NSSize));
  1479. addMethod (@selector (windowDidExitFullScreen:), windowDidExitFullScreen, "v@:@");
  1480. addMethod (@selector (zoom:), zoom, "v@:@");
  1481. addMethod (@selector (windowWillMove:), windowWillMove, "v@:@");
  1482. addMethod (@selector (windowWillStartLiveResize:), windowWillStartLiveResize, "v@:@");
  1483. addMethod (@selector (windowDidEndLiveResize:), windowDidEndLiveResize, "v@:@");
  1484. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  1485. addProtocol (@protocol (NSWindowDelegate));
  1486. #endif
  1487. registerClass();
  1488. }
  1489. private:
  1490. static NSViewComponentPeer* getOwner (id self)
  1491. {
  1492. return getIvar<NSViewComponentPeer*> (self, "owner");
  1493. }
  1494. //==============================================================================
  1495. static BOOL canBecomeKeyWindow (id self, SEL)
  1496. {
  1497. NSViewComponentPeer* const owner = getOwner (self);
  1498. return owner != nullptr
  1499. && owner->canBecomeKeyWindow()
  1500. && ! owner->sendModalInputAttemptIfBlocked();
  1501. }
  1502. static BOOL canBecomeMainWindow (id self, SEL)
  1503. {
  1504. NSViewComponentPeer* const owner = getOwner (self);
  1505. return owner != nullptr
  1506. && owner->canBecomeMainWindow()
  1507. && ! owner->sendModalInputAttemptIfBlocked();
  1508. }
  1509. static void becomeKeyWindow (id self, SEL)
  1510. {
  1511. sendSuperclassMessage (self, @selector (becomeKeyWindow));
  1512. if (NSViewComponentPeer* const owner = getOwner (self))
  1513. owner->becomeKeyWindow();
  1514. }
  1515. static BOOL windowShouldClose (id self, SEL, id /*window*/)
  1516. {
  1517. NSViewComponentPeer* const owner = getOwner (self);
  1518. return owner == nullptr || owner->windowShouldClose();
  1519. }
  1520. static NSRect constrainFrameRect (id self, SEL, NSRect frameRect, NSScreen*)
  1521. {
  1522. if (NSViewComponentPeer* const owner = getOwner (self))
  1523. frameRect = owner->constrainRect (frameRect);
  1524. return frameRect;
  1525. }
  1526. static NSSize windowWillResize (id self, SEL, NSWindow*, NSSize proposedFrameSize)
  1527. {
  1528. NSViewComponentPeer* const owner = getOwner (self);
  1529. if (owner == nullptr || owner->isZooming)
  1530. return proposedFrameSize;
  1531. NSRect frameRect = [(NSWindow*) self frame];
  1532. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  1533. frameRect.size = proposedFrameSize;
  1534. frameRect = owner->constrainRect (frameRect);
  1535. if (owner->hasNativeTitleBar())
  1536. owner->sendModalInputAttemptIfBlocked();
  1537. return frameRect.size;
  1538. }
  1539. static void windowDidExitFullScreen (id, SEL, NSNotification*)
  1540. {
  1541. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  1542. [NSApp setPresentationOptions: NSApplicationPresentationDefault];
  1543. #endif
  1544. }
  1545. static void zoom (id self, SEL, id sender)
  1546. {
  1547. if (NSViewComponentPeer* const owner = getOwner (self))
  1548. {
  1549. owner->isZooming = true;
  1550. objc_super s = { self, [NSWindow class] };
  1551. getMsgSendSuperFn() (&s, @selector (zoom:), sender);
  1552. owner->isZooming = false;
  1553. owner->redirectMovedOrResized();
  1554. }
  1555. }
  1556. static void windowWillMove (id self, SEL, NSNotification*)
  1557. {
  1558. if (NSViewComponentPeer* const owner = getOwner (self))
  1559. if (owner->hasNativeTitleBar())
  1560. owner->sendModalInputAttemptIfBlocked();
  1561. }
  1562. static void windowWillStartLiveResize (id self, SEL, NSNotification*)
  1563. {
  1564. if (NSViewComponentPeer* const owner = getOwner (self))
  1565. owner->liveResizingStart();
  1566. }
  1567. static void windowDidEndLiveResize (id self, SEL, NSNotification*)
  1568. {
  1569. if (NSViewComponentPeer* const owner = getOwner (self))
  1570. owner->liveResizingEnd();
  1571. }
  1572. };
  1573. NSView* NSViewComponentPeer::createViewInstance()
  1574. {
  1575. static JuceNSViewClass cls;
  1576. return cls.createInstance();
  1577. }
  1578. NSWindow* NSViewComponentPeer::createWindowInstance()
  1579. {
  1580. static JuceNSWindowClass cls;
  1581. return cls.createInstance();
  1582. }
  1583. //==============================================================================
  1584. ModifierKeys NSViewComponentPeer::currentModifiers;
  1585. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = nullptr;
  1586. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  1587. //==============================================================================
  1588. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  1589. {
  1590. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  1591. return true;
  1592. if (keyCode >= 'A' && keyCode <= 'Z'
  1593. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  1594. return true;
  1595. if (keyCode >= 'a' && keyCode <= 'z'
  1596. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  1597. return true;
  1598. return false;
  1599. }
  1600. ModifierKeys ModifierKeys::getCurrentModifiersRealtime() noexcept
  1601. {
  1602. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  1603. if ([NSEvent respondsToSelector: @selector (modifierFlags)])
  1604. NSViewComponentPeer::updateModifiers ((NSUInteger) [NSEvent modifierFlags]);
  1605. #endif
  1606. return NSViewComponentPeer::currentModifiers;
  1607. }
  1608. void ModifierKeys::updateCurrentModifiers() noexcept
  1609. {
  1610. currentModifiers = NSViewComponentPeer::currentModifiers;
  1611. }
  1612. //==============================================================================
  1613. bool MouseInputSource::SourceList::addSource()
  1614. {
  1615. if (sources.size() == 0)
  1616. {
  1617. addSource (0, true);
  1618. return true;
  1619. }
  1620. return false;
  1621. }
  1622. //==============================================================================
  1623. void Desktop::setKioskComponent (Component* kioskComp, bool shouldBeEnabled, bool allowMenusAndBars)
  1624. {
  1625. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  1626. NSViewComponentPeer* const peer = dynamic_cast<NSViewComponentPeer*> (kioskComp->getPeer());
  1627. jassert (peer != nullptr); // (this should have been checked by the caller)
  1628. #if defined (MAC_OS_X_VERSION_10_7) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
  1629. if (peer->hasNativeTitleBar()
  1630. && [peer->window respondsToSelector: @selector (toggleFullScreen:)])
  1631. {
  1632. if (shouldBeEnabled && ! allowMenusAndBars)
  1633. [NSApp setPresentationOptions: NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar];
  1634. [peer->window performSelector: @selector (toggleFullScreen:) withObject: nil];
  1635. }
  1636. else
  1637. #endif
  1638. {
  1639. if (shouldBeEnabled)
  1640. {
  1641. if (peer->hasNativeTitleBar())
  1642. [peer->window setStyleMask: NSBorderlessWindowMask];
  1643. [NSApp setPresentationOptions: (allowMenusAndBars ? (NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)
  1644. : (NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar))];
  1645. kioskComp->setBounds (Desktop::getInstance().getDisplays().getMainDisplay().totalArea);
  1646. peer->becomeKeyWindow();
  1647. }
  1648. else
  1649. {
  1650. if (peer->hasNativeTitleBar())
  1651. {
  1652. [peer->window setStyleMask: (NSViewComponentPeer::getNSWindowStyleMask (peer->getStyleFlags()))];
  1653. peer->setTitle (peer->getComponent().getName()); // required to force the OS to update the title
  1654. }
  1655. [NSApp setPresentationOptions: NSApplicationPresentationDefault];
  1656. }
  1657. }
  1658. #elif JUCE_SUPPORT_CARBON
  1659. if (shouldBeEnabled)
  1660. {
  1661. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  1662. kioskComp->setBounds (Desktop::getInstance().getDisplays().getMainDisplay().totalArea);
  1663. }
  1664. else
  1665. {
  1666. SetSystemUIMode (kUIModeNormal, 0);
  1667. }
  1668. #else
  1669. (void) kioskComp; (void) shouldBeEnabled; (void) allowMenusAndBars;
  1670. // If you're targeting OSes earlier than 10.6 and want to use this feature,
  1671. // you'll need to enable JUCE_SUPPORT_CARBON.
  1672. jassertfalse;
  1673. #endif
  1674. }
  1675. //==============================================================================
  1676. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  1677. {
  1678. return new NSViewComponentPeer (*this, styleFlags, (NSView*) windowToAttachTo);
  1679. }
  1680. //==============================================================================
  1681. const int KeyPress::spaceKey = ' ';
  1682. const int KeyPress::returnKey = 0x0d;
  1683. const int KeyPress::escapeKey = 0x1b;
  1684. const int KeyPress::backspaceKey = 0x7f;
  1685. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  1686. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  1687. const int KeyPress::upKey = NSUpArrowFunctionKey;
  1688. const int KeyPress::downKey = NSDownArrowFunctionKey;
  1689. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  1690. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  1691. const int KeyPress::endKey = NSEndFunctionKey;
  1692. const int KeyPress::homeKey = NSHomeFunctionKey;
  1693. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  1694. const int KeyPress::insertKey = -1;
  1695. const int KeyPress::tabKey = 9;
  1696. const int KeyPress::F1Key = NSF1FunctionKey;
  1697. const int KeyPress::F2Key = NSF2FunctionKey;
  1698. const int KeyPress::F3Key = NSF3FunctionKey;
  1699. const int KeyPress::F4Key = NSF4FunctionKey;
  1700. const int KeyPress::F5Key = NSF5FunctionKey;
  1701. const int KeyPress::F6Key = NSF6FunctionKey;
  1702. const int KeyPress::F7Key = NSF7FunctionKey;
  1703. const int KeyPress::F8Key = NSF8FunctionKey;
  1704. const int KeyPress::F9Key = NSF9FunctionKey;
  1705. const int KeyPress::F10Key = NSF10FunctionKey;
  1706. const int KeyPress::F11Key = NSF1FunctionKey;
  1707. const int KeyPress::F12Key = NSF12FunctionKey;
  1708. const int KeyPress::F13Key = NSF13FunctionKey;
  1709. const int KeyPress::F14Key = NSF14FunctionKey;
  1710. const int KeyPress::F15Key = NSF15FunctionKey;
  1711. const int KeyPress::F16Key = NSF16FunctionKey;
  1712. const int KeyPress::numberPad0 = 0x30020;
  1713. const int KeyPress::numberPad1 = 0x30021;
  1714. const int KeyPress::numberPad2 = 0x30022;
  1715. const int KeyPress::numberPad3 = 0x30023;
  1716. const int KeyPress::numberPad4 = 0x30024;
  1717. const int KeyPress::numberPad5 = 0x30025;
  1718. const int KeyPress::numberPad6 = 0x30026;
  1719. const int KeyPress::numberPad7 = 0x30027;
  1720. const int KeyPress::numberPad8 = 0x30028;
  1721. const int KeyPress::numberPad9 = 0x30029;
  1722. const int KeyPress::numberPadAdd = 0x3002a;
  1723. const int KeyPress::numberPadSubtract = 0x3002b;
  1724. const int KeyPress::numberPadMultiply = 0x3002c;
  1725. const int KeyPress::numberPadDivide = 0x3002d;
  1726. const int KeyPress::numberPadSeparator = 0x3002e;
  1727. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  1728. const int KeyPress::numberPadEquals = 0x30030;
  1729. const int KeyPress::numberPadDelete = 0x30031;
  1730. const int KeyPress::playKey = 0x30000;
  1731. const int KeyPress::stopKey = 0x30001;
  1732. const int KeyPress::fastForwardKey = 0x30002;
  1733. const int KeyPress::rewindKey = 0x30003;