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.

1177 lines
40KB

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