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.

1222 lines
40KB

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