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.

2416 lines
79KB

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