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.

2339 lines
76KB

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