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.

1031 lines
34KB

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