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.

2036 lines
75KB

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