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.

1993 lines
73KB

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