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.

1104 lines
37KB

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