Audio plugin host https://kx.studio/carla
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.

2008 lines
74KB

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