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.

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