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.

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