juce_ios_UIViewComponentPeer.mm 40 KB

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