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.

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