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.

1112 lines
37KB

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