Audio plugin host https://kx.studio/carla
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.

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