The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2675 lines
100KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 6 End-User License
  8. Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
  9. End User License Agreement: www.juce.com/juce-6-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. @interface NSEvent (DeviceDelta)
  19. - (float)deviceDeltaX;
  20. - (float)deviceDeltaY;
  21. @end
  22. //==============================================================================
  23. namespace juce
  24. {
  25. typedef void (*AppFocusChangeCallback)();
  26. extern AppFocusChangeCallback appFocusChangeCallback;
  27. typedef bool (*CheckEventBlockedByModalComps) (NSEvent*);
  28. extern CheckEventBlockedByModalComps isEventBlockedByModalComps;
  29. }
  30. namespace juce
  31. {
  32. //==============================================================================
  33. static constexpr int translateVirtualToAsciiKeyCode (int keyCode) noexcept
  34. {
  35. switch (keyCode)
  36. {
  37. // The virtual keycodes are from HIToolbox/Events.h
  38. case 0x00: return 'A';
  39. case 0x01: return 'S';
  40. case 0x02: return 'D';
  41. case 0x03: return 'F';
  42. case 0x04: return 'H';
  43. case 0x05: return 'G';
  44. case 0x06: return 'Z';
  45. case 0x07: return 'X';
  46. case 0x08: return 'C';
  47. case 0x09: return 'V';
  48. case 0x0B: return 'B';
  49. case 0x0C: return 'Q';
  50. case 0x0D: return 'W';
  51. case 0x0E: return 'E';
  52. case 0x0F: return 'R';
  53. case 0x10: return 'Y';
  54. case 0x11: return 'T';
  55. case 0x12: return '1';
  56. case 0x13: return '2';
  57. case 0x14: return '3';
  58. case 0x15: return '4';
  59. case 0x16: return '6';
  60. case 0x17: return '5';
  61. case 0x18: return '='; // kVK_ANSI_Equal
  62. case 0x19: return '9';
  63. case 0x1A: return '7';
  64. case 0x1B: return '-'; // kVK_ANSI_Minus
  65. case 0x1C: return '8';
  66. case 0x1D: return '0';
  67. case 0x1E: return ']'; // kVK_ANSI_RightBracket
  68. case 0x1F: return 'O';
  69. case 0x20: return 'U';
  70. case 0x21: return '['; // kVK_ANSI_LeftBracket
  71. case 0x22: return 'I';
  72. case 0x23: return 'P';
  73. case 0x25: return 'L';
  74. case 0x26: return 'J';
  75. case 0x27: return '"'; // kVK_ANSI_Quote
  76. case 0x28: return 'K';
  77. case 0x29: return ';'; // kVK_ANSI_Semicolon
  78. case 0x2A: return '\\'; // kVK_ANSI_Backslash
  79. case 0x2B: return ','; // kVK_ANSI_Comma
  80. case 0x2C: return '/'; // kVK_ANSI_Slash
  81. case 0x2D: return 'N';
  82. case 0x2E: return 'M';
  83. case 0x2F: return '.'; // kVK_ANSI_Period
  84. case 0x32: return '`'; // kVK_ANSI_Grave
  85. default: return keyCode;
  86. }
  87. }
  88. constexpr int extendedKeyModifier = 0x30000;
  89. //==============================================================================
  90. class NSViewComponentPeer : public ComponentPeer,
  91. private Timer
  92. {
  93. public:
  94. NSViewComponentPeer (Component& comp, const int windowStyleFlags, NSView* viewToAttachTo)
  95. : ComponentPeer (comp, windowStyleFlags),
  96. safeComponent (&comp),
  97. isSharedWindow (viewToAttachTo != nil),
  98. lastRepaintTime (Time::getMillisecondCounter())
  99. {
  100. appFocusChangeCallback = appFocusChanged;
  101. isEventBlockedByModalComps = checkEventBlockedByModalComps;
  102. auto r = makeNSRect (component.getLocalBounds());
  103. view = [createViewInstance() initWithFrame: r];
  104. setOwner (view, this);
  105. [view registerForDraggedTypes: getSupportedDragTypes()];
  106. const auto options = NSTrackingMouseEnteredAndExited
  107. | NSTrackingMouseMoved
  108. | NSTrackingEnabledDuringMouseDrag
  109. | NSTrackingActiveAlways
  110. | NSTrackingInVisibleRect;
  111. [view addTrackingArea: [[NSTrackingArea alloc] initWithRect: r
  112. options: options
  113. owner: view
  114. userInfo: nil]];
  115. notificationCenter = [NSNotificationCenter defaultCenter];
  116. [notificationCenter addObserver: view
  117. selector: frameChangedSelector
  118. name: NSViewFrameDidChangeNotification
  119. object: view];
  120. [view setPostsFrameChangedNotifications: YES];
  121. #if USE_COREGRAPHICS_RENDERING && JUCE_COREGRAPHICS_DRAW_ASYNC
  122. if (! getComponentAsyncLayerBackedViewDisabled (component))
  123. {
  124. if (@available (macOS 10.8, *))
  125. {
  126. [view setWantsLayer: YES];
  127. [[view layer] setDrawsAsynchronously: YES];
  128. }
  129. }
  130. #endif
  131. if (isSharedWindow)
  132. {
  133. window = [viewToAttachTo window];
  134. [viewToAttachTo addSubview: view];
  135. }
  136. else
  137. {
  138. r.origin.x = (CGFloat) component.getX();
  139. r.origin.y = (CGFloat) component.getY();
  140. r = flippedScreenRect (r);
  141. window = [createWindowInstance() initWithContentRect: r
  142. styleMask: getNSWindowStyleMask (windowStyleFlags)
  143. backing: NSBackingStoreBuffered
  144. defer: YES];
  145. setOwner (window, this);
  146. if (@available (macOS 10.10, *))
  147. [window setAccessibilityElement: YES];
  148. [window orderOut: nil];
  149. [window setDelegate: (id<NSWindowDelegate>) window];
  150. [window setOpaque: component.isOpaque()];
  151. if (! [window isOpaque])
  152. [window setBackgroundColor: [NSColor clearColor]];
  153. if (@available (macOS 10.9, *))
  154. [view setAppearance: [NSAppearance appearanceNamed: NSAppearanceNameAqua]];
  155. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  156. if (component.isAlwaysOnTop())
  157. setAlwaysOnTop (true);
  158. [window setContentView: view];
  159. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  160. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  161. [window setReleasedWhenClosed: YES];
  162. [window retain];
  163. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  164. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  165. setCollectionBehaviour (false);
  166. [window setRestorable: NO];
  167. #if defined (MAC_OS_X_VERSION_10_12) && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_12)
  168. if (@available (macOS 10.12, *))
  169. [window setTabbingMode: NSWindowTabbingModeDisallowed];
  170. #endif
  171. [notificationCenter addObserver: view
  172. selector: frameChangedSelector
  173. name: NSWindowDidMoveNotification
  174. object: window];
  175. [notificationCenter addObserver: view
  176. selector: frameChangedSelector
  177. name: NSWindowDidMiniaturizeNotification
  178. object: window];
  179. [notificationCenter addObserver: view
  180. selector: @selector (windowWillMiniaturize:)
  181. name: NSWindowWillMiniaturizeNotification
  182. object: window];
  183. [notificationCenter addObserver: view
  184. selector: @selector (windowDidDeminiaturize:)
  185. name: NSWindowDidDeminiaturizeNotification
  186. object: window];
  187. }
  188. auto alpha = component.getAlpha();
  189. if (alpha < 1.0f)
  190. setAlpha (alpha);
  191. setTitle (component.getName());
  192. getNativeRealtimeModifiers = []
  193. {
  194. if ([NSEvent respondsToSelector: @selector (modifierFlags)])
  195. NSViewComponentPeer::updateModifiers ([NSEvent modifierFlags]);
  196. return ModifierKeys::currentModifiers;
  197. };
  198. }
  199. ~NSViewComponentPeer() override
  200. {
  201. [notificationCenter removeObserver: view];
  202. setOwner (view, nullptr);
  203. if ([view superview] != nil)
  204. {
  205. redirectWillMoveToWindow (nullptr);
  206. [view removeFromSuperview];
  207. }
  208. if (! isSharedWindow)
  209. {
  210. setOwner (window, nullptr);
  211. [window setContentView: nil];
  212. [window close];
  213. [window release];
  214. }
  215. [view release];
  216. }
  217. //==============================================================================
  218. void* getNativeHandle() const override { return view; }
  219. void setVisible (bool shouldBeVisible) override
  220. {
  221. if (isSharedWindow)
  222. {
  223. if (shouldBeVisible)
  224. [view setHidden: false];
  225. else if ([window firstResponder] != view || ([window firstResponder] == view && [window makeFirstResponder: nil]))
  226. [view setHidden: true];
  227. }
  228. else
  229. {
  230. if (shouldBeVisible)
  231. {
  232. ++insideToFrontCall;
  233. [window orderFront: nil];
  234. --insideToFrontCall;
  235. handleBroughtToFront();
  236. }
  237. else
  238. {
  239. [window orderOut: nil];
  240. }
  241. }
  242. }
  243. void setTitle (const String& title) override
  244. {
  245. JUCE_AUTORELEASEPOOL
  246. {
  247. if (! isSharedWindow)
  248. [window setTitle: juceStringToNS (title)];
  249. }
  250. }
  251. bool setDocumentEditedStatus (bool edited) override
  252. {
  253. if (! hasNativeTitleBar())
  254. return false;
  255. [window setDocumentEdited: edited];
  256. return true;
  257. }
  258. void setRepresentedFile (const File& file) override
  259. {
  260. if (! isSharedWindow)
  261. {
  262. [window setRepresentedFilename: juceStringToNS (file != File()
  263. ? file.getFullPathName()
  264. : String())];
  265. windowRepresentsFile = (file != File());
  266. }
  267. }
  268. void setBounds (const Rectangle<int>& newBounds, bool) override
  269. {
  270. auto r = makeNSRect (newBounds);
  271. auto oldViewSize = [view frame].size;
  272. if (isSharedWindow)
  273. {
  274. [view setFrame: r];
  275. }
  276. else
  277. {
  278. // Repaint behaviour of setFrame seemed to change in 10.11, and the drawing became synchronous,
  279. // causing performance issues. But sending an async update causes flickering in older versions,
  280. // hence this version check to use the old behaviour on pre 10.11 machines
  281. static bool isPre10_11 = SystemStats::getOperatingSystemType() <= SystemStats::MacOSX_10_10;
  282. [window setFrame: [window frameRectForContentRect: flippedScreenRect (r)]
  283. display: isPre10_11];
  284. }
  285. if (oldViewSize.width != r.size.width || oldViewSize.height != r.size.height)
  286. [view setNeedsDisplay: true];
  287. }
  288. Rectangle<int> getBounds (const bool global) const
  289. {
  290. auto r = [view frame];
  291. NSWindow* viewWindow = [view window];
  292. if (global && viewWindow != nil)
  293. {
  294. r = [[view superview] convertRect: r toView: nil];
  295. r = [viewWindow convertRectToScreen: r];
  296. r = flippedScreenRect (r);
  297. }
  298. return convertToRectInt (r);
  299. }
  300. Rectangle<int> getBounds() const override
  301. {
  302. return getBounds (! isSharedWindow);
  303. }
  304. Point<float> localToGlobal (Point<float> relativePosition) override
  305. {
  306. return relativePosition + getBounds (true).getPosition().toFloat();
  307. }
  308. using ComponentPeer::localToGlobal;
  309. Point<float> globalToLocal (Point<float> screenPosition) override
  310. {
  311. return screenPosition - getBounds (true).getPosition().toFloat();
  312. }
  313. using ComponentPeer::globalToLocal;
  314. void setAlpha (float newAlpha) override
  315. {
  316. if (isSharedWindow)
  317. [view setAlphaValue: (CGFloat) newAlpha];
  318. else
  319. [window setAlphaValue: (CGFloat) newAlpha];
  320. }
  321. void setMinimised (bool shouldBeMinimised) override
  322. {
  323. if (! isSharedWindow)
  324. {
  325. if (shouldBeMinimised)
  326. [window miniaturize: nil];
  327. else
  328. [window deminiaturize: nil];
  329. }
  330. }
  331. bool isMinimised() const override
  332. {
  333. return [window isMiniaturized];
  334. }
  335. NSWindowCollectionBehavior getCollectionBehavior (bool forceFullScreen) const
  336. {
  337. if (forceFullScreen)
  338. return NSWindowCollectionBehaviorFullScreenPrimary;
  339. // Some SDK versions don't define NSWindowCollectionBehaviorFullScreenNone
  340. constexpr auto fullScreenNone = (NSUInteger) (1 << 9);
  341. return (getStyleFlags() & (windowHasMaximiseButton | windowIsResizable)) == (windowHasMaximiseButton | windowIsResizable)
  342. ? NSWindowCollectionBehaviorFullScreenPrimary
  343. : fullScreenNone;
  344. }
  345. void setCollectionBehaviour (bool forceFullScreen) const
  346. {
  347. [window setCollectionBehavior: getCollectionBehavior (forceFullScreen)];
  348. }
  349. void setFullScreen (bool shouldBeFullScreen) override
  350. {
  351. if (isSharedWindow)
  352. return;
  353. setCollectionBehaviour (shouldBeFullScreen);
  354. if (isMinimised())
  355. setMinimised (false);
  356. if (hasNativeTitleBar())
  357. {
  358. if (shouldBeFullScreen != isFullScreen())
  359. [window toggleFullScreen: nil];
  360. }
  361. else
  362. {
  363. [window zoom: nil];
  364. }
  365. }
  366. bool isFullScreen() const override
  367. {
  368. return ([window styleMask] & NSWindowStyleMaskFullScreen) != 0;
  369. }
  370. bool isKioskMode() const override
  371. {
  372. return isFullScreen() && ComponentPeer::isKioskMode();
  373. }
  374. static bool isWindowAtPoint (NSWindow* w, NSPoint screenPoint)
  375. {
  376. if ([NSWindow respondsToSelector: @selector (windowNumberAtPoint:belowWindowWithWindowNumber:)])
  377. return [NSWindow windowNumberAtPoint: screenPoint belowWindowWithWindowNumber: 0] == [w windowNumber];
  378. return true;
  379. }
  380. bool contains (Point<int> localPos, bool trueIfInAChildWindow) const override
  381. {
  382. NSRect viewFrame = [view frame];
  383. if (! (isPositiveAndBelow (localPos.getX(), viewFrame.size.width)
  384. && isPositiveAndBelow (localPos.getY(), viewFrame.size.height)))
  385. return false;
  386. if (! SystemStats::isRunningInAppExtensionSandbox())
  387. {
  388. if (NSWindow* const viewWindow = [view window])
  389. {
  390. NSRect windowFrame = [viewWindow frame];
  391. NSPoint windowPoint = [view convertPoint: NSMakePoint (localPos.x, localPos.y) toView: nil];
  392. NSPoint screenPoint = NSMakePoint (windowFrame.origin.x + windowPoint.x,
  393. windowFrame.origin.y + windowPoint.y);
  394. if (! isWindowAtPoint (viewWindow, screenPoint))
  395. return false;
  396. }
  397. }
  398. NSView* v = [view hitTest: NSMakePoint (viewFrame.origin.x + localPos.getX(),
  399. viewFrame.origin.y + localPos.getY())];
  400. return trueIfInAChildWindow ? (v != nil)
  401. : (v == view);
  402. }
  403. BorderSize<int> getFrameSize() const override
  404. {
  405. BorderSize<int> b;
  406. if (! isSharedWindow)
  407. {
  408. NSRect v = [view convertRect: [view frame] toView: nil];
  409. NSRect w = [window frame];
  410. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  411. b.setBottom ((int) v.origin.y);
  412. b.setLeft ((int) v.origin.x);
  413. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  414. }
  415. return b;
  416. }
  417. bool hasNativeTitleBar() const
  418. {
  419. return (getStyleFlags() & windowHasTitleBar) != 0;
  420. }
  421. bool setAlwaysOnTop (bool alwaysOnTop) override
  422. {
  423. if (! isSharedWindow)
  424. {
  425. [window setLevel: alwaysOnTop ? ((getStyleFlags() & windowIsTemporary) != 0 ? NSPopUpMenuWindowLevel
  426. : NSFloatingWindowLevel)
  427. : NSNormalWindowLevel];
  428. isAlwaysOnTop = alwaysOnTop;
  429. }
  430. return true;
  431. }
  432. void toFront (bool makeActiveWindow) override
  433. {
  434. if (isSharedWindow)
  435. {
  436. NSView* superview = [view superview];
  437. NSMutableArray* subviews = [NSMutableArray arrayWithArray: [superview subviews]];
  438. const auto isFrontmost = [[subviews lastObject] isEqual: view];
  439. if (! isFrontmost)
  440. {
  441. [view retain];
  442. [subviews removeObject: view];
  443. [subviews addObject: view];
  444. [superview setSubviews: subviews];
  445. [view release];
  446. }
  447. }
  448. if (window != nil && component.isVisible())
  449. {
  450. ++insideToFrontCall;
  451. if (makeActiveWindow)
  452. [window makeKeyAndOrderFront: nil];
  453. else
  454. [window orderFront: nil];
  455. if (insideToFrontCall <= 1)
  456. {
  457. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  458. handleBroughtToFront();
  459. }
  460. --insideToFrontCall;
  461. }
  462. }
  463. void toBehind (ComponentPeer* other) override
  464. {
  465. if (auto* otherPeer = dynamic_cast<NSViewComponentPeer*> (other))
  466. {
  467. if (isSharedWindow)
  468. {
  469. NSView* superview = [view superview];
  470. NSMutableArray* subviews = [NSMutableArray arrayWithArray: [superview subviews]];
  471. const auto otherViewIndex = [subviews indexOfObject: otherPeer->view];
  472. if (otherViewIndex == NSNotFound)
  473. return;
  474. const auto isBehind = [subviews indexOfObject: view] < otherViewIndex;
  475. if (! isBehind)
  476. {
  477. [view retain];
  478. [subviews removeObject: view];
  479. [subviews insertObject: view
  480. atIndex: otherViewIndex];
  481. [superview setSubviews: subviews];
  482. [view release];
  483. }
  484. }
  485. else if (component.isVisible())
  486. {
  487. [window orderWindow: NSWindowBelow
  488. relativeTo: [otherPeer->window windowNumber]];
  489. }
  490. }
  491. else
  492. {
  493. jassertfalse; // wrong type of window?
  494. }
  495. }
  496. void setIcon (const Image& newIcon) override
  497. {
  498. if (! isSharedWindow)
  499. {
  500. // need to set a dummy represented file here to show the file icon (which we then set to the new icon)
  501. if (! windowRepresentsFile)
  502. [window setRepresentedFilename: juceStringToNS (" ")]; // can't just use an empty string for some reason...
  503. auto img = NSUniquePtr<NSImage> { imageToNSImage (ScaledImage (newIcon)) };
  504. [[window standardWindowButton: NSWindowDocumentIconButton] setImage: img.get()];
  505. }
  506. }
  507. StringArray getAvailableRenderingEngines() override
  508. {
  509. StringArray s ("Software Renderer");
  510. #if USE_COREGRAPHICS_RENDERING
  511. s.add ("CoreGraphics Renderer");
  512. #endif
  513. return s;
  514. }
  515. int getCurrentRenderingEngine() const override
  516. {
  517. return usingCoreGraphics ? 1 : 0;
  518. }
  519. void setCurrentRenderingEngine (int index) override
  520. {
  521. #if USE_COREGRAPHICS_RENDERING
  522. if (usingCoreGraphics != (index > 0))
  523. {
  524. usingCoreGraphics = index > 0;
  525. [view setNeedsDisplay: true];
  526. }
  527. #else
  528. ignoreUnused (index);
  529. #endif
  530. }
  531. void redirectMouseDown (NSEvent* ev)
  532. {
  533. if (! Process::isForegroundProcess())
  534. Process::makeForegroundProcess();
  535. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  536. sendMouseEvent (ev);
  537. }
  538. void redirectMouseUp (NSEvent* ev)
  539. {
  540. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  541. sendMouseEvent (ev);
  542. showArrowCursorIfNeeded();
  543. }
  544. void redirectMouseDrag (NSEvent* ev)
  545. {
  546. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  547. sendMouseEvent (ev);
  548. }
  549. void redirectMouseMove (NSEvent* ev)
  550. {
  551. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons();
  552. NSPoint windowPos = [ev locationInWindow];
  553. NSPoint screenPos = [[ev window] convertRectToScreen: NSMakeRect (windowPos.x, windowPos.y, 1.0f, 1.0f)].origin;
  554. if (isWindowAtPoint ([ev window], screenPos))
  555. sendMouseEvent (ev);
  556. else
  557. // moved into another window which overlaps this one, so trigger an exit
  558. handleMouseEvent (MouseInputSource::InputSourceType::mouse, MouseInputSource::offscreenMousePos, ModifierKeys::currentModifiers,
  559. getMousePressure (ev), MouseInputSource::invalidOrientation, getMouseTime (ev));
  560. showArrowCursorIfNeeded();
  561. }
  562. void redirectMouseEnter (NSEvent* ev)
  563. {
  564. sendMouseEnterExit (ev);
  565. }
  566. void redirectMouseExit (NSEvent* ev)
  567. {
  568. sendMouseEnterExit (ev);
  569. }
  570. static float checkDeviceDeltaReturnValue (float v) noexcept
  571. {
  572. // (deviceDeltaX can fail and return NaN, so need to sanity-check the result)
  573. v *= 0.5f / 256.0f;
  574. return (v > -1000.0f && v < 1000.0f) ? v : 0.0f;
  575. }
  576. void redirectMouseWheel (NSEvent* ev)
  577. {
  578. updateModifiers (ev);
  579. MouseWheelDetails wheel;
  580. wheel.deltaX = 0;
  581. wheel.deltaY = 0;
  582. wheel.isReversed = false;
  583. wheel.isSmooth = false;
  584. wheel.isInertial = false;
  585. @try
  586. {
  587. if ([ev respondsToSelector: @selector (isDirectionInvertedFromDevice)])
  588. wheel.isReversed = [ev isDirectionInvertedFromDevice];
  589. wheel.isInertial = ([ev momentumPhase] != NSEventPhaseNone);
  590. if ([ev respondsToSelector: @selector (hasPreciseScrollingDeltas)])
  591. {
  592. if ([ev hasPreciseScrollingDeltas])
  593. {
  594. const float scale = 0.5f / 256.0f;
  595. wheel.deltaX = scale * (float) [ev scrollingDeltaX];
  596. wheel.deltaY = scale * (float) [ev scrollingDeltaY];
  597. wheel.isSmooth = true;
  598. }
  599. }
  600. else if ([ev respondsToSelector: @selector (deviceDeltaX)])
  601. {
  602. wheel.deltaX = checkDeviceDeltaReturnValue ([ev deviceDeltaX]);
  603. wheel.deltaY = checkDeviceDeltaReturnValue ([ev deviceDeltaY]);
  604. }
  605. }
  606. @catch (...)
  607. {}
  608. if (wheel.deltaX == 0.0f && wheel.deltaY == 0.0f)
  609. {
  610. const float scale = 10.0f / 256.0f;
  611. wheel.deltaX = scale * (float) [ev deltaX];
  612. wheel.deltaY = scale * (float) [ev deltaY];
  613. }
  614. handleMouseWheel (MouseInputSource::InputSourceType::mouse, getMousePos (ev, view), getMouseTime (ev), wheel);
  615. }
  616. void redirectMagnify (NSEvent* ev)
  617. {
  618. const float invScale = 1.0f - (float) [ev magnification];
  619. if (invScale > 0.0f)
  620. handleMagnifyGesture (MouseInputSource::InputSourceType::mouse, getMousePos (ev, view), getMouseTime (ev), 1.0f / invScale);
  621. }
  622. void redirectCopy (NSObject*) { handleKeyPress (KeyPress ('c', ModifierKeys (ModifierKeys::commandModifier), 'c')); }
  623. void redirectPaste (NSObject*) { handleKeyPress (KeyPress ('v', ModifierKeys (ModifierKeys::commandModifier), 'v')); }
  624. void redirectCut (NSObject*) { handleKeyPress (KeyPress ('x', ModifierKeys (ModifierKeys::commandModifier), 'x')); }
  625. void redirectSelectAll (NSObject*) { handleKeyPress (KeyPress ('a', ModifierKeys (ModifierKeys::commandModifier), 'a')); }
  626. void redirectWillMoveToWindow (NSWindow* newWindow)
  627. {
  628. if (auto* currentWindow = [view window])
  629. {
  630. [notificationCenter removeObserver: view
  631. name: NSWindowDidMoveNotification
  632. object: currentWindow];
  633. [notificationCenter removeObserver: view
  634. name: NSWindowWillMiniaturizeNotification
  635. object: currentWindow];
  636. #if JUCE_COREGRAPHICS_DRAW_ASYNC
  637. [notificationCenter removeObserver: view
  638. name: NSWindowDidBecomeKeyNotification
  639. object: currentWindow];
  640. #endif
  641. }
  642. if (isSharedWindow && [view window] == window && newWindow == nullptr)
  643. {
  644. if (auto* comp = safeComponent.get())
  645. comp->setVisible (false);
  646. }
  647. }
  648. void sendMouseEvent (NSEvent* ev)
  649. {
  650. updateModifiers (ev);
  651. handleMouseEvent (MouseInputSource::InputSourceType::mouse, getMousePos (ev, view), ModifierKeys::currentModifiers,
  652. getMousePressure (ev), MouseInputSource::invalidOrientation, getMouseTime (ev));
  653. }
  654. bool handleKeyEvent (NSEvent* ev, bool isKeyDown)
  655. {
  656. auto unicode = nsStringToJuce ([ev characters]);
  657. auto keyCode = getKeyCodeFromEvent (ev);
  658. #if JUCE_DEBUG_KEYCODES
  659. DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  660. auto unmodified = nsStringToJuce ([ev charactersIgnoringModifiers]);
  661. DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  662. #endif
  663. if (keyCode != 0 || unicode.isNotEmpty())
  664. {
  665. if (isKeyDown)
  666. {
  667. bool used = false;
  668. for (auto u = unicode.getCharPointer(); ! u.isEmpty();)
  669. {
  670. auto textCharacter = u.getAndAdvance();
  671. switch (keyCode)
  672. {
  673. case NSLeftArrowFunctionKey:
  674. case NSRightArrowFunctionKey:
  675. case NSUpArrowFunctionKey:
  676. case NSDownArrowFunctionKey:
  677. case NSPageUpFunctionKey:
  678. case NSPageDownFunctionKey:
  679. case NSEndFunctionKey:
  680. case NSHomeFunctionKey:
  681. case NSDeleteFunctionKey:
  682. textCharacter = 0;
  683. break; // (these all seem to generate unwanted garbage unicode strings)
  684. default:
  685. if (([ev modifierFlags] & NSEventModifierFlagCommand) != 0
  686. || (keyCode >= NSF1FunctionKey && keyCode <= NSF35FunctionKey))
  687. textCharacter = 0;
  688. break;
  689. }
  690. used = handleKeyUpOrDown (true) || used;
  691. used = handleKeyPress (keyCode, textCharacter) || used;
  692. }
  693. return used;
  694. }
  695. if (handleKeyUpOrDown (false))
  696. return true;
  697. }
  698. return false;
  699. }
  700. bool redirectKeyDown (NSEvent* ev)
  701. {
  702. // (need to retain this in case a modal loop runs in handleKeyEvent and
  703. // our event object gets lost)
  704. const NSUniquePtr<NSEvent> r ([ev retain]);
  705. updateKeysDown (ev, true);
  706. bool used = handleKeyEvent (ev, true);
  707. if (([ev modifierFlags] & NSEventModifierFlagCommand) != 0)
  708. {
  709. // for command keys, the key-up event is thrown away, so simulate one..
  710. updateKeysDown (ev, false);
  711. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  712. }
  713. // (If we're running modally, don't allow unused keystrokes to be passed
  714. // along to other blocked views..)
  715. if (Component::getCurrentlyModalComponent() != nullptr)
  716. used = true;
  717. return used;
  718. }
  719. bool redirectKeyUp (NSEvent* ev)
  720. {
  721. updateKeysDown (ev, false);
  722. return handleKeyEvent (ev, false)
  723. || Component::getCurrentlyModalComponent() != nullptr;
  724. }
  725. void redirectModKeyChange (NSEvent* ev)
  726. {
  727. // (need to retain this in case a modal loop runs and our event object gets lost)
  728. const NSUniquePtr<NSEvent> r ([ev retain]);
  729. keysCurrentlyDown.clear();
  730. handleKeyUpOrDown (true);
  731. updateModifiers (ev);
  732. handleModifierKeysChange();
  733. }
  734. //==============================================================================
  735. void drawRect (NSRect r)
  736. {
  737. if (r.size.width < 1.0f || r.size.height < 1.0f)
  738. return;
  739. auto cg = []
  740. {
  741. if (@available (macOS 10.10, *))
  742. return (CGContextRef) [[NSGraphicsContext currentContext] CGContext];
  743. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
  744. return (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  745. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  746. }();
  747. if (! component.isOpaque())
  748. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  749. float displayScale = 1.0f;
  750. NSScreen* screen = [[view window] screen];
  751. if ([screen respondsToSelector: @selector (backingScaleFactor)])
  752. displayScale = (float) screen.backingScaleFactor;
  753. auto invalidateTransparentWindowShadow = [this]
  754. {
  755. // transparent NSWindows with a drop-shadow need to redraw their shadow when the content
  756. // changes to avoid stale shadows being drawn behind the window
  757. if (! isSharedWindow && ! [window isOpaque] && [window hasShadow])
  758. [window invalidateShadow];
  759. };
  760. #if USE_COREGRAPHICS_RENDERING && JUCE_COREGRAPHICS_RENDER_WITH_MULTIPLE_PAINT_CALLS
  761. // This option invokes a separate paint call for each rectangle of the clip region.
  762. // It's a long story, but this is a basically a workaround for a CGContext not having
  763. // a way of finding whether a rectangle falls within its clip region
  764. if (usingCoreGraphics)
  765. {
  766. const NSRect* rects = nullptr;
  767. NSInteger numRects = 0;
  768. [view getRectsBeingDrawn: &rects count: &numRects];
  769. if (numRects > 1)
  770. {
  771. for (int i = 0; i < numRects; ++i)
  772. {
  773. NSRect rect = rects[i];
  774. CGContextSaveGState (cg);
  775. CGContextClipToRect (cg, CGRectMake (rect.origin.x, rect.origin.y, rect.size.width, rect.size.height));
  776. drawRectWithContext (cg, rect, displayScale);
  777. CGContextRestoreGState (cg);
  778. }
  779. invalidateTransparentWindowShadow();
  780. return;
  781. }
  782. }
  783. #endif
  784. drawRectWithContext (cg, r, displayScale);
  785. invalidateTransparentWindowShadow();
  786. }
  787. void drawRectWithContext (CGContextRef cg, NSRect r, float displayScale)
  788. {
  789. #if USE_COREGRAPHICS_RENDERING
  790. if (usingCoreGraphics)
  791. {
  792. const auto height = getComponent().getHeight();
  793. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, height));
  794. CoreGraphicsContext context (cg, (float) height);
  795. handlePaint (context);
  796. }
  797. else
  798. #endif
  799. {
  800. const Point<int> offset (-roundToInt (r.origin.x), -roundToInt (r.origin.y));
  801. auto clipW = (int) (r.size.width + 0.5f);
  802. auto clipH = (int) (r.size.height + 0.5f);
  803. RectangleList<int> clip;
  804. getClipRects (clip, offset, clipW, clipH);
  805. if (! clip.isEmpty())
  806. {
  807. Image temp (component.isOpaque() ? Image::RGB : Image::ARGB,
  808. roundToInt (clipW * displayScale),
  809. roundToInt (clipH * displayScale),
  810. ! component.isOpaque());
  811. {
  812. auto intScale = roundToInt (displayScale);
  813. if (intScale != 1)
  814. clip.scaleAll (intScale);
  815. auto context = component.getLookAndFeel()
  816. .createGraphicsContext (temp, offset * intScale, clip);
  817. if (intScale != 1)
  818. context->addTransform (AffineTransform::scale (displayScale));
  819. handlePaint (*context);
  820. }
  821. detail::ColorSpacePtr colourSpace { CGColorSpaceCreateWithName (kCGColorSpaceSRGB) };
  822. CGImageRef image = juce_createCoreGraphicsImage (temp, colourSpace.get());
  823. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, r.origin.x, r.origin.y + clipH));
  824. CGContextDrawImage (cg, CGRectMake (0.0f, 0.0f, clipW, clipH), image);
  825. CGImageRelease (image);
  826. }
  827. }
  828. }
  829. void repaint (const Rectangle<int>& area) override
  830. {
  831. // In 10.11 changes were made to the way the OS handles repaint regions, and it seems that it can
  832. // no longer be trusted to coalesce all the regions, or to even remember them all without losing
  833. // a few when there's a lot of activity.
  834. // As a work around for this, we use a RectangleList to do our own coalescing of regions before
  835. // asynchronously asking the OS to repaint them.
  836. deferredRepaints.add ((float) area.getX(), (float) area.getY(),
  837. (float) area.getWidth(), (float) area.getHeight());
  838. if (isTimerRunning())
  839. return;
  840. auto now = Time::getMillisecondCounter();
  841. auto msSinceLastRepaint = (lastRepaintTime >= now) ? now - lastRepaintTime
  842. : (std::numeric_limits<uint32>::max() - lastRepaintTime) + now;
  843. static uint32 minimumRepaintInterval = 1000 / 30; // 30fps
  844. // When windows are being resized, artificially throttling high-frequency repaints helps
  845. // to stop the event queue getting clogged, and keeps everything working smoothly.
  846. // For some reason Logic also needs this throttling to record parameter events correctly.
  847. if (msSinceLastRepaint < minimumRepaintInterval && shouldThrottleRepaint())
  848. {
  849. startTimer (static_cast<int> (minimumRepaintInterval - msSinceLastRepaint));
  850. return;
  851. }
  852. setNeedsDisplayRectangles();
  853. }
  854. static bool shouldThrottleRepaint()
  855. {
  856. return areAnyWindowsInLiveResize() || ! JUCEApplication::isStandaloneApp();
  857. }
  858. void timerCallback() override
  859. {
  860. setNeedsDisplayRectangles();
  861. stopTimer();
  862. }
  863. void setNeedsDisplayRectangles()
  864. {
  865. for (auto& i : deferredRepaints)
  866. [view setNeedsDisplayInRect: makeNSRect (i)];
  867. lastRepaintTime = Time::getMillisecondCounter();
  868. deferredRepaints.clear();
  869. }
  870. void performAnyPendingRepaintsNow() override
  871. {
  872. [view displayIfNeeded];
  873. }
  874. static bool areAnyWindowsInLiveResize() noexcept
  875. {
  876. for (NSWindow* w in [NSApp windows])
  877. if ([w inLiveResize])
  878. return true;
  879. return false;
  880. }
  881. //==============================================================================
  882. bool isBlockedByModalComponent()
  883. {
  884. if (auto* modal = Component::getCurrentlyModalComponent())
  885. {
  886. if (insideToFrontCall == 0
  887. && (! getComponent().isParentOf (modal))
  888. && getComponent().isCurrentlyBlockedByAnotherModalComponent())
  889. {
  890. return true;
  891. }
  892. }
  893. return false;
  894. }
  895. void sendModalInputAttemptIfBlocked()
  896. {
  897. if (isBlockedByModalComponent())
  898. if (auto* modal = Component::getCurrentlyModalComponent())
  899. if (auto* otherPeer = modal->getPeer())
  900. if ((otherPeer->getStyleFlags() & ComponentPeer::windowIsTemporary) != 0)
  901. modal->inputAttemptWhenModal();
  902. }
  903. bool canBecomeKeyWindow()
  904. {
  905. return component.isVisible() && (getStyleFlags() & ComponentPeer::windowIgnoresKeyPresses) == 0;
  906. }
  907. bool canBecomeMainWindow()
  908. {
  909. return component.isVisible() && dynamic_cast<ResizableWindow*> (&component) != nullptr;
  910. }
  911. bool worksWhenModal() const
  912. {
  913. // In plugins, the host could put our plugin window inside a modal window, so this
  914. // allows us to successfully open other popups. Feels like there could be edge-case
  915. // problems caused by this, so let us know if you spot any issues..
  916. return ! JUCEApplication::isStandaloneApp();
  917. }
  918. void becomeKeyWindow()
  919. {
  920. handleBroughtToFront();
  921. grabFocus();
  922. }
  923. void resignKeyWindow()
  924. {
  925. viewFocusLoss();
  926. }
  927. bool windowShouldClose()
  928. {
  929. if (! isValidPeer (this))
  930. return YES;
  931. handleUserClosingWindow();
  932. return NO;
  933. }
  934. void redirectMovedOrResized()
  935. {
  936. handleMovedOrResized();
  937. }
  938. void viewMovedToWindow()
  939. {
  940. if (isSharedWindow)
  941. {
  942. auto newWindow = [view window];
  943. bool shouldSetVisible = (window == nullptr && newWindow != nullptr);
  944. window = newWindow;
  945. if (shouldSetVisible)
  946. getComponent().setVisible (true);
  947. }
  948. if (auto* currentWindow = [view window])
  949. {
  950. [notificationCenter addObserver: view
  951. selector: dismissModalsSelector
  952. name: NSWindowDidMoveNotification
  953. object: currentWindow];
  954. [notificationCenter addObserver: view
  955. selector: dismissModalsSelector
  956. name: NSWindowWillMiniaturizeNotification
  957. object: currentWindow];
  958. [notificationCenter addObserver: view
  959. selector: becomeKeySelector
  960. name: NSWindowDidBecomeKeyNotification
  961. object: currentWindow];
  962. [notificationCenter addObserver: view
  963. selector: resignKeySelector
  964. name: NSWindowDidResignKeyNotification
  965. object: currentWindow];
  966. }
  967. }
  968. void dismissModals()
  969. {
  970. if (hasNativeTitleBar() || isSharedWindow)
  971. sendModalInputAttemptIfBlocked();
  972. }
  973. void becomeKey()
  974. {
  975. component.repaint();
  976. }
  977. void resignKey()
  978. {
  979. viewFocusLoss();
  980. sendModalInputAttemptIfBlocked();
  981. }
  982. void liveResizingStart()
  983. {
  984. if (constrainer == nullptr)
  985. return;
  986. constrainer->resizeStart();
  987. isFirstLiveResize = true;
  988. setFullScreenSizeConstraints (*constrainer);
  989. }
  990. void liveResizingEnd()
  991. {
  992. if (constrainer != nullptr)
  993. constrainer->resizeEnd();
  994. }
  995. NSRect constrainRect (const NSRect r)
  996. {
  997. if (constrainer == nullptr || isKioskMode() || isFullScreen())
  998. return r;
  999. const auto scale = getComponent().getDesktopScaleFactor();
  1000. auto pos = ScalingHelpers::unscaledScreenPosToScaled (scale, convertToRectInt (flippedScreenRect (r)));
  1001. const auto original = ScalingHelpers::unscaledScreenPosToScaled (scale, convertToRectInt (flippedScreenRect ([window frame])));
  1002. const auto screenBounds = Desktop::getInstance().getDisplays().getTotalBounds (true);
  1003. const bool inLiveResize = [window inLiveResize];
  1004. if (! inLiveResize || isFirstLiveResize)
  1005. {
  1006. isFirstLiveResize = false;
  1007. isStretchingTop = (pos.getY() != original.getY() && pos.getBottom() == original.getBottom());
  1008. isStretchingLeft = (pos.getX() != original.getX() && pos.getRight() == original.getRight());
  1009. isStretchingBottom = (pos.getY() == original.getY() && pos.getBottom() != original.getBottom());
  1010. isStretchingRight = (pos.getX() == original.getX() && pos.getRight() != original.getRight());
  1011. }
  1012. constrainer->checkBounds (pos, original, screenBounds,
  1013. isStretchingTop, isStretchingLeft, isStretchingBottom, isStretchingRight);
  1014. return flippedScreenRect (makeNSRect (ScalingHelpers::scaledScreenPosToUnscaled (scale, pos)));
  1015. }
  1016. static void showArrowCursorIfNeeded()
  1017. {
  1018. auto& desktop = Desktop::getInstance();
  1019. auto mouse = desktop.getMainMouseSource();
  1020. if (mouse.getComponentUnderMouse() == nullptr
  1021. && desktop.findComponentAt (mouse.getScreenPosition().roundToInt()) == nullptr)
  1022. {
  1023. [[NSCursor arrowCursor] set];
  1024. }
  1025. }
  1026. static void updateModifiers (NSEvent* e)
  1027. {
  1028. updateModifiers ([e modifierFlags]);
  1029. }
  1030. static void updateModifiers (const NSUInteger flags)
  1031. {
  1032. int m = 0;
  1033. if ((flags & NSEventModifierFlagShift) != 0) m |= ModifierKeys::shiftModifier;
  1034. if ((flags & NSEventModifierFlagControl) != 0) m |= ModifierKeys::ctrlModifier;
  1035. if ((flags & NSEventModifierFlagOption) != 0) m |= ModifierKeys::altModifier;
  1036. if ((flags & NSEventModifierFlagCommand) != 0) m |= ModifierKeys::commandModifier;
  1037. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withOnlyMouseButtons().withFlags (m);
  1038. }
  1039. static void updateKeysDown (NSEvent* ev, bool isKeyDown)
  1040. {
  1041. updateModifiers (ev);
  1042. if (auto keyCode = getKeyCodeFromEvent (ev))
  1043. {
  1044. if (isKeyDown)
  1045. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  1046. else
  1047. keysCurrentlyDown.removeFirstMatchingValue (keyCode);
  1048. }
  1049. }
  1050. static int getKeyCodeFromEvent (NSEvent* ev)
  1051. {
  1052. // Unfortunately, charactersIgnoringModifiers does not ignore the shift key.
  1053. // Using [ev keyCode] is not a solution either as this will,
  1054. // for example, return VK_KEY_Y if the key is pressed which
  1055. // is typically located at the Y key position on a QWERTY
  1056. // keyboard. However, on international keyboards this might not
  1057. // be the key labeled Y (for example, on German keyboards this key
  1058. // has a Z label). Therefore, we need to query the current keyboard
  1059. // layout to figure out what character the key would have produced
  1060. // if the shift key was not pressed
  1061. String unmodified;
  1062. #if JUCE_SUPPORT_CARBON
  1063. if (auto currentKeyboard = CFUniquePtr<TISInputSourceRef> (TISCopyCurrentKeyboardInputSource()))
  1064. {
  1065. if (auto layoutData = (CFDataRef) TISGetInputSourceProperty (currentKeyboard,
  1066. kTISPropertyUnicodeKeyLayoutData))
  1067. {
  1068. if (auto* layoutPtr = (const UCKeyboardLayout*) CFDataGetBytePtr (layoutData))
  1069. {
  1070. UInt32 keysDown = 0;
  1071. UniChar buffer[4];
  1072. UniCharCount actual;
  1073. if (UCKeyTranslate (layoutPtr, [ev keyCode], kUCKeyActionDown, 0, LMGetKbdType(),
  1074. kUCKeyTranslateNoDeadKeysBit, &keysDown, sizeof (buffer) / sizeof (UniChar),
  1075. &actual, buffer) == 0)
  1076. unmodified = String (CharPointer_UTF16 (reinterpret_cast<CharPointer_UTF16::CharType*> (buffer)), 4);
  1077. }
  1078. }
  1079. }
  1080. // did the above layout conversion fail
  1081. if (unmodified.isEmpty())
  1082. #endif
  1083. {
  1084. unmodified = nsStringToJuce ([ev charactersIgnoringModifiers]);
  1085. }
  1086. auto keyCode = (int) unmodified[0];
  1087. if (keyCode == 0x19) // (backwards-tab)
  1088. keyCode = '\t';
  1089. else if (keyCode == 0x03) // (enter)
  1090. keyCode = '\r';
  1091. else
  1092. keyCode = (int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  1093. // The purpose of the keyCode is to provide information about non-printing characters to facilitate
  1094. // keyboard control over the application.
  1095. //
  1096. // So when keyCode is decoded as a printing character outside the ASCII range we need to replace it.
  1097. // This holds when the keyCode is larger than 0xff and not part one of the two MacOS specific
  1098. // non-printing ranges.
  1099. if (keyCode > 0xff
  1100. && ! (keyCode >= NSUpArrowFunctionKey && keyCode <= NSModeSwitchFunctionKey)
  1101. && ! (keyCode >= extendedKeyModifier))
  1102. {
  1103. keyCode = translateVirtualToAsciiKeyCode ([ev keyCode]);
  1104. }
  1105. if (([ev modifierFlags] & NSEventModifierFlagNumericPad) != 0)
  1106. {
  1107. const int numPadConversions[] = { '0', KeyPress::numberPad0, '1', KeyPress::numberPad1,
  1108. '2', KeyPress::numberPad2, '3', KeyPress::numberPad3,
  1109. '4', KeyPress::numberPad4, '5', KeyPress::numberPad5,
  1110. '6', KeyPress::numberPad6, '7', KeyPress::numberPad7,
  1111. '8', KeyPress::numberPad8, '9', KeyPress::numberPad9,
  1112. '+', KeyPress::numberPadAdd, '-', KeyPress::numberPadSubtract,
  1113. '*', KeyPress::numberPadMultiply, '/', KeyPress::numberPadDivide,
  1114. '.', KeyPress::numberPadDecimalPoint,
  1115. ',', KeyPress::numberPadDecimalPoint, // (to deal with non-english kbds)
  1116. '=', KeyPress::numberPadEquals };
  1117. for (int i = 0; i < numElementsInArray (numPadConversions); i += 2)
  1118. if (keyCode == numPadConversions [i])
  1119. keyCode = numPadConversions [i + 1];
  1120. }
  1121. return keyCode;
  1122. }
  1123. static int64 getMouseTime (NSEvent* e) noexcept
  1124. {
  1125. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  1126. + (int64) ([e timestamp] * 1000.0);
  1127. }
  1128. static float getMousePressure (NSEvent* e) noexcept
  1129. {
  1130. @try
  1131. {
  1132. if (e.type != NSEventTypeMouseEntered && e.type != NSEventTypeMouseExited)
  1133. return (float) e.pressure;
  1134. }
  1135. @catch (NSException* e) {}
  1136. @finally {}
  1137. return 0.0f;
  1138. }
  1139. static Point<float> getMousePos (NSEvent* e, NSView* view)
  1140. {
  1141. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  1142. return { (float) p.x, (float) p.y };
  1143. }
  1144. static int getModifierForButtonNumber (const NSInteger num)
  1145. {
  1146. return num == 0 ? ModifierKeys::leftButtonModifier
  1147. : (num == 1 ? ModifierKeys::rightButtonModifier
  1148. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  1149. }
  1150. static unsigned int getNSWindowStyleMask (const int flags) noexcept
  1151. {
  1152. unsigned int style = (flags & windowHasTitleBar) != 0 ? NSWindowStyleMaskTitled
  1153. : NSWindowStyleMaskBorderless;
  1154. if ((flags & windowHasMinimiseButton) != 0) style |= NSWindowStyleMaskMiniaturizable;
  1155. if ((flags & windowHasCloseButton) != 0) style |= NSWindowStyleMaskClosable;
  1156. if ((flags & windowIsResizable) != 0) style |= NSWindowStyleMaskResizable;
  1157. return style;
  1158. }
  1159. static NSArray* getSupportedDragTypes()
  1160. {
  1161. const auto type = []
  1162. {
  1163. #if defined (MAC_OS_X_VERSION_10_13) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_13
  1164. if (@available (macOS 10.13, *))
  1165. return NSPasteboardTypeFileURL;
  1166. #endif
  1167. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
  1168. return (NSString*) kUTTypeFileURL;
  1169. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  1170. }();
  1171. return [NSArray arrayWithObjects: type, (NSString*) kPasteboardTypeFileURLPromise, NSPasteboardTypeString, nil];
  1172. }
  1173. BOOL sendDragCallback (const int type, id <NSDraggingInfo> sender)
  1174. {
  1175. NSPasteboard* pasteboard = [sender draggingPasteboard];
  1176. NSString* contentType = [pasteboard availableTypeFromArray: getSupportedDragTypes()];
  1177. if (contentType == nil)
  1178. return false;
  1179. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  1180. ComponentPeer::DragInfo dragInfo;
  1181. dragInfo.position.setXY ((int) p.x, (int) p.y);
  1182. if (contentType == NSPasteboardTypeString)
  1183. dragInfo.text = nsStringToJuce ([pasteboard stringForType: NSPasteboardTypeString]);
  1184. else
  1185. dragInfo.files = getDroppedFiles (pasteboard, contentType);
  1186. if (! dragInfo.isEmpty())
  1187. {
  1188. switch (type)
  1189. {
  1190. case 0: return handleDragMove (dragInfo);
  1191. case 1: return handleDragExit (dragInfo);
  1192. case 2: return handleDragDrop (dragInfo);
  1193. default: jassertfalse; break;
  1194. }
  1195. }
  1196. return false;
  1197. }
  1198. StringArray getDroppedFiles (NSPasteboard* pasteboard, NSString* contentType)
  1199. {
  1200. StringArray files;
  1201. NSString* iTunesPasteboardType = nsStringLiteral ("CorePasteboardFlavorType 0x6974756E"); // 'itun'
  1202. if ([contentType isEqualToString: (NSString*) kPasteboardTypeFileURLPromise]
  1203. && [[pasteboard types] containsObject: iTunesPasteboardType])
  1204. {
  1205. id list = [pasteboard propertyListForType: iTunesPasteboardType];
  1206. if ([list isKindOfClass: [NSDictionary class]])
  1207. {
  1208. NSDictionary* iTunesDictionary = (NSDictionary*) list;
  1209. NSArray* tracks = [iTunesDictionary valueForKey: nsStringLiteral ("Tracks")];
  1210. NSEnumerator* enumerator = [tracks objectEnumerator];
  1211. NSDictionary* track;
  1212. while ((track = [enumerator nextObject]) != nil)
  1213. {
  1214. if (id value = [track valueForKey: nsStringLiteral ("Location")])
  1215. {
  1216. NSURL* url = [NSURL URLWithString: value];
  1217. if ([url isFileURL])
  1218. files.add (nsStringToJuce ([url path]));
  1219. }
  1220. }
  1221. }
  1222. }
  1223. else
  1224. {
  1225. NSArray* items = [pasteboard readObjectsForClasses:@[[NSURL class]] options: nil];
  1226. for (unsigned int i = 0; i < [items count]; ++i)
  1227. {
  1228. NSURL* url = [items objectAtIndex: i];
  1229. if ([url isFileURL])
  1230. files.add (nsStringToJuce ([url path]));
  1231. }
  1232. }
  1233. return files;
  1234. }
  1235. //==============================================================================
  1236. void viewFocusGain()
  1237. {
  1238. if (currentlyFocusedPeer != this)
  1239. {
  1240. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  1241. currentlyFocusedPeer->handleFocusLoss();
  1242. currentlyFocusedPeer = this;
  1243. handleFocusGain();
  1244. }
  1245. }
  1246. void viewFocusLoss()
  1247. {
  1248. if (currentlyFocusedPeer == this)
  1249. {
  1250. currentlyFocusedPeer = nullptr;
  1251. handleFocusLoss();
  1252. }
  1253. }
  1254. bool isFocused() const override
  1255. {
  1256. return (isSharedWindow || ! JUCEApplication::isStandaloneApp())
  1257. ? this == currentlyFocusedPeer
  1258. : [window isKeyWindow];
  1259. }
  1260. void grabFocus() override
  1261. {
  1262. if (window != nil && [window canBecomeKeyWindow])
  1263. {
  1264. [window makeKeyWindow];
  1265. [window makeFirstResponder: view];
  1266. viewFocusGain();
  1267. }
  1268. }
  1269. void textInputRequired (Point<int>, TextInputTarget&) override {}
  1270. void dismissPendingTextInput() override
  1271. {
  1272. stringBeingComposed.clear();
  1273. const auto* inputContext = [NSTextInputContext currentInputContext];
  1274. if (inputContext != nil)
  1275. [inputContext discardMarkedText];
  1276. }
  1277. void resetWindowPresentation()
  1278. {
  1279. if (hasNativeTitleBar())
  1280. {
  1281. [window setStyleMask: (NSViewComponentPeer::getNSWindowStyleMask (getStyleFlags()))];
  1282. setTitle (getComponent().getName()); // required to force the OS to update the title
  1283. }
  1284. [NSApp setPresentationOptions: NSApplicationPresentationDefault];
  1285. setCollectionBehaviour (isFullScreen());
  1286. }
  1287. void setHasChangedSinceSaved (bool b) override
  1288. {
  1289. if (! isSharedWindow)
  1290. [window setDocumentEdited: b];
  1291. }
  1292. //==============================================================================
  1293. NSWindow* window = nil;
  1294. NSView* view = nil;
  1295. WeakReference<Component> safeComponent;
  1296. bool isSharedWindow = false;
  1297. #if USE_COREGRAPHICS_RENDERING
  1298. bool usingCoreGraphics = true;
  1299. #else
  1300. bool usingCoreGraphics = false;
  1301. #endif
  1302. bool isZooming = false, isFirstLiveResize = false, textWasInserted = false;
  1303. bool isStretchingTop = false, isStretchingLeft = false, isStretchingBottom = false, isStretchingRight = false;
  1304. bool windowRepresentsFile = false;
  1305. bool isAlwaysOnTop = false, wasAlwaysOnTop = false;
  1306. String stringBeingComposed;
  1307. NSNotificationCenter* notificationCenter = nil;
  1308. RectangleList<float> deferredRepaints;
  1309. uint32 lastRepaintTime;
  1310. static ComponentPeer* currentlyFocusedPeer;
  1311. static Array<int> keysCurrentlyDown;
  1312. static int insideToFrontCall;
  1313. static const SEL dismissModalsSelector;
  1314. static const SEL frameChangedSelector;
  1315. static const SEL asyncMouseDownSelector;
  1316. static const SEL asyncMouseUpSelector;
  1317. static const SEL becomeKeySelector;
  1318. static const SEL resignKeySelector;
  1319. private:
  1320. static NSView* createViewInstance();
  1321. static NSWindow* createWindowInstance();
  1322. void sendMouseEnterExit (NSEvent* ev)
  1323. {
  1324. if (auto* area = [ev trackingArea])
  1325. if (! [[view trackingAreas] containsObject: area])
  1326. return;
  1327. sendMouseEvent (ev);
  1328. }
  1329. static void setOwner (id viewOrWindow, NSViewComponentPeer* newOwner)
  1330. {
  1331. object_setInstanceVariable (viewOrWindow, "owner", newOwner);
  1332. }
  1333. void getClipRects (RectangleList<int>& clip, Point<int> offset, int clipW, int clipH)
  1334. {
  1335. const NSRect* rects = nullptr;
  1336. NSInteger numRects = 0;
  1337. [view getRectsBeingDrawn: &rects count: &numRects];
  1338. const Rectangle<int> clipBounds (clipW, clipH);
  1339. clip.ensureStorageAllocated ((int) numRects);
  1340. for (int i = 0; i < numRects; ++i)
  1341. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + offset.x,
  1342. roundToInt (rects[i].origin.y) + offset.y,
  1343. roundToInt (rects[i].size.width),
  1344. roundToInt (rects[i].size.height))));
  1345. }
  1346. static void appFocusChanged()
  1347. {
  1348. keysCurrentlyDown.clear();
  1349. if (isValidPeer (currentlyFocusedPeer))
  1350. {
  1351. if (Process::isForegroundProcess())
  1352. {
  1353. currentlyFocusedPeer->handleFocusGain();
  1354. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  1355. }
  1356. else
  1357. {
  1358. currentlyFocusedPeer->handleFocusLoss();
  1359. }
  1360. }
  1361. }
  1362. static bool checkEventBlockedByModalComps (NSEvent* e)
  1363. {
  1364. if (Component::getNumCurrentlyModalComponents() == 0)
  1365. return false;
  1366. NSWindow* const w = [e window];
  1367. if (w == nil || [w worksWhenModal])
  1368. return false;
  1369. bool isKey = false, isInputAttempt = false;
  1370. switch ([e type])
  1371. {
  1372. case NSEventTypeKeyDown:
  1373. case NSEventTypeKeyUp:
  1374. isKey = isInputAttempt = true;
  1375. break;
  1376. case NSEventTypeLeftMouseDown:
  1377. case NSEventTypeRightMouseDown:
  1378. case NSEventTypeOtherMouseDown:
  1379. isInputAttempt = true;
  1380. break;
  1381. case NSEventTypeLeftMouseDragged:
  1382. case NSEventTypeRightMouseDragged:
  1383. case NSEventTypeLeftMouseUp:
  1384. case NSEventTypeRightMouseUp:
  1385. case NSEventTypeOtherMouseUp:
  1386. case NSEventTypeOtherMouseDragged:
  1387. if (Desktop::getInstance().getDraggingMouseSource(0) != nullptr)
  1388. return false;
  1389. break;
  1390. case NSEventTypeMouseMoved:
  1391. case NSEventTypeMouseEntered:
  1392. case NSEventTypeMouseExited:
  1393. case NSEventTypeCursorUpdate:
  1394. case NSEventTypeScrollWheel:
  1395. case NSEventTypeTabletPoint:
  1396. case NSEventTypeTabletProximity:
  1397. break;
  1398. case NSEventTypeFlagsChanged:
  1399. case NSEventTypeAppKitDefined:
  1400. case NSEventTypeSystemDefined:
  1401. case NSEventTypeApplicationDefined:
  1402. case NSEventTypePeriodic:
  1403. case NSEventTypeGesture:
  1404. case NSEventTypeMagnify:
  1405. case NSEventTypeSwipe:
  1406. case NSEventTypeRotate:
  1407. case NSEventTypeBeginGesture:
  1408. case NSEventTypeEndGesture:
  1409. case NSEventTypeQuickLook:
  1410. #if JUCE_64BIT
  1411. case NSEventTypeSmartMagnify:
  1412. case NSEventTypePressure:
  1413. #endif
  1414. #if defined (MAC_OS_X_VERSION_10_12) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_12
  1415. #if JUCE_64BIT
  1416. case NSEventTypeDirectTouch:
  1417. #endif
  1418. #if defined (MAC_OS_X_VERSION_10_15) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_15
  1419. case NSEventTypeChangeMode:
  1420. #endif
  1421. #endif
  1422. default:
  1423. return false;
  1424. }
  1425. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  1426. {
  1427. if (auto* peer = dynamic_cast<NSViewComponentPeer*> (ComponentPeer::getPeer (i)))
  1428. {
  1429. if ([peer->view window] == w)
  1430. {
  1431. if (isKey)
  1432. {
  1433. if (peer->view == [w firstResponder])
  1434. return false;
  1435. }
  1436. else
  1437. {
  1438. if (peer->isSharedWindow
  1439. ? NSPointInRect ([peer->view convertPoint: [e locationInWindow] fromView: nil], [peer->view bounds])
  1440. : NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height)))
  1441. return false;
  1442. }
  1443. }
  1444. }
  1445. }
  1446. if (isInputAttempt)
  1447. {
  1448. if (! [NSApp isActive])
  1449. [NSApp activateIgnoringOtherApps: YES];
  1450. if (auto* modal = Component::getCurrentlyModalComponent())
  1451. modal->inputAttemptWhenModal();
  1452. }
  1453. return true;
  1454. }
  1455. void setFullScreenSizeConstraints (const ComponentBoundsConstrainer& c)
  1456. {
  1457. const auto minSize = NSMakeSize (static_cast<float> (c.getMinimumWidth()),
  1458. 0.0f);
  1459. [window setMinFullScreenContentSize: minSize];
  1460. [window setMaxFullScreenContentSize: NSMakeSize (100000, 100000)];
  1461. }
  1462. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentPeer)
  1463. };
  1464. int NSViewComponentPeer::insideToFrontCall = 0;
  1465. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wundeclared-selector")
  1466. const SEL NSViewComponentPeer::dismissModalsSelector = @selector (dismissModals);
  1467. const SEL NSViewComponentPeer::frameChangedSelector = @selector (frameChanged:);
  1468. const SEL NSViewComponentPeer::asyncMouseDownSelector = @selector (asyncMouseDown:);
  1469. const SEL NSViewComponentPeer::asyncMouseUpSelector = @selector (asyncMouseUp:);
  1470. const SEL NSViewComponentPeer::becomeKeySelector = @selector (becomeKey:);
  1471. const SEL NSViewComponentPeer::resignKeySelector = @selector (resignKey:);
  1472. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  1473. //==============================================================================
  1474. template <typename Base>
  1475. struct NSViewComponentPeerWrapper : public Base
  1476. {
  1477. explicit NSViewComponentPeerWrapper (const char* baseName)
  1478. : Base (baseName)
  1479. {
  1480. Base::template addIvar<NSViewComponentPeer*> ("owner");
  1481. }
  1482. static NSViewComponentPeer* getOwner (id self)
  1483. {
  1484. return getIvar<NSViewComponentPeer*> (self, "owner");
  1485. }
  1486. static id getAccessibleChild (id self)
  1487. {
  1488. if (auto* owner = getOwner (self))
  1489. if (auto* handler = owner->getComponent().getAccessibilityHandler())
  1490. return (id) handler->getNativeImplementation();
  1491. return nil;
  1492. }
  1493. };
  1494. struct JuceNSViewClass : public NSViewComponentPeerWrapper<ObjCClass<NSView>>
  1495. {
  1496. JuceNSViewClass() : NSViewComponentPeerWrapper ("JUCEView_")
  1497. {
  1498. addMethod (@selector (isOpaque), isOpaque);
  1499. addMethod (@selector (drawRect:), drawRect);
  1500. addMethod (@selector (mouseDown:), mouseDown);
  1501. addMethod (@selector (mouseUp:), mouseUp);
  1502. addMethod (@selector (mouseDragged:), mouseDragged);
  1503. addMethod (@selector (mouseMoved:), mouseMoved);
  1504. addMethod (@selector (mouseEntered:), mouseEntered);
  1505. addMethod (@selector (mouseExited:), mouseExited);
  1506. addMethod (@selector (rightMouseDown:), mouseDown);
  1507. addMethod (@selector (rightMouseDragged:), mouseDragged);
  1508. addMethod (@selector (rightMouseUp:), mouseUp);
  1509. addMethod (@selector (otherMouseDown:), mouseDown);
  1510. addMethod (@selector (otherMouseDragged:), mouseDragged);
  1511. addMethod (@selector (otherMouseUp:), mouseUp);
  1512. addMethod (@selector (scrollWheel:), scrollWheel);
  1513. addMethod (@selector (magnifyWithEvent:), magnify);
  1514. addMethod (@selector (acceptsFirstMouse:), acceptsFirstMouse);
  1515. addMethod (@selector (windowWillMiniaturize:), windowWillMiniaturize);
  1516. addMethod (@selector (windowDidDeminiaturize:), windowDidDeminiaturize);
  1517. addMethod (@selector (wantsDefaultClipping), wantsDefaultClipping);
  1518. addMethod (@selector (worksWhenModal), worksWhenModal);
  1519. addMethod (@selector (viewDidMoveToWindow), viewDidMoveToWindow);
  1520. addMethod (@selector (viewWillDraw), viewWillDraw);
  1521. addMethod (@selector (keyDown:), keyDown);
  1522. addMethod (@selector (keyUp:), keyUp);
  1523. addMethod (@selector (insertText:), insertText);
  1524. addMethod (@selector (doCommandBySelector:), doCommandBySelector);
  1525. addMethod (@selector (setMarkedText:selectedRange:), setMarkedText);
  1526. addMethod (@selector (unmarkText), unmarkText);
  1527. addMethod (@selector (hasMarkedText), hasMarkedText);
  1528. addMethod (@selector (conversationIdentifier), conversationIdentifier);
  1529. addMethod (@selector (attributedSubstringFromRange:), attributedSubstringFromRange);
  1530. addMethod (@selector (markedRange), markedRange);
  1531. addMethod (@selector (selectedRange), selectedRange);
  1532. addMethod (@selector (firstRectForCharacterRange:), firstRectForCharacterRange);
  1533. addMethod (@selector (characterIndexForPoint:), characterIndexForPoint);
  1534. addMethod (@selector (validAttributesForMarkedText), validAttributesForMarkedText);
  1535. addMethod (@selector (flagsChanged:), flagsChanged);
  1536. addMethod (@selector (becomeFirstResponder), becomeFirstResponder);
  1537. addMethod (@selector (resignFirstResponder), resignFirstResponder);
  1538. addMethod (@selector (acceptsFirstResponder), acceptsFirstResponder);
  1539. addMethod (@selector (draggingEntered:), draggingEntered);
  1540. addMethod (@selector (draggingUpdated:), draggingUpdated);
  1541. addMethod (@selector (draggingEnded:), draggingEnded);
  1542. addMethod (@selector (draggingExited:), draggingExited);
  1543. addMethod (@selector (prepareForDragOperation:), prepareForDragOperation);
  1544. addMethod (@selector (performDragOperation:), performDragOperation);
  1545. addMethod (@selector (concludeDragOperation:), concludeDragOperation);
  1546. addMethod (@selector (paste:), paste);
  1547. addMethod (@selector (copy:), copy);
  1548. addMethod (@selector (cut:), cut);
  1549. addMethod (@selector (selectAll:), selectAll);
  1550. addMethod (@selector (viewWillMoveToWindow:), willMoveToWindow);
  1551. addMethod (@selector (isAccessibilityElement), getIsAccessibilityElement);
  1552. addMethod (@selector (accessibilityChildren), getAccessibilityChildren);
  1553. addMethod (@selector (accessibilityHitTest:), accessibilityHitTest);
  1554. addMethod (@selector (accessibilityFocusedUIElement), getAccessibilityFocusedUIElement);
  1555. // deprecated methods required for backwards compatibility
  1556. addMethod (@selector (accessibilityIsIgnored), getAccessibilityIsIgnored);
  1557. addMethod (@selector (accessibilityAttributeValue:), getAccessibilityAttributeValue);
  1558. addMethod (@selector (isFlipped), isFlipped);
  1559. addMethod (NSViewComponentPeer::dismissModalsSelector, dismissModals);
  1560. addMethod (NSViewComponentPeer::asyncMouseDownSelector, asyncMouseDown);
  1561. addMethod (NSViewComponentPeer::asyncMouseUpSelector, asyncMouseUp);
  1562. addMethod (NSViewComponentPeer::frameChangedSelector, frameChanged);
  1563. addMethod (NSViewComponentPeer::becomeKeySelector, becomeKey);
  1564. addMethod (NSViewComponentPeer::resignKeySelector, resignKey);
  1565. addMethod (@selector (performKeyEquivalent:), performKeyEquivalent);
  1566. addProtocol (@protocol (NSTextInput));
  1567. registerClass();
  1568. }
  1569. private:
  1570. static void mouseDown (id self, SEL s, NSEvent* ev)
  1571. {
  1572. if (JUCEApplicationBase::isStandaloneApp())
  1573. {
  1574. asyncMouseDown (self, s, ev);
  1575. }
  1576. else
  1577. {
  1578. // In some host situations, the host will stop modal loops from working
  1579. // correctly if they're called from a mouse event, so we'll trigger
  1580. // the event asynchronously..
  1581. [self performSelectorOnMainThread: NSViewComponentPeer::asyncMouseDownSelector
  1582. withObject: ev
  1583. waitUntilDone: NO];
  1584. }
  1585. }
  1586. static void mouseUp (id self, SEL s, NSEvent* ev)
  1587. {
  1588. if (JUCEApplicationBase::isStandaloneApp())
  1589. {
  1590. asyncMouseUp (self, s, ev);
  1591. }
  1592. else
  1593. {
  1594. // In some host situations, the host will stop modal loops from working
  1595. // correctly if they're called from a mouse event, so we'll trigger
  1596. // the event asynchronously..
  1597. [self performSelectorOnMainThread: NSViewComponentPeer::asyncMouseUpSelector
  1598. withObject: ev
  1599. waitUntilDone: NO];
  1600. }
  1601. }
  1602. static void asyncMouseDown (id self, SEL, NSEvent* ev) { callOnOwner (self, &NSViewComponentPeer::redirectMouseDown, ev); }
  1603. static void asyncMouseUp (id self, SEL, NSEvent* ev) { callOnOwner (self, &NSViewComponentPeer::redirectMouseUp, ev); }
  1604. static void mouseDragged (id self, SEL, NSEvent* ev) { callOnOwner (self, &NSViewComponentPeer::redirectMouseDrag, ev); }
  1605. static void mouseMoved (id self, SEL, NSEvent* ev) { callOnOwner (self, &NSViewComponentPeer::redirectMouseMove, ev); }
  1606. static void mouseEntered (id self, SEL, NSEvent* ev) { callOnOwner (self, &NSViewComponentPeer::redirectMouseEnter, ev); }
  1607. static void mouseExited (id self, SEL, NSEvent* ev) { callOnOwner (self, &NSViewComponentPeer::redirectMouseExit, ev); }
  1608. static void scrollWheel (id self, SEL, NSEvent* ev) { callOnOwner (self, &NSViewComponentPeer::redirectMouseWheel, ev); }
  1609. static void magnify (id self, SEL, NSEvent* ev) { callOnOwner (self, &NSViewComponentPeer::redirectMagnify, ev); }
  1610. static void copy (id self, SEL, NSObject* s) { callOnOwner (self, &NSViewComponentPeer::redirectCopy, s); }
  1611. static void paste (id self, SEL, NSObject* s) { callOnOwner (self, &NSViewComponentPeer::redirectPaste, s); }
  1612. static void cut (id self, SEL, NSObject* s) { callOnOwner (self, &NSViewComponentPeer::redirectCut, s); }
  1613. static void selectAll (id self, SEL, NSObject* s) { callOnOwner (self, &NSViewComponentPeer::redirectSelectAll, s); }
  1614. static void willMoveToWindow (id self, SEL, NSWindow* w) { callOnOwner (self, &NSViewComponentPeer::redirectWillMoveToWindow, w); }
  1615. static BOOL acceptsFirstMouse (id, SEL, NSEvent*) { return YES; }
  1616. static BOOL wantsDefaultClipping (id, SEL) { return YES; } // (this is the default, but may want to customise it in future)
  1617. static BOOL worksWhenModal (id self, SEL) { if (auto* p = getOwner (self)) return p->worksWhenModal(); return NO; }
  1618. static void drawRect (id self, SEL, NSRect r) { callOnOwner (self, &NSViewComponentPeer::drawRect, r); }
  1619. static void frameChanged (id self, SEL, NSNotification*) { callOnOwner (self, &NSViewComponentPeer::redirectMovedOrResized); }
  1620. static void viewDidMoveToWindow (id self, SEL) { callOnOwner (self, &NSViewComponentPeer::viewMovedToWindow); }
  1621. static void dismissModals (id self, SEL) { callOnOwner (self, &NSViewComponentPeer::dismissModals); }
  1622. static void becomeKey (id self, SEL) { callOnOwner (self, &NSViewComponentPeer::becomeKey); }
  1623. static void resignKey (id self, SEL) { callOnOwner (self, &NSViewComponentPeer::resignKey); }
  1624. static BOOL isFlipped (id, SEL) { return true; }
  1625. static void viewWillDraw (id self, SEL)
  1626. {
  1627. // Without setting contentsFormat macOS Big Sur will always set the invalid area
  1628. // to be the entire frame.
  1629. #if defined (MAC_OS_X_VERSION_10_12) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_12
  1630. if (@available (macOS 10.12, *))
  1631. {
  1632. CALayer* layer = ((NSView*) self).layer;
  1633. layer.contentsFormat = kCAContentsFormatRGBA8Uint;
  1634. }
  1635. #endif
  1636. sendSuperclassMessage<void> (self, @selector (viewWillDraw));
  1637. }
  1638. static void windowWillMiniaturize (id self, SEL, NSNotification*)
  1639. {
  1640. if (auto* p = getOwner (self))
  1641. {
  1642. if (p->isAlwaysOnTop)
  1643. {
  1644. // there is a bug when restoring minimised always on top windows so we need
  1645. // to remove this behaviour before minimising and restore it afterwards
  1646. p->setAlwaysOnTop (false);
  1647. p->wasAlwaysOnTop = true;
  1648. }
  1649. }
  1650. }
  1651. static void windowDidDeminiaturize (id self, SEL, NSNotification*)
  1652. {
  1653. if (auto* p = getOwner (self))
  1654. {
  1655. if (p->wasAlwaysOnTop)
  1656. p->setAlwaysOnTop (true);
  1657. p->redirectMovedOrResized();
  1658. }
  1659. }
  1660. static BOOL isOpaque (id self, SEL)
  1661. {
  1662. auto* owner = getOwner (self);
  1663. return owner == nullptr || owner->getComponent().isOpaque();
  1664. }
  1665. //==============================================================================
  1666. static void keyDown (id self, SEL, NSEvent* ev)
  1667. {
  1668. if (auto* owner = getOwner (self))
  1669. {
  1670. auto* target = owner->findCurrentTextInputTarget();
  1671. owner->textWasInserted = false;
  1672. if (target != nullptr)
  1673. [(NSView*) self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  1674. else
  1675. owner->stringBeingComposed.clear();
  1676. if (! (owner->textWasInserted || owner->redirectKeyDown (ev)))
  1677. sendSuperclassMessage<void> (self, @selector (keyDown:), ev);
  1678. }
  1679. }
  1680. static void keyUp (id self, SEL, NSEvent* ev)
  1681. {
  1682. auto* owner = getOwner (self);
  1683. if (! owner->redirectKeyUp (ev))
  1684. sendSuperclassMessage<void> (self, @selector (keyUp:), ev);
  1685. }
  1686. //==============================================================================
  1687. static void insertText (id self, SEL, id aString)
  1688. {
  1689. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  1690. if (auto* owner = getOwner (self))
  1691. {
  1692. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  1693. if ([newText length] > 0)
  1694. {
  1695. if (auto* target = owner->findCurrentTextInputTarget())
  1696. {
  1697. target->insertTextAtCaret (nsStringToJuce (newText));
  1698. owner->textWasInserted = true;
  1699. }
  1700. }
  1701. owner->stringBeingComposed.clear();
  1702. }
  1703. }
  1704. static void doCommandBySelector (id, SEL, SEL) {}
  1705. static void setMarkedText (id self, SEL, id aString, NSRange)
  1706. {
  1707. if (auto* owner = getOwner (self))
  1708. {
  1709. owner->stringBeingComposed = nsStringToJuce ([aString isKindOfClass: [NSAttributedString class]]
  1710. ? [aString string] : aString);
  1711. if (auto* target = owner->findCurrentTextInputTarget())
  1712. {
  1713. auto currentHighlight = target->getHighlightedRegion();
  1714. target->insertTextAtCaret (owner->stringBeingComposed);
  1715. target->setHighlightedRegion (currentHighlight.withLength (owner->stringBeingComposed.length()));
  1716. owner->textWasInserted = true;
  1717. }
  1718. }
  1719. }
  1720. static void unmarkText (id self, SEL)
  1721. {
  1722. if (auto* owner = getOwner (self))
  1723. {
  1724. if (owner->stringBeingComposed.isNotEmpty())
  1725. {
  1726. if (auto* target = owner->findCurrentTextInputTarget())
  1727. {
  1728. target->insertTextAtCaret (owner->stringBeingComposed);
  1729. owner->textWasInserted = true;
  1730. }
  1731. owner->stringBeingComposed.clear();
  1732. }
  1733. }
  1734. }
  1735. static BOOL hasMarkedText (id self, SEL)
  1736. {
  1737. auto* owner = getOwner (self);
  1738. return owner != nullptr && owner->stringBeingComposed.isNotEmpty();
  1739. }
  1740. static long conversationIdentifier (id self, SEL)
  1741. {
  1742. return (long) (pointer_sized_int) self;
  1743. }
  1744. static NSAttributedString* attributedSubstringFromRange (id self, SEL, NSRange theRange)
  1745. {
  1746. if (auto* owner = getOwner (self))
  1747. {
  1748. if (auto* target = owner->findCurrentTextInputTarget())
  1749. {
  1750. Range<int> r ((int) theRange.location,
  1751. (int) (theRange.location + theRange.length));
  1752. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  1753. }
  1754. }
  1755. return nil;
  1756. }
  1757. static NSRange markedRange (id self, SEL)
  1758. {
  1759. if (auto* owner = getOwner (self))
  1760. if (owner->stringBeingComposed.isNotEmpty())
  1761. return NSMakeRange (0, (NSUInteger) owner->stringBeingComposed.length());
  1762. return NSMakeRange (NSNotFound, 0);
  1763. }
  1764. static NSRange selectedRange (id self, SEL)
  1765. {
  1766. if (auto* owner = getOwner (self))
  1767. {
  1768. if (auto* target = owner->findCurrentTextInputTarget())
  1769. {
  1770. auto highlight = target->getHighlightedRegion();
  1771. if (! highlight.isEmpty())
  1772. return NSMakeRange ((NSUInteger) highlight.getStart(),
  1773. (NSUInteger) highlight.getLength());
  1774. }
  1775. }
  1776. return NSMakeRange (NSNotFound, 0);
  1777. }
  1778. static NSRect firstRectForCharacterRange (id self, SEL, NSRange)
  1779. {
  1780. if (auto* owner = getOwner (self))
  1781. if (auto* comp = dynamic_cast<Component*> (owner->findCurrentTextInputTarget()))
  1782. return flippedScreenRect (makeNSRect (comp->getScreenBounds()));
  1783. return NSZeroRect;
  1784. }
  1785. static NSUInteger characterIndexForPoint (id, SEL, NSPoint) { return NSNotFound; }
  1786. static NSArray* validAttributesForMarkedText (id, SEL) { return [NSArray array]; }
  1787. //==============================================================================
  1788. static void flagsChanged (id self, SEL, NSEvent* ev)
  1789. {
  1790. callOnOwner (self, &NSViewComponentPeer::redirectModKeyChange, ev);
  1791. }
  1792. static BOOL becomeFirstResponder (id self, SEL)
  1793. {
  1794. callOnOwner (self, &NSViewComponentPeer::viewFocusGain);
  1795. return YES;
  1796. }
  1797. static BOOL resignFirstResponder (id self, SEL)
  1798. {
  1799. callOnOwner (self, &NSViewComponentPeer::viewFocusLoss);
  1800. return YES;
  1801. }
  1802. static BOOL acceptsFirstResponder (id self, SEL)
  1803. {
  1804. auto* owner = getOwner (self);
  1805. return owner != nullptr && owner->canBecomeKeyWindow();
  1806. }
  1807. //==============================================================================
  1808. static NSDragOperation draggingEntered (id self, SEL s, id<NSDraggingInfo> sender)
  1809. {
  1810. return draggingUpdated (self, s, sender);
  1811. }
  1812. static NSDragOperation draggingUpdated (id self, SEL, id<NSDraggingInfo> sender)
  1813. {
  1814. if (auto* owner = getOwner (self))
  1815. if (owner->sendDragCallback (0, sender))
  1816. return NSDragOperationGeneric;
  1817. return NSDragOperationNone;
  1818. }
  1819. static void draggingEnded (id self, SEL s, id<NSDraggingInfo> sender)
  1820. {
  1821. draggingExited (self, s, sender);
  1822. }
  1823. static void draggingExited (id self, SEL, id<NSDraggingInfo> sender)
  1824. {
  1825. callOnOwner (self, &NSViewComponentPeer::sendDragCallback, 1, sender);
  1826. }
  1827. static BOOL prepareForDragOperation (id, SEL, id<NSDraggingInfo>)
  1828. {
  1829. return YES;
  1830. }
  1831. static BOOL performDragOperation (id self, SEL, id<NSDraggingInfo> sender)
  1832. {
  1833. auto* owner = getOwner (self);
  1834. return owner != nullptr && owner->sendDragCallback (2, sender);
  1835. }
  1836. static void concludeDragOperation (id, SEL, id<NSDraggingInfo>) {}
  1837. //==============================================================================
  1838. static BOOL getIsAccessibilityElement (id, SEL)
  1839. {
  1840. return NO;
  1841. }
  1842. static NSArray* getAccessibilityChildren (id self, SEL)
  1843. {
  1844. return NSAccessibilityUnignoredChildrenForOnlyChild (getAccessibleChild (self));
  1845. }
  1846. static id accessibilityHitTest (id self, SEL, NSPoint point)
  1847. {
  1848. return [getAccessibleChild (self) accessibilityHitTest: point];
  1849. }
  1850. static id getAccessibilityFocusedUIElement (id self, SEL)
  1851. {
  1852. return [getAccessibleChild (self) accessibilityFocusedUIElement];
  1853. }
  1854. static BOOL getAccessibilityIsIgnored (id, SEL)
  1855. {
  1856. return YES;
  1857. }
  1858. static id getAccessibilityAttributeValue (id self, SEL, NSString* attribute)
  1859. {
  1860. if ([attribute isEqualToString: NSAccessibilityChildrenAttribute])
  1861. return getAccessibilityChildren (self, {});
  1862. return sendSuperclassMessage<id> (self, @selector (accessibilityAttributeValue:), attribute);
  1863. }
  1864. static bool tryPassingKeyEventToPeer (NSEvent* e)
  1865. {
  1866. if ([e type] != NSEventTypeKeyDown && [e type] != NSEventTypeKeyUp)
  1867. return false;
  1868. if (auto* focused = Component::getCurrentlyFocusedComponent())
  1869. {
  1870. if (auto* peer = dynamic_cast<NSViewComponentPeer*> (focused->getPeer()))
  1871. {
  1872. return [e type] == NSEventTypeKeyDown ? peer->redirectKeyDown (e)
  1873. : peer->redirectKeyUp (e);
  1874. }
  1875. }
  1876. return false;
  1877. }
  1878. static BOOL performKeyEquivalent (id self, SEL s, NSEvent* event)
  1879. {
  1880. // We try passing shortcut keys to the currently focused component first.
  1881. // If the component doesn't want the event, we'll fall back to the superclass
  1882. // implementation, which will pass the event to the main menu.
  1883. if (tryPassingKeyEventToPeer (event))
  1884. return YES;
  1885. return sendSuperclassMessage<BOOL> (self, s, event);
  1886. }
  1887. template <typename Func, typename... Args>
  1888. static void callOnOwner (id self, Func&& func, Args&&... args)
  1889. {
  1890. if (auto* owner = getOwner (self))
  1891. (owner->*func) (std::forward<Args> (args)...);
  1892. }
  1893. };
  1894. //==============================================================================
  1895. struct JuceNSWindowClass : public NSViewComponentPeerWrapper<ObjCClass<NSWindow>>
  1896. {
  1897. JuceNSWindowClass() : NSViewComponentPeerWrapper ("JUCEWindow_")
  1898. {
  1899. addMethod (@selector (canBecomeKeyWindow), canBecomeKeyWindow);
  1900. addMethod (@selector (canBecomeMainWindow), canBecomeMainWindow);
  1901. addMethod (@selector (becomeKeyWindow), becomeKeyWindow);
  1902. addMethod (@selector (resignKeyWindow), resignKeyWindow);
  1903. addMethod (@selector (windowShouldClose:), windowShouldClose);
  1904. addMethod (@selector (constrainFrameRect:toScreen:), constrainFrameRect);
  1905. addMethod (@selector (windowWillResize:toSize:), windowWillResize);
  1906. addMethod (@selector (windowDidExitFullScreen:), windowDidExitFullScreen);
  1907. addMethod (@selector (windowWillEnterFullScreen:), windowWillEnterFullScreen);
  1908. addMethod (@selector (windowWillStartLiveResize:), windowWillStartLiveResize);
  1909. addMethod (@selector (windowDidEndLiveResize:), windowDidEndLiveResize);
  1910. addMethod (@selector (window:shouldPopUpDocumentPathMenu:), shouldPopUpPathMenu);
  1911. addMethod (@selector (isFlipped), isFlipped);
  1912. addMethod (@selector (windowWillUseStandardFrame:defaultFrame:), windowWillUseStandardFrame);
  1913. addMethod (@selector (windowShouldZoom:toFrame:), windowShouldZoomToFrame);
  1914. addMethod (@selector (accessibilityTitle), getAccessibilityTitle);
  1915. addMethod (@selector (accessibilityLabel), getAccessibilityLabel);
  1916. addMethod (@selector (accessibilityTopLevelUIElement), getAccessibilityWindow);
  1917. addMethod (@selector (accessibilityWindow), getAccessibilityWindow);
  1918. addMethod (@selector (accessibilityRole), getAccessibilityRole);
  1919. addMethod (@selector (accessibilitySubrole), getAccessibilitySubrole);
  1920. addMethod (@selector (window:shouldDragDocumentWithEvent:from:withPasteboard:), shouldAllowIconDrag);
  1921. addProtocol (@protocol (NSWindowDelegate));
  1922. registerClass();
  1923. }
  1924. private:
  1925. //==============================================================================
  1926. static BOOL isFlipped (id, SEL) { return true; }
  1927. static NSRect windowWillUseStandardFrame (id self, SEL, NSWindow*, NSRect)
  1928. {
  1929. if (auto* owner = getOwner (self))
  1930. {
  1931. if (auto* constrainer = owner->getConstrainer())
  1932. {
  1933. return flippedScreenRect (makeNSRect (owner->getFrameSize().addedTo (owner->getComponent().getScreenBounds()
  1934. .withWidth (constrainer->getMaximumWidth())
  1935. .withHeight (constrainer->getMaximumHeight()))));
  1936. }
  1937. }
  1938. return makeNSRect (Rectangle<int> (10000, 10000));
  1939. }
  1940. static BOOL windowShouldZoomToFrame (id self, SEL, NSWindow* window, NSRect frame)
  1941. {
  1942. if (auto* owner = getOwner (self))
  1943. if (owner->hasNativeTitleBar() && (owner->getStyleFlags() & ComponentPeer::windowIsResizable) == 0)
  1944. return NO;
  1945. return convertToRectFloat ([window frame]).withZeroOrigin() != convertToRectFloat (frame).withZeroOrigin();
  1946. }
  1947. static BOOL canBecomeKeyWindow (id self, SEL)
  1948. {
  1949. auto* owner = getOwner (self);
  1950. return owner != nullptr
  1951. && owner->canBecomeKeyWindow()
  1952. && ! owner->isBlockedByModalComponent();
  1953. }
  1954. static BOOL canBecomeMainWindow (id self, SEL)
  1955. {
  1956. auto* owner = getOwner (self);
  1957. return owner != nullptr
  1958. && owner->canBecomeMainWindow()
  1959. && ! owner->isBlockedByModalComponent();
  1960. }
  1961. static void becomeKeyWindow (id self, SEL)
  1962. {
  1963. sendSuperclassMessage<void> (self, @selector (becomeKeyWindow));
  1964. if (auto* owner = getOwner (self))
  1965. {
  1966. if (owner->canBecomeKeyWindow())
  1967. {
  1968. owner->becomeKeyWindow();
  1969. return;
  1970. }
  1971. // this fixes a bug causing hidden windows to sometimes become visible when the app regains focus
  1972. if (! owner->getComponent().isVisible())
  1973. [(NSWindow*) self orderOut: nil];
  1974. }
  1975. }
  1976. static void resignKeyWindow (id self, SEL)
  1977. {
  1978. sendSuperclassMessage<void> (self, @selector (resignKeyWindow));
  1979. if (auto* owner = getOwner (self))
  1980. owner->resignKeyWindow();
  1981. }
  1982. static BOOL windowShouldClose (id self, SEL, id /*window*/)
  1983. {
  1984. auto* owner = getOwner (self);
  1985. return owner == nullptr || owner->windowShouldClose();
  1986. }
  1987. static NSRect constrainFrameRect (id self, SEL, NSRect frameRect, NSScreen* screen)
  1988. {
  1989. if (auto* owner = getOwner (self))
  1990. {
  1991. frameRect = sendSuperclassMessage<NSRect, NSRect, NSScreen*> (self, @selector (constrainFrameRect:toScreen:),
  1992. frameRect, screen);
  1993. frameRect = owner->constrainRect (frameRect);
  1994. }
  1995. return frameRect;
  1996. }
  1997. static NSSize windowWillResize (id self, SEL, NSWindow*, NSSize proposedFrameSize)
  1998. {
  1999. auto* owner = getOwner (self);
  2000. if (owner == nullptr || owner->isZooming)
  2001. return proposedFrameSize;
  2002. NSRect frameRect = flippedScreenRect ([(NSWindow*) self frame]);
  2003. frameRect.size = proposedFrameSize;
  2004. frameRect = owner->constrainRect (flippedScreenRect (frameRect));
  2005. owner->dismissModals();
  2006. return frameRect.size;
  2007. }
  2008. static void windowDidExitFullScreen (id self, SEL, NSNotification*)
  2009. {
  2010. if (auto* owner = getOwner (self))
  2011. owner->resetWindowPresentation();
  2012. }
  2013. static void windowWillEnterFullScreen (id self, SEL, NSNotification*)
  2014. {
  2015. if (SystemStats::getOperatingSystemType() <= SystemStats::MacOSX_10_9)
  2016. return;
  2017. if (auto* owner = getOwner (self))
  2018. if (owner->hasNativeTitleBar() && (owner->getStyleFlags() & ComponentPeer::windowIsResizable) == 0)
  2019. [owner->window setStyleMask: NSWindowStyleMaskBorderless];
  2020. }
  2021. static void windowWillStartLiveResize (id self, SEL, NSNotification*)
  2022. {
  2023. if (auto* owner = getOwner (self))
  2024. owner->liveResizingStart();
  2025. }
  2026. static void windowDidEndLiveResize (id self, SEL, NSNotification*)
  2027. {
  2028. if (auto* owner = getOwner (self))
  2029. owner->liveResizingEnd();
  2030. }
  2031. static bool shouldPopUpPathMenu (id self, SEL, id /*window*/, NSMenu*)
  2032. {
  2033. if (auto* owner = getOwner (self))
  2034. return owner->windowRepresentsFile;
  2035. return false;
  2036. }
  2037. static bool shouldAllowIconDrag (id self, SEL, id /*window*/, NSEvent*, NSPoint, NSPasteboard*)
  2038. {
  2039. if (auto* owner = getOwner (self))
  2040. return owner->windowRepresentsFile;
  2041. return false;
  2042. }
  2043. static NSString* getAccessibilityTitle (id self, SEL)
  2044. {
  2045. return [self title];
  2046. }
  2047. static NSString* getAccessibilityLabel (id self, SEL)
  2048. {
  2049. return [getAccessibleChild (self) accessibilityLabel];
  2050. }
  2051. static id getAccessibilityWindow (id self, SEL)
  2052. {
  2053. return self;
  2054. }
  2055. static NSAccessibilityRole getAccessibilityRole (id, SEL)
  2056. {
  2057. return NSAccessibilityWindowRole;
  2058. }
  2059. static NSAccessibilityRole getAccessibilitySubrole (id self, SEL)
  2060. {
  2061. if (@available (macOS 10.10, *))
  2062. return [getAccessibleChild (self) accessibilitySubrole];
  2063. return nil;
  2064. }
  2065. };
  2066. NSView* NSViewComponentPeer::createViewInstance()
  2067. {
  2068. static JuceNSViewClass cls;
  2069. return cls.createInstance();
  2070. }
  2071. NSWindow* NSViewComponentPeer::createWindowInstance()
  2072. {
  2073. static JuceNSWindowClass cls;
  2074. return cls.createInstance();
  2075. }
  2076. //==============================================================================
  2077. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = nullptr;
  2078. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  2079. //==============================================================================
  2080. bool KeyPress::isKeyCurrentlyDown (int keyCode)
  2081. {
  2082. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  2083. return true;
  2084. if (keyCode >= 'A' && keyCode <= 'Z'
  2085. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  2086. return true;
  2087. if (keyCode >= 'a' && keyCode <= 'z'
  2088. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  2089. return true;
  2090. return false;
  2091. }
  2092. //==============================================================================
  2093. bool MouseInputSource::SourceList::addSource()
  2094. {
  2095. if (sources.size() == 0)
  2096. {
  2097. addSource (0, MouseInputSource::InputSourceType::mouse);
  2098. return true;
  2099. }
  2100. return false;
  2101. }
  2102. bool MouseInputSource::SourceList::canUseTouch()
  2103. {
  2104. return false;
  2105. }
  2106. //==============================================================================
  2107. void Desktop::setKioskComponent (Component* kioskComp, bool shouldBeEnabled, bool allowMenusAndBars)
  2108. {
  2109. auto* peer = dynamic_cast<NSViewComponentPeer*> (kioskComp->getPeer());
  2110. jassert (peer != nullptr); // (this should have been checked by the caller)
  2111. if (peer->hasNativeTitleBar())
  2112. {
  2113. if (shouldBeEnabled && ! allowMenusAndBars)
  2114. [NSApp setPresentationOptions: NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar];
  2115. else if (! shouldBeEnabled)
  2116. [NSApp setPresentationOptions: NSApplicationPresentationDefault];
  2117. peer->setFullScreen (true);
  2118. }
  2119. else
  2120. {
  2121. if (shouldBeEnabled)
  2122. {
  2123. [NSApp setPresentationOptions: (allowMenusAndBars ? (NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)
  2124. : (NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar))];
  2125. kioskComp->setBounds (getDisplays().getDisplayForRect (kioskComp->getScreenBounds())->totalArea);
  2126. peer->becomeKeyWindow();
  2127. }
  2128. else
  2129. {
  2130. peer->resetWindowPresentation();
  2131. }
  2132. }
  2133. }
  2134. void Desktop::allowedOrientationsChanged() {}
  2135. //==============================================================================
  2136. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  2137. {
  2138. return new NSViewComponentPeer (*this, styleFlags, (NSView*) windowToAttachTo);
  2139. }
  2140. //==============================================================================
  2141. const int KeyPress::spaceKey = ' ';
  2142. const int KeyPress::returnKey = 0x0d;
  2143. const int KeyPress::escapeKey = 0x1b;
  2144. const int KeyPress::backspaceKey = 0x7f;
  2145. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  2146. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  2147. const int KeyPress::upKey = NSUpArrowFunctionKey;
  2148. const int KeyPress::downKey = NSDownArrowFunctionKey;
  2149. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  2150. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  2151. const int KeyPress::endKey = NSEndFunctionKey;
  2152. const int KeyPress::homeKey = NSHomeFunctionKey;
  2153. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  2154. const int KeyPress::insertKey = -1;
  2155. const int KeyPress::tabKey = 9;
  2156. const int KeyPress::F1Key = NSF1FunctionKey;
  2157. const int KeyPress::F2Key = NSF2FunctionKey;
  2158. const int KeyPress::F3Key = NSF3FunctionKey;
  2159. const int KeyPress::F4Key = NSF4FunctionKey;
  2160. const int KeyPress::F5Key = NSF5FunctionKey;
  2161. const int KeyPress::F6Key = NSF6FunctionKey;
  2162. const int KeyPress::F7Key = NSF7FunctionKey;
  2163. const int KeyPress::F8Key = NSF8FunctionKey;
  2164. const int KeyPress::F9Key = NSF9FunctionKey;
  2165. const int KeyPress::F10Key = NSF10FunctionKey;
  2166. const int KeyPress::F11Key = NSF11FunctionKey;
  2167. const int KeyPress::F12Key = NSF12FunctionKey;
  2168. const int KeyPress::F13Key = NSF13FunctionKey;
  2169. const int KeyPress::F14Key = NSF14FunctionKey;
  2170. const int KeyPress::F15Key = NSF15FunctionKey;
  2171. const int KeyPress::F16Key = NSF16FunctionKey;
  2172. const int KeyPress::F17Key = NSF17FunctionKey;
  2173. const int KeyPress::F18Key = NSF18FunctionKey;
  2174. const int KeyPress::F19Key = NSF19FunctionKey;
  2175. const int KeyPress::F20Key = NSF20FunctionKey;
  2176. const int KeyPress::F21Key = NSF21FunctionKey;
  2177. const int KeyPress::F22Key = NSF22FunctionKey;
  2178. const int KeyPress::F23Key = NSF23FunctionKey;
  2179. const int KeyPress::F24Key = NSF24FunctionKey;
  2180. const int KeyPress::F25Key = NSF25FunctionKey;
  2181. const int KeyPress::F26Key = NSF26FunctionKey;
  2182. const int KeyPress::F27Key = NSF27FunctionKey;
  2183. const int KeyPress::F28Key = NSF28FunctionKey;
  2184. const int KeyPress::F29Key = NSF29FunctionKey;
  2185. const int KeyPress::F30Key = NSF30FunctionKey;
  2186. const int KeyPress::F31Key = NSF31FunctionKey;
  2187. const int KeyPress::F32Key = NSF32FunctionKey;
  2188. const int KeyPress::F33Key = NSF33FunctionKey;
  2189. const int KeyPress::F34Key = NSF34FunctionKey;
  2190. const int KeyPress::F35Key = NSF35FunctionKey;
  2191. const int KeyPress::numberPad0 = extendedKeyModifier + 0x20;
  2192. const int KeyPress::numberPad1 = extendedKeyModifier + 0x21;
  2193. const int KeyPress::numberPad2 = extendedKeyModifier + 0x22;
  2194. const int KeyPress::numberPad3 = extendedKeyModifier + 0x23;
  2195. const int KeyPress::numberPad4 = extendedKeyModifier + 0x24;
  2196. const int KeyPress::numberPad5 = extendedKeyModifier + 0x25;
  2197. const int KeyPress::numberPad6 = extendedKeyModifier + 0x26;
  2198. const int KeyPress::numberPad7 = extendedKeyModifier + 0x27;
  2199. const int KeyPress::numberPad8 = extendedKeyModifier + 0x28;
  2200. const int KeyPress::numberPad9 = extendedKeyModifier + 0x29;
  2201. const int KeyPress::numberPadAdd = extendedKeyModifier + 0x2a;
  2202. const int KeyPress::numberPadSubtract = extendedKeyModifier + 0x2b;
  2203. const int KeyPress::numberPadMultiply = extendedKeyModifier + 0x2c;
  2204. const int KeyPress::numberPadDivide = extendedKeyModifier + 0x2d;
  2205. const int KeyPress::numberPadSeparator = extendedKeyModifier + 0x2e;
  2206. const int KeyPress::numberPadDecimalPoint = extendedKeyModifier + 0x2f;
  2207. const int KeyPress::numberPadEquals = extendedKeyModifier + 0x30;
  2208. const int KeyPress::numberPadDelete = extendedKeyModifier + 0x31;
  2209. const int KeyPress::playKey = extendedKeyModifier + 0x00;
  2210. const int KeyPress::stopKey = extendedKeyModifier + 0x01;
  2211. const int KeyPress::fastForwardKey = extendedKeyModifier + 0x02;
  2212. const int KeyPress::rewindKey = extendedKeyModifier + 0x03;
  2213. } // namespace juce