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.

1092 lines
36KB

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