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.

1097 lines
36KB

  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. jassert (juceView != nil && juceView->owner != nullptr);
  219. return Desktop::getInstance().getKioskModeComponent() == &(juceView->owner->getComponent());
  220. }
  221. MultiTouchMapper<UITouch*> UIViewComponentPeer::currentTouches;
  222. } // namespace juce
  223. //==============================================================================
  224. //==============================================================================
  225. @implementation JuceUIViewController
  226. - (JuceUIViewController*) init
  227. {
  228. self = [super init];
  229. return self;
  230. }
  231. - (NSUInteger) supportedInterfaceOrientations
  232. {
  233. return Orientations::getSupportedOrientations();
  234. }
  235. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation
  236. {
  237. return Desktop::getInstance().isOrientationEnabled (Orientations::convertToJuce (interfaceOrientation));
  238. }
  239. - (void) willRotateToInterfaceOrientation: (UIInterfaceOrientation) toInterfaceOrientation
  240. duration: (NSTimeInterval) duration
  241. {
  242. ignoreUnused (toInterfaceOrientation, duration);
  243. [UIView setAnimationsEnabled: NO]; // disable this because it goes the wrong way and looks like crap.
  244. }
  245. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation
  246. {
  247. ignoreUnused (fromInterfaceOrientation);
  248. sendScreenBoundsUpdate (self);
  249. [UIView setAnimationsEnabled: YES];
  250. }
  251. - (void) viewWillTransitionToSize: (CGSize) size withTransitionCoordinator: (id<UIViewControllerTransitionCoordinator>) coordinator
  252. {
  253. [super viewWillTransitionToSize: size withTransitionCoordinator: coordinator];
  254. [coordinator animateAlongsideTransition: nil completion: ^void (id<UIViewControllerTransitionCoordinatorContext>)
  255. {
  256. sendScreenBoundsUpdate (self);
  257. }];
  258. }
  259. - (BOOL) prefersStatusBarHidden
  260. {
  261. if (isKioskModeView (self))
  262. return true;
  263. return [[[NSBundle mainBundle] objectForInfoDictionaryKey: @"UIStatusBarHidden"] boolValue];
  264. }
  265. #if defined (__IPHONE_11_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_11_0
  266. - (BOOL) prefersHomeIndicatorAutoHidden
  267. {
  268. return isKioskModeView (self);
  269. }
  270. #endif
  271. - (UIStatusBarStyle) preferredStatusBarStyle
  272. {
  273. return UIStatusBarStyleDefault;
  274. }
  275. - (void) viewDidLoad
  276. {
  277. sendScreenBoundsUpdate (self);
  278. [super viewDidLoad];
  279. }
  280. - (void) viewWillAppear: (BOOL) animated
  281. {
  282. sendScreenBoundsUpdate (self);
  283. [super viewWillAppear:animated];
  284. }
  285. - (void) viewDidAppear: (BOOL) animated
  286. {
  287. sendScreenBoundsUpdate (self);
  288. [super viewDidAppear:animated];
  289. }
  290. - (void) viewWillLayoutSubviews
  291. {
  292. sendScreenBoundsUpdate (self);
  293. }
  294. - (void) viewDidLayoutSubviews
  295. {
  296. sendScreenBoundsUpdate (self);
  297. }
  298. @end
  299. @implementation JuceUIView
  300. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) peer
  301. withFrame: (CGRect) frame
  302. {
  303. [super initWithFrame: frame];
  304. owner = peer;
  305. hiddenTextView = [[UITextView alloc] initWithFrame: CGRectZero];
  306. [self addSubview: hiddenTextView];
  307. hiddenTextView.delegate = self;
  308. hiddenTextView.autocapitalizationType = UITextAutocapitalizationTypeNone;
  309. hiddenTextView.autocorrectionType = UITextAutocorrectionTypeNo;
  310. hiddenTextView.inputAssistantItem.leadingBarButtonGroups = @[];
  311. hiddenTextView.inputAssistantItem.trailingBarButtonGroups = @[];
  312. return self;
  313. }
  314. - (void) dealloc
  315. {
  316. [hiddenTextView removeFromSuperview];
  317. [hiddenTextView release];
  318. [super dealloc];
  319. }
  320. //==============================================================================
  321. - (void) drawRect: (CGRect) r
  322. {
  323. if (owner != nullptr)
  324. owner->drawRect (r);
  325. }
  326. //==============================================================================
  327. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  328. {
  329. ignoreUnused (touches);
  330. if (owner != nullptr)
  331. owner->handleTouches (event, true, false, false);
  332. }
  333. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  334. {
  335. ignoreUnused (touches);
  336. if (owner != nullptr)
  337. owner->handleTouches (event, false, false, false);
  338. }
  339. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  340. {
  341. ignoreUnused (touches);
  342. if (owner != nullptr)
  343. owner->handleTouches (event, false, true, false);
  344. }
  345. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  346. {
  347. if (owner != nullptr)
  348. owner->handleTouches (event, false, true, true);
  349. [self touchesEnded: touches withEvent: event];
  350. }
  351. //==============================================================================
  352. - (BOOL) becomeFirstResponder
  353. {
  354. if (owner != nullptr)
  355. owner->viewFocusGain();
  356. return true;
  357. }
  358. - (BOOL) resignFirstResponder
  359. {
  360. if (owner != nullptr)
  361. owner->viewFocusLoss();
  362. return [super resignFirstResponder];
  363. }
  364. - (BOOL) canBecomeFirstResponder
  365. {
  366. return owner != nullptr && owner->canBecomeKeyWindow();
  367. }
  368. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
  369. {
  370. ignoreUnused (textView);
  371. return owner->textViewReplaceCharacters (Range<int> ((int) range.location, (int) (range.location + range.length)),
  372. nsStringToJuce (text));
  373. }
  374. @end
  375. //==============================================================================
  376. @implementation JuceUIWindow
  377. - (void) setOwner: (UIViewComponentPeer*) peer
  378. {
  379. owner = peer;
  380. }
  381. - (void) becomeKeyWindow
  382. {
  383. [super becomeKeyWindow];
  384. if (owner != nullptr)
  385. owner->grabFocus();
  386. }
  387. @end
  388. //==============================================================================
  389. //==============================================================================
  390. namespace juce
  391. {
  392. bool KeyPress::isKeyCurrentlyDown (int)
  393. {
  394. return false;
  395. }
  396. Point<float> juce_lastMousePos;
  397. //==============================================================================
  398. UIViewComponentPeer::UIViewComponentPeer (Component& comp, int windowStyleFlags, UIView* viewToAttachTo)
  399. : ComponentPeer (comp, windowStyleFlags),
  400. isSharedWindow (viewToAttachTo != nil),
  401. isAppex (SystemStats::isRunningInAppExtensionSandbox())
  402. {
  403. CGRect r = convertToCGRect (component.getBounds());
  404. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  405. view.multipleTouchEnabled = YES;
  406. view.hidden = true;
  407. view.opaque = component.isOpaque();
  408. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  409. if (isSharedWindow)
  410. {
  411. window = [viewToAttachTo window];
  412. [viewToAttachTo addSubview: view];
  413. }
  414. else
  415. {
  416. r = convertToCGRect (component.getBounds());
  417. r.origin.y = [UIScreen mainScreen].bounds.size.height - (r.origin.y + r.size.height);
  418. window = [[JuceUIWindow alloc] initWithFrame: r];
  419. [((JuceUIWindow*) window) setOwner: this];
  420. controller = [[JuceUIViewController alloc] init];
  421. controller.view = view;
  422. window.rootViewController = controller;
  423. window.hidden = true;
  424. window.opaque = component.isOpaque();
  425. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  426. if (component.isAlwaysOnTop())
  427. window.windowLevel = UIWindowLevelAlert;
  428. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  429. }
  430. setTitle (component.getName());
  431. setVisible (component.isVisible());
  432. Desktop::getInstance().addFocusChangeListener (this);
  433. }
  434. UIViewComponentPeer::~UIViewComponentPeer()
  435. {
  436. currentTouches.deleteAllTouchesForPeer (this);
  437. Desktop::getInstance().removeFocusChangeListener (this);
  438. view->owner = nullptr;
  439. [view removeFromSuperview];
  440. [view release];
  441. [controller release];
  442. if (! isSharedWindow)
  443. {
  444. [((JuceUIWindow*) window) setOwner: nil];
  445. [window release];
  446. }
  447. }
  448. //==============================================================================
  449. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  450. {
  451. if (! isSharedWindow)
  452. window.hidden = ! shouldBeVisible;
  453. view.hidden = ! shouldBeVisible;
  454. }
  455. void UIViewComponentPeer::setTitle (const String&)
  456. {
  457. // xxx is this possible?
  458. }
  459. void UIViewComponentPeer::setBounds (const Rectangle<int>& newBounds, const bool isNowFullScreen)
  460. {
  461. fullScreen = isNowFullScreen;
  462. if (isSharedWindow)
  463. {
  464. CGRect r = convertToCGRect (newBounds);
  465. if (view.frame.size.width != r.size.width || view.frame.size.height != r.size.height)
  466. [view setNeedsDisplay];
  467. view.frame = r;
  468. }
  469. else
  470. {
  471. window.frame = convertToCGRect (newBounds);
  472. view.frame = CGRectMake (0, 0, (CGFloat) newBounds.getWidth(), (CGFloat) newBounds.getHeight());
  473. handleMovedOrResized();
  474. }
  475. }
  476. Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  477. {
  478. auto r = view.frame;
  479. if (global)
  480. {
  481. if (view.window != nil)
  482. {
  483. r = [view convertRect: r toView: view.window];
  484. r = [view.window convertRect: r toWindow: nil];
  485. }
  486. else if (window != nil)
  487. {
  488. r.origin.x += window.frame.origin.x;
  489. r.origin.y += window.frame.origin.y;
  490. }
  491. }
  492. return convertToRectInt (r);
  493. }
  494. Point<float> UIViewComponentPeer::localToGlobal (Point<float> relativePosition)
  495. {
  496. return relativePosition + getBounds (true).getPosition().toFloat();
  497. }
  498. Point<float> UIViewComponentPeer::globalToLocal (Point<float> screenPosition)
  499. {
  500. return screenPosition - getBounds (true).getPosition().toFloat();
  501. }
  502. void UIViewComponentPeer::setAlpha (float newAlpha)
  503. {
  504. [view.window setAlpha: (CGFloat) newAlpha];
  505. }
  506. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  507. {
  508. if (! isSharedWindow)
  509. {
  510. auto r = shouldBeFullScreen ? Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea
  511. : lastNonFullscreenBounds;
  512. if ((! shouldBeFullScreen) && r.isEmpty())
  513. r = getBounds();
  514. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  515. if (! r.isEmpty())
  516. setBounds (ScalingHelpers::scaledScreenPosToUnscaled (component, r), shouldBeFullScreen);
  517. component.repaint();
  518. }
  519. }
  520. void UIViewComponentPeer::updateScreenBounds()
  521. {
  522. auto& desktop = Desktop::getInstance();
  523. auto oldArea = component.getBounds();
  524. auto oldDesktop = desktop.getDisplays().getPrimaryDisplay()->userArea;
  525. forceDisplayUpdate();
  526. if (fullScreen)
  527. {
  528. fullScreen = false;
  529. setFullScreen (true);
  530. }
  531. else if (! isSharedWindow)
  532. {
  533. // this will re-centre the window, but leave its size unchanged
  534. auto centreRelX = oldArea.getCentreX() / (float) oldDesktop.getWidth();
  535. auto centreRelY = oldArea.getCentreY() / (float) oldDesktop.getHeight();
  536. auto newDesktop = desktop.getDisplays().getPrimaryDisplay()->userArea;
  537. auto x = ((int) (newDesktop.getWidth() * centreRelX)) - (oldArea.getWidth() / 2);
  538. auto y = ((int) (newDesktop.getHeight() * centreRelY)) - (oldArea.getHeight() / 2);
  539. component.setBounds (oldArea.withPosition (x, y));
  540. }
  541. [view setNeedsDisplay];
  542. }
  543. bool UIViewComponentPeer::contains (Point<int> localPos, bool trueIfInAChildWindow) const
  544. {
  545. if (! ScalingHelpers::scaledScreenPosToUnscaled (component, component.getLocalBounds()).contains (localPos))
  546. return false;
  547. UIView* v = [view hitTest: convertToCGPoint (localPos)
  548. withEvent: nil];
  549. if (trueIfInAChildWindow)
  550. return v != nil;
  551. return v == view;
  552. }
  553. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  554. {
  555. if (! isSharedWindow)
  556. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  557. return true;
  558. }
  559. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  560. {
  561. if (isSharedWindow)
  562. [[view superview] bringSubviewToFront: view];
  563. if (makeActiveWindow && window != nil && component.isVisible())
  564. [window makeKeyAndVisible];
  565. }
  566. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  567. {
  568. if (auto* otherPeer = dynamic_cast<UIViewComponentPeer*> (other))
  569. {
  570. if (isSharedWindow)
  571. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  572. }
  573. else
  574. {
  575. jassertfalse; // wrong type of window?
  576. }
  577. }
  578. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  579. {
  580. // to do..
  581. }
  582. //==============================================================================
  583. static float getMaximumTouchForce (UITouch* touch) noexcept
  584. {
  585. if ([touch respondsToSelector: @selector (maximumPossibleForce)])
  586. return (float) touch.maximumPossibleForce;
  587. return 0.0f;
  588. }
  589. static float getTouchForce (UITouch* touch) noexcept
  590. {
  591. if ([touch respondsToSelector: @selector (force)])
  592. return (float) touch.force;
  593. return 0.0f;
  594. }
  595. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  596. {
  597. NSArray* touches = [[event touchesForView: view] allObjects];
  598. for (unsigned int i = 0; i < [touches count]; ++i)
  599. {
  600. UITouch* touch = [touches objectAtIndex: i];
  601. auto maximumForce = getMaximumTouchForce (touch);
  602. if ([touch phase] == UITouchPhaseStationary && maximumForce <= 0)
  603. continue;
  604. CGPoint p = [touch locationInView: view];
  605. Point<float> pos ((float) p.x, (float) p.y);
  606. juce_lastMousePos = pos + getBounds (true).getPosition().toFloat();
  607. auto time = getMouseTime (event);
  608. auto touchIndex = currentTouches.getIndexOfTouch (this, touch);
  609. auto modsToSend = ModifierKeys::currentModifiers;
  610. if (isDown)
  611. {
  612. if ([touch phase] != UITouchPhaseBegan)
  613. continue;
  614. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  615. modsToSend = ModifierKeys::currentModifiers;
  616. // this forces a mouse-enter/up event, in case for some reason we didn't get a mouse-up before.
  617. handleMouseEvent (MouseInputSource::InputSourceType::touch, pos, modsToSend.withoutMouseButtons(),
  618. MouseInputSource::invalidPressure, MouseInputSource::invalidOrientation, time, {}, touchIndex);
  619. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  620. return;
  621. }
  622. else if (isUp)
  623. {
  624. if (! ([touch phase] == UITouchPhaseEnded || [touch phase] == UITouchPhaseCancelled))
  625. continue;
  626. modsToSend = modsToSend.withoutMouseButtons();
  627. currentTouches.clearTouch (touchIndex);
  628. if (! currentTouches.areAnyTouchesActive())
  629. isCancel = true;
  630. }
  631. if (isCancel)
  632. {
  633. currentTouches.clearTouch (touchIndex);
  634. modsToSend = ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons();
  635. }
  636. // NB: some devices return 0 or 1.0 if pressure is unknown, so we'll clip our value to a believable range:
  637. auto pressure = maximumForce > 0 ? jlimit (0.0001f, 0.9999f, getTouchForce (touch) / maximumForce)
  638. : MouseInputSource::invalidPressure;
  639. handleMouseEvent (MouseInputSource::InputSourceType::touch, pos, modsToSend, pressure,
  640. MouseInputSource::invalidOrientation, time, { }, touchIndex);
  641. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  642. return;
  643. if (isUp || isCancel)
  644. {
  645. handleMouseEvent (MouseInputSource::InputSourceType::touch, MouseInputSource::offscreenMousePos, modsToSend,
  646. MouseInputSource::invalidPressure, MouseInputSource::invalidOrientation, time, {}, touchIndex);
  647. if (! isValidPeer (this))
  648. return;
  649. }
  650. }
  651. }
  652. //==============================================================================
  653. static UIViewComponentPeer* currentlyFocusedPeer = nullptr;
  654. void UIViewComponentPeer::viewFocusGain()
  655. {
  656. if (currentlyFocusedPeer != this)
  657. {
  658. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  659. currentlyFocusedPeer->handleFocusLoss();
  660. currentlyFocusedPeer = this;
  661. handleFocusGain();
  662. }
  663. }
  664. void UIViewComponentPeer::viewFocusLoss()
  665. {
  666. if (currentlyFocusedPeer == this)
  667. {
  668. currentlyFocusedPeer = nullptr;
  669. handleFocusLoss();
  670. }
  671. }
  672. bool UIViewComponentPeer::isFocused() const
  673. {
  674. if (isAppex)
  675. return true;
  676. return isSharedWindow ? this == currentlyFocusedPeer
  677. : (window != nil && [window isKeyWindow]);
  678. }
  679. void UIViewComponentPeer::grabFocus()
  680. {
  681. if (window != nil)
  682. {
  683. [window makeKeyWindow];
  684. viewFocusGain();
  685. }
  686. }
  687. void UIViewComponentPeer::textInputRequired (Point<int>, TextInputTarget&)
  688. {
  689. }
  690. static UIKeyboardType getUIKeyboardType (TextInputTarget::VirtualKeyboardType type) noexcept
  691. {
  692. switch (type)
  693. {
  694. case TextInputTarget::textKeyboard: return UIKeyboardTypeAlphabet;
  695. case TextInputTarget::numericKeyboard: return UIKeyboardTypeNumbersAndPunctuation;
  696. case TextInputTarget::decimalKeyboard: return UIKeyboardTypeNumbersAndPunctuation;
  697. case TextInputTarget::urlKeyboard: return UIKeyboardTypeURL;
  698. case TextInputTarget::emailAddressKeyboard: return UIKeyboardTypeEmailAddress;
  699. case TextInputTarget::phoneNumberKeyboard: return UIKeyboardTypePhonePad;
  700. default: jassertfalse; break;
  701. }
  702. return UIKeyboardTypeDefault;
  703. }
  704. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  705. {
  706. view->hiddenTextView.keyboardType = getUIKeyboardType (target->getKeyboardType());
  707. view->hiddenTextView.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  708. view->hiddenTextView.selectedRange = NSMakeRange ((NSUInteger) target->getHighlightedRegion().getStart(), 0);
  709. }
  710. BOOL UIViewComponentPeer::textViewReplaceCharacters (Range<int> range, const String& text)
  711. {
  712. if (auto* target = findCurrentTextInputTarget())
  713. {
  714. auto currentSelection = target->getHighlightedRegion();
  715. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  716. if (currentSelection.isEmpty())
  717. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  718. if (text == "\r" || text == "\n" || text == "\r\n")
  719. handleKeyPress (KeyPress::returnKey, text[0]);
  720. else
  721. target->insertTextAtCaret (text);
  722. updateHiddenTextContent (target);
  723. }
  724. return NO;
  725. }
  726. void UIViewComponentPeer::globalFocusChanged (Component*)
  727. {
  728. if (auto* target = findCurrentTextInputTarget())
  729. {
  730. if (auto* comp = dynamic_cast<Component*> (target))
  731. {
  732. auto pos = component.getLocalPoint (comp, Point<int>());
  733. view->hiddenTextView.frame = CGRectMake (pos.x, pos.y, 0, 0);
  734. updateHiddenTextContent (target);
  735. [view->hiddenTextView becomeFirstResponder];
  736. }
  737. }
  738. else
  739. {
  740. [view->hiddenTextView resignFirstResponder];
  741. }
  742. }
  743. //==============================================================================
  744. void UIViewComponentPeer::drawRect (CGRect r)
  745. {
  746. if (r.size.width < 1.0f || r.size.height < 1.0f)
  747. return;
  748. CGContextRef cg = UIGraphicsGetCurrentContext();
  749. if (! component.isOpaque())
  750. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  751. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, getComponent().getHeight()));
  752. CoreGraphicsContext g (cg, getComponent().getHeight());
  753. insideDrawRect = true;
  754. handlePaint (g);
  755. insideDrawRect = false;
  756. }
  757. bool UIViewComponentPeer::canBecomeKeyWindow()
  758. {
  759. return (getStyleFlags() & juce::ComponentPeer::windowIgnoresKeyPresses) == 0;
  760. }
  761. //==============================================================================
  762. void Desktop::setKioskComponent (Component* kioskModeComp, bool enableOrDisable, bool /*allowMenusAndBars*/)
  763. {
  764. displays->refresh();
  765. if (auto* peer = kioskModeComp->getPeer())
  766. {
  767. if (auto* uiViewPeer = dynamic_cast<UIViewComponentPeer*> (peer))
  768. [uiViewPeer->controller setNeedsStatusBarAppearanceUpdate];
  769. peer->setFullScreen (enableOrDisable);
  770. }
  771. }
  772. void Desktop::allowedOrientationsChanged()
  773. {
  774. // if the current orientation isn't allowed anymore then switch orientations
  775. if (! isOrientationEnabled (getCurrentOrientation()))
  776. {
  777. auto newOrientation = [this]
  778. {
  779. for (auto orientation : { upright, upsideDown, rotatedClockwise, rotatedAntiClockwise })
  780. if (isOrientationEnabled (orientation))
  781. return orientation;
  782. // you need to support at least one orientation
  783. jassertfalse;
  784. return upright;
  785. }();
  786. NSNumber* value = [NSNumber numberWithInt: (int) Orientations::convertFromJuce (newOrientation)];
  787. [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
  788. [value release];
  789. }
  790. }
  791. //==============================================================================
  792. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  793. {
  794. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  795. (new AsyncRepaintMessage (this, area))->post();
  796. else
  797. [view setNeedsDisplayInRect: convertToCGRect (area)];
  798. }
  799. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  800. {
  801. }
  802. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  803. {
  804. return new UIViewComponentPeer (*this, styleFlags, (UIView*) windowToAttachTo);
  805. }
  806. //==============================================================================
  807. const int KeyPress::spaceKey = ' ';
  808. const int KeyPress::returnKey = 0x0d;
  809. const int KeyPress::escapeKey = 0x1b;
  810. const int KeyPress::backspaceKey = 0x7f;
  811. const int KeyPress::leftKey = 0x1000;
  812. const int KeyPress::rightKey = 0x1001;
  813. const int KeyPress::upKey = 0x1002;
  814. const int KeyPress::downKey = 0x1003;
  815. const int KeyPress::pageUpKey = 0x1004;
  816. const int KeyPress::pageDownKey = 0x1005;
  817. const int KeyPress::endKey = 0x1006;
  818. const int KeyPress::homeKey = 0x1007;
  819. const int KeyPress::deleteKey = 0x1008;
  820. const int KeyPress::insertKey = -1;
  821. const int KeyPress::tabKey = 9;
  822. const int KeyPress::F1Key = 0x2001;
  823. const int KeyPress::F2Key = 0x2002;
  824. const int KeyPress::F3Key = 0x2003;
  825. const int KeyPress::F4Key = 0x2004;
  826. const int KeyPress::F5Key = 0x2005;
  827. const int KeyPress::F6Key = 0x2006;
  828. const int KeyPress::F7Key = 0x2007;
  829. const int KeyPress::F8Key = 0x2008;
  830. const int KeyPress::F9Key = 0x2009;
  831. const int KeyPress::F10Key = 0x200a;
  832. const int KeyPress::F11Key = 0x200b;
  833. const int KeyPress::F12Key = 0x200c;
  834. const int KeyPress::F13Key = 0x200d;
  835. const int KeyPress::F14Key = 0x200e;
  836. const int KeyPress::F15Key = 0x200f;
  837. const int KeyPress::F16Key = 0x2010;
  838. const int KeyPress::F17Key = 0x2011;
  839. const int KeyPress::F18Key = 0x2012;
  840. const int KeyPress::F19Key = 0x2013;
  841. const int KeyPress::F20Key = 0x2014;
  842. const int KeyPress::F21Key = 0x2015;
  843. const int KeyPress::F22Key = 0x2016;
  844. const int KeyPress::F23Key = 0x2017;
  845. const int KeyPress::F24Key = 0x2018;
  846. const int KeyPress::F25Key = 0x2019;
  847. const int KeyPress::F26Key = 0x201a;
  848. const int KeyPress::F27Key = 0x201b;
  849. const int KeyPress::F28Key = 0x201c;
  850. const int KeyPress::F29Key = 0x201d;
  851. const int KeyPress::F30Key = 0x201e;
  852. const int KeyPress::F31Key = 0x201f;
  853. const int KeyPress::F32Key = 0x2020;
  854. const int KeyPress::F33Key = 0x2021;
  855. const int KeyPress::F34Key = 0x2022;
  856. const int KeyPress::F35Key = 0x2023;
  857. const int KeyPress::numberPad0 = 0x30020;
  858. const int KeyPress::numberPad1 = 0x30021;
  859. const int KeyPress::numberPad2 = 0x30022;
  860. const int KeyPress::numberPad3 = 0x30023;
  861. const int KeyPress::numberPad4 = 0x30024;
  862. const int KeyPress::numberPad5 = 0x30025;
  863. const int KeyPress::numberPad6 = 0x30026;
  864. const int KeyPress::numberPad7 = 0x30027;
  865. const int KeyPress::numberPad8 = 0x30028;
  866. const int KeyPress::numberPad9 = 0x30029;
  867. const int KeyPress::numberPadAdd = 0x3002a;
  868. const int KeyPress::numberPadSubtract = 0x3002b;
  869. const int KeyPress::numberPadMultiply = 0x3002c;
  870. const int KeyPress::numberPadDivide = 0x3002d;
  871. const int KeyPress::numberPadSeparator = 0x3002e;
  872. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  873. const int KeyPress::numberPadEquals = 0x30030;
  874. const int KeyPress::numberPadDelete = 0x30031;
  875. const int KeyPress::playKey = 0x30000;
  876. const int KeyPress::stopKey = 0x30001;
  877. const int KeyPress::fastForwardKey = 0x30002;
  878. const int KeyPress::rewindKey = 0x30003;
  879. } // namespace juce