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.

1927 lines
63KB

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