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.

1932 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, 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. } // (juce namespace)
  350. //==============================================================================
  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. namespace juce
  695. {
  696. //==============================================================================
  697. ModifierKeys NSViewComponentPeer::currentModifiers;
  698. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = nullptr;
  699. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  700. //==============================================================================
  701. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  702. {
  703. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  704. return true;
  705. if (keyCode >= 'A' && keyCode <= 'Z'
  706. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  707. return true;
  708. if (keyCode >= 'a' && keyCode <= 'z'
  709. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  710. return true;
  711. return false;
  712. }
  713. void NSViewComponentPeer::updateModifiers (const NSUInteger flags)
  714. {
  715. int m = 0;
  716. if ((flags & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  717. if ((flags & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  718. if ((flags & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  719. if ((flags & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  720. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  721. }
  722. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  723. {
  724. updateModifiers ([e modifierFlags]);
  725. }
  726. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  727. {
  728. updateModifiers (ev);
  729. int keyCode = getKeyCodeFromEvent (ev);
  730. if (keyCode != 0)
  731. {
  732. if (isKeyDown)
  733. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  734. else
  735. keysCurrentlyDown.removeValue (keyCode);
  736. }
  737. }
  738. ModifierKeys ModifierKeys::getCurrentModifiersRealtime() noexcept
  739. {
  740. if ([NSEvent respondsToSelector: @selector (modifierFlags)])
  741. NSViewComponentPeer::updateModifiers ([NSEvent modifierFlags]);
  742. return NSViewComponentPeer::currentModifiers;
  743. }
  744. void ModifierKeys::updateCurrentModifiers() noexcept
  745. {
  746. currentModifiers = NSViewComponentPeer::currentModifiers;
  747. }
  748. //==============================================================================
  749. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  750. const int windowStyleFlags,
  751. NSView* viewToAttachTo)
  752. : ComponentPeer (component_, windowStyleFlags),
  753. window (nil),
  754. view (nil),
  755. isSharedWindow (viewToAttachTo != nil),
  756. fullScreen (false),
  757. insideDrawRect (false),
  758. #if USE_COREGRAPHICS_RENDERING
  759. usingCoreGraphics (true),
  760. #else
  761. usingCoreGraphics (false),
  762. #endif
  763. usingOpenGL (false),
  764. recursiveToFrontCall (false)
  765. {
  766. appFocusChangeCallback = appFocusChanged;
  767. isEventBlockedByModalComps = checkEventBlockedByModalComps;
  768. NSRect r = NSMakeRect (0, 0, (CGFloat) component->getWidth(), (CGFloat) component->getHeight());
  769. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  770. [view setPostsFrameChangedNotifications: YES];
  771. if (isSharedWindow)
  772. {
  773. window = [viewToAttachTo window];
  774. [viewToAttachTo addSubview: view];
  775. }
  776. else
  777. {
  778. r.origin.x = (CGFloat) component->getX();
  779. r.origin.y = (CGFloat) component->getY();
  780. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  781. window = [[JuceNSWindow alloc] initWithContentRect: r
  782. styleMask: getNSWindowStyleMask (windowStyleFlags)
  783. backing: NSBackingStoreBuffered
  784. defer: YES];
  785. [((JuceNSWindow*) window) setOwner: this];
  786. [window orderOut: nil];
  787. [window setDelegate: (JuceNSWindow*) window];
  788. [window setOpaque: component->isOpaque()];
  789. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  790. if (component->isAlwaysOnTop())
  791. [window setLevel: NSFloatingWindowLevel];
  792. [window setContentView: view];
  793. [window setAutodisplay: YES];
  794. [window setAcceptsMouseMovedEvents: YES];
  795. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  796. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  797. [window setReleasedWhenClosed: YES];
  798. [window retain];
  799. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  800. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  801. #if defined (MAC_OS_X_VERSION_10_7) && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7)
  802. if ((windowStyleFlags & (windowHasMaximiseButton | windowHasTitleBar)) == (windowHasMaximiseButton | windowHasTitleBar))
  803. [window setCollectionBehavior: NSWindowCollectionBehaviorFullScreenPrimary];
  804. #endif
  805. }
  806. const float alpha = component->getAlpha();
  807. if (alpha < 1.0f)
  808. setAlpha (alpha);
  809. setTitle (component->getName());
  810. }
  811. NSViewComponentPeer::~NSViewComponentPeer()
  812. {
  813. view->owner = nullptr;
  814. [view removeFromSuperview];
  815. [view release];
  816. if (! isSharedWindow)
  817. {
  818. [((JuceNSWindow*) window) setOwner: 0];
  819. [window close];
  820. [window release];
  821. }
  822. }
  823. //==============================================================================
  824. void* NSViewComponentPeer::getNativeHandle() const
  825. {
  826. return view;
  827. }
  828. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  829. {
  830. if (isSharedWindow)
  831. {
  832. [view setHidden: ! shouldBeVisible];
  833. }
  834. else
  835. {
  836. if (shouldBeVisible)
  837. {
  838. [window orderFront: nil];
  839. handleBroughtToFront();
  840. }
  841. else
  842. {
  843. [window orderOut: nil];
  844. }
  845. }
  846. }
  847. void NSViewComponentPeer::setTitle (const String& title)
  848. {
  849. JUCE_AUTORELEASEPOOL
  850. if (! isSharedWindow)
  851. [window setTitle: juceStringToNS (title)];
  852. }
  853. void NSViewComponentPeer::setPosition (int x, int y)
  854. {
  855. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  856. }
  857. void NSViewComponentPeer::setSize (int w, int h)
  858. {
  859. setBounds (component->getX(), component->getY(), w, h, false);
  860. }
  861. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  862. {
  863. fullScreen = isNowFullScreen;
  864. NSRect r = NSMakeRect ((CGFloat) x, (CGFloat) y, (CGFloat) jmax (0, w), (CGFloat) jmax (0, h));
  865. if (isSharedWindow)
  866. {
  867. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  868. if ([view frame].size.width != r.size.width
  869. || [view frame].size.height != r.size.height)
  870. {
  871. [view setNeedsDisplay: true];
  872. }
  873. [view setFrame: r];
  874. }
  875. else
  876. {
  877. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  878. [window setFrame: [window frameRectForContentRect: r]
  879. display: true];
  880. }
  881. }
  882. Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  883. {
  884. NSRect r = [view frame];
  885. if (global && [view window] != nil)
  886. {
  887. r = [view convertRect: r toView: nil];
  888. NSRect wr = [[view window] frame];
  889. r.origin.x += wr.origin.x;
  890. r.origin.y += wr.origin.y;
  891. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  892. }
  893. else
  894. {
  895. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  896. }
  897. return Rectangle<int> (convertToRectInt (r));
  898. }
  899. Rectangle<int> NSViewComponentPeer::getBounds() const
  900. {
  901. return getBounds (! isSharedWindow);
  902. }
  903. Point<int> NSViewComponentPeer::getScreenPosition() const
  904. {
  905. return getBounds (true).getPosition();
  906. }
  907. Point<int> NSViewComponentPeer::localToGlobal (const Point<int>& relativePosition)
  908. {
  909. return relativePosition + getScreenPosition();
  910. }
  911. Point<int> NSViewComponentPeer::globalToLocal (const Point<int>& screenPosition)
  912. {
  913. return screenPosition - getScreenPosition();
  914. }
  915. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  916. {
  917. if (constrainer != nullptr
  918. #if defined (MAC_OS_X_VERSION_10_7) && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7)
  919. && ([window styleMask] & NSFullScreenWindowMask) == 0
  920. #endif
  921. )
  922. {
  923. NSRect current = [window frame];
  924. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  925. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  926. Rectangle<int> pos (convertToRectInt (r));
  927. Rectangle<int> original (convertToRectInt (current));
  928. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_6
  929. if ([window inLiveResize])
  930. #else
  931. if ([window respondsToSelector: @selector (inLiveResize)]
  932. && [window performSelector: @selector (inLiveResize)])
  933. #endif
  934. {
  935. constrainer->checkBounds (pos, original,
  936. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  937. false, false, true, true);
  938. }
  939. else
  940. {
  941. constrainer->checkBounds (pos, original,
  942. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  943. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  944. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  945. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  946. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  947. }
  948. r.origin.x = pos.getX();
  949. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  950. r.size.width = pos.getWidth();
  951. r.size.height = pos.getHeight();
  952. }
  953. return r;
  954. }
  955. void NSViewComponentPeer::setAlpha (float newAlpha)
  956. {
  957. if (! isSharedWindow)
  958. {
  959. [window setAlphaValue: (CGFloat) newAlpha];
  960. }
  961. else
  962. {
  963. #if defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5
  964. [view setAlphaValue: (CGFloat) newAlpha];
  965. #else
  966. if ([view respondsToSelector: @selector (setAlphaValue:)])
  967. {
  968. // PITA dynamic invocation for 10.4 builds..
  969. NSInvocation* inv = [NSInvocation invocationWithMethodSignature: [view methodSignatureForSelector: @selector (setAlphaValue:)]];
  970. [inv setSelector: @selector (setAlphaValue:)];
  971. [inv setTarget: view];
  972. CGFloat cgNewAlpha = (CGFloat) newAlpha;
  973. [inv setArgument: &cgNewAlpha atIndex: 2];
  974. [inv invoke];
  975. }
  976. #endif
  977. }
  978. }
  979. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  980. {
  981. if (! isSharedWindow)
  982. {
  983. if (shouldBeMinimised)
  984. [window miniaturize: nil];
  985. else
  986. [window deminiaturize: nil];
  987. }
  988. }
  989. bool NSViewComponentPeer::isMinimised() const
  990. {
  991. return [window isMiniaturized];
  992. }
  993. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  994. {
  995. if (! isSharedWindow)
  996. {
  997. Rectangle<int> r (lastNonFullscreenBounds);
  998. if (isMinimised())
  999. setMinimised (false);
  1000. if (fullScreen != shouldBeFullScreen)
  1001. {
  1002. if (shouldBeFullScreen && hasNativeTitleBar())
  1003. {
  1004. fullScreen = true;
  1005. [window performZoom: nil];
  1006. }
  1007. else
  1008. {
  1009. if (shouldBeFullScreen)
  1010. r = component->getParentMonitorArea();
  1011. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  1012. if (r != getComponent()->getBounds() && ! r.isEmpty())
  1013. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  1014. }
  1015. }
  1016. }
  1017. }
  1018. bool NSViewComponentPeer::isFullScreen() const
  1019. {
  1020. return fullScreen;
  1021. }
  1022. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  1023. {
  1024. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  1025. && isPositiveAndBelow (position.getY(), component->getHeight())))
  1026. return false;
  1027. NSRect frameRect = [view frame];
  1028. NSView* v = [view hitTest: NSMakePoint (frameRect.origin.x + position.getX(),
  1029. frameRect.origin.y + frameRect.size.height - position.getY())];
  1030. if (trueIfInAChildWindow)
  1031. return v != nil;
  1032. return v == view;
  1033. }
  1034. BorderSize<int> NSViewComponentPeer::getFrameSize() const
  1035. {
  1036. BorderSize<int> b;
  1037. if (! isSharedWindow)
  1038. {
  1039. NSRect v = [view convertRect: [view frame] toView: nil];
  1040. NSRect w = [window frame];
  1041. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  1042. b.setBottom ((int) v.origin.y);
  1043. b.setLeft ((int) v.origin.x);
  1044. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  1045. }
  1046. return b;
  1047. }
  1048. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  1049. {
  1050. if (! isSharedWindow)
  1051. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  1052. : NSNormalWindowLevel];
  1053. return true;
  1054. }
  1055. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  1056. {
  1057. if (isSharedWindow)
  1058. [[view superview] addSubview: view
  1059. positioned: NSWindowAbove
  1060. relativeTo: nil];
  1061. if (window != nil && component->isVisible())
  1062. {
  1063. if (makeActiveWindow)
  1064. [window makeKeyAndOrderFront: nil];
  1065. else
  1066. [window orderFront: nil];
  1067. if (! recursiveToFrontCall)
  1068. {
  1069. recursiveToFrontCall = true;
  1070. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  1071. handleBroughtToFront();
  1072. recursiveToFrontCall = false;
  1073. }
  1074. }
  1075. }
  1076. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  1077. {
  1078. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  1079. jassert (otherPeer != nullptr); // wrong type of window?
  1080. if (otherPeer != nullptr)
  1081. {
  1082. if (isSharedWindow)
  1083. {
  1084. [[view superview] addSubview: view
  1085. positioned: NSWindowBelow
  1086. relativeTo: otherPeer->view];
  1087. }
  1088. else
  1089. {
  1090. [window orderWindow: NSWindowBelow
  1091. relativeTo: [otherPeer->window windowNumber]];
  1092. }
  1093. }
  1094. }
  1095. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  1096. {
  1097. // to do..
  1098. }
  1099. //==============================================================================
  1100. void NSViewComponentPeer::viewFocusGain()
  1101. {
  1102. if (currentlyFocusedPeer != this)
  1103. {
  1104. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  1105. currentlyFocusedPeer->handleFocusLoss();
  1106. currentlyFocusedPeer = this;
  1107. handleFocusGain();
  1108. }
  1109. }
  1110. void NSViewComponentPeer::viewFocusLoss()
  1111. {
  1112. if (currentlyFocusedPeer == this)
  1113. {
  1114. currentlyFocusedPeer = nullptr;
  1115. handleFocusLoss();
  1116. }
  1117. }
  1118. bool NSViewComponentPeer::isFocused() const
  1119. {
  1120. return isSharedWindow ? this == currentlyFocusedPeer
  1121. : [window isKeyWindow];
  1122. }
  1123. void NSViewComponentPeer::grabFocus()
  1124. {
  1125. if (window != nil)
  1126. {
  1127. [window makeKeyWindow];
  1128. [window makeFirstResponder: view];
  1129. viewFocusGain();
  1130. }
  1131. }
  1132. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  1133. {
  1134. }
  1135. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  1136. {
  1137. String unicode (nsStringToJuce ([ev characters]));
  1138. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  1139. int keyCode = getKeyCodeFromEvent (ev);
  1140. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  1141. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  1142. if (unicode.isNotEmpty() || keyCode != 0)
  1143. {
  1144. if (isKeyDown)
  1145. {
  1146. bool used = false;
  1147. while (unicode.length() > 0)
  1148. {
  1149. juce_wchar textCharacter = unicode[0];
  1150. unicode = unicode.substring (1);
  1151. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  1152. textCharacter = 0;
  1153. used = handleKeyUpOrDown (true) || used;
  1154. used = handleKeyPress (keyCode, textCharacter) || used;
  1155. }
  1156. return used;
  1157. }
  1158. else
  1159. {
  1160. if (handleKeyUpOrDown (false))
  1161. return true;
  1162. }
  1163. }
  1164. return false;
  1165. }
  1166. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  1167. {
  1168. updateKeysDown (ev, true);
  1169. bool used = handleKeyEvent (ev, true);
  1170. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  1171. {
  1172. // for command keys, the key-up event is thrown away, so simulate one..
  1173. updateKeysDown (ev, false);
  1174. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  1175. }
  1176. // (If we're running modally, don't allow unused keystrokes to be passed
  1177. // along to other blocked views..)
  1178. if (Component::getCurrentlyModalComponent() != nullptr)
  1179. used = true;
  1180. return used;
  1181. }
  1182. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  1183. {
  1184. updateKeysDown (ev, false);
  1185. return handleKeyEvent (ev, false)
  1186. || Component::getCurrentlyModalComponent() != nullptr;
  1187. }
  1188. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  1189. {
  1190. keysCurrentlyDown.clear();
  1191. handleKeyUpOrDown (true);
  1192. updateModifiers (ev);
  1193. handleModifierKeysChange();
  1194. }
  1195. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  1196. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  1197. {
  1198. if ([ev type] == NSKeyDown)
  1199. return redirectKeyDown (ev);
  1200. else if ([ev type] == NSKeyUp)
  1201. return redirectKeyUp (ev);
  1202. return false;
  1203. }
  1204. #endif
  1205. //==============================================================================
  1206. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  1207. {
  1208. updateModifiers (ev);
  1209. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  1210. }
  1211. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  1212. {
  1213. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  1214. sendMouseEvent (ev);
  1215. }
  1216. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  1217. {
  1218. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  1219. sendMouseEvent (ev);
  1220. showArrowCursorIfNeeded();
  1221. }
  1222. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  1223. {
  1224. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  1225. sendMouseEvent (ev);
  1226. }
  1227. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  1228. {
  1229. currentModifiers = currentModifiers.withoutMouseButtons();
  1230. sendMouseEvent (ev);
  1231. showArrowCursorIfNeeded();
  1232. }
  1233. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  1234. {
  1235. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  1236. currentModifiers = currentModifiers.withoutMouseButtons();
  1237. sendMouseEvent (ev);
  1238. }
  1239. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  1240. {
  1241. currentModifiers = currentModifiers.withoutMouseButtons();
  1242. sendMouseEvent (ev);
  1243. }
  1244. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  1245. {
  1246. updateModifiers (ev);
  1247. float x = 0, y = 0;
  1248. @try
  1249. {
  1250. #if defined (MAC_OS_X_VERSION_10_7) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
  1251. if ([ev respondsToSelector: @selector (hasPreciseScrollingDeltas)])
  1252. {
  1253. if ([ev hasPreciseScrollingDeltas])
  1254. {
  1255. x = [ev scrollingDeltaX] * 0.5f;
  1256. y = [ev scrollingDeltaY] * 0.5f;
  1257. }
  1258. }
  1259. else
  1260. #endif
  1261. {
  1262. x = [ev deviceDeltaX] * 0.5f;
  1263. y = [ev deviceDeltaY] * 0.5f;
  1264. }
  1265. }
  1266. @catch (...)
  1267. {}
  1268. if (x == 0 && y == 0)
  1269. {
  1270. x = [ev deltaX] * 10.0f;
  1271. y = [ev deltaY] * 10.0f;
  1272. }
  1273. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), x, y);
  1274. }
  1275. void NSViewComponentPeer::showArrowCursorIfNeeded()
  1276. {
  1277. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  1278. if (mouse.getComponentUnderMouse() == nullptr
  1279. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == nullptr)
  1280. {
  1281. [[NSCursor arrowCursor] set];
  1282. }
  1283. }
  1284. //==============================================================================
  1285. BOOL NSViewComponentPeer::sendDragCallback (const int type, id <NSDraggingInfo> sender)
  1286. {
  1287. NSString* bestType
  1288. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  1289. if (bestType == nil)
  1290. return false;
  1291. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  1292. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  1293. NSPasteboard* pasteBoard = [sender draggingPasteboard];
  1294. StringArray files;
  1295. NSString* iTunesPasteboardType = nsStringLiteral ("CorePasteboardFlavorType 0x6974756E"); // 'itun'
  1296. if (bestType == NSFilesPromisePboardType
  1297. && [[pasteBoard types] containsObject: iTunesPasteboardType])
  1298. {
  1299. id list = [pasteBoard propertyListForType: iTunesPasteboardType];
  1300. if ([list isKindOfClass: [NSDictionary class]])
  1301. {
  1302. NSDictionary* iTunesDictionary = (NSDictionary*) list;
  1303. NSArray* tracks = [iTunesDictionary valueForKey: nsStringLiteral ("Tracks")];
  1304. NSEnumerator* enumerator = [tracks objectEnumerator];
  1305. NSDictionary* track;
  1306. while ((track = [enumerator nextObject]) != nil)
  1307. {
  1308. NSURL* url = [NSURL URLWithString: [track valueForKey: nsStringLiteral ("Location")]];
  1309. if ([url isFileURL])
  1310. files.add (nsStringToJuce ([url path]));
  1311. }
  1312. }
  1313. }
  1314. else
  1315. {
  1316. id list = [pasteBoard propertyListForType: NSFilenamesPboardType];
  1317. if ([list isKindOfClass: [NSArray class]])
  1318. {
  1319. NSArray* items = (NSArray*) [pasteBoard propertyListForType: NSFilenamesPboardType];
  1320. for (unsigned int i = 0; i < [items count]; ++i)
  1321. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  1322. }
  1323. }
  1324. if (files.size() > 0)
  1325. {
  1326. switch (type)
  1327. {
  1328. case 0: return handleFileDragMove (files, pos);
  1329. case 1: return handleFileDragExit (files);
  1330. case 2: return handleFileDragDrop (files, pos);
  1331. default: jassertfalse; break;
  1332. }
  1333. }
  1334. return false;
  1335. }
  1336. bool NSViewComponentPeer::isOpaque()
  1337. {
  1338. return component == nullptr || component->isOpaque();
  1339. }
  1340. static void getClipRects (RectangleList& clip, NSView* view,
  1341. const int xOffset, const int yOffset, const int clipW, const int clipH)
  1342. {
  1343. const NSRect* rects = nullptr;
  1344. NSInteger numRects = 0;
  1345. [view getRectsBeingDrawn: &rects count: &numRects];
  1346. const Rectangle<int> clipBounds (clipW, clipH);
  1347. const CGFloat viewH = [view frame].size.height;
  1348. for (int i = 0; i < numRects; ++i)
  1349. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  1350. roundToInt (viewH - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  1351. roundToInt (rects[i].size.width),
  1352. roundToInt (rects[i].size.height))));
  1353. }
  1354. void NSViewComponentPeer::drawRect (NSRect r)
  1355. {
  1356. if (r.size.width < 1.0f || r.size.height < 1.0f)
  1357. return;
  1358. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  1359. if (! component->isOpaque())
  1360. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  1361. #if USE_COREGRAPHICS_RENDERING
  1362. if (usingCoreGraphics)
  1363. {
  1364. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  1365. insideDrawRect = true;
  1366. handlePaint (context);
  1367. insideDrawRect = false;
  1368. }
  1369. else
  1370. #endif
  1371. {
  1372. const int xOffset = -roundToInt (r.origin.x);
  1373. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  1374. const int clipW = (int) (r.size.width + 0.5f);
  1375. const int clipH = (int) (r.size.height + 0.5f);
  1376. RectangleList clip;
  1377. getClipRects (clip, view, xOffset, yOffset, clipW, clipH);
  1378. if (! clip.isEmpty())
  1379. {
  1380. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  1381. clipW, clipH, ! getComponent()->isOpaque());
  1382. {
  1383. ScopedPointer<LowLevelGraphicsContext> context (component->getLookAndFeel()
  1384. .createGraphicsContext (temp, Point<int> (xOffset, yOffset), clip));
  1385. insideDrawRect = true;
  1386. handlePaint (*context);
  1387. insideDrawRect = false;
  1388. }
  1389. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  1390. CGImageRef image = juce_createCoreGraphicsImage (temp, false, colourSpace, false);
  1391. CGColorSpaceRelease (colourSpace);
  1392. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, clipW, clipH), image);
  1393. CGImageRelease (image);
  1394. }
  1395. }
  1396. }
  1397. StringArray NSViewComponentPeer::getAvailableRenderingEngines()
  1398. {
  1399. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  1400. #if USE_COREGRAPHICS_RENDERING
  1401. s.add ("CoreGraphics Renderer");
  1402. #endif
  1403. return s;
  1404. }
  1405. int NSViewComponentPeer::getCurrentRenderingEngine() const
  1406. {
  1407. return usingCoreGraphics ? 1 : 0;
  1408. }
  1409. void NSViewComponentPeer::setCurrentRenderingEngine (int index)
  1410. {
  1411. #if USE_COREGRAPHICS_RENDERING
  1412. if (usingCoreGraphics != (index > 0))
  1413. {
  1414. usingCoreGraphics = index > 0;
  1415. [view setNeedsDisplay: true];
  1416. }
  1417. #endif
  1418. }
  1419. bool NSViewComponentPeer::canBecomeKeyWindow()
  1420. {
  1421. return (getStyleFlags() & juce::ComponentPeer::windowIgnoresKeyPresses) == 0;
  1422. }
  1423. void NSViewComponentPeer::becomeKeyWindow()
  1424. {
  1425. handleBroughtToFront();
  1426. grabFocus();
  1427. }
  1428. bool NSViewComponentPeer::windowShouldClose()
  1429. {
  1430. if (! isValidPeer (this))
  1431. return YES;
  1432. handleUserClosingWindow();
  1433. return NO;
  1434. }
  1435. void NSViewComponentPeer::updateFullscreenStatus()
  1436. {
  1437. if (hasNativeTitleBar())
  1438. {
  1439. const Rectangle<int> screen (getFrameSize().subtractedFrom (component->getParentMonitorArea()));
  1440. const Rectangle<int> window (component->getScreenBounds());
  1441. fullScreen = std::abs (screen.getX() - window.getX()) <= 2
  1442. && std::abs (screen.getY() - window.getY()) <= 2
  1443. && std::abs (screen.getRight() - window.getRight()) <= 2
  1444. && std::abs (screen.getBottom() - window.getBottom()) <= 2;
  1445. }
  1446. }
  1447. void NSViewComponentPeer::redirectMovedOrResized()
  1448. {
  1449. updateFullscreenStatus();
  1450. handleMovedOrResized();
  1451. }
  1452. void NSViewComponentPeer::viewMovedToWindow()
  1453. {
  1454. if (isSharedWindow)
  1455. window = [view window];
  1456. }
  1457. //==============================================================================
  1458. void Desktop::createMouseInputSources()
  1459. {
  1460. mouseSources.add (new MouseInputSource (0, true));
  1461. }
  1462. //==============================================================================
  1463. void Desktop::setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  1464. {
  1465. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  1466. NSViewComponentPeer* const peer = dynamic_cast<NSViewComponentPeer*> (kioskModeComponent->getPeer());
  1467. #if defined (MAC_OS_X_VERSION_10_7) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
  1468. if (peer != nullptr
  1469. && peer->hasNativeTitleBar()
  1470. && [peer->window respondsToSelector: @selector (toggleFullScreen:)])
  1471. {
  1472. [peer->window performSelector: @selector (toggleFullScreen:)
  1473. withObject: [NSNumber numberWithBool: (BOOL) enableOrDisable]];
  1474. }
  1475. else
  1476. #endif
  1477. {
  1478. if (enableOrDisable)
  1479. {
  1480. if (peer->hasNativeTitleBar())
  1481. [peer->window setStyleMask: NSBorderlessWindowMask];
  1482. [NSApp setPresentationOptions: (allowMenusAndBars ? (NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)
  1483. : (NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar))];
  1484. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  1485. }
  1486. else
  1487. {
  1488. if (peer->hasNativeTitleBar())
  1489. {
  1490. [peer->window setStyleMask: (NSViewComponentPeer::getNSWindowStyleMask (peer->getStyleFlags()))];
  1491. peer->setTitle (peer->component->getName()); // required to force the OS to update the title
  1492. }
  1493. [NSApp setPresentationOptions: NSApplicationPresentationDefault];
  1494. }
  1495. }
  1496. #elif JUCE_SUPPORT_CARBON
  1497. if (enableOrDisable)
  1498. {
  1499. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  1500. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  1501. }
  1502. else
  1503. {
  1504. SetSystemUIMode (kUIModeNormal, 0);
  1505. }
  1506. #else
  1507. // If you're targeting OSes earlier than 10.6 and want to use this feature,
  1508. // you'll need to enable JUCE_SUPPORT_CARBON.
  1509. jassertfalse;
  1510. #endif
  1511. }
  1512. //==============================================================================
  1513. void NSViewComponentPeer::repaint (const Rectangle<int>& area)
  1514. {
  1515. if (insideDrawRect)
  1516. {
  1517. class AsyncRepaintMessage : public CallbackMessage
  1518. {
  1519. public:
  1520. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  1521. : peer (peer_), rect (rect_)
  1522. {
  1523. }
  1524. void messageCallback()
  1525. {
  1526. if (ComponentPeer::isValidPeer (peer))
  1527. peer->repaint (rect);
  1528. }
  1529. private:
  1530. NSViewComponentPeer* const peer;
  1531. const Rectangle<int> rect;
  1532. };
  1533. (new AsyncRepaintMessage (this, area))->post();
  1534. }
  1535. else
  1536. {
  1537. [view setNeedsDisplayInRect: NSMakeRect ((CGFloat) area.getX(), [view frame].size.height - (CGFloat) area.getBottom(),
  1538. (CGFloat) area.getWidth(), (CGFloat) area.getHeight())];
  1539. }
  1540. }
  1541. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  1542. {
  1543. [view displayIfNeeded];
  1544. }
  1545. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  1546. {
  1547. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  1548. }
  1549. //==============================================================================
  1550. const int KeyPress::spaceKey = ' ';
  1551. const int KeyPress::returnKey = 0x0d;
  1552. const int KeyPress::escapeKey = 0x1b;
  1553. const int KeyPress::backspaceKey = 0x7f;
  1554. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  1555. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  1556. const int KeyPress::upKey = NSUpArrowFunctionKey;
  1557. const int KeyPress::downKey = NSDownArrowFunctionKey;
  1558. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  1559. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  1560. const int KeyPress::endKey = NSEndFunctionKey;
  1561. const int KeyPress::homeKey = NSHomeFunctionKey;
  1562. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  1563. const int KeyPress::insertKey = -1;
  1564. const int KeyPress::tabKey = 9;
  1565. const int KeyPress::F1Key = NSF1FunctionKey;
  1566. const int KeyPress::F2Key = NSF2FunctionKey;
  1567. const int KeyPress::F3Key = NSF3FunctionKey;
  1568. const int KeyPress::F4Key = NSF4FunctionKey;
  1569. const int KeyPress::F5Key = NSF5FunctionKey;
  1570. const int KeyPress::F6Key = NSF6FunctionKey;
  1571. const int KeyPress::F7Key = NSF7FunctionKey;
  1572. const int KeyPress::F8Key = NSF8FunctionKey;
  1573. const int KeyPress::F9Key = NSF9FunctionKey;
  1574. const int KeyPress::F10Key = NSF10FunctionKey;
  1575. const int KeyPress::F11Key = NSF1FunctionKey;
  1576. const int KeyPress::F12Key = NSF12FunctionKey;
  1577. const int KeyPress::F13Key = NSF13FunctionKey;
  1578. const int KeyPress::F14Key = NSF14FunctionKey;
  1579. const int KeyPress::F15Key = NSF15FunctionKey;
  1580. const int KeyPress::F16Key = NSF16FunctionKey;
  1581. const int KeyPress::numberPad0 = 0x30020;
  1582. const int KeyPress::numberPad1 = 0x30021;
  1583. const int KeyPress::numberPad2 = 0x30022;
  1584. const int KeyPress::numberPad3 = 0x30023;
  1585. const int KeyPress::numberPad4 = 0x30024;
  1586. const int KeyPress::numberPad5 = 0x30025;
  1587. const int KeyPress::numberPad6 = 0x30026;
  1588. const int KeyPress::numberPad7 = 0x30027;
  1589. const int KeyPress::numberPad8 = 0x30028;
  1590. const int KeyPress::numberPad9 = 0x30029;
  1591. const int KeyPress::numberPadAdd = 0x3002a;
  1592. const int KeyPress::numberPadSubtract = 0x3002b;
  1593. const int KeyPress::numberPadMultiply = 0x3002c;
  1594. const int KeyPress::numberPadDivide = 0x3002d;
  1595. const int KeyPress::numberPadSeparator = 0x3002e;
  1596. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  1597. const int KeyPress::numberPadEquals = 0x30030;
  1598. const int KeyPress::numberPadDelete = 0x30031;
  1599. const int KeyPress::playKey = 0x30000;
  1600. const int KeyPress::stopKey = 0x30001;
  1601. const int KeyPress::fastForwardKey = 0x30002;
  1602. const int KeyPress::rewindKey = 0x30003;