Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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