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.

1898 lines
62KB

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