Audio plugin host https://kx.studio/carla
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.

juce_ios_UIViewComponentPeer.mm 41KB

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