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.

1179 lines
40KB

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