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.

1152 lines
39KB

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