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.

2032 lines
63KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - 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 7 End-User License
  8. Agreement and JUCE Privacy Policy.
  9. End User License Agreement: www.juce.com/juce-7-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. #include "juce_mac_CGMetalLayerRenderer.h"
  19. #if TARGET_OS_SIMULATOR && JUCE_COREGRAPHICS_RENDER_WITH_MULTIPLE_PAINT_CALLS
  20. #warning JUCE_COREGRAPHICS_RENDER_WITH_MULTIPLE_PAINT_CALLS uses parts of the Metal API that are currently unsupported in the simulator - falling back to JUCE_COREGRAPHICS_RENDER_WITH_MULTIPLE_PAINT_CALLS=0
  21. #undef JUCE_COREGRAPHICS_RENDER_WITH_MULTIPLE_PAINT_CALLS
  22. #endif
  23. #if defined (__IPHONE_13_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0
  24. #define JUCE_HAS_IOS_POINTER_SUPPORT 1
  25. #else
  26. #define JUCE_HAS_IOS_POINTER_SUPPORT 0
  27. #endif
  28. namespace juce
  29. {
  30. //==============================================================================
  31. static NSArray* getContainerAccessibilityElements (AccessibilityHandler& handler)
  32. {
  33. const auto children = handler.getChildren();
  34. NSMutableArray* accessibleChildren = [NSMutableArray arrayWithCapacity: (NSUInteger) children.size()];
  35. for (auto* childHandler : children)
  36. {
  37. id accessibleElement = [&childHandler]
  38. {
  39. id native = static_cast<id> (childHandler->getNativeImplementation());
  40. if (! childHandler->getChildren().empty())
  41. return [native accessibilityContainer];
  42. return native;
  43. }();
  44. if (accessibleElement != nil)
  45. [accessibleChildren addObject: accessibleElement];
  46. }
  47. [accessibleChildren addObject: static_cast<id> (handler.getNativeImplementation())];
  48. return accessibleChildren;
  49. }
  50. class UIViewComponentPeer;
  51. static UIInterfaceOrientation getWindowOrientation()
  52. {
  53. UIApplication* sharedApplication = [UIApplication sharedApplication];
  54. #if defined (__IPHONE_13_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0
  55. if (@available (iOS 13.0, *))
  56. {
  57. for (UIScene* scene in [sharedApplication connectedScenes])
  58. if ([scene isKindOfClass: [UIWindowScene class]])
  59. return [(UIWindowScene*) scene interfaceOrientation];
  60. }
  61. #endif
  62. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
  63. return [sharedApplication statusBarOrientation];
  64. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  65. }
  66. namespace Orientations
  67. {
  68. static Desktop::DisplayOrientation convertToJuce (UIInterfaceOrientation orientation)
  69. {
  70. switch (orientation)
  71. {
  72. case UIInterfaceOrientationPortrait: return Desktop::upright;
  73. case UIInterfaceOrientationPortraitUpsideDown: return Desktop::upsideDown;
  74. case UIInterfaceOrientationLandscapeLeft: return Desktop::rotatedClockwise;
  75. case UIInterfaceOrientationLandscapeRight: return Desktop::rotatedAntiClockwise;
  76. case UIInterfaceOrientationUnknown:
  77. default: jassertfalse; // unknown orientation!
  78. }
  79. return Desktop::upright;
  80. }
  81. static UIInterfaceOrientation convertFromJuce (Desktop::DisplayOrientation orientation)
  82. {
  83. switch (orientation)
  84. {
  85. case Desktop::upright: return UIInterfaceOrientationPortrait;
  86. case Desktop::upsideDown: return UIInterfaceOrientationPortraitUpsideDown;
  87. case Desktop::rotatedClockwise: return UIInterfaceOrientationLandscapeLeft;
  88. case Desktop::rotatedAntiClockwise: return UIInterfaceOrientationLandscapeRight;
  89. case Desktop::allOrientations:
  90. default: jassertfalse; // unknown orientation!
  91. }
  92. return UIInterfaceOrientationPortrait;
  93. }
  94. static NSUInteger getSupportedOrientations()
  95. {
  96. NSUInteger allowed = 0;
  97. auto& d = Desktop::getInstance();
  98. if (d.isOrientationEnabled (Desktop::upright)) allowed |= UIInterfaceOrientationMaskPortrait;
  99. if (d.isOrientationEnabled (Desktop::upsideDown)) allowed |= UIInterfaceOrientationMaskPortraitUpsideDown;
  100. if (d.isOrientationEnabled (Desktop::rotatedClockwise)) allowed |= UIInterfaceOrientationMaskLandscapeLeft;
  101. if (d.isOrientationEnabled (Desktop::rotatedAntiClockwise)) allowed |= UIInterfaceOrientationMaskLandscapeRight;
  102. return allowed;
  103. }
  104. }
  105. enum class MouseEventFlags
  106. {
  107. none,
  108. down,
  109. up,
  110. upAndCancel,
  111. };
  112. //==============================================================================
  113. } // namespace juce
  114. using namespace juce;
  115. @interface JuceUITextPosition : UITextPosition
  116. {
  117. @public
  118. int index;
  119. }
  120. @end
  121. @implementation JuceUITextPosition
  122. + (instancetype) withIndex: (int) indexIn
  123. {
  124. auto* result = [[JuceUITextPosition alloc] init];
  125. result->index = indexIn;
  126. return [result autorelease];
  127. }
  128. @end
  129. //==============================================================================
  130. @interface JuceUITextRange : UITextRange
  131. {
  132. @public
  133. int from, to;
  134. }
  135. @end
  136. @implementation JuceUITextRange
  137. + (instancetype) withRange: (juce::Range<int>) range
  138. {
  139. return [JuceUITextRange from: range.getStart() to: range.getEnd()];
  140. }
  141. + (instancetype) from: (int) from to: (int) to
  142. {
  143. auto* result = [[JuceUITextRange alloc] init];
  144. result->from = from;
  145. result->to = to;
  146. return [result autorelease];
  147. }
  148. - (UITextPosition*) start
  149. {
  150. return [JuceUITextPosition withIndex: from];
  151. }
  152. - (UITextPosition*) end
  153. {
  154. return [JuceUITextPosition withIndex: to];
  155. }
  156. - (Range<int>) range
  157. {
  158. return Range<int>::between (from, to);
  159. }
  160. - (BOOL) isEmpty
  161. {
  162. return from == to;
  163. }
  164. @end
  165. //==============================================================================
  166. // UITextInputStringTokenizer doesn't handle 'line' granularities correctly by default, hence
  167. // this subclass.
  168. @interface JuceTextInputTokenizer : UITextInputStringTokenizer
  169. {
  170. UIViewComponentPeer* peer;
  171. }
  172. - (instancetype) initWithPeer: (UIViewComponentPeer*) peer;
  173. @end
  174. //==============================================================================
  175. @interface JuceUITextSelectionRect : UITextSelectionRect
  176. {
  177. CGRect _rect;
  178. }
  179. @end
  180. @implementation JuceUITextSelectionRect
  181. + (instancetype) withRect: (CGRect) rect
  182. {
  183. auto* result = [[JuceUITextSelectionRect alloc] init];
  184. result->_rect = rect;
  185. return [result autorelease];
  186. }
  187. - (CGRect) rect { return _rect; }
  188. - (NSWritingDirection) writingDirection { return NSWritingDirectionNatural; }
  189. - (BOOL) containsStart { return NO; }
  190. - (BOOL) containsEnd { return NO; }
  191. - (BOOL) isVertical { return NO; }
  192. @end
  193. //==============================================================================
  194. struct CADisplayLinkDeleter
  195. {
  196. void operator() (CADisplayLink* displayLink) const noexcept
  197. {
  198. [displayLink invalidate];
  199. [displayLink release];
  200. }
  201. };
  202. @interface JuceTextView : UIView <UITextInput>
  203. {
  204. @public
  205. UIViewComponentPeer* owner;
  206. id<UITextInputDelegate> delegate;
  207. }
  208. - (instancetype) initWithOwner: (UIViewComponentPeer*) owner;
  209. @end
  210. @interface JuceUIView : UIView
  211. {
  212. @public
  213. UIViewComponentPeer* owner;
  214. std::unique_ptr<CADisplayLink, CADisplayLinkDeleter> displayLink;
  215. }
  216. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  217. - (void) dealloc;
  218. + (Class) layerClass;
  219. - (void) displayLinkCallback: (CADisplayLink*) dl;
  220. - (void) drawRect: (CGRect) r;
  221. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  222. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  223. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  224. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  225. #if JUCE_HAS_IOS_POINTER_SUPPORT
  226. - (void) onHover: (UIHoverGestureRecognizer*) gesture API_AVAILABLE (ios (13.0));
  227. - (void) onScroll: (UIPanGestureRecognizer*) gesture;
  228. #endif
  229. - (BOOL) becomeFirstResponder;
  230. - (BOOL) resignFirstResponder;
  231. - (BOOL) canBecomeFirstResponder;
  232. - (void) traitCollectionDidChange: (UITraitCollection*) previousTraitCollection;
  233. - (BOOL) isAccessibilityElement;
  234. - (CGRect) accessibilityFrame;
  235. - (NSArray*) accessibilityElements;
  236. @end
  237. //==============================================================================
  238. @interface JuceUIViewController : UIViewController
  239. {
  240. }
  241. - (JuceUIViewController*) init;
  242. - (NSUInteger) supportedInterfaceOrientations;
  243. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation;
  244. - (void) willRotateToInterfaceOrientation: (UIInterfaceOrientation) toInterfaceOrientation duration: (NSTimeInterval) duration;
  245. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation;
  246. - (void) viewWillTransitionToSize: (CGSize) size withTransitionCoordinator: (id<UIViewControllerTransitionCoordinator>) coordinator;
  247. - (BOOL) prefersStatusBarHidden;
  248. - (UIStatusBarStyle) preferredStatusBarStyle;
  249. - (void) viewDidLoad;
  250. - (void) viewWillAppear: (BOOL) animated;
  251. - (void) viewDidAppear: (BOOL) animated;
  252. - (void) viewWillLayoutSubviews;
  253. - (void) viewDidLayoutSubviews;
  254. @end
  255. //==============================================================================
  256. @interface JuceUIWindow : UIWindow
  257. {
  258. @private
  259. UIViewComponentPeer* owner;
  260. }
  261. - (void) setOwner: (UIViewComponentPeer*) owner;
  262. - (void) becomeKeyWindow;
  263. @end
  264. //==============================================================================
  265. //==============================================================================
  266. namespace juce
  267. {
  268. struct UIViewPeerControllerReceiver
  269. {
  270. virtual ~UIViewPeerControllerReceiver() = default;
  271. virtual void setViewController (UIViewController*) = 0;
  272. };
  273. //==============================================================================
  274. class UIViewComponentPeer : public ComponentPeer,
  275. private UIViewPeerControllerReceiver
  276. {
  277. public:
  278. UIViewComponentPeer (Component&, int windowStyleFlags, UIView* viewToAttachTo);
  279. ~UIViewComponentPeer() override;
  280. //==============================================================================
  281. void* getNativeHandle() const override { return view; }
  282. void setVisible (bool shouldBeVisible) override;
  283. void setTitle (const String& title) override;
  284. void setBounds (const Rectangle<int>&, bool isNowFullScreen) override;
  285. void setViewController (UIViewController* newController) override
  286. {
  287. jassert (controller == nullptr);
  288. controller = [newController retain];
  289. }
  290. Rectangle<int> getBounds() const override { return getBounds (! isSharedWindow); }
  291. Rectangle<int> getBounds (bool global) const;
  292. Point<float> localToGlobal (Point<float> relativePosition) override;
  293. Point<float> globalToLocal (Point<float> screenPosition) override;
  294. using ComponentPeer::localToGlobal;
  295. using ComponentPeer::globalToLocal;
  296. void setAlpha (float newAlpha) override;
  297. void setMinimised (bool) override {}
  298. bool isMinimised() const override { return false; }
  299. void setFullScreen (bool shouldBeFullScreen) override;
  300. bool isFullScreen() const override { return fullScreen; }
  301. bool contains (Point<int> localPos, bool trueIfInAChildWindow) const override;
  302. OptionalBorderSize getFrameSizeIfPresent() const override { return {}; }
  303. BorderSize<int> getFrameSize() const override { return BorderSize<int>(); }
  304. bool setAlwaysOnTop (bool alwaysOnTop) override;
  305. void toFront (bool makeActiveWindow) override;
  306. void toBehind (ComponentPeer* other) override;
  307. void setIcon (const Image& newIcon) override;
  308. StringArray getAvailableRenderingEngines() override { return StringArray ("CoreGraphics Renderer"); }
  309. void displayLinkCallback();
  310. void drawRect (CGRect);
  311. void drawRectWithContext (CGContextRef, CGRect);
  312. bool canBecomeKeyWindow();
  313. //==============================================================================
  314. void viewFocusGain();
  315. void viewFocusLoss();
  316. bool isFocused() const override;
  317. void grabFocus() override;
  318. void textInputRequired (Point<int>, TextInputTarget&) override;
  319. void dismissPendingTextInput() override;
  320. void closeInputMethodContext() override;
  321. BOOL textViewReplaceCharacters (Range<int>, const String&);
  322. void updateScreenBounds();
  323. void handleTouches (UIEvent*, MouseEventFlags);
  324. #if JUCE_HAS_IOS_POINTER_SUPPORT
  325. API_AVAILABLE (ios (13.0)) void onHover (UIHoverGestureRecognizer*);
  326. void onScroll (UIPanGestureRecognizer*);
  327. #endif
  328. //==============================================================================
  329. void repaint (const Rectangle<int>& area) override;
  330. void performAnyPendingRepaintsNow() override;
  331. //==============================================================================
  332. UIWindow* window = nil;
  333. JuceUIView* view = nil;
  334. UIViewController* controller = nil;
  335. const bool isSharedWindow, isAppex;
  336. String stringBeingComposed;
  337. bool fullScreen = false, insideDrawRect = false;
  338. NSUniquePtr<JuceTextView> hiddenTextInput { [[JuceTextView alloc] initWithOwner: this] };
  339. NSUniquePtr<JuceTextInputTokenizer> tokenizer { [[JuceTextInputTokenizer alloc] initWithPeer: this] };
  340. static int64 getMouseTime (NSTimeInterval timestamp) noexcept
  341. {
  342. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  343. + (int64) (timestamp * 1000.0);
  344. }
  345. static int64 getMouseTime (UIEvent* e) noexcept
  346. {
  347. return getMouseTime ([e timestamp]);
  348. }
  349. static NSString* getDarkModeNotificationName()
  350. {
  351. return @"ViewDarkModeChanged";
  352. }
  353. static MultiTouchMapper<UITouch*> currentTouches;
  354. static UIKeyboardType getUIKeyboardType (TextInputTarget::VirtualKeyboardType type) noexcept
  355. {
  356. switch (type)
  357. {
  358. case TextInputTarget::textKeyboard: return UIKeyboardTypeDefault;
  359. case TextInputTarget::numericKeyboard: return UIKeyboardTypeNumbersAndPunctuation;
  360. case TextInputTarget::decimalKeyboard: return UIKeyboardTypeNumbersAndPunctuation;
  361. case TextInputTarget::urlKeyboard: return UIKeyboardTypeURL;
  362. case TextInputTarget::emailAddressKeyboard: return UIKeyboardTypeEmailAddress;
  363. case TextInputTarget::phoneNumberKeyboard: return UIKeyboardTypePhonePad;
  364. default: jassertfalse; break;
  365. }
  366. return UIKeyboardTypeDefault;
  367. }
  368. private:
  369. void appStyleChanged() override
  370. {
  371. [controller setNeedsStatusBarAppearanceUpdate];
  372. }
  373. //==============================================================================
  374. class AsyncRepaintMessage : public CallbackMessage
  375. {
  376. public:
  377. UIViewComponentPeer* const peer;
  378. const Rectangle<int> rect;
  379. AsyncRepaintMessage (UIViewComponentPeer* const p, const Rectangle<int>& r)
  380. : peer (p), rect (r)
  381. {
  382. }
  383. void messageCallback() override
  384. {
  385. if (ComponentPeer::isValidPeer (peer))
  386. peer->repaint (rect);
  387. }
  388. };
  389. std::unique_ptr<CoreGraphicsMetalLayerRenderer<UIView>> metalRenderer;
  390. RectangleList<float> deferredRepaints;
  391. //==============================================================================
  392. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UIViewComponentPeer)
  393. };
  394. static UIViewComponentPeer* getViewPeer (JuceUIViewController* c)
  395. {
  396. if (JuceUIView* juceView = (JuceUIView*) [c view])
  397. return juceView->owner;
  398. jassertfalse;
  399. return nullptr;
  400. }
  401. static void sendScreenBoundsUpdate (JuceUIViewController* c)
  402. {
  403. if (auto* peer = getViewPeer (c))
  404. peer->updateScreenBounds();
  405. }
  406. static bool isKioskModeView (JuceUIViewController* c)
  407. {
  408. if (auto* peer = getViewPeer (c))
  409. return Desktop::getInstance().getKioskModeComponent() == &(peer->getComponent());
  410. return false;
  411. }
  412. MultiTouchMapper<UITouch*> UIViewComponentPeer::currentTouches;
  413. } // namespace juce
  414. //==============================================================================
  415. //==============================================================================
  416. @implementation JuceUIViewController
  417. - (JuceUIViewController*) init
  418. {
  419. self = [super init];
  420. return self;
  421. }
  422. - (NSUInteger) supportedInterfaceOrientations
  423. {
  424. return Orientations::getSupportedOrientations();
  425. }
  426. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation
  427. {
  428. return Desktop::getInstance().isOrientationEnabled (Orientations::convertToJuce (interfaceOrientation));
  429. }
  430. - (void) willRotateToInterfaceOrientation: (UIInterfaceOrientation) toInterfaceOrientation
  431. duration: (NSTimeInterval) duration
  432. {
  433. ignoreUnused (toInterfaceOrientation, duration);
  434. [UIView setAnimationsEnabled: NO]; // disable this because it goes the wrong way and looks like crap.
  435. }
  436. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation
  437. {
  438. ignoreUnused (fromInterfaceOrientation);
  439. sendScreenBoundsUpdate (self);
  440. [UIView setAnimationsEnabled: YES];
  441. }
  442. - (void) viewWillTransitionToSize: (CGSize) size withTransitionCoordinator: (id<UIViewControllerTransitionCoordinator>) coordinator
  443. {
  444. [super viewWillTransitionToSize: size withTransitionCoordinator: coordinator];
  445. [coordinator animateAlongsideTransition: nil completion: ^void (id<UIViewControllerTransitionCoordinatorContext>)
  446. {
  447. sendScreenBoundsUpdate (self);
  448. }];
  449. }
  450. - (BOOL) prefersStatusBarHidden
  451. {
  452. if (isKioskModeView (self))
  453. return true;
  454. return [[[NSBundle mainBundle] objectForInfoDictionaryKey: @"UIStatusBarHidden"] boolValue];
  455. }
  456. - (BOOL) prefersHomeIndicatorAutoHidden
  457. {
  458. return isKioskModeView (self);
  459. }
  460. - (UIStatusBarStyle) preferredStatusBarStyle
  461. {
  462. #if defined (__IPHONE_13_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0
  463. if (@available (iOS 13.0, *))
  464. {
  465. if (auto* peer = getViewPeer (self))
  466. {
  467. switch (peer->getAppStyle())
  468. {
  469. case ComponentPeer::Style::automatic:
  470. return UIStatusBarStyleDefault;
  471. case ComponentPeer::Style::light:
  472. return UIStatusBarStyleDarkContent;
  473. case ComponentPeer::Style::dark:
  474. return UIStatusBarStyleLightContent;
  475. }
  476. }
  477. }
  478. #endif
  479. return UIStatusBarStyleDefault;
  480. }
  481. - (void) viewDidLoad
  482. {
  483. sendScreenBoundsUpdate (self);
  484. [super viewDidLoad];
  485. }
  486. - (void) viewWillAppear: (BOOL) animated
  487. {
  488. sendScreenBoundsUpdate (self);
  489. [super viewWillAppear:animated];
  490. }
  491. - (void) viewDidAppear: (BOOL) animated
  492. {
  493. sendScreenBoundsUpdate (self);
  494. [super viewDidAppear:animated];
  495. }
  496. - (void) viewWillLayoutSubviews
  497. {
  498. sendScreenBoundsUpdate (self);
  499. }
  500. - (void) viewDidLayoutSubviews
  501. {
  502. sendScreenBoundsUpdate (self);
  503. }
  504. @end
  505. @implementation JuceUIView
  506. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) peer
  507. withFrame: (CGRect) frame
  508. {
  509. [super initWithFrame: frame];
  510. owner = peer;
  511. displayLink.reset ([CADisplayLink displayLinkWithTarget: self
  512. selector: @selector (displayLinkCallback:)]);
  513. [displayLink.get() addToRunLoop: [NSRunLoop mainRunLoop]
  514. forMode: NSDefaultRunLoopMode];
  515. [self addSubview: owner->hiddenTextInput.get()];
  516. #if JUCE_HAS_IOS_POINTER_SUPPORT
  517. if (@available (iOS 13.4, *))
  518. {
  519. auto hoverRecognizer = [[[UIHoverGestureRecognizer alloc] initWithTarget: self action: @selector (onHover:)] autorelease];
  520. [hoverRecognizer setCancelsTouchesInView: NO];
  521. [hoverRecognizer setRequiresExclusiveTouchType: YES];
  522. [self addGestureRecognizer: hoverRecognizer];
  523. auto panRecognizer = [[[UIPanGestureRecognizer alloc] initWithTarget: self action: @selector (onScroll:)] autorelease];
  524. [panRecognizer setCancelsTouchesInView: NO];
  525. [panRecognizer setRequiresExclusiveTouchType: YES];
  526. [panRecognizer setAllowedScrollTypesMask: UIScrollTypeMaskAll];
  527. [panRecognizer setMaximumNumberOfTouches: 0];
  528. [self addGestureRecognizer: panRecognizer];
  529. }
  530. #endif
  531. return self;
  532. }
  533. - (void) dealloc
  534. {
  535. [owner->hiddenTextInput.get() removeFromSuperview];
  536. displayLink = nullptr;
  537. [super dealloc];
  538. }
  539. //==============================================================================
  540. + (Class) layerClass
  541. {
  542. #if JUCE_COREGRAPHICS_RENDER_WITH_MULTIPLE_PAINT_CALLS
  543. if (@available (iOS 13, *))
  544. return [CAMetalLayer class];
  545. #endif
  546. return [CALayer class];
  547. }
  548. - (void) displayLinkCallback: (CADisplayLink*) dl
  549. {
  550. if (owner != nullptr)
  551. owner->displayLinkCallback();
  552. }
  553. //==============================================================================
  554. - (void) drawRect: (CGRect) r
  555. {
  556. if (owner != nullptr)
  557. owner->drawRect (r);
  558. }
  559. //==============================================================================
  560. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  561. {
  562. ignoreUnused (touches);
  563. if (owner != nullptr)
  564. owner->handleTouches (event, MouseEventFlags::down);
  565. }
  566. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  567. {
  568. ignoreUnused (touches);
  569. if (owner != nullptr)
  570. owner->handleTouches (event, MouseEventFlags::none);
  571. }
  572. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  573. {
  574. ignoreUnused (touches);
  575. if (owner != nullptr)
  576. owner->handleTouches (event, MouseEventFlags::up);
  577. }
  578. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  579. {
  580. if (owner != nullptr)
  581. owner->handleTouches (event, MouseEventFlags::upAndCancel);
  582. [self touchesEnded: touches withEvent: event];
  583. }
  584. #if JUCE_HAS_IOS_POINTER_SUPPORT
  585. - (void) onHover: (UIHoverGestureRecognizer*) gesture
  586. {
  587. if (owner != nullptr)
  588. owner->onHover (gesture);
  589. }
  590. - (void) onScroll: (UIPanGestureRecognizer*) gesture
  591. {
  592. if (owner != nullptr)
  593. owner->onScroll (gesture);
  594. }
  595. #endif
  596. //==============================================================================
  597. - (BOOL) becomeFirstResponder
  598. {
  599. if (owner != nullptr)
  600. owner->viewFocusGain();
  601. return true;
  602. }
  603. - (BOOL) resignFirstResponder
  604. {
  605. if (owner != nullptr)
  606. owner->viewFocusLoss();
  607. return [super resignFirstResponder];
  608. }
  609. - (BOOL) canBecomeFirstResponder
  610. {
  611. return owner != nullptr && owner->canBecomeKeyWindow();
  612. }
  613. - (void) traitCollectionDidChange: (UITraitCollection*) previousTraitCollection
  614. {
  615. [super traitCollectionDidChange: previousTraitCollection];
  616. if (@available (iOS 12.0, *))
  617. {
  618. const auto wasDarkModeActive = ([previousTraitCollection userInterfaceStyle] == UIUserInterfaceStyleDark);
  619. if (wasDarkModeActive != Desktop::getInstance().isDarkModeActive())
  620. [[NSNotificationCenter defaultCenter] postNotificationName: UIViewComponentPeer::getDarkModeNotificationName()
  621. object: nil];
  622. }
  623. }
  624. - (BOOL) isAccessibilityElement
  625. {
  626. return NO;
  627. }
  628. - (CGRect) accessibilityFrame
  629. {
  630. if (owner != nullptr)
  631. if (auto* handler = owner->getComponent().getAccessibilityHandler())
  632. return convertToCGRect (handler->getComponent().getScreenBounds());
  633. return CGRectZero;
  634. }
  635. - (NSArray*) accessibilityElements
  636. {
  637. if (owner != nullptr)
  638. if (auto* handler = owner->getComponent().getAccessibilityHandler())
  639. return getContainerAccessibilityElements (*handler);
  640. return nil;
  641. }
  642. @end
  643. //==============================================================================
  644. @implementation JuceUIWindow
  645. - (void) setOwner: (UIViewComponentPeer*) peer
  646. {
  647. owner = peer;
  648. }
  649. - (void) becomeKeyWindow
  650. {
  651. [super becomeKeyWindow];
  652. if (owner != nullptr)
  653. owner->grabFocus();
  654. }
  655. @end
  656. /** see https://developer.apple.com/library/archive/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/LowerLevelText-HandlingTechnologies/LowerLevelText-HandlingTechnologies.html */
  657. @implementation JuceTextView
  658. - (TextInputTarget*) getTextInputTarget
  659. {
  660. if (owner != nullptr)
  661. return owner->findCurrentTextInputTarget();
  662. return nullptr;
  663. }
  664. - (instancetype) initWithOwner: (UIViewComponentPeer*) ownerIn
  665. {
  666. [super init];
  667. owner = ownerIn;
  668. delegate = nil;
  669. // The frame must have a finite size, otherwise some accessibility events will be ignored
  670. self.frame = CGRectMake (0.0, 0.0, 1.0, 1.0);
  671. return self;
  672. }
  673. - (BOOL) canPerformAction: (SEL) action withSender: (id) sender
  674. {
  675. if (auto* target = [self getTextInputTarget])
  676. {
  677. if (action == @selector (paste:))
  678. {
  679. if (@available (iOS 10, *))
  680. return [[UIPasteboard generalPasteboard] hasStrings];
  681. return [[UIPasteboard generalPasteboard] string] != nil;
  682. }
  683. }
  684. return [super canPerformAction: action withSender: sender];
  685. }
  686. - (void) cut: (id) sender
  687. {
  688. [self copy: sender];
  689. if (auto* target = [self getTextInputTarget])
  690. {
  691. if (delegate != nil)
  692. [delegate textWillChange: self];
  693. target->insertTextAtCaret ("");
  694. if (delegate != nil)
  695. [delegate textDidChange: self];
  696. }
  697. }
  698. - (void) copy: (id) sender
  699. {
  700. if (auto* target = [self getTextInputTarget])
  701. [[UIPasteboard generalPasteboard] setString: juceStringToNS (target->getTextInRange (target->getHighlightedRegion()))];
  702. }
  703. - (void) paste: (id) sender
  704. {
  705. if (auto* target = [self getTextInputTarget])
  706. {
  707. if (auto* string = [[UIPasteboard generalPasteboard] string])
  708. {
  709. if (delegate != nil)
  710. [delegate textWillChange: self];
  711. target->insertTextAtCaret (nsStringToJuce (string));
  712. if (delegate != nil)
  713. [delegate textDidChange: self];
  714. }
  715. }
  716. }
  717. - (void) selectAll: (id) sender
  718. {
  719. if (auto* target = [self getTextInputTarget])
  720. target->setHighlightedRegion ({ 0, target->getTotalNumChars() });
  721. }
  722. - (void) deleteBackward
  723. {
  724. auto* target = [self getTextInputTarget];
  725. if (target == nullptr)
  726. return;
  727. const auto range = target->getHighlightedRegion();
  728. const auto rangeToDelete = range.isEmpty() ? range.withStartAndLength (jmax (range.getStart() - 1, 0),
  729. range.getStart() != 0 ? 1 : 0)
  730. : range;
  731. target->setHighlightedRegion (rangeToDelete);
  732. target->insertTextAtCaret ("");
  733. }
  734. - (void) insertText: (NSString*) text
  735. {
  736. if (owner == nullptr)
  737. return;
  738. owner->stringBeingComposed.clear();
  739. if (auto* target = owner->findCurrentTextInputTarget())
  740. target->insertTextAtCaret (nsStringToJuce (text));
  741. }
  742. - (BOOL) hasText
  743. {
  744. if (auto* target = [self getTextInputTarget])
  745. return target->getTextInRange ({ 0, 1 }).isNotEmpty();
  746. return NO;
  747. }
  748. - (BOOL) accessibilityElementsHidden
  749. {
  750. return NO;
  751. }
  752. - (UITextRange*) selectedTextRangeForTarget: (TextInputTarget*) target
  753. {
  754. if (target != nullptr)
  755. return [JuceUITextRange withRange: target->getHighlightedRegion()];
  756. return nil;
  757. }
  758. - (UITextRange*) selectedTextRange
  759. {
  760. return [self selectedTextRangeForTarget: [self getTextInputTarget]];
  761. }
  762. - (void) setSelectedTextRange: (JuceUITextRange*) range
  763. {
  764. if (auto* target = [self getTextInputTarget])
  765. target->setHighlightedRegion (range != nil ? [range range] : Range<int>());
  766. }
  767. - (UITextRange*) markedTextRange
  768. {
  769. if (owner != nullptr && owner->stringBeingComposed.isNotEmpty())
  770. if (auto* target = owner->findCurrentTextInputTarget())
  771. return [JuceUITextRange withRange: target->getHighlightedRegion()];
  772. return nil;
  773. }
  774. - (void) setMarkedText: (NSString*) markedText
  775. selectedRange: (NSRange) selectedRange
  776. {
  777. ignoreUnused (selectedRange);
  778. if (owner == nullptr)
  779. return;
  780. owner->stringBeingComposed = nsStringToJuce (markedText);
  781. auto* target = owner->findCurrentTextInputTarget();
  782. if (target == nullptr)
  783. return;
  784. const auto currentHighlight = target->getHighlightedRegion();
  785. target->insertTextAtCaret (owner->stringBeingComposed);
  786. target->setHighlightedRegion (currentHighlight.withLength (0));
  787. target->setHighlightedRegion (currentHighlight.withLength (owner->stringBeingComposed.length()));
  788. }
  789. - (void) unmarkText
  790. {
  791. if (owner == nullptr)
  792. return;
  793. auto* target = owner->findCurrentTextInputTarget();
  794. if (target == nullptr)
  795. return;
  796. target->insertTextAtCaret (owner->stringBeingComposed);
  797. owner->stringBeingComposed.clear();
  798. }
  799. - (NSDictionary<NSAttributedStringKey, id>*) markedTextStyle
  800. {
  801. return nil;
  802. }
  803. - (void) setMarkedTextStyle: (NSDictionary<NSAttributedStringKey, id>*) dict
  804. {
  805. }
  806. - (UITextPosition*) beginningOfDocument
  807. {
  808. return [JuceUITextPosition withIndex: 0];
  809. }
  810. - (UITextPosition*) endOfDocument
  811. {
  812. if (auto* target = [self getTextInputTarget])
  813. return [JuceUITextPosition withIndex: target->getTotalNumChars()];
  814. return [JuceUITextPosition withIndex: 0];
  815. }
  816. - (id<UITextInputTokenizer>) tokenizer
  817. {
  818. return owner->tokenizer.get();
  819. }
  820. - (NSWritingDirection) baseWritingDirectionForPosition: (UITextPosition*) position
  821. inDirection: (UITextStorageDirection) direction
  822. {
  823. return NSWritingDirectionNatural;
  824. }
  825. - (CGRect) caretRectForPosition: (JuceUITextPosition*) position
  826. {
  827. if (position == nil)
  828. return CGRectZero;
  829. // Currently we ignore the requested position and just return the text editor's caret position
  830. if (auto* target = [self getTextInputTarget])
  831. {
  832. if (auto* comp = dynamic_cast<Component*> (target))
  833. {
  834. const auto areaOnDesktop = comp->localAreaToGlobal (target->getCaretRectangle());
  835. return convertToCGRect (ScalingHelpers::scaledScreenPosToUnscaled (areaOnDesktop));
  836. }
  837. }
  838. return CGRectZero;
  839. }
  840. - (UITextRange*) characterRangeByExtendingPosition: (JuceUITextPosition*) position
  841. inDirection: (UITextLayoutDirection) direction
  842. {
  843. const auto newPosition = [self indexFromPosition: position inDirection: direction offset: 1];
  844. return [JuceUITextRange from: position->index to: newPosition];
  845. }
  846. - (int) closestIndexToPoint: (CGPoint) point
  847. {
  848. if (auto* target = [self getTextInputTarget])
  849. {
  850. if (auto* comp = dynamic_cast<Component*> (target))
  851. {
  852. const auto pointOnDesktop = ScalingHelpers::unscaledScreenPosToScaled (convertToPointFloat (point));
  853. return target->getCharIndexForPoint (comp->getLocalPoint (nullptr, pointOnDesktop).roundToInt());
  854. }
  855. }
  856. return -1;
  857. }
  858. - (UITextRange*) characterRangeAtPoint: (CGPoint) point
  859. {
  860. const auto index = [self closestIndexToPoint: point];
  861. const auto result = index != -1 ? [JuceUITextRange from: index to: index] : nil;
  862. jassert (result != nullptr);
  863. return result;
  864. }
  865. - (UITextPosition*) closestPositionToPoint: (CGPoint) point
  866. {
  867. const auto index = [self closestIndexToPoint: point];
  868. const auto result = index != -1 ? [JuceUITextPosition withIndex: index] : nil;
  869. jassert (result != nullptr);
  870. return result;
  871. }
  872. - (UITextPosition*) closestPositionToPoint: (CGPoint) point
  873. withinRange: (JuceUITextRange*) range
  874. {
  875. const auto index = [self closestIndexToPoint: point];
  876. const auto result = index != -1 ? [JuceUITextPosition withIndex: [range range].clipValue (index)] : nil;
  877. jassert (result != nullptr);
  878. return result;
  879. }
  880. - (NSComparisonResult) comparePosition: (JuceUITextPosition*) position
  881. toPosition: (JuceUITextPosition*) other
  882. {
  883. const auto a = position != nil ? makeOptional (position->index) : nullopt;
  884. const auto b = other != nil ? makeOptional (other ->index) : nullopt;
  885. if (a < b)
  886. return NSOrderedAscending;
  887. if (b < a)
  888. return NSOrderedDescending;
  889. return NSOrderedSame;
  890. }
  891. - (NSInteger) offsetFromPosition: (JuceUITextPosition*) from
  892. toPosition: (JuceUITextPosition*) toPosition
  893. {
  894. if (from != nil && toPosition != nil)
  895. return toPosition->index - from->index;
  896. return 0;
  897. }
  898. - (int) indexFromPosition: (JuceUITextPosition*) position
  899. inDirection: (UITextLayoutDirection) direction
  900. offset: (NSInteger) offset
  901. {
  902. switch (direction)
  903. {
  904. case UITextLayoutDirectionLeft:
  905. case UITextLayoutDirectionRight:
  906. return position->index + (int) (offset * (direction == UITextLayoutDirectionLeft ? -1 : 1));
  907. case UITextLayoutDirectionUp:
  908. case UITextLayoutDirectionDown:
  909. {
  910. if (auto* target = [self getTextInputTarget])
  911. {
  912. const auto originalRectangle = target->getCaretRectangleForCharIndex (position->index);
  913. auto testIndex = position->index;
  914. for (auto lineOffset = 0; lineOffset < offset; ++lineOffset)
  915. {
  916. const auto caretRect = target->getCaretRectangleForCharIndex (testIndex);
  917. const auto newY = direction == UITextLayoutDirectionUp ? caretRect.getY() - 1
  918. : caretRect.getBottom() + 1;
  919. testIndex = target->getCharIndexForPoint ({ originalRectangle.getX(), newY });
  920. }
  921. return testIndex;
  922. }
  923. }
  924. }
  925. return position->index;
  926. }
  927. - (UITextPosition*) positionFromPosition: (JuceUITextPosition*) position
  928. inDirection: (UITextLayoutDirection) direction
  929. offset: (NSInteger) offset
  930. {
  931. return [JuceUITextPosition withIndex: [self indexFromPosition: position inDirection: direction offset: offset]];
  932. }
  933. - (UITextPosition*) positionFromPosition: (JuceUITextPosition*) position
  934. offset: (NSInteger) offset
  935. {
  936. if (position != nil)
  937. {
  938. if (auto* target = [self getTextInputTarget])
  939. {
  940. const auto newIndex = position->index + (int) offset;
  941. if (isPositiveAndBelow (newIndex, target->getTotalNumChars() + 1))
  942. return [JuceUITextPosition withIndex: newIndex];
  943. }
  944. }
  945. return nil;
  946. }
  947. - (CGRect) firstRectForRange: (JuceUITextRange*) range
  948. {
  949. if (auto* target = [self getTextInputTarget])
  950. {
  951. if (auto* comp = dynamic_cast<Component*> (target))
  952. {
  953. const auto list = target->getTextBounds ([range range]);
  954. if (! list.isEmpty())
  955. {
  956. const auto areaOnDesktop = comp->localAreaToGlobal (list.getRectangle (0));
  957. return convertToCGRect (ScalingHelpers::scaledScreenPosToUnscaled (areaOnDesktop));
  958. }
  959. }
  960. }
  961. return {};
  962. }
  963. - (NSArray<UITextSelectionRect*>*) selectionRectsForRange: (JuceUITextRange*) range
  964. {
  965. if (auto* target = [self getTextInputTarget])
  966. {
  967. if (auto* comp = dynamic_cast<Component*> (target))
  968. {
  969. const auto list = target->getTextBounds ([range range]);
  970. auto* result = [NSMutableArray arrayWithCapacity: (NSUInteger) list.getNumRectangles()];
  971. for (const auto& rect : list)
  972. {
  973. const auto areaOnDesktop = comp->localAreaToGlobal (rect);
  974. const auto nativeArea = convertToCGRect (ScalingHelpers::scaledScreenPosToUnscaled (areaOnDesktop));
  975. [result addObject: [JuceUITextSelectionRect withRect: nativeArea]];
  976. }
  977. return result;
  978. }
  979. }
  980. return nil;
  981. }
  982. - (UITextPosition*) positionWithinRange: (JuceUITextRange*) range
  983. farthestInDirection: (UITextLayoutDirection) direction
  984. {
  985. return direction == UITextLayoutDirectionUp || direction == UITextLayoutDirectionLeft
  986. ? [range start]
  987. : [range end];
  988. }
  989. - (void) replaceRange: (JuceUITextRange*) range
  990. withText: (NSString*) text
  991. {
  992. if (owner == nullptr)
  993. return;
  994. owner->stringBeingComposed.clear();
  995. if (auto* target = owner->findCurrentTextInputTarget())
  996. {
  997. target->setHighlightedRegion ([range range]);
  998. target->insertTextAtCaret (nsStringToJuce (text));
  999. }
  1000. }
  1001. - (void) setBaseWritingDirection: (NSWritingDirection) writingDirection
  1002. forRange: (UITextRange*) range
  1003. {
  1004. }
  1005. - (NSString*) textInRange: (JuceUITextRange*) range
  1006. {
  1007. if (auto* target = [self getTextInputTarget])
  1008. return juceStringToNS (target->getTextInRange ([range range]));
  1009. return nil;
  1010. }
  1011. - (UITextRange*) textRangeFromPosition: (JuceUITextPosition*) fromPosition
  1012. toPosition: (JuceUITextPosition*) toPosition
  1013. {
  1014. const auto from = fromPosition != nil ? fromPosition->index : 0;
  1015. const auto to = toPosition != nil ? toPosition ->index : 0;
  1016. return [JuceUITextRange withRange: Range<int>::between (from, to)];
  1017. }
  1018. - (void) setInputDelegate: (id<UITextInputDelegate>) delegateIn
  1019. {
  1020. delegate = delegateIn;
  1021. }
  1022. - (id<UITextInputDelegate>) inputDelegate
  1023. {
  1024. return delegate;
  1025. }
  1026. - (UIKeyboardType) keyboardType
  1027. {
  1028. if (auto* target = [self getTextInputTarget])
  1029. return UIViewComponentPeer::getUIKeyboardType (target->getKeyboardType());
  1030. return UIKeyboardTypeDefault;
  1031. }
  1032. - (UITextAutocapitalizationType) autocapitalizationType
  1033. {
  1034. return UITextAutocapitalizationTypeNone;
  1035. }
  1036. - (UITextAutocorrectionType) autocorrectionType
  1037. {
  1038. return UITextAutocorrectionTypeNo;
  1039. }
  1040. - (BOOL) canBecomeFirstResponder
  1041. {
  1042. return YES;
  1043. }
  1044. @end
  1045. //==============================================================================
  1046. @implementation JuceTextInputTokenizer
  1047. - (instancetype) initWithPeer: (UIViewComponentPeer*) peerIn
  1048. {
  1049. [super initWithTextInput: peerIn->hiddenTextInput.get()];
  1050. peer = peerIn;
  1051. return self;
  1052. }
  1053. - (UITextRange*) rangeEnclosingPosition: (JuceUITextPosition*) position
  1054. withGranularity: (UITextGranularity) granularity
  1055. inDirection: (UITextDirection) direction
  1056. {
  1057. if (granularity != UITextGranularityLine)
  1058. return [super rangeEnclosingPosition: position withGranularity: granularity inDirection: direction];
  1059. auto* target = peer->findCurrentTextInputTarget();
  1060. if (target == nullptr)
  1061. return nullptr;
  1062. const auto numChars = target->getTotalNumChars();
  1063. if (! isPositiveAndBelow (position->index, numChars))
  1064. return nullptr;
  1065. const auto allText = target->getTextInRange ({ 0, numChars });
  1066. const auto begin = AccessibilityTextHelpers::makeCharPtrIteratorAdapter (allText.begin());
  1067. const auto end = AccessibilityTextHelpers::makeCharPtrIteratorAdapter (allText.end());
  1068. const auto positionIter = begin + position->index;
  1069. const auto nextNewlineIter = std::find (positionIter, end, '\n');
  1070. const auto lastNewlineIter = std::find (std::make_reverse_iterator (positionIter),
  1071. std::make_reverse_iterator (begin),
  1072. '\n').base();
  1073. const auto from = std::distance (begin, lastNewlineIter);
  1074. const auto to = std::distance (begin, nextNewlineIter);
  1075. return [JuceUITextRange from: from to: to];
  1076. }
  1077. @end
  1078. //==============================================================================
  1079. //==============================================================================
  1080. namespace juce
  1081. {
  1082. bool KeyPress::isKeyCurrentlyDown (int)
  1083. {
  1084. return false;
  1085. }
  1086. Point<float> juce_lastMousePos;
  1087. //==============================================================================
  1088. UIViewComponentPeer::UIViewComponentPeer (Component& comp, int windowStyleFlags, UIView* viewToAttachTo)
  1089. : ComponentPeer (comp, windowStyleFlags),
  1090. isSharedWindow (viewToAttachTo != nil),
  1091. isAppex (SystemStats::isRunningInAppExtensionSandbox())
  1092. {
  1093. CGRect r = convertToCGRect (component.getBounds());
  1094. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  1095. view.multipleTouchEnabled = YES;
  1096. view.hidden = true;
  1097. view.opaque = component.isOpaque();
  1098. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  1099. #if JUCE_COREGRAPHICS_RENDER_WITH_MULTIPLE_PAINT_CALLS
  1100. if (@available (iOS 13, *))
  1101. metalRenderer = std::make_unique<CoreGraphicsMetalLayerRenderer<UIView>> (view, comp.isOpaque());
  1102. #endif
  1103. if ((windowStyleFlags & ComponentPeer::windowRequiresSynchronousCoreGraphicsRendering) == 0)
  1104. [[view layer] setDrawsAsynchronously: YES];
  1105. if (isSharedWindow)
  1106. {
  1107. window = [viewToAttachTo window];
  1108. [viewToAttachTo addSubview: view];
  1109. }
  1110. else
  1111. {
  1112. r = convertToCGRect (component.getBounds());
  1113. r.origin.y = [UIScreen mainScreen].bounds.size.height - (r.origin.y + r.size.height);
  1114. window = [[JuceUIWindow alloc] initWithFrame: r];
  1115. [((JuceUIWindow*) window) setOwner: this];
  1116. controller = [[JuceUIViewController alloc] init];
  1117. controller.view = view;
  1118. window.rootViewController = controller;
  1119. window.hidden = true;
  1120. window.opaque = component.isOpaque();
  1121. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  1122. if (component.isAlwaysOnTop())
  1123. window.windowLevel = UIWindowLevelAlert;
  1124. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  1125. }
  1126. setTitle (component.getName());
  1127. setVisible (component.isVisible());
  1128. }
  1129. static UIViewComponentPeer* currentlyFocusedPeer = nullptr;
  1130. UIViewComponentPeer::~UIViewComponentPeer()
  1131. {
  1132. if (currentlyFocusedPeer == this)
  1133. currentlyFocusedPeer = nullptr;
  1134. currentTouches.deleteAllTouchesForPeer (this);
  1135. view->owner = nullptr;
  1136. [view removeFromSuperview];
  1137. [view release];
  1138. [controller release];
  1139. if (! isSharedWindow)
  1140. {
  1141. [((JuceUIWindow*) window) setOwner: nil];
  1142. #if defined (__IPHONE_13_0)
  1143. if (@available (iOS 13.0, *))
  1144. window.windowScene = nil;
  1145. #endif
  1146. [window release];
  1147. }
  1148. }
  1149. //==============================================================================
  1150. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  1151. {
  1152. if (! isSharedWindow)
  1153. window.hidden = ! shouldBeVisible;
  1154. view.hidden = ! shouldBeVisible;
  1155. }
  1156. void UIViewComponentPeer::setTitle (const String&)
  1157. {
  1158. // xxx is this possible?
  1159. }
  1160. void UIViewComponentPeer::setBounds (const Rectangle<int>& newBounds, const bool isNowFullScreen)
  1161. {
  1162. fullScreen = isNowFullScreen;
  1163. if (isSharedWindow)
  1164. {
  1165. CGRect r = convertToCGRect (newBounds);
  1166. if (view.frame.size.width != r.size.width || view.frame.size.height != r.size.height)
  1167. [view setNeedsDisplay];
  1168. view.frame = r;
  1169. }
  1170. else
  1171. {
  1172. window.frame = convertToCGRect (newBounds);
  1173. view.frame = CGRectMake (0, 0, (CGFloat) newBounds.getWidth(), (CGFloat) newBounds.getHeight());
  1174. handleMovedOrResized();
  1175. }
  1176. }
  1177. Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  1178. {
  1179. auto r = view.frame;
  1180. if (global)
  1181. {
  1182. if (view.window != nil)
  1183. {
  1184. r = [view convertRect: r toView: view.window];
  1185. r = [view.window convertRect: r toWindow: nil];
  1186. }
  1187. else if (window != nil)
  1188. {
  1189. r.origin.x += window.frame.origin.x;
  1190. r.origin.y += window.frame.origin.y;
  1191. }
  1192. }
  1193. return convertToRectInt (r);
  1194. }
  1195. Point<float> UIViewComponentPeer::localToGlobal (Point<float> relativePosition)
  1196. {
  1197. return relativePosition + getBounds (true).getPosition().toFloat();
  1198. }
  1199. Point<float> UIViewComponentPeer::globalToLocal (Point<float> screenPosition)
  1200. {
  1201. return screenPosition - getBounds (true).getPosition().toFloat();
  1202. }
  1203. void UIViewComponentPeer::setAlpha (float newAlpha)
  1204. {
  1205. [view.window setAlpha: (CGFloat) newAlpha];
  1206. }
  1207. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  1208. {
  1209. if (! isSharedWindow)
  1210. {
  1211. auto r = shouldBeFullScreen ? Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea
  1212. : lastNonFullscreenBounds;
  1213. if ((! shouldBeFullScreen) && r.isEmpty())
  1214. r = getBounds();
  1215. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  1216. if (! r.isEmpty())
  1217. setBounds (ScalingHelpers::scaledScreenPosToUnscaled (component, r), shouldBeFullScreen);
  1218. component.repaint();
  1219. }
  1220. }
  1221. void UIViewComponentPeer::updateScreenBounds()
  1222. {
  1223. auto& desktop = Desktop::getInstance();
  1224. auto oldArea = component.getBounds();
  1225. auto oldDesktop = desktop.getDisplays().getPrimaryDisplay()->userArea;
  1226. forceDisplayUpdate();
  1227. if (fullScreen)
  1228. {
  1229. fullScreen = false;
  1230. setFullScreen (true);
  1231. }
  1232. else if (! isSharedWindow)
  1233. {
  1234. auto newDesktop = desktop.getDisplays().getPrimaryDisplay()->userArea;
  1235. if (newDesktop != oldDesktop)
  1236. {
  1237. // this will re-centre the window, but leave its size unchanged
  1238. auto centreRelX = oldArea.getCentreX() / (float) oldDesktop.getWidth();
  1239. auto centreRelY = oldArea.getCentreY() / (float) oldDesktop.getHeight();
  1240. auto x = ((int) (newDesktop.getWidth() * centreRelX)) - (oldArea.getWidth() / 2);
  1241. auto y = ((int) (newDesktop.getHeight() * centreRelY)) - (oldArea.getHeight() / 2);
  1242. component.setBounds (oldArea.withPosition (x, y));
  1243. }
  1244. }
  1245. [view setNeedsDisplay];
  1246. }
  1247. bool UIViewComponentPeer::contains (Point<int> localPos, bool trueIfInAChildWindow) const
  1248. {
  1249. if (! ScalingHelpers::scaledScreenPosToUnscaled (component, component.getLocalBounds()).contains (localPos))
  1250. return false;
  1251. UIView* v = [view hitTest: convertToCGPoint (localPos)
  1252. withEvent: nil];
  1253. if (trueIfInAChildWindow)
  1254. return v != nil;
  1255. return v == view;
  1256. }
  1257. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  1258. {
  1259. if (! isSharedWindow)
  1260. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  1261. return true;
  1262. }
  1263. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  1264. {
  1265. if (isSharedWindow)
  1266. [[view superview] bringSubviewToFront: view];
  1267. if (makeActiveWindow && window != nil && component.isVisible())
  1268. [window makeKeyAndVisible];
  1269. }
  1270. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  1271. {
  1272. if (auto* otherPeer = dynamic_cast<UIViewComponentPeer*> (other))
  1273. {
  1274. if (isSharedWindow)
  1275. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  1276. }
  1277. else
  1278. {
  1279. jassertfalse; // wrong type of window?
  1280. }
  1281. }
  1282. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  1283. {
  1284. // to do..
  1285. }
  1286. //==============================================================================
  1287. static float getMaximumTouchForce (UITouch* touch) noexcept
  1288. {
  1289. if ([touch respondsToSelector: @selector (maximumPossibleForce)])
  1290. return (float) touch.maximumPossibleForce;
  1291. return 0.0f;
  1292. }
  1293. static float getTouchForce (UITouch* touch) noexcept
  1294. {
  1295. if ([touch respondsToSelector: @selector (force)])
  1296. return (float) touch.force;
  1297. return 0.0f;
  1298. }
  1299. void UIViewComponentPeer::handleTouches (UIEvent* event, MouseEventFlags mouseEventFlags)
  1300. {
  1301. if (event == nullptr)
  1302. return;
  1303. NSArray* touches = [[event touchesForView: view] allObjects];
  1304. for (unsigned int i = 0; i < [touches count]; ++i)
  1305. {
  1306. UITouch* touch = [touches objectAtIndex: i];
  1307. auto maximumForce = getMaximumTouchForce (touch);
  1308. if ([touch phase] == UITouchPhaseStationary && maximumForce <= 0)
  1309. continue;
  1310. auto pos = convertToPointFloat ([touch locationInView: view]);
  1311. juce_lastMousePos = pos + getBounds (true).getPosition().toFloat();
  1312. auto time = getMouseTime (event);
  1313. auto touchIndex = currentTouches.getIndexOfTouch (this, touch);
  1314. auto modsToSend = ModifierKeys::currentModifiers;
  1315. auto isUp = [] (MouseEventFlags m)
  1316. {
  1317. return m == MouseEventFlags::up || m == MouseEventFlags::upAndCancel;
  1318. };
  1319. if (mouseEventFlags == MouseEventFlags::down)
  1320. {
  1321. if ([touch phase] != UITouchPhaseBegan)
  1322. continue;
  1323. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  1324. modsToSend = ModifierKeys::currentModifiers;
  1325. // this forces a mouse-enter/up event, in case for some reason we didn't get a mouse-up before.
  1326. handleMouseEvent (MouseInputSource::InputSourceType::touch, pos, modsToSend.withoutMouseButtons(),
  1327. MouseInputSource::defaultPressure, MouseInputSource::defaultOrientation, time, {}, touchIndex);
  1328. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  1329. return;
  1330. }
  1331. else if (isUp (mouseEventFlags))
  1332. {
  1333. if (! ([touch phase] == UITouchPhaseEnded || [touch phase] == UITouchPhaseCancelled))
  1334. continue;
  1335. modsToSend = modsToSend.withoutMouseButtons();
  1336. currentTouches.clearTouch (touchIndex);
  1337. if (! currentTouches.areAnyTouchesActive())
  1338. mouseEventFlags = MouseEventFlags::upAndCancel;
  1339. }
  1340. if (mouseEventFlags == MouseEventFlags::upAndCancel)
  1341. {
  1342. currentTouches.clearTouch (touchIndex);
  1343. modsToSend = ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons();
  1344. }
  1345. // NB: some devices return 0 or 1.0 if pressure is unknown, so we'll clip our value to a believable range:
  1346. auto pressure = maximumForce > 0 ? jlimit (0.0001f, 0.9999f, getTouchForce (touch) / maximumForce)
  1347. : MouseInputSource::defaultPressure;
  1348. handleMouseEvent (MouseInputSource::InputSourceType::touch,
  1349. pos, modsToSend, pressure, MouseInputSource::defaultOrientation, time, { }, touchIndex);
  1350. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  1351. return;
  1352. if (isUp (mouseEventFlags))
  1353. {
  1354. handleMouseEvent (MouseInputSource::InputSourceType::touch, MouseInputSource::offscreenMousePos, modsToSend,
  1355. MouseInputSource::defaultPressure, MouseInputSource::defaultOrientation, time, {}, touchIndex);
  1356. if (! isValidPeer (this))
  1357. return;
  1358. }
  1359. }
  1360. }
  1361. #if JUCE_HAS_IOS_POINTER_SUPPORT
  1362. void UIViewComponentPeer::onHover (UIHoverGestureRecognizer* gesture)
  1363. {
  1364. auto pos = convertToPointFloat ([gesture locationInView: view]);
  1365. juce_lastMousePos = pos + getBounds (true).getPosition().toFloat();
  1366. handleMouseEvent (MouseInputSource::InputSourceType::touch,
  1367. pos,
  1368. ModifierKeys::currentModifiers,
  1369. MouseInputSource::defaultPressure, MouseInputSource::defaultOrientation,
  1370. UIViewComponentPeer::getMouseTime ([[NSProcessInfo processInfo] systemUptime]),
  1371. {});
  1372. }
  1373. void UIViewComponentPeer::onScroll (UIPanGestureRecognizer* gesture)
  1374. {
  1375. const auto offset = [gesture translationInView: view];
  1376. const auto scale = 0.5f / 256.0f;
  1377. MouseWheelDetails details;
  1378. details.deltaX = scale * (float) offset.x;
  1379. details.deltaY = scale * (float) offset.y;
  1380. details.isReversed = false;
  1381. details.isSmooth = true;
  1382. details.isInertial = false;
  1383. handleMouseWheel (MouseInputSource::InputSourceType::touch,
  1384. convertToPointFloat ([gesture locationInView: view]),
  1385. UIViewComponentPeer::getMouseTime ([[NSProcessInfo processInfo] systemUptime]),
  1386. details);
  1387. }
  1388. #endif
  1389. //==============================================================================
  1390. void UIViewComponentPeer::viewFocusGain()
  1391. {
  1392. if (currentlyFocusedPeer != this)
  1393. {
  1394. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  1395. currentlyFocusedPeer->handleFocusLoss();
  1396. currentlyFocusedPeer = this;
  1397. handleFocusGain();
  1398. }
  1399. }
  1400. void UIViewComponentPeer::viewFocusLoss()
  1401. {
  1402. if (currentlyFocusedPeer == this)
  1403. {
  1404. currentlyFocusedPeer = nullptr;
  1405. handleFocusLoss();
  1406. }
  1407. }
  1408. bool UIViewComponentPeer::isFocused() const
  1409. {
  1410. if (isAppex)
  1411. return true;
  1412. return isSharedWindow ? this == currentlyFocusedPeer
  1413. : (window != nil && [window isKeyWindow]);
  1414. }
  1415. void UIViewComponentPeer::grabFocus()
  1416. {
  1417. if (window != nil)
  1418. {
  1419. [window makeKeyWindow];
  1420. viewFocusGain();
  1421. }
  1422. }
  1423. void UIViewComponentPeer::textInputRequired (Point<int>, TextInputTarget&)
  1424. {
  1425. [hiddenTextInput.get() becomeFirstResponder];
  1426. }
  1427. void UIViewComponentPeer::closeInputMethodContext()
  1428. {
  1429. if (auto* input = hiddenTextInput.get())
  1430. {
  1431. if (auto* delegate = [input inputDelegate])
  1432. {
  1433. [delegate selectionWillChange: input];
  1434. [delegate selectionDidChange: input];
  1435. }
  1436. }
  1437. }
  1438. void UIViewComponentPeer::dismissPendingTextInput()
  1439. {
  1440. closeInputMethodContext();
  1441. [hiddenTextInput.get() resignFirstResponder];
  1442. }
  1443. BOOL UIViewComponentPeer::textViewReplaceCharacters (Range<int> range, const String& text)
  1444. {
  1445. if (auto* target = findCurrentTextInputTarget())
  1446. {
  1447. auto currentSelection = target->getHighlightedRegion();
  1448. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  1449. if (currentSelection.isEmpty())
  1450. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  1451. WeakReference<Component> deletionChecker (dynamic_cast<Component*> (target));
  1452. if (text == "\r" || text == "\n" || text == "\r\n")
  1453. handleKeyPress (KeyPress::returnKey, text[0]);
  1454. else
  1455. target->insertTextAtCaret (text);
  1456. }
  1457. return NO;
  1458. }
  1459. //==============================================================================
  1460. void UIViewComponentPeer::displayLinkCallback()
  1461. {
  1462. if (deferredRepaints.isEmpty())
  1463. return;
  1464. auto dispatchRectangles = [this] ()
  1465. {
  1466. if (metalRenderer != nullptr)
  1467. return metalRenderer->drawRectangleList (view,
  1468. (float) view.contentScaleFactor,
  1469. [this] (CGContextRef ctx, CGRect r) { drawRectWithContext (ctx, r); },
  1470. deferredRepaints);
  1471. for (const auto& r : deferredRepaints)
  1472. [view setNeedsDisplayInRect: convertToCGRect (r)];
  1473. return true;
  1474. };
  1475. if (dispatchRectangles())
  1476. deferredRepaints.clear();
  1477. }
  1478. //==============================================================================
  1479. void UIViewComponentPeer::drawRect (CGRect r)
  1480. {
  1481. if (r.size.width < 1.0f || r.size.height < 1.0f)
  1482. return;
  1483. drawRectWithContext (UIGraphicsGetCurrentContext(), r);
  1484. }
  1485. void UIViewComponentPeer::drawRectWithContext (CGContextRef cg, CGRect)
  1486. {
  1487. if (! component.isOpaque())
  1488. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  1489. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, getComponent().getHeight()));
  1490. CoreGraphicsContext g (cg, getComponent().getHeight());
  1491. insideDrawRect = true;
  1492. handlePaint (g);
  1493. insideDrawRect = false;
  1494. }
  1495. bool UIViewComponentPeer::canBecomeKeyWindow()
  1496. {
  1497. return (getStyleFlags() & juce::ComponentPeer::windowIgnoresKeyPresses) == 0;
  1498. }
  1499. //==============================================================================
  1500. void Desktop::setKioskComponent (Component* kioskModeComp, bool enableOrDisable, bool /*allowMenusAndBars*/)
  1501. {
  1502. displays->refresh();
  1503. if (auto* peer = kioskModeComp->getPeer())
  1504. {
  1505. if (auto* uiViewPeer = dynamic_cast<UIViewComponentPeer*> (peer))
  1506. [uiViewPeer->controller setNeedsStatusBarAppearanceUpdate];
  1507. peer->setFullScreen (enableOrDisable);
  1508. }
  1509. }
  1510. void Desktop::allowedOrientationsChanged()
  1511. {
  1512. // if the current orientation isn't allowed anymore then switch orientations
  1513. if (! isOrientationEnabled (getCurrentOrientation()))
  1514. {
  1515. auto newOrientation = [this]
  1516. {
  1517. for (auto orientation : { upright, upsideDown, rotatedClockwise, rotatedAntiClockwise })
  1518. if (isOrientationEnabled (orientation))
  1519. return orientation;
  1520. // you need to support at least one orientation
  1521. jassertfalse;
  1522. return upright;
  1523. }();
  1524. NSNumber* value = [NSNumber numberWithInt: (int) Orientations::convertFromJuce (newOrientation)];
  1525. [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
  1526. [value release];
  1527. }
  1528. }
  1529. //==============================================================================
  1530. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  1531. {
  1532. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  1533. {
  1534. (new AsyncRepaintMessage (this, area))->post();
  1535. return;
  1536. }
  1537. deferredRepaints.add (area.toFloat());
  1538. }
  1539. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  1540. {
  1541. }
  1542. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  1543. {
  1544. return new UIViewComponentPeer (*this, styleFlags, (UIView*) windowToAttachTo);
  1545. }
  1546. //==============================================================================
  1547. const int KeyPress::spaceKey = ' ';
  1548. const int KeyPress::returnKey = 0x0d;
  1549. const int KeyPress::escapeKey = 0x1b;
  1550. const int KeyPress::backspaceKey = 0x7f;
  1551. const int KeyPress::leftKey = 0x1000;
  1552. const int KeyPress::rightKey = 0x1001;
  1553. const int KeyPress::upKey = 0x1002;
  1554. const int KeyPress::downKey = 0x1003;
  1555. const int KeyPress::pageUpKey = 0x1004;
  1556. const int KeyPress::pageDownKey = 0x1005;
  1557. const int KeyPress::endKey = 0x1006;
  1558. const int KeyPress::homeKey = 0x1007;
  1559. const int KeyPress::deleteKey = 0x1008;
  1560. const int KeyPress::insertKey = -1;
  1561. const int KeyPress::tabKey = 9;
  1562. const int KeyPress::F1Key = 0x2001;
  1563. const int KeyPress::F2Key = 0x2002;
  1564. const int KeyPress::F3Key = 0x2003;
  1565. const int KeyPress::F4Key = 0x2004;
  1566. const int KeyPress::F5Key = 0x2005;
  1567. const int KeyPress::F6Key = 0x2006;
  1568. const int KeyPress::F7Key = 0x2007;
  1569. const int KeyPress::F8Key = 0x2008;
  1570. const int KeyPress::F9Key = 0x2009;
  1571. const int KeyPress::F10Key = 0x200a;
  1572. const int KeyPress::F11Key = 0x200b;
  1573. const int KeyPress::F12Key = 0x200c;
  1574. const int KeyPress::F13Key = 0x200d;
  1575. const int KeyPress::F14Key = 0x200e;
  1576. const int KeyPress::F15Key = 0x200f;
  1577. const int KeyPress::F16Key = 0x2010;
  1578. const int KeyPress::F17Key = 0x2011;
  1579. const int KeyPress::F18Key = 0x2012;
  1580. const int KeyPress::F19Key = 0x2013;
  1581. const int KeyPress::F20Key = 0x2014;
  1582. const int KeyPress::F21Key = 0x2015;
  1583. const int KeyPress::F22Key = 0x2016;
  1584. const int KeyPress::F23Key = 0x2017;
  1585. const int KeyPress::F24Key = 0x2018;
  1586. const int KeyPress::F25Key = 0x2019;
  1587. const int KeyPress::F26Key = 0x201a;
  1588. const int KeyPress::F27Key = 0x201b;
  1589. const int KeyPress::F28Key = 0x201c;
  1590. const int KeyPress::F29Key = 0x201d;
  1591. const int KeyPress::F30Key = 0x201e;
  1592. const int KeyPress::F31Key = 0x201f;
  1593. const int KeyPress::F32Key = 0x2020;
  1594. const int KeyPress::F33Key = 0x2021;
  1595. const int KeyPress::F34Key = 0x2022;
  1596. const int KeyPress::F35Key = 0x2023;
  1597. const int KeyPress::numberPad0 = 0x30020;
  1598. const int KeyPress::numberPad1 = 0x30021;
  1599. const int KeyPress::numberPad2 = 0x30022;
  1600. const int KeyPress::numberPad3 = 0x30023;
  1601. const int KeyPress::numberPad4 = 0x30024;
  1602. const int KeyPress::numberPad5 = 0x30025;
  1603. const int KeyPress::numberPad6 = 0x30026;
  1604. const int KeyPress::numberPad7 = 0x30027;
  1605. const int KeyPress::numberPad8 = 0x30028;
  1606. const int KeyPress::numberPad9 = 0x30029;
  1607. const int KeyPress::numberPadAdd = 0x3002a;
  1608. const int KeyPress::numberPadSubtract = 0x3002b;
  1609. const int KeyPress::numberPadMultiply = 0x3002c;
  1610. const int KeyPress::numberPadDivide = 0x3002d;
  1611. const int KeyPress::numberPadSeparator = 0x3002e;
  1612. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  1613. const int KeyPress::numberPadEquals = 0x30030;
  1614. const int KeyPress::numberPadDelete = 0x30031;
  1615. const int KeyPress::playKey = 0x30000;
  1616. const int KeyPress::stopKey = 0x30001;
  1617. const int KeyPress::fastForwardKey = 0x30002;
  1618. const int KeyPress::rewindKey = 0x30003;
  1619. } // namespace juce