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.

1247 lines
41KB

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