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.

1892 lines
69KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-11 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. typedef void (*AppFocusChangeCallback)();
  19. extern AppFocusChangeCallback appFocusChangeCallback;
  20. typedef bool (*CheckEventBlockedByModalComps) (NSEvent*);
  21. extern CheckEventBlockedByModalComps isEventBlockedByModalComps;
  22. //==============================================================================
  23. #if ! (defined (MAC_OS_X_VERSION_10_7) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_7)
  24. } // (juce namespace)
  25. @interface NSEvent (JuceDeviceDelta)
  26. - (CGFloat) scrollingDeltaX;
  27. - (CGFloat) scrollingDeltaY;
  28. - (BOOL) hasPreciseScrollingDeltas;
  29. - (BOOL) isDirectionInvertedFromDevice;
  30. @end
  31. namespace juce {
  32. #endif
  33. //==============================================================================
  34. class NSViewComponentPeer : public ComponentPeer
  35. {
  36. public:
  37. NSViewComponentPeer (Component* const comp, const int windowStyleFlags, NSView* viewToAttachTo)
  38. : ComponentPeer (comp, windowStyleFlags),
  39. window (nil),
  40. view (nil),
  41. isSharedWindow (viewToAttachTo != nil),
  42. fullScreen (false),
  43. insideDrawRect (false),
  44. #if USE_COREGRAPHICS_RENDERING
  45. usingCoreGraphics (true),
  46. #else
  47. usingCoreGraphics (false),
  48. #endif
  49. recursiveToFrontCall (false),
  50. isZooming (false),
  51. textWasInserted (false),
  52. notificationCenter (nil)
  53. {
  54. appFocusChangeCallback = appFocusChanged;
  55. isEventBlockedByModalComps = checkEventBlockedByModalComps;
  56. NSRect r = NSMakeRect (0, 0, (CGFloat) component->getWidth(), (CGFloat) component->getHeight());
  57. view = [createViewInstance() initWithFrame: r];
  58. setOwner (view, this);
  59. [view registerForDraggedTypes: getSupportedDragTypes()];
  60. notificationCenter = [NSNotificationCenter defaultCenter];
  61. [notificationCenter addObserver: view
  62. selector: @selector (frameChanged:)
  63. name: NSViewFrameDidChangeNotification
  64. object: view];
  65. if (! isSharedWindow)
  66. [notificationCenter addObserver: view
  67. selector: @selector (frameChanged:)
  68. name: NSWindowDidMoveNotification
  69. object: window];
  70. [view setPostsFrameChangedNotifications: YES];
  71. if (isSharedWindow)
  72. {
  73. window = [viewToAttachTo window];
  74. [viewToAttachTo addSubview: view];
  75. }
  76. else
  77. {
  78. r.origin.x = (CGFloat) component->getX();
  79. r.origin.y = (CGFloat) component->getY();
  80. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  81. window = [createWindowInstance() initWithContentRect: r
  82. styleMask: getNSWindowStyleMask (windowStyleFlags)
  83. backing: NSBackingStoreBuffered
  84. defer: YES];
  85. setOwner (window, this);
  86. [window orderOut: nil];
  87. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  88. [window setDelegate: (id<NSWindowDelegate>) window];
  89. #else
  90. [window setDelegate: window];
  91. #endif
  92. [window setOpaque: component->isOpaque()];
  93. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  94. if (component->isAlwaysOnTop())
  95. [window setLevel: NSFloatingWindowLevel];
  96. [window setContentView: view];
  97. [window setAutodisplay: YES];
  98. [window setAcceptsMouseMovedEvents: YES];
  99. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  100. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  101. [window setReleasedWhenClosed: YES];
  102. [window retain];
  103. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  104. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  105. #if defined (MAC_OS_X_VERSION_10_7) && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7)
  106. if ((windowStyleFlags & (windowHasMaximiseButton | windowHasTitleBar)) == (windowHasMaximiseButton | windowHasTitleBar))
  107. [window setCollectionBehavior: NSWindowCollectionBehaviorFullScreenPrimary];
  108. #endif
  109. }
  110. const float alpha = component->getAlpha();
  111. if (alpha < 1.0f)
  112. setAlpha (alpha);
  113. setTitle (component->getName());
  114. }
  115. ~NSViewComponentPeer()
  116. {
  117. [notificationCenter removeObserver: view];
  118. setOwner (view, nullptr);
  119. [view removeFromSuperview];
  120. [view release];
  121. if (! isSharedWindow)
  122. {
  123. setOwner (window, nullptr);
  124. [window close];
  125. [window release];
  126. }
  127. }
  128. //==============================================================================
  129. void* getNativeHandle() const { return view; }
  130. void setVisible (bool shouldBeVisible)
  131. {
  132. if (isSharedWindow)
  133. {
  134. [view setHidden: ! shouldBeVisible];
  135. }
  136. else
  137. {
  138. if (shouldBeVisible)
  139. {
  140. [window orderFront: nil];
  141. handleBroughtToFront();
  142. }
  143. else
  144. {
  145. [window orderOut: nil];
  146. }
  147. }
  148. }
  149. void setTitle (const String& title)
  150. {
  151. JUCE_AUTORELEASEPOOL
  152. if (! isSharedWindow)
  153. [window setTitle: juceStringToNS (title)];
  154. }
  155. void setPosition (int x, int y)
  156. {
  157. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  158. }
  159. void setSize (int w, int h)
  160. {
  161. setBounds (component->getX(), component->getY(), w, h, false);
  162. }
  163. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  164. {
  165. fullScreen = isNowFullScreen;
  166. NSRect r = NSMakeRect ((CGFloat) x, (CGFloat) y, (CGFloat) jmax (0, w), (CGFloat) jmax (0, h));
  167. if (isSharedWindow)
  168. {
  169. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  170. if ([view frame].size.width != r.size.width
  171. || [view frame].size.height != r.size.height)
  172. {
  173. [view setNeedsDisplay: true];
  174. }
  175. [view setFrame: r];
  176. }
  177. else
  178. {
  179. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  180. [window setFrame: [window frameRectForContentRect: r]
  181. display: true];
  182. }
  183. }
  184. Rectangle<int> getBounds (const bool global) const
  185. {
  186. NSRect r = [view frame];
  187. NSWindow* window = [view window];
  188. if (global && window != nil)
  189. {
  190. r = [[view superview] convertRect: r toView: nil];
  191. #if defined (MAC_OS_X_VERSION_10_7) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_7
  192. r = [window convertRectToScreen: r];
  193. #else
  194. r.origin = [window convertBaseToScreen: r.origin];
  195. #endif
  196. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  197. }
  198. else
  199. {
  200. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  201. }
  202. return Rectangle<int> (convertToRectInt (r));
  203. }
  204. Rectangle<int> getBounds() const
  205. {
  206. return getBounds (! isSharedWindow);
  207. }
  208. Point<int> getScreenPosition() const
  209. {
  210. return getBounds (true).getPosition();
  211. }
  212. Point<int> localToGlobal (const Point<int>& relativePosition)
  213. {
  214. return relativePosition + getScreenPosition();
  215. }
  216. Point<int> globalToLocal (const Point<int>& screenPosition)
  217. {
  218. return screenPosition - getScreenPosition();
  219. }
  220. void setAlpha (float newAlpha)
  221. {
  222. if (! isSharedWindow)
  223. {
  224. [window setAlphaValue: (CGFloat) newAlpha];
  225. }
  226. else
  227. {
  228. #if defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5
  229. [view setAlphaValue: (CGFloat) newAlpha];
  230. #else
  231. if ([view respondsToSelector: @selector (setAlphaValue:)])
  232. {
  233. // PITA dynamic invocation for 10.4 builds..
  234. NSInvocation* inv = [NSInvocation invocationWithMethodSignature: [view methodSignatureForSelector: @selector (setAlphaValue:)]];
  235. [inv setSelector: @selector (setAlphaValue:)];
  236. [inv setTarget: view];
  237. CGFloat cgNewAlpha = (CGFloat) newAlpha;
  238. [inv setArgument: &cgNewAlpha atIndex: 2];
  239. [inv invoke];
  240. }
  241. #endif
  242. }
  243. }
  244. void setMinimised (bool shouldBeMinimised)
  245. {
  246. if (! isSharedWindow)
  247. {
  248. if (shouldBeMinimised)
  249. [window miniaturize: nil];
  250. else
  251. [window deminiaturize: nil];
  252. }
  253. }
  254. bool isMinimised() const
  255. {
  256. return [window isMiniaturized];
  257. }
  258. void setFullScreen (bool shouldBeFullScreen)
  259. {
  260. if (! isSharedWindow)
  261. {
  262. Rectangle<int> r (lastNonFullscreenBounds);
  263. if (isMinimised())
  264. setMinimised (false);
  265. if (fullScreen != shouldBeFullScreen)
  266. {
  267. if (shouldBeFullScreen && hasNativeTitleBar())
  268. {
  269. fullScreen = true;
  270. [window performZoom: nil];
  271. }
  272. else
  273. {
  274. if (shouldBeFullScreen)
  275. r = component->getParentMonitorArea();
  276. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  277. if (r != getComponent()->getBounds() && ! r.isEmpty())
  278. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  279. }
  280. }
  281. }
  282. }
  283. bool isFullScreen() const
  284. {
  285. return fullScreen;
  286. }
  287. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  288. {
  289. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  290. && isPositiveAndBelow (position.getY(), component->getHeight())))
  291. return false;
  292. NSRect frameRect = [view frame];
  293. NSView* v = [view hitTest: NSMakePoint (frameRect.origin.x + position.getX(),
  294. frameRect.origin.y + frameRect.size.height - position.getY())];
  295. if (trueIfInAChildWindow)
  296. return v != nil;
  297. return v == view;
  298. }
  299. BorderSize<int> getFrameSize() const
  300. {
  301. BorderSize<int> b;
  302. if (! isSharedWindow)
  303. {
  304. NSRect v = [view convertRect: [view frame] toView: nil];
  305. NSRect w = [window frame];
  306. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  307. b.setBottom ((int) v.origin.y);
  308. b.setLeft ((int) v.origin.x);
  309. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  310. }
  311. return b;
  312. }
  313. void updateFullscreenStatus()
  314. {
  315. if (hasNativeTitleBar())
  316. {
  317. const Rectangle<int> screen (getFrameSize().subtractedFrom (component->getParentMonitorArea()));
  318. const Rectangle<int> window (component->getScreenBounds());
  319. fullScreen = std::abs (screen.getX() - window.getX()) <= 2
  320. && std::abs (screen.getY() - window.getY()) <= 2
  321. && std::abs (screen.getRight() - window.getRight()) <= 2
  322. && std::abs (screen.getBottom() - window.getBottom()) <= 2;
  323. }
  324. }
  325. bool hasNativeTitleBar() const
  326. {
  327. return (getStyleFlags() & windowHasTitleBar) != 0;
  328. }
  329. bool setAlwaysOnTop (bool alwaysOnTop)
  330. {
  331. if (! isSharedWindow)
  332. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  333. : NSNormalWindowLevel];
  334. return true;
  335. }
  336. void toFront (bool makeActiveWindow)
  337. {
  338. if (isSharedWindow)
  339. [[view superview] addSubview: view
  340. positioned: NSWindowAbove
  341. relativeTo: nil];
  342. if (window != nil && component->isVisible())
  343. {
  344. if (makeActiveWindow)
  345. [window makeKeyAndOrderFront: nil];
  346. else
  347. [window orderFront: nil];
  348. if (! recursiveToFrontCall)
  349. {
  350. recursiveToFrontCall = true;
  351. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  352. handleBroughtToFront();
  353. recursiveToFrontCall = false;
  354. }
  355. }
  356. }
  357. void toBehind (ComponentPeer* other)
  358. {
  359. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  360. jassert (otherPeer != nullptr); // wrong type of window?
  361. if (otherPeer != nullptr)
  362. {
  363. if (isSharedWindow)
  364. {
  365. [[view superview] addSubview: view
  366. positioned: NSWindowBelow
  367. relativeTo: otherPeer->view];
  368. }
  369. else
  370. {
  371. [window orderWindow: NSWindowBelow
  372. relativeTo: [otherPeer->window windowNumber]];
  373. }
  374. }
  375. }
  376. void setIcon (const Image&)
  377. {
  378. // to do..
  379. }
  380. StringArray getAvailableRenderingEngines()
  381. {
  382. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  383. #if USE_COREGRAPHICS_RENDERING
  384. s.add ("CoreGraphics Renderer");
  385. #endif
  386. return s;
  387. }
  388. int getCurrentRenderingEngine() const
  389. {
  390. return usingCoreGraphics ? 1 : 0;
  391. }
  392. void setCurrentRenderingEngine (int index)
  393. {
  394. #if USE_COREGRAPHICS_RENDERING
  395. if (usingCoreGraphics != (index > 0))
  396. {
  397. usingCoreGraphics = index > 0;
  398. [view setNeedsDisplay: true];
  399. }
  400. #endif
  401. }
  402. void redirectMouseDown (NSEvent* ev)
  403. {
  404. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  405. sendMouseEvent (ev);
  406. }
  407. void redirectMouseUp (NSEvent* ev)
  408. {
  409. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  410. sendMouseEvent (ev);
  411. showArrowCursorIfNeeded();
  412. }
  413. void redirectMouseDrag (NSEvent* ev)
  414. {
  415. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  416. sendMouseEvent (ev);
  417. }
  418. void redirectMouseMove (NSEvent* ev)
  419. {
  420. currentModifiers = currentModifiers.withoutMouseButtons();
  421. sendMouseEvent (ev);
  422. showArrowCursorIfNeeded();
  423. }
  424. void redirectMouseEnter (NSEvent* ev)
  425. {
  426. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  427. currentModifiers = currentModifiers.withoutMouseButtons();
  428. sendMouseEvent (ev);
  429. }
  430. void redirectMouseExit (NSEvent* ev)
  431. {
  432. currentModifiers = currentModifiers.withoutMouseButtons();
  433. sendMouseEvent (ev);
  434. }
  435. void redirectMouseWheel (NSEvent* ev)
  436. {
  437. updateModifiers (ev);
  438. MouseWheelDetails wheel;
  439. wheel.deltaX = 0;
  440. wheel.deltaY = 0;
  441. wheel.isReversed = false;
  442. wheel.isSmooth = false;
  443. #if ! JUCE_PPC
  444. @try
  445. {
  446. #if defined (MAC_OS_X_VERSION_10_7) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
  447. if ([ev respondsToSelector: @selector (isDirectionInvertedFromDevice)])
  448. wheel.isReversed = [ev isDirectionInvertedFromDevice];
  449. if ([ev respondsToSelector: @selector (hasPreciseScrollingDeltas)])
  450. {
  451. if ([ev hasPreciseScrollingDeltas])
  452. {
  453. const float scale = 0.5f / 256.0f;
  454. wheel.deltaX = [ev scrollingDeltaX] * scale;
  455. wheel.deltaY = [ev scrollingDeltaY] * scale;
  456. wheel.isSmooth = true;
  457. }
  458. }
  459. else
  460. #endif
  461. if ([ev respondsToSelector: @selector (deviceDeltaX)])
  462. {
  463. const float scale = 0.5f / 256.0f;
  464. wheel.deltaX = scale * (float) objc_msgSend_fpret (ev, @selector (deviceDeltaX));
  465. wheel.deltaY = scale * (float) objc_msgSend_fpret (ev, @selector (deviceDeltaY));
  466. }
  467. }
  468. @catch (...)
  469. {}
  470. #endif
  471. if (wheel.deltaX == 0 && wheel.deltaY == 0)
  472. {
  473. const float scale = 10.0f / 256.0f;
  474. wheel.deltaX = [ev deltaX] * scale;
  475. wheel.deltaY = [ev deltaY] * scale;
  476. }
  477. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), wheel);
  478. }
  479. void sendMouseEvent (NSEvent* ev)
  480. {
  481. updateModifiers (ev);
  482. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  483. }
  484. bool handleKeyEvent (NSEvent* ev, bool isKeyDown)
  485. {
  486. String unicode (nsStringToJuce ([ev characters]));
  487. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  488. int keyCode = getKeyCodeFromEvent (ev);
  489. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  490. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  491. if (unicode.isNotEmpty() || keyCode != 0)
  492. {
  493. if (isKeyDown)
  494. {
  495. bool used = false;
  496. while (unicode.length() > 0)
  497. {
  498. juce_wchar textCharacter = unicode[0];
  499. unicode = unicode.substring (1);
  500. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  501. textCharacter = 0;
  502. used = handleKeyUpOrDown (true) || used;
  503. used = handleKeyPress (keyCode, textCharacter) || used;
  504. }
  505. return used;
  506. }
  507. else
  508. {
  509. if (handleKeyUpOrDown (false))
  510. return true;
  511. }
  512. }
  513. return false;
  514. }
  515. bool redirectKeyDown (NSEvent* ev)
  516. {
  517. updateKeysDown (ev, true);
  518. bool used = handleKeyEvent (ev, true);
  519. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  520. {
  521. // for command keys, the key-up event is thrown away, so simulate one..
  522. updateKeysDown (ev, false);
  523. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  524. }
  525. // (If we're running modally, don't allow unused keystrokes to be passed
  526. // along to other blocked views..)
  527. if (Component::getCurrentlyModalComponent() != nullptr)
  528. used = true;
  529. return used;
  530. }
  531. bool redirectKeyUp (NSEvent* ev)
  532. {
  533. updateKeysDown (ev, false);
  534. return handleKeyEvent (ev, false)
  535. || Component::getCurrentlyModalComponent() != nullptr;
  536. }
  537. void redirectModKeyChange (NSEvent* ev)
  538. {
  539. keysCurrentlyDown.clear();
  540. handleKeyUpOrDown (true);
  541. updateModifiers (ev);
  542. handleModifierKeysChange();
  543. }
  544. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  545. bool redirectPerformKeyEquivalent (NSEvent* ev)
  546. {
  547. if ([ev type] == NSKeyDown)
  548. return redirectKeyDown (ev);
  549. else if ([ev type] == NSKeyUp)
  550. return redirectKeyUp (ev);
  551. return false;
  552. }
  553. #endif
  554. bool isOpaque()
  555. {
  556. return component == nullptr || component->isOpaque();
  557. }
  558. void drawRect (NSRect r)
  559. {
  560. if (r.size.width < 1.0f || r.size.height < 1.0f)
  561. return;
  562. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  563. if (! component->isOpaque())
  564. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  565. #if USE_COREGRAPHICS_RENDERING
  566. if (usingCoreGraphics)
  567. {
  568. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  569. insideDrawRect = true;
  570. handlePaint (context);
  571. insideDrawRect = false;
  572. }
  573. else
  574. #endif
  575. {
  576. const int xOffset = -roundToInt (r.origin.x);
  577. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  578. const int clipW = (int) (r.size.width + 0.5f);
  579. const int clipH = (int) (r.size.height + 0.5f);
  580. RectangleList clip;
  581. getClipRects (clip, xOffset, yOffset, clipW, clipH);
  582. if (! clip.isEmpty())
  583. {
  584. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  585. clipW, clipH, ! getComponent()->isOpaque());
  586. {
  587. ScopedPointer<LowLevelGraphicsContext> context (component->getLookAndFeel()
  588. .createGraphicsContext (temp, Point<int> (xOffset, yOffset), clip));
  589. insideDrawRect = true;
  590. handlePaint (*context);
  591. insideDrawRect = false;
  592. }
  593. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  594. CGImageRef image = juce_createCoreGraphicsImage (temp, false, colourSpace, false);
  595. CGColorSpaceRelease (colourSpace);
  596. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, clipW, clipH), image);
  597. CGImageRelease (image);
  598. }
  599. }
  600. }
  601. bool canBecomeKeyWindow()
  602. {
  603. return (getStyleFlags() & juce::ComponentPeer::windowIgnoresKeyPresses) == 0;
  604. }
  605. void becomeKeyWindow()
  606. {
  607. handleBroughtToFront();
  608. grabFocus();
  609. }
  610. bool windowShouldClose()
  611. {
  612. if (! isValidPeer (this))
  613. return YES;
  614. handleUserClosingWindow();
  615. return NO;
  616. }
  617. void redirectMovedOrResized()
  618. {
  619. updateFullscreenStatus();
  620. handleMovedOrResized();
  621. }
  622. void viewMovedToWindow()
  623. {
  624. if (isSharedWindow)
  625. window = [view window];
  626. }
  627. NSRect constrainRect (NSRect r)
  628. {
  629. if (constrainer != nullptr
  630. #if defined (MAC_OS_X_VERSION_10_7) && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7)
  631. && ([window styleMask] & NSFullScreenWindowMask) == 0
  632. #endif
  633. )
  634. {
  635. NSRect current = [window frame];
  636. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  637. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  638. Rectangle<int> pos (convertToRectInt (r));
  639. Rectangle<int> original (convertToRectInt (current));
  640. const Rectangle<int> screenBounds (Desktop::getInstance().getDisplays().getTotalBounds (true));
  641. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_6
  642. if ([window inLiveResize])
  643. #else
  644. if ([window respondsToSelector: @selector (inLiveResize)]
  645. && [window performSelector: @selector (inLiveResize)])
  646. #endif
  647. {
  648. constrainer->checkBounds (pos, original, screenBounds,
  649. false, false, true, true);
  650. }
  651. else
  652. {
  653. constrainer->checkBounds (pos, original, screenBounds,
  654. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  655. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  656. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  657. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  658. }
  659. r.origin.x = pos.getX();
  660. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  661. r.size.width = pos.getWidth();
  662. r.size.height = pos.getHeight();
  663. }
  664. return r;
  665. }
  666. static void showArrowCursorIfNeeded()
  667. {
  668. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  669. if (mouse.getComponentUnderMouse() == nullptr
  670. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == nullptr)
  671. {
  672. [[NSCursor arrowCursor] set];
  673. }
  674. }
  675. static void updateModifiers (NSEvent* e)
  676. {
  677. updateModifiers ([e modifierFlags]);
  678. }
  679. static void updateModifiers (const NSUInteger flags)
  680. {
  681. int m = 0;
  682. if ((flags & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  683. if ((flags & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  684. if ((flags & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  685. if ((flags & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  686. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  687. }
  688. static void updateKeysDown (NSEvent* ev, bool isKeyDown)
  689. {
  690. updateModifiers (ev);
  691. int keyCode = getKeyCodeFromEvent (ev);
  692. if (keyCode != 0)
  693. {
  694. if (isKeyDown)
  695. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  696. else
  697. keysCurrentlyDown.removeValue (keyCode);
  698. }
  699. }
  700. static int getKeyCodeFromEvent (NSEvent* ev)
  701. {
  702. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  703. int keyCode = unmodified[0];
  704. if (keyCode == 0x19) // (backwards-tab)
  705. keyCode = '\t';
  706. else if (keyCode == 0x03) // (enter)
  707. keyCode = '\r';
  708. else
  709. keyCode = (int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  710. if (([ev modifierFlags] & NSNumericPadKeyMask) != 0)
  711. {
  712. const int numPadConversions[] = { '0', KeyPress::numberPad0, '1', KeyPress::numberPad1,
  713. '2', KeyPress::numberPad2, '3', KeyPress::numberPad3,
  714. '4', KeyPress::numberPad4, '5', KeyPress::numberPad5,
  715. '6', KeyPress::numberPad6, '7', KeyPress::numberPad7,
  716. '8', KeyPress::numberPad8, '9', KeyPress::numberPad9,
  717. '+', KeyPress::numberPadAdd, '-', KeyPress::numberPadSubtract,
  718. '*', KeyPress::numberPadMultiply, '/', KeyPress::numberPadDivide,
  719. '.', KeyPress::numberPadDecimalPoint, '=', KeyPress::numberPadEquals };
  720. for (int i = 0; i < numElementsInArray (numPadConversions); i += 2)
  721. if (keyCode == numPadConversions [i])
  722. keyCode = numPadConversions [i + 1];
  723. }
  724. return keyCode;
  725. }
  726. static int64 getMouseTime (NSEvent* e)
  727. {
  728. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  729. + (int64) ([e timestamp] * 1000.0);
  730. }
  731. static Point<int> getMousePos (NSEvent* e, NSView* view)
  732. {
  733. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  734. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  735. }
  736. static int getModifierForButtonNumber (const NSInteger num)
  737. {
  738. return num == 0 ? ModifierKeys::leftButtonModifier
  739. : (num == 1 ? ModifierKeys::rightButtonModifier
  740. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  741. }
  742. static unsigned int getNSWindowStyleMask (const int flags) noexcept
  743. {
  744. unsigned int style = (flags & windowHasTitleBar) != 0 ? NSTitledWindowMask
  745. : NSBorderlessWindowMask;
  746. if ((flags & windowHasMinimiseButton) != 0) style |= NSMiniaturizableWindowMask;
  747. if ((flags & windowHasCloseButton) != 0) style |= NSClosableWindowMask;
  748. if ((flags & windowIsResizable) != 0) style |= NSResizableWindowMask;
  749. return style;
  750. }
  751. static NSArray* getSupportedDragTypes()
  752. {
  753. return [NSArray arrayWithObjects: NSFilenamesPboardType, NSFilesPromisePboardType, NSStringPboardType, nil];
  754. }
  755. BOOL sendDragCallback (const int type, id <NSDraggingInfo> sender)
  756. {
  757. NSPasteboard* pasteboard = [sender draggingPasteboard];
  758. NSString* contentType = [pasteboard availableTypeFromArray: getSupportedDragTypes()];
  759. if (contentType == nil)
  760. return false;
  761. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  762. ComponentPeer::DragInfo dragInfo;
  763. dragInfo.position.setXY ((int) p.x, (int) ([view frame].size.height - p.y));
  764. if (contentType == NSStringPboardType)
  765. dragInfo.text = nsStringToJuce ([pasteboard stringForType: NSStringPboardType]);
  766. else
  767. dragInfo.files = getDroppedFiles (pasteboard, contentType);
  768. if (dragInfo.files.size() > 0 || dragInfo.text.isNotEmpty())
  769. {
  770. switch (type)
  771. {
  772. case 0: return handleDragMove (dragInfo);
  773. case 1: return handleDragExit (dragInfo);
  774. case 2: return handleDragDrop (dragInfo);
  775. default: jassertfalse; break;
  776. }
  777. }
  778. return false;
  779. }
  780. StringArray getDroppedFiles (NSPasteboard* pasteboard, NSString* contentType)
  781. {
  782. StringArray files;
  783. NSString* iTunesPasteboardType = nsStringLiteral ("CorePasteboardFlavorType 0x6974756E"); // 'itun'
  784. if (contentType == NSFilesPromisePboardType
  785. && [[pasteboard types] containsObject: iTunesPasteboardType])
  786. {
  787. id list = [pasteboard propertyListForType: iTunesPasteboardType];
  788. if ([list isKindOfClass: [NSDictionary class]])
  789. {
  790. NSDictionary* iTunesDictionary = (NSDictionary*) list;
  791. NSArray* tracks = [iTunesDictionary valueForKey: nsStringLiteral ("Tracks")];
  792. NSEnumerator* enumerator = [tracks objectEnumerator];
  793. NSDictionary* track;
  794. while ((track = [enumerator nextObject]) != nil)
  795. {
  796. NSURL* url = [NSURL URLWithString: [track valueForKey: nsStringLiteral ("Location")]];
  797. if ([url isFileURL])
  798. files.add (nsStringToJuce ([url path]));
  799. }
  800. }
  801. }
  802. else
  803. {
  804. id list = [pasteboard propertyListForType: NSFilenamesPboardType];
  805. if ([list isKindOfClass: [NSArray class]])
  806. {
  807. NSArray* items = (NSArray*) [pasteboard propertyListForType: NSFilenamesPboardType];
  808. for (unsigned int i = 0; i < [items count]; ++i)
  809. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  810. }
  811. }
  812. return files;
  813. }
  814. //==============================================================================
  815. void viewFocusGain()
  816. {
  817. if (currentlyFocusedPeer != this)
  818. {
  819. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  820. currentlyFocusedPeer->handleFocusLoss();
  821. currentlyFocusedPeer = this;
  822. handleFocusGain();
  823. }
  824. }
  825. void viewFocusLoss()
  826. {
  827. if (currentlyFocusedPeer == this)
  828. {
  829. currentlyFocusedPeer = nullptr;
  830. handleFocusLoss();
  831. }
  832. }
  833. bool isFocused() const
  834. {
  835. return isSharedWindow ? this == currentlyFocusedPeer
  836. : [window isKeyWindow];
  837. }
  838. void grabFocus()
  839. {
  840. if (window != nil)
  841. {
  842. [window makeKeyWindow];
  843. [window makeFirstResponder: view];
  844. viewFocusGain();
  845. }
  846. }
  847. void textInputRequired (const Point<int>&) {}
  848. //==============================================================================
  849. void repaint (const Rectangle<int>& area)
  850. {
  851. if (insideDrawRect)
  852. {
  853. class AsyncRepaintMessage : public CallbackMessage
  854. {
  855. public:
  856. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  857. : peer (peer_), rect (rect_)
  858. {}
  859. void messageCallback()
  860. {
  861. if (ComponentPeer::isValidPeer (peer))
  862. peer->repaint (rect);
  863. }
  864. private:
  865. NSViewComponentPeer* const peer;
  866. const Rectangle<int> rect;
  867. };
  868. (new AsyncRepaintMessage (this, area))->post();
  869. }
  870. else
  871. {
  872. [view setNeedsDisplayInRect: NSMakeRect ((CGFloat) area.getX(), [view frame].size.height - (CGFloat) area.getBottom(),
  873. (CGFloat) area.getWidth(), (CGFloat) area.getHeight())];
  874. }
  875. }
  876. void performAnyPendingRepaintsNow()
  877. {
  878. [view displayIfNeeded];
  879. }
  880. //==============================================================================
  881. NSWindow* window;
  882. NSView* view;
  883. bool isSharedWindow, fullScreen, insideDrawRect;
  884. bool usingCoreGraphics, recursiveToFrontCall, isZooming, textWasInserted;
  885. String stringBeingComposed;
  886. NSNotificationCenter* notificationCenter;
  887. static ModifierKeys currentModifiers;
  888. static ComponentPeer* currentlyFocusedPeer;
  889. static Array<int> keysCurrentlyDown;
  890. private:
  891. static NSView* createViewInstance();
  892. static NSWindow* createWindowInstance();
  893. static void setOwner (id viewOrWindow, NSViewComponentPeer* newOwner)
  894. {
  895. object_setInstanceVariable (viewOrWindow, "owner", newOwner);
  896. }
  897. void getClipRects (RectangleList& clip, const int xOffset, const int yOffset, const int clipW, const int clipH)
  898. {
  899. const NSRect* rects = nullptr;
  900. NSInteger numRects = 0;
  901. [view getRectsBeingDrawn: &rects count: &numRects];
  902. const Rectangle<int> clipBounds (clipW, clipH);
  903. const CGFloat viewH = [view frame].size.height;
  904. for (int i = 0; i < numRects; ++i)
  905. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  906. roundToInt (viewH - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  907. roundToInt (rects[i].size.width),
  908. roundToInt (rects[i].size.height))));
  909. }
  910. static void appFocusChanged()
  911. {
  912. keysCurrentlyDown.clear();
  913. if (isValidPeer (currentlyFocusedPeer))
  914. {
  915. if (Process::isForegroundProcess())
  916. {
  917. currentlyFocusedPeer->handleFocusGain();
  918. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  919. }
  920. else
  921. {
  922. currentlyFocusedPeer->handleFocusLoss();
  923. }
  924. }
  925. }
  926. static bool checkEventBlockedByModalComps (NSEvent* e)
  927. {
  928. if (Component::getNumCurrentlyModalComponents() == 0)
  929. return false;
  930. NSWindow* const w = [e window];
  931. if (w == nil || [w worksWhenModal])
  932. return false;
  933. bool isKey = false, isInputAttempt = false;
  934. switch ([e type])
  935. {
  936. case NSKeyDown:
  937. case NSKeyUp:
  938. isKey = isInputAttempt = true;
  939. break;
  940. case NSLeftMouseDown:
  941. case NSRightMouseDown:
  942. case NSOtherMouseDown:
  943. isInputAttempt = true;
  944. break;
  945. case NSLeftMouseDragged:
  946. case NSRightMouseDragged:
  947. case NSLeftMouseUp:
  948. case NSRightMouseUp:
  949. case NSOtherMouseUp:
  950. case NSOtherMouseDragged:
  951. if (Desktop::getInstance().getDraggingMouseSource(0) != nullptr)
  952. return false;
  953. break;
  954. case NSMouseMoved:
  955. case NSMouseEntered:
  956. case NSMouseExited:
  957. case NSCursorUpdate:
  958. case NSScrollWheel:
  959. case NSTabletPoint:
  960. case NSTabletProximity:
  961. break;
  962. default:
  963. return false;
  964. }
  965. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  966. {
  967. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  968. NSView* const compView = (NSView*) peer->getNativeHandle();
  969. if ([compView window] == w)
  970. {
  971. if (isKey)
  972. {
  973. if (compView == [w firstResponder])
  974. return false;
  975. }
  976. else
  977. {
  978. NSViewComponentPeer* nsViewPeer = dynamic_cast<NSViewComponentPeer*> (peer);
  979. if ((nsViewPeer == nullptr || ! nsViewPeer->isSharedWindow)
  980. ? NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height))
  981. : NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil], [compView bounds]))
  982. return false;
  983. }
  984. }
  985. }
  986. if (isInputAttempt)
  987. {
  988. if (! [NSApp isActive])
  989. [NSApp activateIgnoringOtherApps: YES];
  990. Component* const modal = Component::getCurrentlyModalComponent (0);
  991. if (modal != nullptr)
  992. modal->inputAttemptWhenModal();
  993. }
  994. return true;
  995. }
  996. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentPeer);
  997. };
  998. //==============================================================================
  999. struct JuceNSViewClass : public ObjCClass <NSView>
  1000. {
  1001. JuceNSViewClass() : ObjCClass <NSView> ("JUCEView_")
  1002. {
  1003. addIvar<NSViewComponentPeer*> ("owner");
  1004. addMethod (@selector (isOpaque), isOpaque, "c@:");
  1005. addMethod (@selector (drawRect:), drawRect, "v@:", @encode (NSRect));
  1006. addMethod (@selector (mouseDown:), mouseDown, "v@:@");
  1007. addMethod (@selector (asyncMouseDown:), asyncMouseDown, "v@:@");
  1008. addMethod (@selector (mouseUp:), mouseUp, "v@:@");
  1009. addMethod (@selector (asyncMouseUp:), asyncMouseUp, "v@:@");
  1010. addMethod (@selector (mouseDragged:), mouseDragged, "v@:@");
  1011. addMethod (@selector (mouseMoved:), mouseMoved, "v@:@");
  1012. addMethod (@selector (mouseEntered:), mouseEntered, "v@:@");
  1013. addMethod (@selector (mouseExited:), mouseExited, "v@:@");
  1014. addMethod (@selector (rightMouseDown:), rightMouseDown, "v@:@");
  1015. addMethod (@selector (rightMouseDragged:), rightMouseDragged, "v@:@");
  1016. addMethod (@selector (rightMouseUp:), rightMouseUp, "v@:@");
  1017. addMethod (@selector (otherMouseDown:), otherMouseDown, "v@:@");
  1018. addMethod (@selector (otherMouseDragged:), otherMouseDragged, "v@:@");
  1019. addMethod (@selector (otherMouseUp:), otherMouseUp, "v@:@");
  1020. addMethod (@selector (scrollWheel:), scrollWheel, "v@:@");
  1021. addMethod (@selector (acceptsFirstMouse:), acceptsFirstMouse, "v@:@");
  1022. addMethod (@selector (frameChanged:), frameChanged, "v@:@");
  1023. addMethod (@selector (viewDidMoveToWindow), viewDidMoveToWindow, "v@:");
  1024. addMethod (@selector (keyDown:), keyDown, "v@:@");
  1025. addMethod (@selector (keyUp:), keyUp, "v@:@");
  1026. addMethod (@selector (insertText:), insertText, "v@:@");
  1027. addMethod (@selector (doCommandBySelector:), doCommandBySelector, "v@::");
  1028. addMethod (@selector (setMarkedText:selectedRange:), setMarkedText, "v@:@", @encode (NSRange));
  1029. addMethod (@selector (unmarkText), unmarkText, "v@:");
  1030. addMethod (@selector (hasMarkedText), hasMarkedText, "c@:");
  1031. addMethod (@selector (conversationIdentifier), conversationIdentifier, "l@:");
  1032. addMethod (@selector (attributedSubstringFromRange:), attributedSubstringFromRange, "@@:", @encode (NSRange));
  1033. addMethod (@selector (markedRange), markedRange, @encode (NSRange), "@:");
  1034. addMethod (@selector (selectedRange), selectedRange, @encode (NSRange), "@:");
  1035. addMethod (@selector (firstRectForCharacterRange:), firstRectForCharacterRange, @encode (NSRect), "@:", @encode (NSRange));
  1036. addMethod (@selector (validAttributesForMarkedText), validAttributesForMarkedText, "@@:");
  1037. addMethod (@selector (flagsChanged:), flagsChanged, "v@:@");
  1038. addMethod (@selector (becomeFirstResponder), becomeFirstResponder, "c@:");
  1039. addMethod (@selector (resignFirstResponder), resignFirstResponder, "c@:");
  1040. addMethod (@selector (acceptsFirstResponder), acceptsFirstResponder, "c@:");
  1041. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  1042. addMethod (@selector (performKeyEquivalent:), performKeyEquivalent, "c@:@");
  1043. #endif
  1044. addMethod (@selector (draggingEntered:), draggingEntered, @encode (NSDragOperation), "@:@");
  1045. addMethod (@selector (draggingUpdated:), draggingUpdated, @encode (NSDragOperation), "@:@");
  1046. addMethod (@selector (draggingEnded:), draggingEnded, "v@:@");
  1047. addMethod (@selector (draggingExited:), draggingExited, "v@:@");
  1048. addMethod (@selector (prepareForDragOperation:), prepareForDragOperation, "c@:@");
  1049. addMethod (@selector (performDragOperation:), performDragOperation, "c@:@");
  1050. addMethod (@selector (concludeDragOperation:), concludeDragOperation, "v@:@");
  1051. addProtocol (@protocol (NSTextInput));
  1052. registerClass();
  1053. }
  1054. private:
  1055. static NSViewComponentPeer* getOwner (id self)
  1056. {
  1057. return getIvar<NSViewComponentPeer*> (self, "owner");
  1058. }
  1059. //==============================================================================
  1060. static void drawRect (id self, SEL, NSRect r)
  1061. {
  1062. NSViewComponentPeer* const owner = getOwner (self);
  1063. if (owner != nullptr)
  1064. owner->drawRect (r);
  1065. }
  1066. static BOOL isOpaque (id self, SEL)
  1067. {
  1068. NSViewComponentPeer* const owner = getOwner (self);
  1069. return owner == nullptr || owner->isOpaque();
  1070. }
  1071. //==============================================================================
  1072. static void mouseDown (id self, SEL, NSEvent* ev)
  1073. {
  1074. if (JUCEApplication::isStandaloneApp())
  1075. [self performSelector: @selector (asyncMouseDown:)
  1076. withObject: ev];
  1077. else
  1078. // In some host situations, the host will stop modal loops from working
  1079. // correctly if they're called from a mouse event, so we'll trigger
  1080. // the event asynchronously..
  1081. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  1082. withObject: ev
  1083. waitUntilDone: NO];
  1084. }
  1085. static void asyncMouseDown (id self, SEL, NSEvent* ev)
  1086. {
  1087. NSViewComponentPeer* const owner = getOwner (self);
  1088. if (owner != nullptr)
  1089. owner->redirectMouseDown (ev);
  1090. }
  1091. static void mouseUp (id self, SEL, NSEvent* ev)
  1092. {
  1093. if (! JUCEApplication::isStandaloneApp())
  1094. [self performSelector: @selector (asyncMouseUp:)
  1095. withObject: ev];
  1096. else
  1097. // In some host situations, the host will stop modal loops from working
  1098. // correctly if they're called from a mouse event, so we'll trigger
  1099. // the event asynchronously..
  1100. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  1101. withObject: ev
  1102. waitUntilDone: NO];
  1103. }
  1104. static void asyncMouseUp (id self, SEL, NSEvent* ev) { NSViewComponentPeer* const owner = getOwner (self); if (owner != nullptr) owner->redirectMouseUp (ev); }
  1105. static void mouseDragged (id self, SEL, NSEvent* ev) { NSViewComponentPeer* const owner = getOwner (self); if (owner != nullptr) owner->redirectMouseDrag (ev); }
  1106. static void mouseMoved (id self, SEL, NSEvent* ev) { NSViewComponentPeer* const owner = getOwner (self); if (owner != nullptr) owner->redirectMouseMove (ev); }
  1107. static void mouseEntered (id self, SEL, NSEvent* ev) { NSViewComponentPeer* const owner = getOwner (self); if (owner != nullptr) owner->redirectMouseEnter (ev); }
  1108. static void mouseExited (id self, SEL, NSEvent* ev) { NSViewComponentPeer* const owner = getOwner (self); if (owner != nullptr) owner->redirectMouseExit (ev); }
  1109. static void scrollWheel (id self, SEL, NSEvent* ev) { NSViewComponentPeer* const owner = getOwner (self); if (owner != nullptr) owner->redirectMouseWheel (ev); }
  1110. static void rightMouseDown (id self, SEL, NSEvent* ev) { [(NSView*) self mouseDown: ev]; }
  1111. static void rightMouseDragged (id self, SEL, NSEvent* ev) { [(NSView*) self mouseDragged: ev]; }
  1112. static void rightMouseUp (id self, SEL, NSEvent* ev) { [(NSView*) self mouseUp: ev]; }
  1113. static void otherMouseDown (id self, SEL, NSEvent* ev) { [(NSView*) self mouseDown: ev]; }
  1114. static void otherMouseDragged (id self, SEL, NSEvent* ev) { [(NSView*) self mouseDragged: ev]; }
  1115. static void otherMouseUp (id self, SEL, NSEvent* ev) { [(NSView*) self mouseUp: ev]; }
  1116. static BOOL acceptsFirstMouse (id, SEL, NSEvent*) { return YES; }
  1117. static void frameChanged (id self, SEL, NSNotification*)
  1118. {
  1119. NSViewComponentPeer* const owner = getOwner (self);
  1120. if (owner != nullptr)
  1121. owner->redirectMovedOrResized();
  1122. }
  1123. static void viewDidMoveToWindow (id self, SEL)
  1124. {
  1125. NSViewComponentPeer* const owner = getOwner (self);
  1126. if (owner != nullptr)
  1127. owner->viewMovedToWindow();
  1128. }
  1129. //==============================================================================
  1130. static void keyDown (id self, SEL, NSEvent* ev)
  1131. {
  1132. NSViewComponentPeer* const owner = getOwner (self);
  1133. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  1134. owner->textWasInserted = false;
  1135. if (target != nullptr)
  1136. [(NSView*) self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  1137. else
  1138. owner->stringBeingComposed = String::empty;
  1139. if ((! owner->textWasInserted) && (owner == nullptr || ! owner->redirectKeyDown (ev)))
  1140. {
  1141. objc_super s = { self, [NSView class] };
  1142. objc_msgSendSuper (&s, @selector (keyDown:), ev);
  1143. }
  1144. }
  1145. static void keyUp (id self, SEL, NSEvent* ev)
  1146. {
  1147. NSViewComponentPeer* const owner = getOwner (self);
  1148. if (owner == nullptr || ! owner->redirectKeyUp (ev))
  1149. {
  1150. objc_super s = { self, [NSView class] };
  1151. objc_msgSendSuper (&s, @selector (keyUp:), ev);
  1152. }
  1153. }
  1154. //==============================================================================
  1155. static void insertText (id self, SEL, id aString)
  1156. {
  1157. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  1158. NSViewComponentPeer* const owner = getOwner (self);
  1159. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  1160. if ([newText length] > 0)
  1161. {
  1162. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  1163. if (target != nullptr)
  1164. {
  1165. target->insertTextAtCaret (nsStringToJuce (newText));
  1166. owner->textWasInserted = true;
  1167. }
  1168. }
  1169. owner->stringBeingComposed = String::empty;
  1170. }
  1171. static void doCommandBySelector (id, SEL, SEL) {}
  1172. static void setMarkedText (id self, SEL, id aString, NSRange)
  1173. {
  1174. NSViewComponentPeer* const owner = getOwner (self);
  1175. owner->stringBeingComposed = nsStringToJuce ([aString isKindOfClass: [NSAttributedString class]]
  1176. ? [aString string] : aString);
  1177. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  1178. if (target != nullptr)
  1179. {
  1180. const Range<int> currentHighlight (target->getHighlightedRegion());
  1181. target->insertTextAtCaret (owner->stringBeingComposed);
  1182. target->setHighlightedRegion (currentHighlight.withLength (owner->stringBeingComposed.length()));
  1183. owner->textWasInserted = true;
  1184. }
  1185. }
  1186. static void unmarkText (id self, SEL)
  1187. {
  1188. NSViewComponentPeer* const owner = getOwner (self);
  1189. if (owner->stringBeingComposed.isNotEmpty())
  1190. {
  1191. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  1192. if (target != nullptr)
  1193. {
  1194. target->insertTextAtCaret (owner->stringBeingComposed);
  1195. owner->textWasInserted = true;
  1196. }
  1197. owner->stringBeingComposed = String::empty;
  1198. }
  1199. }
  1200. static BOOL hasMarkedText (id self, SEL)
  1201. {
  1202. return getOwner (self)->stringBeingComposed.isNotEmpty();
  1203. }
  1204. static long conversationIdentifier (id self, SEL)
  1205. {
  1206. return (long) (pointer_sized_int) self;
  1207. }
  1208. static NSAttributedString* attributedSubstringFromRange (id self, SEL, NSRange theRange)
  1209. {
  1210. NSViewComponentPeer* const owner = getOwner (self);
  1211. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  1212. if (target != nullptr)
  1213. {
  1214. const Range<int> r ((int) theRange.location,
  1215. (int) (theRange.location + theRange.length));
  1216. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  1217. }
  1218. return nil;
  1219. }
  1220. static NSRange markedRange (id self, SEL)
  1221. {
  1222. NSViewComponentPeer* const owner = getOwner (self);
  1223. return owner->stringBeingComposed.isNotEmpty() ? NSMakeRange (0, owner->stringBeingComposed.length())
  1224. : NSMakeRange (NSNotFound, 0);
  1225. }
  1226. static NSRange selectedRange (id self, SEL)
  1227. {
  1228. NSViewComponentPeer* const owner = getOwner (self);
  1229. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  1230. if (target != nullptr)
  1231. {
  1232. const Range<int> highlight (target->getHighlightedRegion());
  1233. if (! highlight.isEmpty())
  1234. return NSMakeRange (highlight.getStart(), highlight.getLength());
  1235. }
  1236. return NSMakeRange (NSNotFound, 0);
  1237. }
  1238. static NSRect firstRectForCharacterRange (id self, SEL, NSRange)
  1239. {
  1240. NSViewComponentPeer* const owner = getOwner (self);
  1241. Component* const comp = dynamic_cast <Component*> (owner->findCurrentTextInputTarget());
  1242. if (comp == nullptr)
  1243. return NSMakeRect (0, 0, 0, 0);
  1244. const Rectangle<int> bounds (comp->getScreenBounds());
  1245. return NSMakeRect (bounds.getX(),
  1246. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  1247. bounds.getWidth(),
  1248. bounds.getHeight());
  1249. }
  1250. static NSUInteger characterIndexForPoint (id, SEL, NSPoint) { return NSNotFound; }
  1251. static NSArray* validAttributesForMarkedText (id, SEL) { return [NSArray array]; }
  1252. //==============================================================================
  1253. static void flagsChanged (id self, SEL, NSEvent* ev)
  1254. {
  1255. NSViewComponentPeer* const owner = getOwner (self);
  1256. if (owner != nullptr)
  1257. owner->redirectModKeyChange (ev);
  1258. }
  1259. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  1260. static BOOL performKeyEquivalent (id self, SEL, NSEvent* ev)
  1261. {
  1262. NSViewComponentPeer* const owner = getOwner (self);
  1263. if (owner != nullptr && owner->redirectPerformKeyEquivalent (ev))
  1264. return true;
  1265. objc_super s = { self, [NSView class] };
  1266. return objc_msgSendSuper (&s, @selector (performKeyEquivalent:), ev) != nil;
  1267. }
  1268. #endif
  1269. static BOOL becomeFirstResponder (id self, SEL)
  1270. {
  1271. NSViewComponentPeer* const owner = getOwner (self);
  1272. if (owner != nullptr)
  1273. owner->viewFocusGain();
  1274. return YES;
  1275. }
  1276. static BOOL resignFirstResponder (id self, SEL)
  1277. {
  1278. NSViewComponentPeer* const owner = getOwner (self);
  1279. if (owner != nullptr)
  1280. owner->viewFocusLoss();
  1281. return YES;
  1282. }
  1283. static BOOL acceptsFirstResponder (id self, SEL)
  1284. {
  1285. NSViewComponentPeer* const owner = getOwner (self);
  1286. return owner != nullptr && owner->canBecomeKeyWindow();
  1287. }
  1288. //==============================================================================
  1289. static NSDragOperation draggingEntered (id self, SEL, id <NSDraggingInfo> sender)
  1290. {
  1291. NSViewComponentPeer* const owner = getOwner (self);
  1292. if (owner != nullptr && owner->sendDragCallback (0, sender))
  1293. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  1294. else
  1295. return NSDragOperationNone;
  1296. }
  1297. static NSDragOperation draggingUpdated (id self, SEL, id <NSDraggingInfo> sender)
  1298. {
  1299. NSViewComponentPeer* const owner = getOwner (self);
  1300. if (owner != nullptr && owner->sendDragCallback (0, sender))
  1301. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  1302. else
  1303. return NSDragOperationNone;
  1304. }
  1305. static void draggingEnded (id self, SEL, id <NSDraggingInfo> sender)
  1306. {
  1307. NSViewComponentPeer* const owner = getOwner (self);
  1308. if (owner != nullptr)
  1309. owner->sendDragCallback (1, sender);
  1310. }
  1311. static void draggingExited (id self, SEL, id <NSDraggingInfo> sender)
  1312. {
  1313. NSViewComponentPeer* const owner = getOwner (self);
  1314. if (owner != nullptr)
  1315. owner->sendDragCallback (1, sender);
  1316. }
  1317. static BOOL prepareForDragOperation (id self, SEL, id <NSDraggingInfo>)
  1318. {
  1319. return YES;
  1320. }
  1321. static BOOL performDragOperation (id self, SEL, id <NSDraggingInfo> sender)
  1322. {
  1323. NSViewComponentPeer* const owner = getOwner (self);
  1324. return owner != nullptr && owner->sendDragCallback (2, sender);
  1325. }
  1326. static void concludeDragOperation (id, SEL, id <NSDraggingInfo>) {}
  1327. };
  1328. //==============================================================================
  1329. struct JuceNSWindowClass : public ObjCClass <NSWindow>
  1330. {
  1331. JuceNSWindowClass() : ObjCClass <NSWindow> ("JUCEWindow_")
  1332. {
  1333. addIvar<NSViewComponentPeer*> ("owner");
  1334. addMethod (@selector (canBecomeKeyWindow), canBecomeKeyWindow, "c@:");
  1335. addMethod (@selector (becomeKeyWindow), becomeKeyWindow, "v@:");
  1336. addMethod (@selector (windowShouldClose:), windowShouldClose, "c@:@");
  1337. addMethod (@selector (constrainFrameRect:toScreen:), constrainFrameRect, @encode (NSRect), "@:", @encode (NSRect*), "@");
  1338. addMethod (@selector (windowWillResize:toSize:), windowWillResize, @encode (NSSize), "@:@", @encode (NSSize));
  1339. addMethod (@selector (zoom), zoom, "v@:@");
  1340. addMethod (@selector (windowWillMove), windowWillMove, "v@:@");
  1341. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  1342. addProtocol (@protocol (NSWindowDelegate));
  1343. #endif
  1344. registerClass();
  1345. }
  1346. private:
  1347. static NSViewComponentPeer* getOwner (id self)
  1348. {
  1349. return getIvar<NSViewComponentPeer*> (self, "owner");
  1350. }
  1351. //==============================================================================
  1352. static BOOL canBecomeKeyWindow (id self, SEL)
  1353. {
  1354. NSViewComponentPeer* const owner = getOwner (self);
  1355. return owner != nullptr && owner->canBecomeKeyWindow();
  1356. }
  1357. static void becomeKeyWindow (id self, SEL)
  1358. {
  1359. sendSuperclassMessage (self, @selector (becomeKeyWindow));
  1360. NSViewComponentPeer* const owner = getOwner (self);
  1361. if (owner != nullptr)
  1362. owner->becomeKeyWindow();
  1363. }
  1364. static BOOL windowShouldClose (id self, SEL, id /*window*/)
  1365. {
  1366. NSViewComponentPeer* const owner = getOwner (self);
  1367. return owner == nullptr || owner->windowShouldClose();
  1368. }
  1369. static NSRect constrainFrameRect (id self, SEL, NSRect frameRect, NSScreen*)
  1370. {
  1371. NSViewComponentPeer* const owner = getOwner (self);
  1372. if (owner != nullptr)
  1373. frameRect = owner->constrainRect (frameRect);
  1374. return frameRect;
  1375. }
  1376. static NSSize windowWillResize (id self, SEL, NSWindow*, NSSize proposedFrameSize)
  1377. {
  1378. NSViewComponentPeer* const owner = getOwner (self);
  1379. if (owner->isZooming)
  1380. return proposedFrameSize;
  1381. NSRect frameRect = [(NSWindow*) self frame];
  1382. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  1383. frameRect.size = proposedFrameSize;
  1384. if (owner != nullptr)
  1385. frameRect = owner->constrainRect (frameRect);
  1386. if (juce::Component::getCurrentlyModalComponent() != nullptr
  1387. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  1388. && owner->hasNativeTitleBar())
  1389. juce::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  1390. return frameRect.size;
  1391. }
  1392. static void zoom (id self, SEL, id sender)
  1393. {
  1394. NSViewComponentPeer* const owner = getOwner (self);
  1395. owner->isZooming = true;
  1396. objc_super s = { self, [NSWindow class] };
  1397. objc_msgSendSuper (&s, @selector(zoom), sender);
  1398. owner->isZooming = false;
  1399. owner->redirectMovedOrResized();
  1400. }
  1401. static void windowWillMove (id self, SEL, NSNotification*)
  1402. {
  1403. NSViewComponentPeer* const owner = getOwner (self);
  1404. if (juce::Component::getCurrentlyModalComponent() != nullptr
  1405. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  1406. && owner->hasNativeTitleBar())
  1407. juce::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  1408. }
  1409. };
  1410. NSView* NSViewComponentPeer::createViewInstance()
  1411. {
  1412. static JuceNSViewClass cls;
  1413. return cls.createInstance();
  1414. }
  1415. NSWindow* NSViewComponentPeer::createWindowInstance()
  1416. {
  1417. static JuceNSWindowClass cls;
  1418. return cls.createInstance();
  1419. }
  1420. //==============================================================================
  1421. ModifierKeys NSViewComponentPeer::currentModifiers;
  1422. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = nullptr;
  1423. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  1424. //==============================================================================
  1425. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  1426. {
  1427. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  1428. return true;
  1429. if (keyCode >= 'A' && keyCode <= 'Z'
  1430. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  1431. return true;
  1432. if (keyCode >= 'a' && keyCode <= 'z'
  1433. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  1434. return true;
  1435. return false;
  1436. }
  1437. ModifierKeys ModifierKeys::getCurrentModifiersRealtime() noexcept
  1438. {
  1439. if ([NSEvent respondsToSelector: @selector (modifierFlags)])
  1440. NSViewComponentPeer::updateModifiers ((NSUInteger) [NSEvent modifierFlags]);
  1441. return NSViewComponentPeer::currentModifiers;
  1442. }
  1443. void ModifierKeys::updateCurrentModifiers() noexcept
  1444. {
  1445. currentModifiers = NSViewComponentPeer::currentModifiers;
  1446. }
  1447. //==============================================================================
  1448. void Desktop::createMouseInputSources()
  1449. {
  1450. mouseSources.add (new MouseInputSource (0, true));
  1451. }
  1452. //==============================================================================
  1453. void Desktop::setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  1454. {
  1455. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  1456. NSViewComponentPeer* const peer = dynamic_cast<NSViewComponentPeer*> (kioskModeComponent->getPeer());
  1457. #if defined (MAC_OS_X_VERSION_10_7) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
  1458. if (peer != nullptr
  1459. && peer->hasNativeTitleBar()
  1460. && [peer->window respondsToSelector: @selector (toggleFullScreen:)])
  1461. {
  1462. [peer->window performSelector: @selector (toggleFullScreen:)
  1463. withObject: [NSNumber numberWithBool: (BOOL) enableOrDisable]];
  1464. }
  1465. else
  1466. #endif
  1467. {
  1468. if (enableOrDisable)
  1469. {
  1470. if (peer->hasNativeTitleBar())
  1471. [peer->window setStyleMask: NSBorderlessWindowMask];
  1472. [NSApp setPresentationOptions: (allowMenusAndBars ? (NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)
  1473. : (NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar))];
  1474. kioskModeComponent->setBounds (Desktop::getInstance().getDisplays().getMainDisplay().totalArea);
  1475. peer->becomeKeyWindow();
  1476. }
  1477. else
  1478. {
  1479. if (peer->hasNativeTitleBar())
  1480. {
  1481. [peer->window setStyleMask: (NSViewComponentPeer::getNSWindowStyleMask (peer->getStyleFlags()))];
  1482. peer->setTitle (peer->component->getName()); // required to force the OS to update the title
  1483. }
  1484. [NSApp setPresentationOptions: NSApplicationPresentationDefault];
  1485. }
  1486. }
  1487. #elif JUCE_SUPPORT_CARBON
  1488. if (enableOrDisable)
  1489. {
  1490. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  1491. kioskModeComponent->setBounds (Desktop::getInstance().getDisplays().getMainDisplay().totalArea);
  1492. }
  1493. else
  1494. {
  1495. SetSystemUIMode (kUIModeNormal, 0);
  1496. }
  1497. #else
  1498. // If you're targeting OSes earlier than 10.6 and want to use this feature,
  1499. // you'll need to enable JUCE_SUPPORT_CARBON.
  1500. jassertfalse;
  1501. #endif
  1502. }
  1503. //==============================================================================
  1504. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  1505. {
  1506. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  1507. }
  1508. //==============================================================================
  1509. const int KeyPress::spaceKey = ' ';
  1510. const int KeyPress::returnKey = 0x0d;
  1511. const int KeyPress::escapeKey = 0x1b;
  1512. const int KeyPress::backspaceKey = 0x7f;
  1513. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  1514. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  1515. const int KeyPress::upKey = NSUpArrowFunctionKey;
  1516. const int KeyPress::downKey = NSDownArrowFunctionKey;
  1517. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  1518. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  1519. const int KeyPress::endKey = NSEndFunctionKey;
  1520. const int KeyPress::homeKey = NSHomeFunctionKey;
  1521. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  1522. const int KeyPress::insertKey = -1;
  1523. const int KeyPress::tabKey = 9;
  1524. const int KeyPress::F1Key = NSF1FunctionKey;
  1525. const int KeyPress::F2Key = NSF2FunctionKey;
  1526. const int KeyPress::F3Key = NSF3FunctionKey;
  1527. const int KeyPress::F4Key = NSF4FunctionKey;
  1528. const int KeyPress::F5Key = NSF5FunctionKey;
  1529. const int KeyPress::F6Key = NSF6FunctionKey;
  1530. const int KeyPress::F7Key = NSF7FunctionKey;
  1531. const int KeyPress::F8Key = NSF8FunctionKey;
  1532. const int KeyPress::F9Key = NSF9FunctionKey;
  1533. const int KeyPress::F10Key = NSF10FunctionKey;
  1534. const int KeyPress::F11Key = NSF1FunctionKey;
  1535. const int KeyPress::F12Key = NSF12FunctionKey;
  1536. const int KeyPress::F13Key = NSF13FunctionKey;
  1537. const int KeyPress::F14Key = NSF14FunctionKey;
  1538. const int KeyPress::F15Key = NSF15FunctionKey;
  1539. const int KeyPress::F16Key = NSF16FunctionKey;
  1540. const int KeyPress::numberPad0 = 0x30020;
  1541. const int KeyPress::numberPad1 = 0x30021;
  1542. const int KeyPress::numberPad2 = 0x30022;
  1543. const int KeyPress::numberPad3 = 0x30023;
  1544. const int KeyPress::numberPad4 = 0x30024;
  1545. const int KeyPress::numberPad5 = 0x30025;
  1546. const int KeyPress::numberPad6 = 0x30026;
  1547. const int KeyPress::numberPad7 = 0x30027;
  1548. const int KeyPress::numberPad8 = 0x30028;
  1549. const int KeyPress::numberPad9 = 0x30029;
  1550. const int KeyPress::numberPadAdd = 0x3002a;
  1551. const int KeyPress::numberPadSubtract = 0x3002b;
  1552. const int KeyPress::numberPadMultiply = 0x3002c;
  1553. const int KeyPress::numberPadDivide = 0x3002d;
  1554. const int KeyPress::numberPadSeparator = 0x3002e;
  1555. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  1556. const int KeyPress::numberPadEquals = 0x30030;
  1557. const int KeyPress::numberPadDelete = 0x30031;
  1558. const int KeyPress::playKey = 0x30000;
  1559. const int KeyPress::stopKey = 0x30001;
  1560. const int KeyPress::fastForwardKey = 0x30002;
  1561. const int KeyPress::rewindKey = 0x30003;