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.

1046 lines
35KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2015 - ROLI Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. class UIViewComponentPeer;
  18. // The way rotation works changed in iOS8..
  19. static bool isUsingOldRotationMethod() noexcept
  20. {
  21. static bool isPreV8 = ([[[UIDevice currentDevice] systemVersion] compare: @"8.0"
  22. options: NSNumericSearch] == NSOrderedAscending);
  23. return isPreV8;
  24. }
  25. namespace Orientations
  26. {
  27. static Desktop::DisplayOrientation convertToJuce (UIInterfaceOrientation orientation)
  28. {
  29. switch (orientation)
  30. {
  31. case UIInterfaceOrientationPortrait: return Desktop::upright;
  32. case UIInterfaceOrientationPortraitUpsideDown: return Desktop::upsideDown;
  33. case UIInterfaceOrientationLandscapeLeft: return Desktop::rotatedClockwise;
  34. case UIInterfaceOrientationLandscapeRight: return Desktop::rotatedAntiClockwise;
  35. default: jassertfalse; // unknown orientation!
  36. }
  37. return Desktop::upright;
  38. }
  39. static CGAffineTransform getCGTransformFor (const Desktop::DisplayOrientation orientation) noexcept
  40. {
  41. if (isUsingOldRotationMethod())
  42. {
  43. switch (orientation)
  44. {
  45. case Desktop::upsideDown: return CGAffineTransformMake (-1, 0, 0, -1, 0, 0);
  46. case Desktop::rotatedClockwise: return CGAffineTransformMake (0, -1, 1, 0, 0, 0);
  47. case Desktop::rotatedAntiClockwise: return CGAffineTransformMake (0, 1, -1, 0, 0, 0);
  48. default: break;
  49. }
  50. }
  51. return CGAffineTransformIdentity;
  52. }
  53. static NSUInteger getSupportedOrientations()
  54. {
  55. NSUInteger allowed = 0;
  56. Desktop& d = Desktop::getInstance();
  57. if (d.isOrientationEnabled (Desktop::upright)) allowed |= UIInterfaceOrientationMaskPortrait;
  58. if (d.isOrientationEnabled (Desktop::upsideDown)) allowed |= UIInterfaceOrientationMaskPortraitUpsideDown;
  59. if (d.isOrientationEnabled (Desktop::rotatedClockwise)) allowed |= UIInterfaceOrientationMaskLandscapeLeft;
  60. if (d.isOrientationEnabled (Desktop::rotatedAntiClockwise)) allowed |= UIInterfaceOrientationMaskLandscapeRight;
  61. return allowed;
  62. }
  63. }
  64. //==============================================================================
  65. } // (juce namespace)
  66. using namespace juce;
  67. @interface JuceUIView : UIView <UITextViewDelegate>
  68. {
  69. @public
  70. UIViewComponentPeer* owner;
  71. UITextView* hiddenTextView;
  72. }
  73. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  74. - (void) dealloc;
  75. - (void) drawRect: (CGRect) r;
  76. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  77. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  78. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  79. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  80. - (BOOL) becomeFirstResponder;
  81. - (BOOL) resignFirstResponder;
  82. - (BOOL) canBecomeFirstResponder;
  83. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text;
  84. @end
  85. //==============================================================================
  86. @interface JuceUIViewController : UIViewController
  87. {
  88. }
  89. - (NSUInteger) supportedInterfaceOrientations;
  90. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation;
  91. - (void) willRotateToInterfaceOrientation: (UIInterfaceOrientation) toInterfaceOrientation duration: (NSTimeInterval) duration;
  92. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation;
  93. - (void) viewWillTransitionToSize: (CGSize) size withTransitionCoordinator: (id<UIViewControllerTransitionCoordinator>) coordinator;
  94. - (void) viewDidLoad;
  95. - (void) viewWillAppear: (BOOL) animated;
  96. - (void) viewDidAppear: (BOOL) animated;
  97. - (void) viewWillLayoutSubviews;
  98. - (void) viewDidLayoutSubviews;
  99. @end
  100. //==============================================================================
  101. @interface JuceUIWindow : UIWindow
  102. {
  103. @private
  104. UIViewComponentPeer* owner;
  105. }
  106. - (void) setOwner: (UIViewComponentPeer*) owner;
  107. - (void) becomeKeyWindow;
  108. @end
  109. //==============================================================================
  110. //==============================================================================
  111. namespace juce
  112. {
  113. class UIViewComponentPeer : public ComponentPeer,
  114. public FocusChangeListener
  115. {
  116. public:
  117. UIViewComponentPeer (Component&, int windowStyleFlags, UIView* viewToAttachTo);
  118. ~UIViewComponentPeer();
  119. //==============================================================================
  120. void* getNativeHandle() const override { return view; }
  121. void setVisible (bool shouldBeVisible) override;
  122. void setTitle (const String& title) override;
  123. void setBounds (const Rectangle<int>&, bool isNowFullScreen) override;
  124. Rectangle<int> getBounds() const override { return getBounds (! isSharedWindow); }
  125. Rectangle<int> getBounds (bool global) const;
  126. Point<float> localToGlobal (Point<float> relativePosition) override;
  127. Point<float> globalToLocal (Point<float> screenPosition) override;
  128. void setAlpha (float newAlpha) override;
  129. void setMinimised (bool) override {}
  130. bool isMinimised() const override { return false; }
  131. void setFullScreen (bool shouldBeFullScreen) override;
  132. bool isFullScreen() const override { return fullScreen; }
  133. bool contains (Point<int> localPos, bool trueIfInAChildWindow) const override;
  134. BorderSize<int> getFrameSize() const override { return BorderSize<int>(); }
  135. bool setAlwaysOnTop (bool alwaysOnTop) override;
  136. void toFront (bool makeActiveWindow) override;
  137. void toBehind (ComponentPeer* other) override;
  138. void setIcon (const Image& newIcon) override;
  139. StringArray getAvailableRenderingEngines() override { return StringArray ("CoreGraphics Renderer"); }
  140. void drawRect (CGRect);
  141. bool canBecomeKeyWindow();
  142. //==============================================================================
  143. void viewFocusGain();
  144. void viewFocusLoss();
  145. bool isFocused() const override;
  146. void grabFocus() override;
  147. void textInputRequired (Point<int>, TextInputTarget&) override;
  148. BOOL textViewReplaceCharacters (Range<int>, const String&);
  149. void updateHiddenTextContent (TextInputTarget*);
  150. void globalFocusChanged (Component*) override;
  151. void updateTransformAndScreenBounds();
  152. void handleTouches (UIEvent*, bool isDown, bool isUp, bool isCancel);
  153. //==============================================================================
  154. void repaint (const Rectangle<int>& area) override;
  155. void performAnyPendingRepaintsNow() override;
  156. //==============================================================================
  157. UIWindow* window;
  158. JuceUIView* view;
  159. JuceUIViewController* controller;
  160. bool isSharedWindow, fullScreen, insideDrawRect;
  161. static ModifierKeys currentModifiers;
  162. static int64 getMouseTime (UIEvent* e) noexcept
  163. {
  164. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  165. + (int64) ([e timestamp] * 1000.0);
  166. }
  167. static Rectangle<int> rotatedScreenPosToReal (const Rectangle<int>& r)
  168. {
  169. if (isUsingOldRotationMethod())
  170. {
  171. const Rectangle<int> screen (convertToRectInt ([UIScreen mainScreen].bounds));
  172. switch ([[UIApplication sharedApplication] statusBarOrientation])
  173. {
  174. case UIInterfaceOrientationPortrait:
  175. return r;
  176. case UIInterfaceOrientationPortraitUpsideDown:
  177. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  178. r.getWidth(), r.getHeight());
  179. case UIInterfaceOrientationLandscapeLeft:
  180. return Rectangle<int> (r.getY(), screen.getHeight() - r.getRight(),
  181. r.getHeight(), r.getWidth());
  182. case UIInterfaceOrientationLandscapeRight:
  183. return Rectangle<int> (screen.getWidth() - r.getBottom(), r.getX(),
  184. r.getHeight(), r.getWidth());
  185. default: jassertfalse; // unknown orientation!
  186. }
  187. }
  188. return r;
  189. }
  190. static Rectangle<int> realScreenPosToRotated (const Rectangle<int>& r)
  191. {
  192. if (isUsingOldRotationMethod())
  193. {
  194. const Rectangle<int> screen (convertToRectInt ([UIScreen mainScreen].bounds));
  195. switch ([[UIApplication sharedApplication] statusBarOrientation])
  196. {
  197. case UIInterfaceOrientationPortrait:
  198. return r;
  199. case UIInterfaceOrientationPortraitUpsideDown:
  200. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  201. r.getWidth(), r.getHeight());
  202. case UIInterfaceOrientationLandscapeLeft:
  203. return Rectangle<int> (screen.getHeight() - r.getBottom(), r.getX(),
  204. r.getHeight(), r.getWidth());
  205. case UIInterfaceOrientationLandscapeRight:
  206. return Rectangle<int> (r.getY(), screen.getWidth() - r.getRight(),
  207. r.getHeight(), r.getWidth());
  208. default: jassertfalse; // unknown orientation!
  209. }
  210. }
  211. return r;
  212. }
  213. MultiTouchMapper<UITouch*> currentTouches;
  214. private:
  215. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UIViewComponentPeer)
  216. class AsyncRepaintMessage : public CallbackMessage
  217. {
  218. public:
  219. UIViewComponentPeer* const peer;
  220. const Rectangle<int> rect;
  221. AsyncRepaintMessage (UIViewComponentPeer* const p, const Rectangle<int>& r)
  222. : peer (p), rect (r)
  223. {
  224. }
  225. void messageCallback() override
  226. {
  227. if (ComponentPeer::isValidPeer (peer))
  228. peer->repaint (rect);
  229. }
  230. };
  231. };
  232. static void sendScreenBoundsUpdate (JuceUIViewController* c)
  233. {
  234. JuceUIView* juceView = (JuceUIView*) [c view];
  235. jassert (juceView != nil && juceView->owner != nullptr);
  236. juceView->owner->updateTransformAndScreenBounds();
  237. }
  238. } // (juce namespace)
  239. //==============================================================================
  240. //==============================================================================
  241. @implementation JuceUIViewController
  242. - (NSUInteger) supportedInterfaceOrientations
  243. {
  244. return Orientations::getSupportedOrientations();
  245. }
  246. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation
  247. {
  248. return Desktop::getInstance().isOrientationEnabled (Orientations::convertToJuce (interfaceOrientation));
  249. }
  250. - (void) willRotateToInterfaceOrientation: (UIInterfaceOrientation) toInterfaceOrientation
  251. duration: (NSTimeInterval) duration
  252. {
  253. (void) toInterfaceOrientation;
  254. (void) duration;
  255. [UIView setAnimationsEnabled: NO]; // disable this because it goes the wrong way and looks like crap.
  256. }
  257. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation
  258. {
  259. (void) fromInterfaceOrientation;
  260. sendScreenBoundsUpdate (self);
  261. [UIView setAnimationsEnabled: YES];
  262. }
  263. - (void) viewWillTransitionToSize: (CGSize) size withTransitionCoordinator: (id<UIViewControllerTransitionCoordinator>) coordinator
  264. {
  265. [super viewWillTransitionToSize: size withTransitionCoordinator: coordinator];
  266. sendScreenBoundsUpdate (self);
  267. // On some devices the screen-size isn't yet updated at this point, so also trigger another
  268. // async update to double-check..
  269. MessageManager::callAsync ([=]() { sendScreenBoundsUpdate (self); });
  270. }
  271. - (void) viewDidLoad
  272. {
  273. sendScreenBoundsUpdate (self);
  274. }
  275. - (void) viewWillAppear: (BOOL) animated
  276. {
  277. (void) animated;
  278. [self viewDidLoad];
  279. }
  280. - (void) viewDidAppear: (BOOL) animated
  281. {
  282. (void) animated;
  283. [self viewDidLoad];
  284. }
  285. - (void) viewWillLayoutSubviews
  286. {
  287. [self viewDidLoad];
  288. }
  289. - (void) viewDidLayoutSubviews
  290. {
  291. [self viewDidLoad];
  292. }
  293. @end
  294. @implementation JuceUIView
  295. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) peer
  296. withFrame: (CGRect) frame
  297. {
  298. [super initWithFrame: frame];
  299. owner = peer;
  300. hiddenTextView = [[UITextView alloc] initWithFrame: CGRectZero];
  301. [self addSubview: hiddenTextView];
  302. hiddenTextView.delegate = self;
  303. hiddenTextView.autocapitalizationType = UITextAutocapitalizationTypeNone;
  304. hiddenTextView.autocorrectionType = UITextAutocorrectionTypeNo;
  305. return self;
  306. }
  307. - (void) dealloc
  308. {
  309. [hiddenTextView removeFromSuperview];
  310. [hiddenTextView release];
  311. [super dealloc];
  312. }
  313. //==============================================================================
  314. - (void) drawRect: (CGRect) r
  315. {
  316. if (owner != nullptr)
  317. owner->drawRect (r);
  318. }
  319. //==============================================================================
  320. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  321. {
  322. (void) touches;
  323. if (owner != nullptr)
  324. owner->handleTouches (event, true, false, false);
  325. }
  326. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  327. {
  328. (void) touches;
  329. if (owner != nullptr)
  330. owner->handleTouches (event, false, false, false);
  331. }
  332. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  333. {
  334. (void) touches;
  335. if (owner != nullptr)
  336. owner->handleTouches (event, false, true, false);
  337. }
  338. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  339. {
  340. if (owner != nullptr)
  341. owner->handleTouches (event, false, true, true);
  342. [self touchesEnded: touches withEvent: event];
  343. }
  344. //==============================================================================
  345. - (BOOL) becomeFirstResponder
  346. {
  347. if (owner != nullptr)
  348. owner->viewFocusGain();
  349. return true;
  350. }
  351. - (BOOL) resignFirstResponder
  352. {
  353. if (owner != nullptr)
  354. owner->viewFocusLoss();
  355. return true;
  356. }
  357. - (BOOL) canBecomeFirstResponder
  358. {
  359. return owner != nullptr && owner->canBecomeKeyWindow();
  360. }
  361. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
  362. {
  363. (void) textView;
  364. return owner->textViewReplaceCharacters (Range<int> ((int) range.location, (int) (range.location + range.length)),
  365. nsStringToJuce (text));
  366. }
  367. @end
  368. //==============================================================================
  369. @implementation JuceUIWindow
  370. - (void) setOwner: (UIViewComponentPeer*) peer
  371. {
  372. owner = peer;
  373. }
  374. - (void) becomeKeyWindow
  375. {
  376. [super becomeKeyWindow];
  377. if (owner != nullptr)
  378. owner->grabFocus();
  379. }
  380. @end
  381. //==============================================================================
  382. //==============================================================================
  383. namespace juce
  384. {
  385. bool KeyPress::isKeyCurrentlyDown (int)
  386. {
  387. return false;
  388. }
  389. ModifierKeys UIViewComponentPeer::currentModifiers;
  390. ModifierKeys ModifierKeys::getCurrentModifiersRealtime() noexcept
  391. {
  392. return UIViewComponentPeer::currentModifiers;
  393. }
  394. void ModifierKeys::updateCurrentModifiers() noexcept
  395. {
  396. currentModifiers = UIViewComponentPeer::currentModifiers;
  397. }
  398. Point<float> juce_lastMousePos;
  399. //==============================================================================
  400. UIViewComponentPeer::UIViewComponentPeer (Component& comp, const int windowStyleFlags, UIView* viewToAttachTo)
  401. : ComponentPeer (comp, windowStyleFlags),
  402. window (nil),
  403. view (nil),
  404. controller (nil),
  405. isSharedWindow (viewToAttachTo != nil),
  406. fullScreen (false),
  407. insideDrawRect (false)
  408. {
  409. CGRect r = convertToCGRect (component.getBounds());
  410. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  411. view.multipleTouchEnabled = YES;
  412. view.hidden = true;
  413. view.opaque = component.isOpaque();
  414. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  415. view.transform = CGAffineTransformIdentity;
  416. if (isSharedWindow)
  417. {
  418. window = [viewToAttachTo window];
  419. [viewToAttachTo addSubview: view];
  420. }
  421. else
  422. {
  423. r = convertToCGRect (rotatedScreenPosToReal (component.getBounds()));
  424. r.origin.y = [UIScreen mainScreen].bounds.size.height - (r.origin.y + r.size.height);
  425. window = [[JuceUIWindow alloc] initWithFrame: r];
  426. [((JuceUIWindow*) window) setOwner: this];
  427. controller = [[JuceUIViewController alloc] init];
  428. controller.view = view;
  429. window.rootViewController = controller;
  430. window.hidden = true;
  431. window.autoresizesSubviews = NO;
  432. window.transform = Orientations::getCGTransformFor (Desktop::getInstance().getCurrentOrientation());
  433. window.opaque = component.isOpaque();
  434. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  435. if (component.isAlwaysOnTop())
  436. window.windowLevel = UIWindowLevelAlert;
  437. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  438. [window addSubview: view];
  439. }
  440. setTitle (component.getName());
  441. setVisible (component.isVisible());
  442. Desktop::getInstance().addFocusChangeListener (this);
  443. }
  444. UIViewComponentPeer::~UIViewComponentPeer()
  445. {
  446. Desktop::getInstance().removeFocusChangeListener (this);
  447. view->owner = nullptr;
  448. [view removeFromSuperview];
  449. [view release];
  450. [controller release];
  451. if (! isSharedWindow)
  452. {
  453. [((JuceUIWindow*) window) setOwner: nil];
  454. [window release];
  455. }
  456. }
  457. //==============================================================================
  458. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  459. {
  460. if (! isSharedWindow)
  461. window.hidden = ! shouldBeVisible;
  462. view.hidden = ! shouldBeVisible;
  463. }
  464. void UIViewComponentPeer::setTitle (const String&)
  465. {
  466. // xxx is this possible?
  467. }
  468. void UIViewComponentPeer::setBounds (const Rectangle<int>& newBounds, const bool isNowFullScreen)
  469. {
  470. fullScreen = isNowFullScreen;
  471. if (isSharedWindow)
  472. {
  473. CGRect r = convertToCGRect (newBounds);
  474. if (view.frame.size.width != r.size.width || view.frame.size.height != r.size.height)
  475. [view setNeedsDisplay];
  476. view.frame = r;
  477. }
  478. else
  479. {
  480. window.frame = convertToCGRect (rotatedScreenPosToReal (newBounds));
  481. view.frame = CGRectMake (0, 0, (CGFloat) newBounds.getWidth(), (CGFloat) newBounds.getHeight());
  482. handleMovedOrResized();
  483. }
  484. }
  485. Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  486. {
  487. CGRect r = view.frame;
  488. if (global && view.window != nil)
  489. {
  490. r = [view convertRect: r toView: view.window];
  491. r = [view.window convertRect: r toWindow: nil];
  492. return realScreenPosToRotated (convertToRectInt (r));
  493. }
  494. return convertToRectInt (r);
  495. }
  496. Point<float> UIViewComponentPeer::localToGlobal (Point<float> relativePosition)
  497. {
  498. return relativePosition + getBounds (true).getPosition().toFloat();
  499. }
  500. Point<float> UIViewComponentPeer::globalToLocal (Point<float> screenPosition)
  501. {
  502. return screenPosition - getBounds (true).getPosition().toFloat();
  503. }
  504. void UIViewComponentPeer::setAlpha (float newAlpha)
  505. {
  506. [view.window setAlpha: (CGFloat) newAlpha];
  507. }
  508. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  509. {
  510. if (! isSharedWindow)
  511. {
  512. Rectangle<int> r (shouldBeFullScreen ? Desktop::getInstance().getDisplays().getMainDisplay().userArea
  513. : lastNonFullscreenBounds);
  514. if ((! shouldBeFullScreen) && r.isEmpty())
  515. r = getBounds();
  516. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  517. if (! r.isEmpty())
  518. setBounds (ScalingHelpers::scaledScreenPosToUnscaled (component, r), shouldBeFullScreen);
  519. component.repaint();
  520. }
  521. }
  522. void UIViewComponentPeer::updateTransformAndScreenBounds()
  523. {
  524. Desktop& desktop = Desktop::getInstance();
  525. const Rectangle<int> oldArea (component.getBounds());
  526. const Rectangle<int> oldDesktop (desktop.getDisplays().getMainDisplay().userArea);
  527. const_cast<Desktop::Displays&> (desktop.getDisplays()).refresh();
  528. window.transform = Orientations::getCGTransformFor (desktop.getCurrentOrientation());
  529. view.transform = CGAffineTransformIdentity;
  530. if (fullScreen)
  531. {
  532. fullScreen = false;
  533. setFullScreen (true);
  534. }
  535. else if (! isSharedWindow)
  536. {
  537. // this will re-centre the window, but leave its size unchanged
  538. const float centreRelX = oldArea.getCentreX() / (float) oldDesktop.getWidth();
  539. const float centreRelY = oldArea.getCentreY() / (float) oldDesktop.getHeight();
  540. const Rectangle<int> newDesktop (desktop.getDisplays().getMainDisplay().userArea);
  541. const int x = ((int) (newDesktop.getWidth() * centreRelX)) - (oldArea.getWidth() / 2);
  542. const int y = ((int) (newDesktop.getHeight() * centreRelY)) - (oldArea.getHeight() / 2);
  543. setBounds (oldArea.withPosition (x, y), false);
  544. }
  545. [view setNeedsDisplay];
  546. }
  547. bool UIViewComponentPeer::contains (Point<int> localPos, bool trueIfInAChildWindow) const
  548. {
  549. {
  550. Rectangle<int> localBounds =
  551. ScalingHelpers::scaledScreenPosToUnscaled (component, component.getLocalBounds());
  552. if (! localBounds.contains (localPos))
  553. return false;
  554. }
  555. UIView* v = [view hitTest: convertToCGPoint (localPos)
  556. withEvent: nil];
  557. if (trueIfInAChildWindow)
  558. return v != nil;
  559. return v == view;
  560. }
  561. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  562. {
  563. if (! isSharedWindow)
  564. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  565. return true;
  566. }
  567. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  568. {
  569. if (isSharedWindow)
  570. [[view superview] bringSubviewToFront: view];
  571. if (makeActiveWindow && window != nil && component.isVisible())
  572. [window makeKeyAndVisible];
  573. }
  574. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  575. {
  576. if (UIViewComponentPeer* const otherPeer = dynamic_cast<UIViewComponentPeer*> (other))
  577. {
  578. if (isSharedWindow)
  579. {
  580. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  581. }
  582. else
  583. {
  584. // don't know how to do this
  585. }
  586. }
  587. else
  588. {
  589. jassertfalse; // wrong type of window?
  590. }
  591. }
  592. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  593. {
  594. // to do..
  595. }
  596. //==============================================================================
  597. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  598. {
  599. NSArray* touches = [[event touchesForView: view] allObjects];
  600. for (unsigned int i = 0; i < [touches count]; ++i)
  601. {
  602. UITouch* touch = [touches objectAtIndex: i];
  603. if ([touch phase] == UITouchPhaseStationary)
  604. continue;
  605. CGPoint p = [touch locationInView: view];
  606. const Point<float> pos (static_cast<float> (p.x), static_cast<float> (p.y));
  607. juce_lastMousePos = pos + getBounds (true).getPosition().toFloat();
  608. const int64 time = getMouseTime (event);
  609. const int touchIndex = currentTouches.getIndexOfTouch (touch);
  610. ModifierKeys modsToSend (currentModifiers);
  611. if (isDown)
  612. {
  613. if ([touch phase] != UITouchPhaseBegan)
  614. continue;
  615. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  616. modsToSend = currentModifiers;
  617. // this forces a mouse-enter/up event, in case for some reason we didn't get a mouse-up before.
  618. handleMouseEvent (touchIndex, pos, modsToSend.withoutMouseButtons(), time);
  619. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  620. return;
  621. }
  622. else if (isUp)
  623. {
  624. if (! ([touch phase] == UITouchPhaseEnded || [touch phase] == UITouchPhaseCancelled))
  625. continue;
  626. modsToSend = modsToSend.withoutMouseButtons();
  627. currentTouches.clearTouch (touchIndex);
  628. if (! currentTouches.areAnyTouchesActive())
  629. isCancel = true;
  630. }
  631. if (isCancel)
  632. {
  633. currentTouches.clearTouch (touchIndex);
  634. modsToSend = currentModifiers = currentModifiers.withoutMouseButtons();
  635. }
  636. handleMouseEvent (touchIndex, pos, modsToSend, time);
  637. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  638. return;
  639. if (isUp || isCancel)
  640. {
  641. handleMouseEvent (touchIndex, Point<float> (-1.0f, -1.0f), modsToSend, time);
  642. if (! isValidPeer (this))
  643. return;
  644. }
  645. }
  646. }
  647. //==============================================================================
  648. static UIViewComponentPeer* currentlyFocusedPeer = nullptr;
  649. void UIViewComponentPeer::viewFocusGain()
  650. {
  651. if (currentlyFocusedPeer != this)
  652. {
  653. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  654. currentlyFocusedPeer->handleFocusLoss();
  655. currentlyFocusedPeer = this;
  656. handleFocusGain();
  657. }
  658. }
  659. void UIViewComponentPeer::viewFocusLoss()
  660. {
  661. if (currentlyFocusedPeer == this)
  662. {
  663. currentlyFocusedPeer = nullptr;
  664. handleFocusLoss();
  665. }
  666. }
  667. bool UIViewComponentPeer::isFocused() const
  668. {
  669. return isSharedWindow ? this == currentlyFocusedPeer
  670. : (window != nil && [window isKeyWindow]);
  671. }
  672. void UIViewComponentPeer::grabFocus()
  673. {
  674. if (window != nil)
  675. {
  676. [window makeKeyWindow];
  677. viewFocusGain();
  678. }
  679. }
  680. void UIViewComponentPeer::textInputRequired (Point<int>, TextInputTarget&)
  681. {
  682. }
  683. static bool isIOS4_1() noexcept
  684. {
  685. return [[[UIDevice currentDevice] systemVersion] doubleValue] >= 4.1;
  686. }
  687. static UIKeyboardType getUIKeyboardType (TextInputTarget::VirtualKeyboardType type) noexcept
  688. {
  689. switch (type)
  690. {
  691. case TextInputTarget::textKeyboard: return UIKeyboardTypeAlphabet;
  692. case TextInputTarget::numericKeyboard: return isIOS4_1() ? UIKeyboardTypeNumberPad : UIKeyboardTypeNumbersAndPunctuation;
  693. case TextInputTarget::decimalKeyboard: return isIOS4_1() ? UIKeyboardTypeDecimalPad : UIKeyboardTypeNumbersAndPunctuation;
  694. case TextInputTarget::urlKeyboard: return UIKeyboardTypeURL;
  695. case TextInputTarget::emailAddressKeyboard: return UIKeyboardTypeEmailAddress;
  696. case TextInputTarget::phoneNumberKeyboard: return UIKeyboardTypePhonePad;
  697. default: jassertfalse; break;
  698. }
  699. return UIKeyboardTypeDefault;
  700. }
  701. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  702. {
  703. view->hiddenTextView.keyboardType = getUIKeyboardType (target->getKeyboardType());
  704. view->hiddenTextView.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  705. view->hiddenTextView.selectedRange = NSMakeRange ((NSUInteger) target->getHighlightedRegion().getStart(), 0);
  706. }
  707. BOOL UIViewComponentPeer::textViewReplaceCharacters (Range<int> range, const String& text)
  708. {
  709. if (TextInputTarget* const target = findCurrentTextInputTarget())
  710. {
  711. const Range<int> currentSelection (target->getHighlightedRegion());
  712. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  713. if (currentSelection.isEmpty())
  714. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  715. if (text == "\r" || text == "\n" || text == "\r\n")
  716. handleKeyPress (KeyPress::returnKey, text[0]);
  717. else
  718. target->insertTextAtCaret (text);
  719. updateHiddenTextContent (target);
  720. }
  721. return NO;
  722. }
  723. void UIViewComponentPeer::globalFocusChanged (Component*)
  724. {
  725. if (TextInputTarget* const target = findCurrentTextInputTarget())
  726. {
  727. Component* comp = dynamic_cast<Component*> (target);
  728. Point<int> pos (component.getLocalPoint (comp, Point<int>()));
  729. view->hiddenTextView.frame = CGRectMake (pos.x, pos.y, 0, 0);
  730. updateHiddenTextContent (target);
  731. [view->hiddenTextView becomeFirstResponder];
  732. }
  733. else
  734. {
  735. [view->hiddenTextView resignFirstResponder];
  736. }
  737. }
  738. //==============================================================================
  739. void UIViewComponentPeer::drawRect (CGRect r)
  740. {
  741. if (r.size.width < 1.0f || r.size.height < 1.0f)
  742. return;
  743. CGContextRef cg = UIGraphicsGetCurrentContext();
  744. if (! component.isOpaque())
  745. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  746. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, getComponent().getHeight()));
  747. CoreGraphicsContext g (cg, getComponent().getHeight(), static_cast<float> ([UIScreen mainScreen].scale));
  748. insideDrawRect = true;
  749. handlePaint (g);
  750. insideDrawRect = false;
  751. }
  752. bool UIViewComponentPeer::canBecomeKeyWindow()
  753. {
  754. return (getStyleFlags() & juce::ComponentPeer::windowIgnoresKeyPresses) == 0;
  755. }
  756. //==============================================================================
  757. void Desktop::setKioskComponent (Component* kioskModeComp, bool enableOrDisable, bool /*allowMenusAndBars*/)
  758. {
  759. [[UIApplication sharedApplication] setStatusBarHidden: enableOrDisable
  760. withAnimation: UIStatusBarAnimationSlide];
  761. displays->refresh();
  762. if (ComponentPeer* const peer = kioskModeComp->getPeer())
  763. peer->setFullScreen (enableOrDisable);
  764. }
  765. //==============================================================================
  766. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  767. {
  768. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  769. (new AsyncRepaintMessage (this, area))->post();
  770. else
  771. [view setNeedsDisplayInRect: convertToCGRect (area)];
  772. }
  773. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  774. {
  775. }
  776. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  777. {
  778. return new UIViewComponentPeer (*this, styleFlags, (UIView*) windowToAttachTo);
  779. }
  780. //==============================================================================
  781. const int KeyPress::spaceKey = ' ';
  782. const int KeyPress::returnKey = 0x0d;
  783. const int KeyPress::escapeKey = 0x1b;
  784. const int KeyPress::backspaceKey = 0x7f;
  785. const int KeyPress::leftKey = 0x1000;
  786. const int KeyPress::rightKey = 0x1001;
  787. const int KeyPress::upKey = 0x1002;
  788. const int KeyPress::downKey = 0x1003;
  789. const int KeyPress::pageUpKey = 0x1004;
  790. const int KeyPress::pageDownKey = 0x1005;
  791. const int KeyPress::endKey = 0x1006;
  792. const int KeyPress::homeKey = 0x1007;
  793. const int KeyPress::deleteKey = 0x1008;
  794. const int KeyPress::insertKey = -1;
  795. const int KeyPress::tabKey = 9;
  796. const int KeyPress::F1Key = 0x2001;
  797. const int KeyPress::F2Key = 0x2002;
  798. const int KeyPress::F3Key = 0x2003;
  799. const int KeyPress::F4Key = 0x2004;
  800. const int KeyPress::F5Key = 0x2005;
  801. const int KeyPress::F6Key = 0x2006;
  802. const int KeyPress::F7Key = 0x2007;
  803. const int KeyPress::F8Key = 0x2008;
  804. const int KeyPress::F9Key = 0x2009;
  805. const int KeyPress::F10Key = 0x200a;
  806. const int KeyPress::F11Key = 0x200b;
  807. const int KeyPress::F12Key = 0x200c;
  808. const int KeyPress::F13Key = 0x200d;
  809. const int KeyPress::F14Key = 0x200e;
  810. const int KeyPress::F15Key = 0x200f;
  811. const int KeyPress::F16Key = 0x2010;
  812. const int KeyPress::numberPad0 = 0x30020;
  813. const int KeyPress::numberPad1 = 0x30021;
  814. const int KeyPress::numberPad2 = 0x30022;
  815. const int KeyPress::numberPad3 = 0x30023;
  816. const int KeyPress::numberPad4 = 0x30024;
  817. const int KeyPress::numberPad5 = 0x30025;
  818. const int KeyPress::numberPad6 = 0x30026;
  819. const int KeyPress::numberPad7 = 0x30027;
  820. const int KeyPress::numberPad8 = 0x30028;
  821. const int KeyPress::numberPad9 = 0x30029;
  822. const int KeyPress::numberPadAdd = 0x3002a;
  823. const int KeyPress::numberPadSubtract = 0x3002b;
  824. const int KeyPress::numberPadMultiply = 0x3002c;
  825. const int KeyPress::numberPadDivide = 0x3002d;
  826. const int KeyPress::numberPadSeparator = 0x3002e;
  827. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  828. const int KeyPress::numberPadEquals = 0x30030;
  829. const int KeyPress::numberPadDelete = 0x30031;
  830. const int KeyPress::playKey = 0x30000;
  831. const int KeyPress::stopKey = 0x30001;
  832. const int KeyPress::fastForwardKey = 0x30002;
  833. const int KeyPress::rewindKey = 0x30003;