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.

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