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.

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