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.

1897 lines
70KB

  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 = window.expanded (2, 2).contains (screen);
  320. }
  321. }
  322. bool hasNativeTitleBar() const
  323. {
  324. return (getStyleFlags() & windowHasTitleBar) != 0;
  325. }
  326. bool setAlwaysOnTop (bool alwaysOnTop)
  327. {
  328. if (! isSharedWindow)
  329. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  330. : NSNormalWindowLevel];
  331. return true;
  332. }
  333. void toFront (bool makeActiveWindow)
  334. {
  335. if (isSharedWindow)
  336. [[view superview] addSubview: view
  337. positioned: NSWindowAbove
  338. relativeTo: nil];
  339. if (window != nil && component->isVisible())
  340. {
  341. if (makeActiveWindow)
  342. [window makeKeyAndOrderFront: nil];
  343. else
  344. [window orderFront: nil];
  345. if (! recursiveToFrontCall)
  346. {
  347. recursiveToFrontCall = true;
  348. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  349. handleBroughtToFront();
  350. recursiveToFrontCall = false;
  351. }
  352. }
  353. }
  354. void toBehind (ComponentPeer* other)
  355. {
  356. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  357. jassert (otherPeer != nullptr); // wrong type of window?
  358. if (otherPeer != nullptr)
  359. {
  360. if (isSharedWindow)
  361. {
  362. [[view superview] addSubview: view
  363. positioned: NSWindowBelow
  364. relativeTo: otherPeer->view];
  365. }
  366. else
  367. {
  368. [window orderWindow: NSWindowBelow
  369. relativeTo: [otherPeer->window windowNumber]];
  370. }
  371. }
  372. }
  373. void setIcon (const Image&)
  374. {
  375. // to do..
  376. }
  377. StringArray getAvailableRenderingEngines()
  378. {
  379. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  380. #if USE_COREGRAPHICS_RENDERING
  381. s.add ("CoreGraphics Renderer");
  382. #endif
  383. return s;
  384. }
  385. int getCurrentRenderingEngine() const
  386. {
  387. return usingCoreGraphics ? 1 : 0;
  388. }
  389. void setCurrentRenderingEngine (int index)
  390. {
  391. #if USE_COREGRAPHICS_RENDERING
  392. if (usingCoreGraphics != (index > 0))
  393. {
  394. usingCoreGraphics = index > 0;
  395. [view setNeedsDisplay: true];
  396. }
  397. #endif
  398. }
  399. void redirectMouseDown (NSEvent* ev)
  400. {
  401. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  402. sendMouseEvent (ev);
  403. }
  404. void redirectMouseUp (NSEvent* ev)
  405. {
  406. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  407. sendMouseEvent (ev);
  408. showArrowCursorIfNeeded();
  409. }
  410. void redirectMouseDrag (NSEvent* ev)
  411. {
  412. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  413. sendMouseEvent (ev);
  414. }
  415. void redirectMouseMove (NSEvent* ev)
  416. {
  417. currentModifiers = currentModifiers.withoutMouseButtons();
  418. sendMouseEvent (ev);
  419. showArrowCursorIfNeeded();
  420. }
  421. void redirectMouseEnter (NSEvent* ev)
  422. {
  423. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  424. currentModifiers = currentModifiers.withoutMouseButtons();
  425. sendMouseEvent (ev);
  426. }
  427. void redirectMouseExit (NSEvent* ev)
  428. {
  429. currentModifiers = currentModifiers.withoutMouseButtons();
  430. sendMouseEvent (ev);
  431. }
  432. void redirectMouseWheel (NSEvent* ev)
  433. {
  434. updateModifiers (ev);
  435. MouseWheelDetails wheel;
  436. wheel.deltaX = 0;
  437. wheel.deltaY = 0;
  438. wheel.isReversed = false;
  439. wheel.isSmooth = false;
  440. #if ! JUCE_PPC
  441. @try
  442. {
  443. #if defined (MAC_OS_X_VERSION_10_7) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
  444. if ([ev respondsToSelector: @selector (isDirectionInvertedFromDevice)])
  445. wheel.isReversed = [ev isDirectionInvertedFromDevice];
  446. if ([ev respondsToSelector: @selector (hasPreciseScrollingDeltas)])
  447. {
  448. if ([ev hasPreciseScrollingDeltas])
  449. {
  450. const float scale = 0.5f / 256.0f;
  451. wheel.deltaX = [ev scrollingDeltaX] * scale;
  452. wheel.deltaY = [ev scrollingDeltaY] * scale;
  453. wheel.isSmooth = true;
  454. }
  455. }
  456. else
  457. #endif
  458. if ([ev respondsToSelector: @selector (deviceDeltaX)])
  459. {
  460. const float scale = 0.5f / 256.0f;
  461. wheel.deltaX = scale * (float) objc_msgSend_fpret (ev, @selector (deviceDeltaX));
  462. wheel.deltaY = scale * (float) objc_msgSend_fpret (ev, @selector (deviceDeltaY));
  463. }
  464. }
  465. @catch (...)
  466. {}
  467. #endif
  468. if (wheel.deltaX == 0 && wheel.deltaY == 0)
  469. {
  470. const float scale = 10.0f / 256.0f;
  471. wheel.deltaX = [ev deltaX] * scale;
  472. wheel.deltaY = [ev deltaY] * scale;
  473. }
  474. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), wheel);
  475. }
  476. void sendMouseEvent (NSEvent* ev)
  477. {
  478. updateModifiers (ev);
  479. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  480. }
  481. bool handleKeyEvent (NSEvent* ev, bool isKeyDown)
  482. {
  483. String unicode (nsStringToJuce ([ev characters]));
  484. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  485. int keyCode = getKeyCodeFromEvent (ev);
  486. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  487. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  488. if (unicode.isNotEmpty() || keyCode != 0)
  489. {
  490. if (isKeyDown)
  491. {
  492. bool used = false;
  493. while (unicode.length() > 0)
  494. {
  495. juce_wchar textCharacter = unicode[0];
  496. unicode = unicode.substring (1);
  497. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  498. textCharacter = 0;
  499. used = handleKeyUpOrDown (true) || used;
  500. used = handleKeyPress (keyCode, textCharacter) || used;
  501. }
  502. return used;
  503. }
  504. else
  505. {
  506. if (handleKeyUpOrDown (false))
  507. return true;
  508. }
  509. }
  510. return false;
  511. }
  512. bool redirectKeyDown (NSEvent* ev)
  513. {
  514. updateKeysDown (ev, true);
  515. bool used = handleKeyEvent (ev, true);
  516. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  517. {
  518. // for command keys, the key-up event is thrown away, so simulate one..
  519. updateKeysDown (ev, false);
  520. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  521. }
  522. // (If we're running modally, don't allow unused keystrokes to be passed
  523. // along to other blocked views..)
  524. if (Component::getCurrentlyModalComponent() != nullptr)
  525. used = true;
  526. return used;
  527. }
  528. bool redirectKeyUp (NSEvent* ev)
  529. {
  530. updateKeysDown (ev, false);
  531. return handleKeyEvent (ev, false)
  532. || Component::getCurrentlyModalComponent() != nullptr;
  533. }
  534. void redirectModKeyChange (NSEvent* ev)
  535. {
  536. keysCurrentlyDown.clear();
  537. handleKeyUpOrDown (true);
  538. updateModifiers (ev);
  539. handleModifierKeysChange();
  540. }
  541. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  542. bool redirectPerformKeyEquivalent (NSEvent* ev)
  543. {
  544. if ([ev type] == NSKeyDown)
  545. return redirectKeyDown (ev);
  546. else if ([ev type] == NSKeyUp)
  547. return redirectKeyUp (ev);
  548. return false;
  549. }
  550. #endif
  551. bool isOpaque()
  552. {
  553. return component == nullptr || component->isOpaque();
  554. }
  555. void drawRect (NSRect r)
  556. {
  557. if (r.size.width < 1.0f || r.size.height < 1.0f)
  558. return;
  559. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  560. if (! component->isOpaque())
  561. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  562. #if USE_COREGRAPHICS_RENDERING
  563. if (usingCoreGraphics)
  564. {
  565. float displayScale = 1.0f;
  566. #if defined (MAC_OS_X_VERSION_10_7) && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7)
  567. NSScreen* screen = [[view window] screen];
  568. if ([screen respondsToSelector: @selector (backingScaleFactor)])
  569. displayScale = screen.backingScaleFactor;
  570. #endif
  571. CoreGraphicsContext context (cg, (float) [view frame].size.height, displayScale);
  572. insideDrawRect = true;
  573. handlePaint (context);
  574. insideDrawRect = false;
  575. }
  576. else
  577. #endif
  578. {
  579. const int xOffset = -roundToInt (r.origin.x);
  580. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  581. const int clipW = (int) (r.size.width + 0.5f);
  582. const int clipH = (int) (r.size.height + 0.5f);
  583. RectangleList clip;
  584. getClipRects (clip, xOffset, yOffset, clipW, clipH);
  585. if (! clip.isEmpty())
  586. {
  587. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  588. clipW, clipH, ! getComponent()->isOpaque());
  589. {
  590. ScopedPointer<LowLevelGraphicsContext> context (component->getLookAndFeel()
  591. .createGraphicsContext (temp, Point<int> (xOffset, yOffset), clip));
  592. insideDrawRect = true;
  593. handlePaint (*context);
  594. insideDrawRect = false;
  595. }
  596. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  597. CGImageRef image = juce_createCoreGraphicsImage (temp, false, colourSpace, false);
  598. CGColorSpaceRelease (colourSpace);
  599. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, clipW, clipH), image);
  600. CGImageRelease (image);
  601. }
  602. }
  603. }
  604. bool canBecomeKeyWindow()
  605. {
  606. return (getStyleFlags() & juce::ComponentPeer::windowIgnoresKeyPresses) == 0;
  607. }
  608. void becomeKeyWindow()
  609. {
  610. handleBroughtToFront();
  611. grabFocus();
  612. }
  613. bool windowShouldClose()
  614. {
  615. if (! isValidPeer (this))
  616. return YES;
  617. handleUserClosingWindow();
  618. return NO;
  619. }
  620. void redirectMovedOrResized()
  621. {
  622. updateFullscreenStatus();
  623. handleMovedOrResized();
  624. }
  625. void viewMovedToWindow()
  626. {
  627. if (isSharedWindow)
  628. window = [view window];
  629. }
  630. NSRect constrainRect (NSRect r)
  631. {
  632. if (constrainer != nullptr
  633. #if defined (MAC_OS_X_VERSION_10_7) && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7)
  634. && ([window styleMask] & NSFullScreenWindowMask) == 0
  635. #endif
  636. )
  637. {
  638. NSRect current = [window frame];
  639. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  640. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  641. Rectangle<int> pos (convertToRectInt (r));
  642. Rectangle<int> original (convertToRectInt (current));
  643. const Rectangle<int> screenBounds (Desktop::getInstance().getDisplays().getTotalBounds (true));
  644. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_6
  645. if ([window inLiveResize])
  646. #else
  647. if ([window respondsToSelector: @selector (inLiveResize)]
  648. && [window performSelector: @selector (inLiveResize)])
  649. #endif
  650. {
  651. constrainer->checkBounds (pos, original, screenBounds,
  652. false, false, true, true);
  653. }
  654. else
  655. {
  656. constrainer->checkBounds (pos, original, screenBounds,
  657. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  658. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  659. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  660. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  661. }
  662. r.origin.x = pos.getX();
  663. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  664. r.size.width = pos.getWidth();
  665. r.size.height = pos.getHeight();
  666. }
  667. return r;
  668. }
  669. static void showArrowCursorIfNeeded()
  670. {
  671. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  672. if (mouse.getComponentUnderMouse() == nullptr
  673. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == nullptr)
  674. {
  675. [[NSCursor arrowCursor] set];
  676. }
  677. }
  678. static void updateModifiers (NSEvent* e)
  679. {
  680. updateModifiers ([e modifierFlags]);
  681. }
  682. static void updateModifiers (const NSUInteger flags)
  683. {
  684. int m = 0;
  685. if ((flags & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  686. if ((flags & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  687. if ((flags & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  688. if ((flags & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  689. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  690. }
  691. static void updateKeysDown (NSEvent* ev, bool isKeyDown)
  692. {
  693. updateModifiers (ev);
  694. int keyCode = getKeyCodeFromEvent (ev);
  695. if (keyCode != 0)
  696. {
  697. if (isKeyDown)
  698. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  699. else
  700. keysCurrentlyDown.removeFirstMatchingValue (keyCode);
  701. }
  702. }
  703. static int getKeyCodeFromEvent (NSEvent* ev)
  704. {
  705. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  706. int keyCode = unmodified[0];
  707. if (keyCode == 0x19) // (backwards-tab)
  708. keyCode = '\t';
  709. else if (keyCode == 0x03) // (enter)
  710. keyCode = '\r';
  711. else
  712. keyCode = (int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  713. if (([ev modifierFlags] & NSNumericPadKeyMask) != 0)
  714. {
  715. const int numPadConversions[] = { '0', KeyPress::numberPad0, '1', KeyPress::numberPad1,
  716. '2', KeyPress::numberPad2, '3', KeyPress::numberPad3,
  717. '4', KeyPress::numberPad4, '5', KeyPress::numberPad5,
  718. '6', KeyPress::numberPad6, '7', KeyPress::numberPad7,
  719. '8', KeyPress::numberPad8, '9', KeyPress::numberPad9,
  720. '+', KeyPress::numberPadAdd, '-', KeyPress::numberPadSubtract,
  721. '*', KeyPress::numberPadMultiply, '/', KeyPress::numberPadDivide,
  722. '.', KeyPress::numberPadDecimalPoint, '=', KeyPress::numberPadEquals };
  723. for (int i = 0; i < numElementsInArray (numPadConversions); i += 2)
  724. if (keyCode == numPadConversions [i])
  725. keyCode = numPadConversions [i + 1];
  726. }
  727. return keyCode;
  728. }
  729. static int64 getMouseTime (NSEvent* e)
  730. {
  731. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  732. + (int64) ([e timestamp] * 1000.0);
  733. }
  734. static Point<int> getMousePos (NSEvent* e, NSView* view)
  735. {
  736. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  737. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  738. }
  739. static int getModifierForButtonNumber (const NSInteger num)
  740. {
  741. return num == 0 ? ModifierKeys::leftButtonModifier
  742. : (num == 1 ? ModifierKeys::rightButtonModifier
  743. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  744. }
  745. static unsigned int getNSWindowStyleMask (const int flags) noexcept
  746. {
  747. unsigned int style = (flags & windowHasTitleBar) != 0 ? NSTitledWindowMask
  748. : NSBorderlessWindowMask;
  749. if ((flags & windowHasMinimiseButton) != 0) style |= NSMiniaturizableWindowMask;
  750. if ((flags & windowHasCloseButton) != 0) style |= NSClosableWindowMask;
  751. if ((flags & windowIsResizable) != 0) style |= NSResizableWindowMask;
  752. return style;
  753. }
  754. static NSArray* getSupportedDragTypes()
  755. {
  756. return [NSArray arrayWithObjects: NSFilenamesPboardType, NSFilesPromisePboardType, NSStringPboardType, nil];
  757. }
  758. BOOL sendDragCallback (const int type, id <NSDraggingInfo> sender)
  759. {
  760. NSPasteboard* pasteboard = [sender draggingPasteboard];
  761. NSString* contentType = [pasteboard availableTypeFromArray: getSupportedDragTypes()];
  762. if (contentType == nil)
  763. return false;
  764. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  765. ComponentPeer::DragInfo dragInfo;
  766. dragInfo.position.setXY ((int) p.x, (int) ([view frame].size.height - p.y));
  767. if (contentType == NSStringPboardType)
  768. dragInfo.text = nsStringToJuce ([pasteboard stringForType: NSStringPboardType]);
  769. else
  770. dragInfo.files = getDroppedFiles (pasteboard, contentType);
  771. if (dragInfo.files.size() > 0 || dragInfo.text.isNotEmpty())
  772. {
  773. switch (type)
  774. {
  775. case 0: return handleDragMove (dragInfo);
  776. case 1: return handleDragExit (dragInfo);
  777. case 2: return handleDragDrop (dragInfo);
  778. default: jassertfalse; break;
  779. }
  780. }
  781. return false;
  782. }
  783. StringArray getDroppedFiles (NSPasteboard* pasteboard, NSString* contentType)
  784. {
  785. StringArray files;
  786. NSString* iTunesPasteboardType = nsStringLiteral ("CorePasteboardFlavorType 0x6974756E"); // 'itun'
  787. if (contentType == NSFilesPromisePboardType
  788. && [[pasteboard types] containsObject: iTunesPasteboardType])
  789. {
  790. id list = [pasteboard propertyListForType: iTunesPasteboardType];
  791. if ([list isKindOfClass: [NSDictionary class]])
  792. {
  793. NSDictionary* iTunesDictionary = (NSDictionary*) list;
  794. NSArray* tracks = [iTunesDictionary valueForKey: nsStringLiteral ("Tracks")];
  795. NSEnumerator* enumerator = [tracks objectEnumerator];
  796. NSDictionary* track;
  797. while ((track = [enumerator nextObject]) != nil)
  798. {
  799. NSURL* url = [NSURL URLWithString: [track valueForKey: nsStringLiteral ("Location")]];
  800. if ([url isFileURL])
  801. files.add (nsStringToJuce ([url path]));
  802. }
  803. }
  804. }
  805. else
  806. {
  807. id list = [pasteboard propertyListForType: NSFilenamesPboardType];
  808. if ([list isKindOfClass: [NSArray class]])
  809. {
  810. NSArray* items = (NSArray*) [pasteboard propertyListForType: NSFilenamesPboardType];
  811. for (unsigned int i = 0; i < [items count]; ++i)
  812. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  813. }
  814. }
  815. return files;
  816. }
  817. //==============================================================================
  818. void viewFocusGain()
  819. {
  820. if (currentlyFocusedPeer != this)
  821. {
  822. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  823. currentlyFocusedPeer->handleFocusLoss();
  824. currentlyFocusedPeer = this;
  825. handleFocusGain();
  826. }
  827. }
  828. void viewFocusLoss()
  829. {
  830. if (currentlyFocusedPeer == this)
  831. {
  832. currentlyFocusedPeer = nullptr;
  833. handleFocusLoss();
  834. }
  835. }
  836. bool isFocused() const
  837. {
  838. return isSharedWindow ? this == currentlyFocusedPeer
  839. : [window isKeyWindow];
  840. }
  841. void grabFocus()
  842. {
  843. if (window != nil)
  844. {
  845. [window makeKeyWindow];
  846. [window makeFirstResponder: view];
  847. viewFocusGain();
  848. }
  849. }
  850. void textInputRequired (const Point<int>&) {}
  851. //==============================================================================
  852. void repaint (const Rectangle<int>& area)
  853. {
  854. if (insideDrawRect)
  855. {
  856. class AsyncRepaintMessage : public CallbackMessage
  857. {
  858. public:
  859. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  860. : peer (peer_), rect (rect_)
  861. {}
  862. void messageCallback()
  863. {
  864. if (ComponentPeer::isValidPeer (peer))
  865. peer->repaint (rect);
  866. }
  867. private:
  868. NSViewComponentPeer* const peer;
  869. const Rectangle<int> rect;
  870. };
  871. (new AsyncRepaintMessage (this, area))->post();
  872. }
  873. else
  874. {
  875. [view setNeedsDisplayInRect: NSMakeRect ((CGFloat) area.getX(), [view frame].size.height - (CGFloat) area.getBottom(),
  876. (CGFloat) area.getWidth(), (CGFloat) area.getHeight())];
  877. }
  878. }
  879. void performAnyPendingRepaintsNow()
  880. {
  881. [view displayIfNeeded];
  882. }
  883. //==============================================================================
  884. NSWindow* window;
  885. NSView* view;
  886. bool isSharedWindow, fullScreen, insideDrawRect;
  887. bool usingCoreGraphics, recursiveToFrontCall, isZooming, textWasInserted;
  888. String stringBeingComposed;
  889. NSNotificationCenter* notificationCenter;
  890. static ModifierKeys currentModifiers;
  891. static ComponentPeer* currentlyFocusedPeer;
  892. static Array<int> keysCurrentlyDown;
  893. private:
  894. static NSView* createViewInstance();
  895. static NSWindow* createWindowInstance();
  896. static void setOwner (id viewOrWindow, NSViewComponentPeer* newOwner)
  897. {
  898. object_setInstanceVariable (viewOrWindow, "owner", newOwner);
  899. }
  900. void getClipRects (RectangleList& clip, const int xOffset, const int yOffset, const int clipW, const int clipH)
  901. {
  902. const NSRect* rects = nullptr;
  903. NSInteger numRects = 0;
  904. [view getRectsBeingDrawn: &rects count: &numRects];
  905. const Rectangle<int> clipBounds (clipW, clipH);
  906. const CGFloat viewH = [view frame].size.height;
  907. for (int i = 0; i < numRects; ++i)
  908. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  909. roundToInt (viewH - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  910. roundToInt (rects[i].size.width),
  911. roundToInt (rects[i].size.height))));
  912. }
  913. static void appFocusChanged()
  914. {
  915. keysCurrentlyDown.clear();
  916. if (isValidPeer (currentlyFocusedPeer))
  917. {
  918. if (Process::isForegroundProcess())
  919. {
  920. currentlyFocusedPeer->handleFocusGain();
  921. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  922. }
  923. else
  924. {
  925. currentlyFocusedPeer->handleFocusLoss();
  926. }
  927. }
  928. }
  929. static bool checkEventBlockedByModalComps (NSEvent* e)
  930. {
  931. if (Component::getNumCurrentlyModalComponents() == 0)
  932. return false;
  933. NSWindow* const w = [e window];
  934. if (w == nil || [w worksWhenModal])
  935. return false;
  936. bool isKey = false, isInputAttempt = false;
  937. switch ([e type])
  938. {
  939. case NSKeyDown:
  940. case NSKeyUp:
  941. isKey = isInputAttempt = true;
  942. break;
  943. case NSLeftMouseDown:
  944. case NSRightMouseDown:
  945. case NSOtherMouseDown:
  946. isInputAttempt = true;
  947. break;
  948. case NSLeftMouseDragged:
  949. case NSRightMouseDragged:
  950. case NSLeftMouseUp:
  951. case NSRightMouseUp:
  952. case NSOtherMouseUp:
  953. case NSOtherMouseDragged:
  954. if (Desktop::getInstance().getDraggingMouseSource(0) != nullptr)
  955. return false;
  956. break;
  957. case NSMouseMoved:
  958. case NSMouseEntered:
  959. case NSMouseExited:
  960. case NSCursorUpdate:
  961. case NSScrollWheel:
  962. case NSTabletPoint:
  963. case NSTabletProximity:
  964. break;
  965. default:
  966. return false;
  967. }
  968. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  969. {
  970. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  971. NSView* const compView = (NSView*) peer->getNativeHandle();
  972. if ([compView window] == w)
  973. {
  974. if (isKey)
  975. {
  976. if (compView == [w firstResponder])
  977. return false;
  978. }
  979. else
  980. {
  981. NSViewComponentPeer* nsViewPeer = dynamic_cast<NSViewComponentPeer*> (peer);
  982. if ((nsViewPeer == nullptr || ! nsViewPeer->isSharedWindow)
  983. ? NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height))
  984. : NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil], [compView bounds]))
  985. return false;
  986. }
  987. }
  988. }
  989. if (isInputAttempt)
  990. {
  991. if (! [NSApp isActive])
  992. [NSApp activateIgnoringOtherApps: YES];
  993. Component* const modal = Component::getCurrentlyModalComponent (0);
  994. if (modal != nullptr)
  995. modal->inputAttemptWhenModal();
  996. }
  997. return true;
  998. }
  999. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentPeer);
  1000. };
  1001. //==============================================================================
  1002. struct JuceNSViewClass : public ObjCClass <NSView>
  1003. {
  1004. JuceNSViewClass() : ObjCClass <NSView> ("JUCEView_")
  1005. {
  1006. addIvar<NSViewComponentPeer*> ("owner");
  1007. addMethod (@selector (isOpaque), isOpaque, "c@:");
  1008. addMethod (@selector (drawRect:), drawRect, "v@:", @encode (NSRect));
  1009. addMethod (@selector (mouseDown:), mouseDown, "v@:@");
  1010. addMethod (@selector (asyncMouseDown:), asyncMouseDown, "v@:@");
  1011. addMethod (@selector (mouseUp:), mouseUp, "v@:@");
  1012. addMethod (@selector (asyncMouseUp:), asyncMouseUp, "v@:@");
  1013. addMethod (@selector (mouseDragged:), mouseDragged, "v@:@");
  1014. addMethod (@selector (mouseMoved:), mouseMoved, "v@:@");
  1015. addMethod (@selector (mouseEntered:), mouseEntered, "v@:@");
  1016. addMethod (@selector (mouseExited:), mouseExited, "v@:@");
  1017. addMethod (@selector (rightMouseDown:), rightMouseDown, "v@:@");
  1018. addMethod (@selector (rightMouseDragged:), rightMouseDragged, "v@:@");
  1019. addMethod (@selector (rightMouseUp:), rightMouseUp, "v@:@");
  1020. addMethod (@selector (otherMouseDown:), otherMouseDown, "v@:@");
  1021. addMethod (@selector (otherMouseDragged:), otherMouseDragged, "v@:@");
  1022. addMethod (@selector (otherMouseUp:), otherMouseUp, "v@:@");
  1023. addMethod (@selector (scrollWheel:), scrollWheel, "v@:@");
  1024. addMethod (@selector (acceptsFirstMouse:), acceptsFirstMouse, "v@:@");
  1025. addMethod (@selector (frameChanged:), frameChanged, "v@:@");
  1026. addMethod (@selector (viewDidMoveToWindow), viewDidMoveToWindow, "v@:");
  1027. addMethod (@selector (keyDown:), keyDown, "v@:@");
  1028. addMethod (@selector (keyUp:), keyUp, "v@:@");
  1029. addMethod (@selector (insertText:), insertText, "v@:@");
  1030. addMethod (@selector (doCommandBySelector:), doCommandBySelector, "v@::");
  1031. addMethod (@selector (setMarkedText:selectedRange:), setMarkedText, "v@:@", @encode (NSRange));
  1032. addMethod (@selector (unmarkText), unmarkText, "v@:");
  1033. addMethod (@selector (hasMarkedText), hasMarkedText, "c@:");
  1034. addMethod (@selector (conversationIdentifier), conversationIdentifier, "l@:");
  1035. addMethod (@selector (attributedSubstringFromRange:), attributedSubstringFromRange, "@@:", @encode (NSRange));
  1036. addMethod (@selector (markedRange), markedRange, @encode (NSRange), "@:");
  1037. addMethod (@selector (selectedRange), selectedRange, @encode (NSRange), "@:");
  1038. addMethod (@selector (firstRectForCharacterRange:), firstRectForCharacterRange, @encode (NSRect), "@:", @encode (NSRange));
  1039. addMethod (@selector (validAttributesForMarkedText), validAttributesForMarkedText, "@@:");
  1040. addMethod (@selector (flagsChanged:), flagsChanged, "v@:@");
  1041. addMethod (@selector (becomeFirstResponder), becomeFirstResponder, "c@:");
  1042. addMethod (@selector (resignFirstResponder), resignFirstResponder, "c@:");
  1043. addMethod (@selector (acceptsFirstResponder), acceptsFirstResponder, "c@:");
  1044. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  1045. addMethod (@selector (performKeyEquivalent:), performKeyEquivalent, "c@:@");
  1046. #endif
  1047. addMethod (@selector (draggingEntered:), draggingEntered, @encode (NSDragOperation), "@:@");
  1048. addMethod (@selector (draggingUpdated:), draggingUpdated, @encode (NSDragOperation), "@:@");
  1049. addMethod (@selector (draggingEnded:), draggingEnded, "v@:@");
  1050. addMethod (@selector (draggingExited:), draggingExited, "v@:@");
  1051. addMethod (@selector (prepareForDragOperation:), prepareForDragOperation, "c@:@");
  1052. addMethod (@selector (performDragOperation:), performDragOperation, "c@:@");
  1053. addMethod (@selector (concludeDragOperation:), concludeDragOperation, "v@:@");
  1054. addProtocol (@protocol (NSTextInput));
  1055. registerClass();
  1056. }
  1057. private:
  1058. static NSViewComponentPeer* getOwner (id self)
  1059. {
  1060. return getIvar<NSViewComponentPeer*> (self, "owner");
  1061. }
  1062. //==============================================================================
  1063. static void drawRect (id self, SEL, NSRect r)
  1064. {
  1065. NSViewComponentPeer* const owner = getOwner (self);
  1066. if (owner != nullptr)
  1067. owner->drawRect (r);
  1068. }
  1069. static BOOL isOpaque (id self, SEL)
  1070. {
  1071. NSViewComponentPeer* const owner = getOwner (self);
  1072. return owner == nullptr || owner->isOpaque();
  1073. }
  1074. //==============================================================================
  1075. static void mouseDown (id self, SEL, NSEvent* ev)
  1076. {
  1077. if (JUCEApplication::isStandaloneApp())
  1078. [self performSelector: @selector (asyncMouseDown:)
  1079. withObject: ev];
  1080. else
  1081. // In some host situations, the host will stop modal loops from working
  1082. // correctly if they're called from a mouse event, so we'll trigger
  1083. // the event asynchronously..
  1084. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  1085. withObject: ev
  1086. waitUntilDone: NO];
  1087. }
  1088. static void asyncMouseDown (id self, SEL, NSEvent* ev)
  1089. {
  1090. NSViewComponentPeer* const owner = getOwner (self);
  1091. if (owner != nullptr)
  1092. owner->redirectMouseDown (ev);
  1093. }
  1094. static void mouseUp (id self, SEL, NSEvent* ev)
  1095. {
  1096. if (! JUCEApplication::isStandaloneApp())
  1097. [self performSelector: @selector (asyncMouseUp:)
  1098. withObject: ev];
  1099. else
  1100. // In some host situations, the host will stop modal loops from working
  1101. // correctly if they're called from a mouse event, so we'll trigger
  1102. // the event asynchronously..
  1103. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  1104. withObject: ev
  1105. waitUntilDone: NO];
  1106. }
  1107. static void asyncMouseUp (id self, SEL, NSEvent* ev) { NSViewComponentPeer* const owner = getOwner (self); if (owner != nullptr) owner->redirectMouseUp (ev); }
  1108. static void mouseDragged (id self, SEL, NSEvent* ev) { NSViewComponentPeer* const owner = getOwner (self); if (owner != nullptr) owner->redirectMouseDrag (ev); }
  1109. static void mouseMoved (id self, SEL, NSEvent* ev) { NSViewComponentPeer* const owner = getOwner (self); if (owner != nullptr) owner->redirectMouseMove (ev); }
  1110. static void mouseEntered (id self, SEL, NSEvent* ev) { NSViewComponentPeer* const owner = getOwner (self); if (owner != nullptr) owner->redirectMouseEnter (ev); }
  1111. static void mouseExited (id self, SEL, NSEvent* ev) { NSViewComponentPeer* const owner = getOwner (self); if (owner != nullptr) owner->redirectMouseExit (ev); }
  1112. static void scrollWheel (id self, SEL, NSEvent* ev) { NSViewComponentPeer* const owner = getOwner (self); if (owner != nullptr) owner->redirectMouseWheel (ev); }
  1113. static void rightMouseDown (id self, SEL, NSEvent* ev) { [(NSView*) self mouseDown: ev]; }
  1114. static void rightMouseDragged (id self, SEL, NSEvent* ev) { [(NSView*) self mouseDragged: ev]; }
  1115. static void rightMouseUp (id self, SEL, NSEvent* ev) { [(NSView*) self mouseUp: ev]; }
  1116. static void otherMouseDown (id self, SEL, NSEvent* ev) { [(NSView*) self mouseDown: ev]; }
  1117. static void otherMouseDragged (id self, SEL, NSEvent* ev) { [(NSView*) self mouseDragged: ev]; }
  1118. static void otherMouseUp (id self, SEL, NSEvent* ev) { [(NSView*) self mouseUp: ev]; }
  1119. static BOOL acceptsFirstMouse (id, SEL, NSEvent*) { return YES; }
  1120. static void frameChanged (id self, SEL, NSNotification*)
  1121. {
  1122. NSViewComponentPeer* const owner = getOwner (self);
  1123. if (owner != nullptr)
  1124. owner->redirectMovedOrResized();
  1125. }
  1126. static void viewDidMoveToWindow (id self, SEL)
  1127. {
  1128. NSViewComponentPeer* const owner = getOwner (self);
  1129. if (owner != nullptr)
  1130. owner->viewMovedToWindow();
  1131. }
  1132. //==============================================================================
  1133. static void keyDown (id self, SEL, NSEvent* ev)
  1134. {
  1135. NSViewComponentPeer* const owner = getOwner (self);
  1136. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  1137. owner->textWasInserted = false;
  1138. if (target != nullptr)
  1139. [(NSView*) self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  1140. else
  1141. owner->stringBeingComposed = String::empty;
  1142. if ((! owner->textWasInserted) && (owner == nullptr || ! owner->redirectKeyDown (ev)))
  1143. {
  1144. objc_super s = { self, [NSView class] };
  1145. objc_msgSendSuper (&s, @selector (keyDown:), ev);
  1146. }
  1147. }
  1148. static void keyUp (id self, SEL, NSEvent* ev)
  1149. {
  1150. NSViewComponentPeer* const owner = getOwner (self);
  1151. if (owner == nullptr || ! owner->redirectKeyUp (ev))
  1152. {
  1153. objc_super s = { self, [NSView class] };
  1154. objc_msgSendSuper (&s, @selector (keyUp:), ev);
  1155. }
  1156. }
  1157. //==============================================================================
  1158. static void insertText (id self, SEL, id aString)
  1159. {
  1160. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  1161. NSViewComponentPeer* const owner = getOwner (self);
  1162. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  1163. if ([newText length] > 0)
  1164. {
  1165. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  1166. if (target != nullptr)
  1167. {
  1168. target->insertTextAtCaret (nsStringToJuce (newText));
  1169. owner->textWasInserted = true;
  1170. }
  1171. }
  1172. owner->stringBeingComposed = String::empty;
  1173. }
  1174. static void doCommandBySelector (id, SEL, SEL) {}
  1175. static void setMarkedText (id self, SEL, id aString, NSRange)
  1176. {
  1177. NSViewComponentPeer* const owner = getOwner (self);
  1178. owner->stringBeingComposed = nsStringToJuce ([aString isKindOfClass: [NSAttributedString class]]
  1179. ? [aString string] : aString);
  1180. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  1181. if (target != nullptr)
  1182. {
  1183. const Range<int> currentHighlight (target->getHighlightedRegion());
  1184. target->insertTextAtCaret (owner->stringBeingComposed);
  1185. target->setHighlightedRegion (currentHighlight.withLength (owner->stringBeingComposed.length()));
  1186. owner->textWasInserted = true;
  1187. }
  1188. }
  1189. static void unmarkText (id self, SEL)
  1190. {
  1191. NSViewComponentPeer* const owner = getOwner (self);
  1192. if (owner->stringBeingComposed.isNotEmpty())
  1193. {
  1194. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  1195. if (target != nullptr)
  1196. {
  1197. target->insertTextAtCaret (owner->stringBeingComposed);
  1198. owner->textWasInserted = true;
  1199. }
  1200. owner->stringBeingComposed = String::empty;
  1201. }
  1202. }
  1203. static BOOL hasMarkedText (id self, SEL)
  1204. {
  1205. return getOwner (self)->stringBeingComposed.isNotEmpty();
  1206. }
  1207. static long conversationIdentifier (id self, SEL)
  1208. {
  1209. return (long) (pointer_sized_int) self;
  1210. }
  1211. static NSAttributedString* attributedSubstringFromRange (id self, SEL, NSRange theRange)
  1212. {
  1213. NSViewComponentPeer* const owner = getOwner (self);
  1214. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  1215. if (target != nullptr)
  1216. {
  1217. const Range<int> r ((int) theRange.location,
  1218. (int) (theRange.location + theRange.length));
  1219. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  1220. }
  1221. return nil;
  1222. }
  1223. static NSRange markedRange (id self, SEL)
  1224. {
  1225. NSViewComponentPeer* const owner = getOwner (self);
  1226. return owner->stringBeingComposed.isNotEmpty() ? NSMakeRange (0, owner->stringBeingComposed.length())
  1227. : NSMakeRange (NSNotFound, 0);
  1228. }
  1229. static NSRange selectedRange (id self, SEL)
  1230. {
  1231. NSViewComponentPeer* const owner = getOwner (self);
  1232. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  1233. if (target != nullptr)
  1234. {
  1235. const Range<int> highlight (target->getHighlightedRegion());
  1236. if (! highlight.isEmpty())
  1237. return NSMakeRange (highlight.getStart(), highlight.getLength());
  1238. }
  1239. return NSMakeRange (NSNotFound, 0);
  1240. }
  1241. static NSRect firstRectForCharacterRange (id self, SEL, NSRange)
  1242. {
  1243. NSViewComponentPeer* const owner = getOwner (self);
  1244. Component* const comp = dynamic_cast <Component*> (owner->findCurrentTextInputTarget());
  1245. if (comp == nullptr)
  1246. return NSMakeRect (0, 0, 0, 0);
  1247. const Rectangle<int> bounds (comp->getScreenBounds());
  1248. return NSMakeRect (bounds.getX(),
  1249. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  1250. bounds.getWidth(),
  1251. bounds.getHeight());
  1252. }
  1253. static NSUInteger characterIndexForPoint (id, SEL, NSPoint) { return NSNotFound; }
  1254. static NSArray* validAttributesForMarkedText (id, SEL) { return [NSArray array]; }
  1255. //==============================================================================
  1256. static void flagsChanged (id self, SEL, NSEvent* ev)
  1257. {
  1258. NSViewComponentPeer* const owner = getOwner (self);
  1259. if (owner != nullptr)
  1260. owner->redirectModKeyChange (ev);
  1261. }
  1262. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  1263. static BOOL performKeyEquivalent (id self, SEL, NSEvent* ev)
  1264. {
  1265. NSViewComponentPeer* const owner = getOwner (self);
  1266. if (owner != nullptr && owner->redirectPerformKeyEquivalent (ev))
  1267. return true;
  1268. objc_super s = { self, [NSView class] };
  1269. return objc_msgSendSuper (&s, @selector (performKeyEquivalent:), ev) != nil;
  1270. }
  1271. #endif
  1272. static BOOL becomeFirstResponder (id self, SEL)
  1273. {
  1274. NSViewComponentPeer* const owner = getOwner (self);
  1275. if (owner != nullptr)
  1276. owner->viewFocusGain();
  1277. return YES;
  1278. }
  1279. static BOOL resignFirstResponder (id self, SEL)
  1280. {
  1281. NSViewComponentPeer* const owner = getOwner (self);
  1282. if (owner != nullptr)
  1283. owner->viewFocusLoss();
  1284. return YES;
  1285. }
  1286. static BOOL acceptsFirstResponder (id self, SEL)
  1287. {
  1288. NSViewComponentPeer* const owner = getOwner (self);
  1289. return owner != nullptr && owner->canBecomeKeyWindow();
  1290. }
  1291. //==============================================================================
  1292. static NSDragOperation draggingEntered (id self, SEL, id <NSDraggingInfo> sender)
  1293. {
  1294. NSViewComponentPeer* const owner = getOwner (self);
  1295. if (owner != nullptr && owner->sendDragCallback (0, sender))
  1296. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  1297. else
  1298. return NSDragOperationNone;
  1299. }
  1300. static NSDragOperation draggingUpdated (id self, SEL, id <NSDraggingInfo> sender)
  1301. {
  1302. NSViewComponentPeer* const owner = getOwner (self);
  1303. if (owner != nullptr && owner->sendDragCallback (0, sender))
  1304. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  1305. else
  1306. return NSDragOperationNone;
  1307. }
  1308. static void draggingEnded (id self, SEL, id <NSDraggingInfo> sender)
  1309. {
  1310. NSViewComponentPeer* const owner = getOwner (self);
  1311. if (owner != nullptr)
  1312. owner->sendDragCallback (1, sender);
  1313. }
  1314. static void draggingExited (id self, SEL, id <NSDraggingInfo> sender)
  1315. {
  1316. NSViewComponentPeer* const owner = getOwner (self);
  1317. if (owner != nullptr)
  1318. owner->sendDragCallback (1, sender);
  1319. }
  1320. static BOOL prepareForDragOperation (id self, SEL, id <NSDraggingInfo>)
  1321. {
  1322. return YES;
  1323. }
  1324. static BOOL performDragOperation (id self, SEL, id <NSDraggingInfo> sender)
  1325. {
  1326. NSViewComponentPeer* const owner = getOwner (self);
  1327. return owner != nullptr && owner->sendDragCallback (2, sender);
  1328. }
  1329. static void concludeDragOperation (id, SEL, id <NSDraggingInfo>) {}
  1330. };
  1331. //==============================================================================
  1332. struct JuceNSWindowClass : public ObjCClass <NSWindow>
  1333. {
  1334. JuceNSWindowClass() : ObjCClass <NSWindow> ("JUCEWindow_")
  1335. {
  1336. addIvar<NSViewComponentPeer*> ("owner");
  1337. addMethod (@selector (canBecomeKeyWindow), canBecomeKeyWindow, "c@:");
  1338. addMethod (@selector (becomeKeyWindow), becomeKeyWindow, "v@:");
  1339. addMethod (@selector (windowShouldClose:), windowShouldClose, "c@:@");
  1340. addMethod (@selector (constrainFrameRect:toScreen:), constrainFrameRect, @encode (NSRect), "@:", @encode (NSRect*), "@");
  1341. addMethod (@selector (windowWillResize:toSize:), windowWillResize, @encode (NSSize), "@:@", @encode (NSSize));
  1342. addMethod (@selector (zoom), zoom, "v@:@");
  1343. addMethod (@selector (windowWillMove), windowWillMove, "v@:@");
  1344. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  1345. addProtocol (@protocol (NSWindowDelegate));
  1346. #endif
  1347. registerClass();
  1348. }
  1349. private:
  1350. static NSViewComponentPeer* getOwner (id self)
  1351. {
  1352. return getIvar<NSViewComponentPeer*> (self, "owner");
  1353. }
  1354. //==============================================================================
  1355. static BOOL canBecomeKeyWindow (id self, SEL)
  1356. {
  1357. NSViewComponentPeer* const owner = getOwner (self);
  1358. return owner != nullptr && owner->canBecomeKeyWindow();
  1359. }
  1360. static void becomeKeyWindow (id self, SEL)
  1361. {
  1362. sendSuperclassMessage (self, @selector (becomeKeyWindow));
  1363. NSViewComponentPeer* const owner = getOwner (self);
  1364. if (owner != nullptr)
  1365. owner->becomeKeyWindow();
  1366. }
  1367. static BOOL windowShouldClose (id self, SEL, id /*window*/)
  1368. {
  1369. NSViewComponentPeer* const owner = getOwner (self);
  1370. return owner == nullptr || owner->windowShouldClose();
  1371. }
  1372. static NSRect constrainFrameRect (id self, SEL, NSRect frameRect, NSScreen*)
  1373. {
  1374. NSViewComponentPeer* const owner = getOwner (self);
  1375. if (owner != nullptr)
  1376. frameRect = owner->constrainRect (frameRect);
  1377. return frameRect;
  1378. }
  1379. static NSSize windowWillResize (id self, SEL, NSWindow*, NSSize proposedFrameSize)
  1380. {
  1381. NSViewComponentPeer* const owner = getOwner (self);
  1382. if (owner->isZooming)
  1383. return proposedFrameSize;
  1384. NSRect frameRect = [(NSWindow*) self frame];
  1385. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  1386. frameRect.size = proposedFrameSize;
  1387. if (owner != nullptr)
  1388. frameRect = owner->constrainRect (frameRect);
  1389. if (juce::Component::getCurrentlyModalComponent() != nullptr
  1390. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  1391. && owner->hasNativeTitleBar())
  1392. juce::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  1393. return frameRect.size;
  1394. }
  1395. static void zoom (id self, SEL, id sender)
  1396. {
  1397. NSViewComponentPeer* const owner = getOwner (self);
  1398. owner->isZooming = true;
  1399. objc_super s = { self, [NSWindow class] };
  1400. objc_msgSendSuper (&s, @selector(zoom), sender);
  1401. owner->isZooming = false;
  1402. owner->redirectMovedOrResized();
  1403. }
  1404. static void windowWillMove (id self, SEL, NSNotification*)
  1405. {
  1406. NSViewComponentPeer* const owner = getOwner (self);
  1407. if (juce::Component::getCurrentlyModalComponent() != nullptr
  1408. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  1409. && owner->hasNativeTitleBar())
  1410. juce::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  1411. }
  1412. };
  1413. NSView* NSViewComponentPeer::createViewInstance()
  1414. {
  1415. static JuceNSViewClass cls;
  1416. return cls.createInstance();
  1417. }
  1418. NSWindow* NSViewComponentPeer::createWindowInstance()
  1419. {
  1420. static JuceNSWindowClass cls;
  1421. return cls.createInstance();
  1422. }
  1423. //==============================================================================
  1424. ModifierKeys NSViewComponentPeer::currentModifiers;
  1425. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = nullptr;
  1426. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  1427. //==============================================================================
  1428. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  1429. {
  1430. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  1431. return true;
  1432. if (keyCode >= 'A' && keyCode <= 'Z'
  1433. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  1434. return true;
  1435. if (keyCode >= 'a' && keyCode <= 'z'
  1436. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  1437. return true;
  1438. return false;
  1439. }
  1440. ModifierKeys ModifierKeys::getCurrentModifiersRealtime() noexcept
  1441. {
  1442. if ([NSEvent respondsToSelector: @selector (modifierFlags)])
  1443. NSViewComponentPeer::updateModifiers ((NSUInteger) [NSEvent modifierFlags]);
  1444. return NSViewComponentPeer::currentModifiers;
  1445. }
  1446. void ModifierKeys::updateCurrentModifiers() noexcept
  1447. {
  1448. currentModifiers = NSViewComponentPeer::currentModifiers;
  1449. }
  1450. //==============================================================================
  1451. void Desktop::createMouseInputSources()
  1452. {
  1453. mouseSources.add (new MouseInputSource (0, true));
  1454. }
  1455. //==============================================================================
  1456. void Desktop::setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  1457. {
  1458. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  1459. NSViewComponentPeer* const peer = dynamic_cast<NSViewComponentPeer*> (kioskModeComponent->getPeer());
  1460. #if defined (MAC_OS_X_VERSION_10_7) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
  1461. if (peer != nullptr
  1462. && peer->hasNativeTitleBar()
  1463. && [peer->window respondsToSelector: @selector (toggleFullScreen:)])
  1464. {
  1465. [peer->window performSelector: @selector (toggleFullScreen:)
  1466. withObject: [NSNumber numberWithBool: (BOOL) enableOrDisable]];
  1467. }
  1468. else
  1469. #endif
  1470. {
  1471. if (enableOrDisable)
  1472. {
  1473. if (peer->hasNativeTitleBar())
  1474. [peer->window setStyleMask: NSBorderlessWindowMask];
  1475. [NSApp setPresentationOptions: (allowMenusAndBars ? (NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)
  1476. : (NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar))];
  1477. kioskModeComponent->setBounds (Desktop::getInstance().getDisplays().getMainDisplay().totalArea);
  1478. peer->becomeKeyWindow();
  1479. }
  1480. else
  1481. {
  1482. if (peer->hasNativeTitleBar())
  1483. {
  1484. [peer->window setStyleMask: (NSViewComponentPeer::getNSWindowStyleMask (peer->getStyleFlags()))];
  1485. peer->setTitle (peer->component->getName()); // required to force the OS to update the title
  1486. }
  1487. [NSApp setPresentationOptions: NSApplicationPresentationDefault];
  1488. }
  1489. }
  1490. #elif JUCE_SUPPORT_CARBON
  1491. if (enableOrDisable)
  1492. {
  1493. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  1494. kioskModeComponent->setBounds (Desktop::getInstance().getDisplays().getMainDisplay().totalArea);
  1495. }
  1496. else
  1497. {
  1498. SetSystemUIMode (kUIModeNormal, 0);
  1499. }
  1500. #else
  1501. // If you're targeting OSes earlier than 10.6 and want to use this feature,
  1502. // you'll need to enable JUCE_SUPPORT_CARBON.
  1503. jassertfalse;
  1504. #endif
  1505. }
  1506. //==============================================================================
  1507. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  1508. {
  1509. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  1510. }
  1511. //==============================================================================
  1512. const int KeyPress::spaceKey = ' ';
  1513. const int KeyPress::returnKey = 0x0d;
  1514. const int KeyPress::escapeKey = 0x1b;
  1515. const int KeyPress::backspaceKey = 0x7f;
  1516. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  1517. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  1518. const int KeyPress::upKey = NSUpArrowFunctionKey;
  1519. const int KeyPress::downKey = NSDownArrowFunctionKey;
  1520. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  1521. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  1522. const int KeyPress::endKey = NSEndFunctionKey;
  1523. const int KeyPress::homeKey = NSHomeFunctionKey;
  1524. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  1525. const int KeyPress::insertKey = -1;
  1526. const int KeyPress::tabKey = 9;
  1527. const int KeyPress::F1Key = NSF1FunctionKey;
  1528. const int KeyPress::F2Key = NSF2FunctionKey;
  1529. const int KeyPress::F3Key = NSF3FunctionKey;
  1530. const int KeyPress::F4Key = NSF4FunctionKey;
  1531. const int KeyPress::F5Key = NSF5FunctionKey;
  1532. const int KeyPress::F6Key = NSF6FunctionKey;
  1533. const int KeyPress::F7Key = NSF7FunctionKey;
  1534. const int KeyPress::F8Key = NSF8FunctionKey;
  1535. const int KeyPress::F9Key = NSF9FunctionKey;
  1536. const int KeyPress::F10Key = NSF10FunctionKey;
  1537. const int KeyPress::F11Key = NSF1FunctionKey;
  1538. const int KeyPress::F12Key = NSF12FunctionKey;
  1539. const int KeyPress::F13Key = NSF13FunctionKey;
  1540. const int KeyPress::F14Key = NSF14FunctionKey;
  1541. const int KeyPress::F15Key = NSF15FunctionKey;
  1542. const int KeyPress::F16Key = NSF16FunctionKey;
  1543. const int KeyPress::numberPad0 = 0x30020;
  1544. const int KeyPress::numberPad1 = 0x30021;
  1545. const int KeyPress::numberPad2 = 0x30022;
  1546. const int KeyPress::numberPad3 = 0x30023;
  1547. const int KeyPress::numberPad4 = 0x30024;
  1548. const int KeyPress::numberPad5 = 0x30025;
  1549. const int KeyPress::numberPad6 = 0x30026;
  1550. const int KeyPress::numberPad7 = 0x30027;
  1551. const int KeyPress::numberPad8 = 0x30028;
  1552. const int KeyPress::numberPad9 = 0x30029;
  1553. const int KeyPress::numberPadAdd = 0x3002a;
  1554. const int KeyPress::numberPadSubtract = 0x3002b;
  1555. const int KeyPress::numberPadMultiply = 0x3002c;
  1556. const int KeyPress::numberPadDivide = 0x3002d;
  1557. const int KeyPress::numberPadSeparator = 0x3002e;
  1558. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  1559. const int KeyPress::numberPadEquals = 0x30030;
  1560. const int KeyPress::numberPadDelete = 0x30031;
  1561. const int KeyPress::playKey = 0x30000;
  1562. const int KeyPress::stopKey = 0x30001;
  1563. const int KeyPress::fastForwardKey = 0x30002;
  1564. const int KeyPress::rewindKey = 0x30003;