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.

1866 lines
60KB

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