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.

2355 lines
77KB

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