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.

1975 lines
73KB

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