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.

2125 lines
80KB

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