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.

1148 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;
  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. {
  440. CGRect r = convertToCGRect (component.getBounds());
  441. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  442. view.multipleTouchEnabled = YES;
  443. view.hidden = true;
  444. view.opaque = component.isOpaque();
  445. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  446. view.transform = CGAffineTransformIdentity;
  447. if (isSharedWindow)
  448. {
  449. window = [viewToAttachTo window];
  450. [viewToAttachTo addSubview: view];
  451. }
  452. else
  453. {
  454. r = convertToCGRect (rotatedScreenPosToReal (component.getBounds()));
  455. r.origin.y = [UIScreen mainScreen].bounds.size.height - (r.origin.y + r.size.height);
  456. window = [[JuceUIWindow alloc] initWithFrame: r];
  457. [((JuceUIWindow*) window) setOwner: this];
  458. controller = [[JuceUIViewController alloc] init];
  459. controller.view = view;
  460. window.rootViewController = controller;
  461. window.hidden = true;
  462. window.autoresizesSubviews = NO;
  463. window.transform = Orientations::getCGTransformFor (Desktop::getInstance().getCurrentOrientation());
  464. window.opaque = component.isOpaque();
  465. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  466. if (component.isAlwaysOnTop())
  467. window.windowLevel = UIWindowLevelAlert;
  468. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  469. [window addSubview: view];
  470. }
  471. setTitle (component.getName());
  472. setVisible (component.isVisible());
  473. Desktop::getInstance().addFocusChangeListener (this);
  474. }
  475. UIViewComponentPeer::~UIViewComponentPeer()
  476. {
  477. Desktop::getInstance().removeFocusChangeListener (this);
  478. view->owner = nullptr;
  479. [view removeFromSuperview];
  480. [view release];
  481. [controller release];
  482. if (! isSharedWindow)
  483. {
  484. [((JuceUIWindow*) window) setOwner: nil];
  485. [window release];
  486. }
  487. }
  488. //==============================================================================
  489. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  490. {
  491. if (! isSharedWindow)
  492. window.hidden = ! shouldBeVisible;
  493. view.hidden = ! shouldBeVisible;
  494. }
  495. void UIViewComponentPeer::setTitle (const String&)
  496. {
  497. // xxx is this possible?
  498. }
  499. void UIViewComponentPeer::setBounds (const Rectangle<int>& newBounds, const bool isNowFullScreen)
  500. {
  501. fullScreen = isNowFullScreen;
  502. if (isSharedWindow)
  503. {
  504. CGRect r = convertToCGRect (newBounds);
  505. if (view.frame.size.width != r.size.width || view.frame.size.height != r.size.height)
  506. [view setNeedsDisplay];
  507. view.frame = r;
  508. }
  509. else
  510. {
  511. window.frame = convertToCGRect (rotatedScreenPosToReal (newBounds));
  512. view.frame = CGRectMake (0, 0, (CGFloat) newBounds.getWidth(), (CGFloat) newBounds.getHeight());
  513. handleMovedOrResized();
  514. }
  515. }
  516. Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  517. {
  518. CGRect r = view.frame;
  519. if (global && view.window != nil)
  520. {
  521. r = [view convertRect: r toView: view.window];
  522. r = [view.window convertRect: r toWindow: nil];
  523. return realScreenPosToRotated (convertToRectInt (r));
  524. }
  525. return convertToRectInt (r);
  526. }
  527. Point<float> UIViewComponentPeer::localToGlobal (Point<float> relativePosition)
  528. {
  529. return relativePosition + getBounds (true).getPosition().toFloat();
  530. }
  531. Point<float> UIViewComponentPeer::globalToLocal (Point<float> screenPosition)
  532. {
  533. return screenPosition - getBounds (true).getPosition().toFloat();
  534. }
  535. void UIViewComponentPeer::setAlpha (float newAlpha)
  536. {
  537. [view.window setAlpha: (CGFloat) newAlpha];
  538. }
  539. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  540. {
  541. if (! isSharedWindow)
  542. {
  543. Rectangle<int> r (shouldBeFullScreen ? Desktop::getInstance().getDisplays().getMainDisplay().userArea
  544. : lastNonFullscreenBounds);
  545. if ((! shouldBeFullScreen) && r.isEmpty())
  546. r = getBounds();
  547. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  548. if (! r.isEmpty())
  549. setBounds (ScalingHelpers::scaledScreenPosToUnscaled (component, r), shouldBeFullScreen);
  550. component.repaint();
  551. }
  552. }
  553. void UIViewComponentPeer::updateTransformAndScreenBounds()
  554. {
  555. Desktop& desktop = Desktop::getInstance();
  556. const Rectangle<int> oldArea (component.getBounds());
  557. const Rectangle<int> oldDesktop (desktop.getDisplays().getMainDisplay().userArea);
  558. const_cast<Desktop::Displays&> (desktop.getDisplays()).refresh();
  559. window.transform = Orientations::getCGTransformFor (desktop.getCurrentOrientation());
  560. view.transform = CGAffineTransformIdentity;
  561. if (fullScreen)
  562. {
  563. fullScreen = false;
  564. setFullScreen (true);
  565. }
  566. else if (! isSharedWindow)
  567. {
  568. // this will re-centre the window, but leave its size unchanged
  569. const float centreRelX = oldArea.getCentreX() / (float) oldDesktop.getWidth();
  570. const float centreRelY = oldArea.getCentreY() / (float) oldDesktop.getHeight();
  571. const Rectangle<int> newDesktop (desktop.getDisplays().getMainDisplay().userArea);
  572. const int x = ((int) (newDesktop.getWidth() * centreRelX)) - (oldArea.getWidth() / 2);
  573. const int y = ((int) (newDesktop.getHeight() * centreRelY)) - (oldArea.getHeight() / 2);
  574. component.setBounds (oldArea.withPosition (x, y));
  575. }
  576. [view setNeedsDisplay];
  577. }
  578. bool UIViewComponentPeer::contains (Point<int> localPos, bool trueIfInAChildWindow) const
  579. {
  580. {
  581. Rectangle<int> localBounds =
  582. ScalingHelpers::scaledScreenPosToUnscaled (component, component.getLocalBounds());
  583. if (! localBounds.contains (localPos))
  584. return false;
  585. }
  586. UIView* v = [view hitTest: convertToCGPoint (localPos)
  587. withEvent: nil];
  588. if (trueIfInAChildWindow)
  589. return v != nil;
  590. return v == view;
  591. }
  592. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  593. {
  594. if (! isSharedWindow)
  595. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  596. return true;
  597. }
  598. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  599. {
  600. if (isSharedWindow)
  601. [[view superview] bringSubviewToFront: view];
  602. if (makeActiveWindow && window != nil && component.isVisible())
  603. [window makeKeyAndVisible];
  604. }
  605. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  606. {
  607. if (UIViewComponentPeer* const otherPeer = dynamic_cast<UIViewComponentPeer*> (other))
  608. {
  609. if (isSharedWindow)
  610. {
  611. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  612. }
  613. else
  614. {
  615. // don't know how to do this
  616. }
  617. }
  618. else
  619. {
  620. jassertfalse; // wrong type of window?
  621. }
  622. }
  623. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  624. {
  625. // to do..
  626. }
  627. //==============================================================================
  628. static float getMaximumTouchForce (UITouch* touch) noexcept
  629. {
  630. #if defined (__IPHONE_9_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_9_0
  631. if ([touch respondsToSelector: @selector (maximumPossibleForce)])
  632. return (float) touch.maximumPossibleForce;
  633. #endif
  634. ignoreUnused (touch);
  635. return 0.0f;
  636. }
  637. static float getTouchForce (UITouch* touch) noexcept
  638. {
  639. #if defined (__IPHONE_9_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_9_0
  640. if ([touch respondsToSelector: @selector (force)])
  641. return (float) touch.force;
  642. #endif
  643. ignoreUnused (touch);
  644. return 0.0f;
  645. }
  646. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  647. {
  648. NSArray* touches = [[event touchesForView: view] allObjects];
  649. for (unsigned int i = 0; i < [touches count]; ++i)
  650. {
  651. UITouch* touch = [touches objectAtIndex: i];
  652. const float maximumForce = getMaximumTouchForce (touch);
  653. if ([touch phase] == UITouchPhaseStationary && maximumForce <= 0)
  654. continue;
  655. CGPoint p = [touch locationInView: view];
  656. const Point<float> pos (static_cast<float> (p.x), static_cast<float> (p.y));
  657. juce_lastMousePos = pos + getBounds (true).getPosition().toFloat();
  658. const int64 time = getMouseTime (event);
  659. const int touchIndex = currentTouches.getIndexOfTouch (touch);
  660. ModifierKeys modsToSend (currentModifiers);
  661. if (isDown)
  662. {
  663. if ([touch phase] != UITouchPhaseBegan)
  664. continue;
  665. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  666. modsToSend = currentModifiers;
  667. // this forces a mouse-enter/up event, in case for some reason we didn't get a mouse-up before.
  668. handleMouseEvent (MouseInputSource::InputSourceType::touch, pos, modsToSend.withoutMouseButtons(),
  669. MouseInputSource::invalidPressure, MouseInputSource::invalidOrientation, time, {}, touchIndex);
  670. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  671. return;
  672. }
  673. else if (isUp)
  674. {
  675. if (! ([touch phase] == UITouchPhaseEnded || [touch phase] == UITouchPhaseCancelled))
  676. continue;
  677. modsToSend = modsToSend.withoutMouseButtons();
  678. currentTouches.clearTouch (touchIndex);
  679. if (! currentTouches.areAnyTouchesActive())
  680. isCancel = true;
  681. }
  682. if (isCancel)
  683. {
  684. currentTouches.clearTouch (touchIndex);
  685. modsToSend = currentModifiers = currentModifiers.withoutMouseButtons();
  686. }
  687. // NB: some devices return 0 or 1.0 if pressure is unknown, so we'll clip our value to a believable range:
  688. float pressure = maximumForce > 0 ? jlimit (0.0001f, 0.9999f, getTouchForce (touch) / maximumForce)
  689. : MouseInputSource::invalidPressure;
  690. handleMouseEvent (MouseInputSource::InputSourceType::touch, pos, modsToSend, pressure,
  691. MouseInputSource::invalidOrientation, time, { }, touchIndex);
  692. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  693. return;
  694. if (isUp || isCancel)
  695. {
  696. handleMouseEvent (MouseInputSource::InputSourceType::touch, Point<float> (-1.0f, -1.0f), modsToSend,
  697. MouseInputSource::invalidPressure, MouseInputSource::invalidOrientation, time, {}, touchIndex);
  698. if (! isValidPeer (this))
  699. return;
  700. }
  701. }
  702. }
  703. //==============================================================================
  704. static UIViewComponentPeer* currentlyFocusedPeer = nullptr;
  705. void UIViewComponentPeer::viewFocusGain()
  706. {
  707. if (currentlyFocusedPeer != this)
  708. {
  709. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  710. currentlyFocusedPeer->handleFocusLoss();
  711. currentlyFocusedPeer = this;
  712. handleFocusGain();
  713. }
  714. }
  715. void UIViewComponentPeer::viewFocusLoss()
  716. {
  717. if (currentlyFocusedPeer == this)
  718. {
  719. currentlyFocusedPeer = nullptr;
  720. handleFocusLoss();
  721. }
  722. }
  723. bool UIViewComponentPeer::isFocused() const
  724. {
  725. return isSharedWindow ? this == currentlyFocusedPeer
  726. : (window != nil && [window isKeyWindow]);
  727. }
  728. void UIViewComponentPeer::grabFocus()
  729. {
  730. if (window != nil)
  731. {
  732. [window makeKeyWindow];
  733. viewFocusGain();
  734. }
  735. }
  736. void UIViewComponentPeer::textInputRequired (Point<int>, TextInputTarget&)
  737. {
  738. }
  739. static bool isIOS4_1() noexcept
  740. {
  741. return [[[UIDevice currentDevice] systemVersion] doubleValue] >= 4.1;
  742. }
  743. static UIKeyboardType getUIKeyboardType (TextInputTarget::VirtualKeyboardType type) noexcept
  744. {
  745. switch (type)
  746. {
  747. case TextInputTarget::textKeyboard: return UIKeyboardTypeAlphabet;
  748. case TextInputTarget::numericKeyboard: return isIOS4_1() ? UIKeyboardTypeNumberPad : UIKeyboardTypeNumbersAndPunctuation;
  749. case TextInputTarget::decimalKeyboard: return isIOS4_1() ? UIKeyboardTypeDecimalPad : UIKeyboardTypeNumbersAndPunctuation;
  750. case TextInputTarget::urlKeyboard: return UIKeyboardTypeURL;
  751. case TextInputTarget::emailAddressKeyboard: return UIKeyboardTypeEmailAddress;
  752. case TextInputTarget::phoneNumberKeyboard: return UIKeyboardTypePhonePad;
  753. default: jassertfalse; break;
  754. }
  755. return UIKeyboardTypeDefault;
  756. }
  757. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  758. {
  759. view->hiddenTextView.keyboardType = getUIKeyboardType (target->getKeyboardType());
  760. view->hiddenTextView.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  761. view->hiddenTextView.selectedRange = NSMakeRange ((NSUInteger) target->getHighlightedRegion().getStart(), 0);
  762. }
  763. BOOL UIViewComponentPeer::textViewReplaceCharacters (Range<int> range, const String& text)
  764. {
  765. if (TextInputTarget* const target = findCurrentTextInputTarget())
  766. {
  767. const Range<int> currentSelection (target->getHighlightedRegion());
  768. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  769. if (currentSelection.isEmpty())
  770. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  771. if (text == "\r" || text == "\n" || text == "\r\n")
  772. handleKeyPress (KeyPress::returnKey, text[0]);
  773. else
  774. target->insertTextAtCaret (text);
  775. updateHiddenTextContent (target);
  776. }
  777. return NO;
  778. }
  779. void UIViewComponentPeer::globalFocusChanged (Component*)
  780. {
  781. if (TextInputTarget* const target = findCurrentTextInputTarget())
  782. {
  783. Component* comp = dynamic_cast<Component*> (target);
  784. Point<int> pos (component.getLocalPoint (comp, Point<int>()));
  785. view->hiddenTextView.frame = CGRectMake (pos.x, pos.y, 0, 0);
  786. updateHiddenTextContent (target);
  787. [view->hiddenTextView becomeFirstResponder];
  788. }
  789. else
  790. {
  791. [view->hiddenTextView resignFirstResponder];
  792. }
  793. }
  794. //==============================================================================
  795. void UIViewComponentPeer::drawRect (CGRect r)
  796. {
  797. if (r.size.width < 1.0f || r.size.height < 1.0f)
  798. return;
  799. CGContextRef cg = UIGraphicsGetCurrentContext();
  800. if (! component.isOpaque())
  801. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  802. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, getComponent().getHeight()));
  803. // NB the CTM on iOS already includes a factor for the display scale, so
  804. // we'll tell the context that the scale is 1.0 to avoid it using it twice
  805. CoreGraphicsContext g (cg, getComponent().getHeight(), 1.0f);
  806. insideDrawRect = true;
  807. handlePaint (g);
  808. insideDrawRect = false;
  809. }
  810. bool UIViewComponentPeer::canBecomeKeyWindow()
  811. {
  812. return (getStyleFlags() & juce::ComponentPeer::windowIgnoresKeyPresses) == 0;
  813. }
  814. //==============================================================================
  815. void Desktop::setKioskComponent (Component* kioskModeComp, bool enableOrDisable, bool /*allowMenusAndBars*/)
  816. {
  817. displays->refresh();
  818. if (ComponentPeer* peer = kioskModeComp->getPeer())
  819. {
  820. if (UIViewComponentPeer* uiViewPeer = dynamic_cast<UIViewComponentPeer*> (peer))
  821. [uiViewPeer->controller setNeedsStatusBarAppearanceUpdate];
  822. peer->setFullScreen (enableOrDisable);
  823. }
  824. }
  825. void Desktop::allowedOrientationsChanged()
  826. {
  827. // if the current orientation isn't allowed anymore then switch orientations
  828. if (! isOrientationEnabled (getCurrentOrientation()))
  829. {
  830. DisplayOrientation orientations[] = { upright, upsideDown, rotatedClockwise, rotatedAntiClockwise };
  831. const int n = sizeof (orientations) / sizeof (DisplayOrientation);
  832. int i;
  833. for (i = 0; i < n; ++i)
  834. if (isOrientationEnabled (orientations[i]))
  835. break;
  836. // you need to support at least one orientation
  837. jassert (i < n);
  838. i = jmin (n - 1, i);
  839. NSNumber *value = [NSNumber numberWithInt:Orientations::convertFromJuce (orientations[i])];
  840. [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
  841. [value release];
  842. }
  843. }
  844. //==============================================================================
  845. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  846. {
  847. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  848. (new AsyncRepaintMessage (this, area))->post();
  849. else
  850. [view setNeedsDisplayInRect: convertToCGRect (area)];
  851. }
  852. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  853. {
  854. }
  855. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  856. {
  857. return new UIViewComponentPeer (*this, styleFlags, (UIView*) windowToAttachTo);
  858. }
  859. //==============================================================================
  860. const int KeyPress::spaceKey = ' ';
  861. const int KeyPress::returnKey = 0x0d;
  862. const int KeyPress::escapeKey = 0x1b;
  863. const int KeyPress::backspaceKey = 0x7f;
  864. const int KeyPress::leftKey = 0x1000;
  865. const int KeyPress::rightKey = 0x1001;
  866. const int KeyPress::upKey = 0x1002;
  867. const int KeyPress::downKey = 0x1003;
  868. const int KeyPress::pageUpKey = 0x1004;
  869. const int KeyPress::pageDownKey = 0x1005;
  870. const int KeyPress::endKey = 0x1006;
  871. const int KeyPress::homeKey = 0x1007;
  872. const int KeyPress::deleteKey = 0x1008;
  873. const int KeyPress::insertKey = -1;
  874. const int KeyPress::tabKey = 9;
  875. const int KeyPress::F1Key = 0x2001;
  876. const int KeyPress::F2Key = 0x2002;
  877. const int KeyPress::F3Key = 0x2003;
  878. const int KeyPress::F4Key = 0x2004;
  879. const int KeyPress::F5Key = 0x2005;
  880. const int KeyPress::F6Key = 0x2006;
  881. const int KeyPress::F7Key = 0x2007;
  882. const int KeyPress::F8Key = 0x2008;
  883. const int KeyPress::F9Key = 0x2009;
  884. const int KeyPress::F10Key = 0x200a;
  885. const int KeyPress::F11Key = 0x200b;
  886. const int KeyPress::F12Key = 0x200c;
  887. const int KeyPress::F13Key = 0x200d;
  888. const int KeyPress::F14Key = 0x200e;
  889. const int KeyPress::F15Key = 0x200f;
  890. const int KeyPress::F16Key = 0x2010;
  891. const int KeyPress::numberPad0 = 0x30020;
  892. const int KeyPress::numberPad1 = 0x30021;
  893. const int KeyPress::numberPad2 = 0x30022;
  894. const int KeyPress::numberPad3 = 0x30023;
  895. const int KeyPress::numberPad4 = 0x30024;
  896. const int KeyPress::numberPad5 = 0x30025;
  897. const int KeyPress::numberPad6 = 0x30026;
  898. const int KeyPress::numberPad7 = 0x30027;
  899. const int KeyPress::numberPad8 = 0x30028;
  900. const int KeyPress::numberPad9 = 0x30029;
  901. const int KeyPress::numberPadAdd = 0x3002a;
  902. const int KeyPress::numberPadSubtract = 0x3002b;
  903. const int KeyPress::numberPadMultiply = 0x3002c;
  904. const int KeyPress::numberPadDivide = 0x3002d;
  905. const int KeyPress::numberPadSeparator = 0x3002e;
  906. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  907. const int KeyPress::numberPadEquals = 0x30030;
  908. const int KeyPress::numberPadDelete = 0x30031;
  909. const int KeyPress::playKey = 0x30000;
  910. const int KeyPress::stopKey = 0x30001;
  911. const int KeyPress::fastForwardKey = 0x30002;
  912. const int KeyPress::rewindKey = 0x30003;