Flutter iOS Embedder
FlutterPlatformPlugin.mm
Go to the documentation of this file.
1 // Copyright 2013 The Flutter Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
6 
7 #import <AudioToolbox/AudioToolbox.h>
8 #import <Foundation/Foundation.h>
9 #import <UIKit/UIApplication.h>
10 #import <UIKit/UIKit.h>
11 
12 #include "flutter/fml/logging.h"
13 #import "flutter/shell/platform/darwin/common/InternalFlutterSwiftCommon/InternalFlutterSwiftCommon.h"
19 
21 
22 namespace {
23 
24 constexpr char kTextPlainFormat[] = "text/plain";
25 // Some of the official iOS system sounds. A full list can be found in many places online, such as:
26 // https://github.com/p-x9/swift-system-sound/blob/cb4327b223d55d01e9156539c8442db16f4b1f85/SystemSoundTable.md
27 const UInt32 kKeyPressClickSoundId = 1306;
28 const UInt32 kWheelsOfTimeSoundId = 1157;
29 
30 NSString* const kSearchURLPrefix = @"x-web-search://?";
31 
32 } // namespace
33 
34 namespace flutter {
35 
36 // TODO(abarth): Move these definitions from system_chrome_impl.cc to here.
38  "io.flutter.plugin.platform.SystemChromeOrientationNotificationName";
40  "io.flutter.plugin.platform.SystemChromeOrientationNotificationKey";
42  "io.flutter.plugin.platform.SystemChromeOverlayNotificationName";
44  "io.flutter.plugin.platform.SystemChromeOverlayNotificationKey";
45 
46 } // namespace flutter
47 
48 using namespace flutter;
49 
50 static void SetStatusBarHiddenForSharedApplication(BOOL hidden) {
51  UIApplication* flutterApplication = FlutterSharedApplication.application;
52  if (flutterApplication) {
53  flutterApplication.statusBarHidden = hidden;
54  } else {
55  [FlutterLogger logWarning:@"Application based status bar styling is not available in app "
56  "extension."];
57  }
58 }
59 
60 static void SetStatusBarStyleForSharedApplication(UIStatusBarStyle style) {
61  UIApplication* flutterApplication = FlutterSharedApplication.application;
62  if (flutterApplication) {
63  // Note: -[UIApplication setStatusBarStyle] is deprecated in iOS9
64  // in favor of delegating to the view controller.
65  [flutterApplication setStatusBarStyle:style];
66  } else {
67  [FlutterLogger logWarning:@"Application based status bar styling is not available in app "
68  "extension."];
69  }
70 }
71 
72 @interface FlutterPlatformPlugin ()
73 
74 /**
75  * @brief Whether the status bar appearance is based on the style preferred for this ViewController.
76  *
77  * The default value is YES.
78  * Explicitly add `UIViewControllerBasedStatusBarAppearance` as `false` in
79  * info.plist makes this value to be false.
80  */
81 @property(nonatomic, assign) BOOL enableViewControllerBasedStatusBarAppearance;
82 @property(nonatomic, weak) FlutterEngine* engine;
83 
84 /**
85  * @brief Used to detect whether or not this device supports live text input from the camera.
86  */
87 @property(nonatomic, strong) UITextField* textField;
88 @end
89 
90 @implementation FlutterPlatformPlugin
91 
92 - (instancetype)initWithEngine:(FlutterEngine*)engine {
93  FML_DCHECK(engine) << "engine must be set";
94  self = [super init];
95 
96  if (self) {
97  _engine = engine;
98  NSObject* infoValue = [[NSBundle mainBundle]
99  objectForInfoDictionaryKey:@"UIViewControllerBasedStatusBarAppearance"];
100 #if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG
101  if (infoValue != nil && ![infoValue isKindOfClass:[NSNumber class]]) {
102  [FlutterLogger logError:@"The value of UIViewControllerBasedStatusBarAppearance in "
103  "Info.plist must be a Boolean type."];
104  }
105 #endif
106  _enableViewControllerBasedStatusBarAppearance =
107  (infoValue == nil || [(NSNumber*)infoValue boolValue]);
108  }
109 
110  return self;
111 }
112 
113 - (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
114  NSString* method = call.method;
115  id args = call.arguments;
116  if ([method isEqualToString:@"SystemSound.play"]) {
117  [self playSystemSound:args];
118  result(nil);
119  } else if ([method isEqualToString:@"HapticFeedback.vibrate"]) {
120  [self vibrateHapticFeedback:args];
121  result(nil);
122  } else if ([method isEqualToString:@"SystemChrome.setPreferredOrientations"]) {
123  [self setSystemChromePreferredOrientations:args];
124  result(nil);
125  } else if ([method isEqualToString:@"SystemChrome.setApplicationSwitcherDescription"]) {
126  [self setSystemChromeApplicationSwitcherDescription:args];
127  result(nil);
128  } else if ([method isEqualToString:@"SystemChrome.setEnabledSystemUIOverlays"]) {
129  [self setSystemChromeEnabledSystemUIOverlays:args];
130  result(nil);
131  } else if ([method isEqualToString:@"SystemChrome.setEnabledSystemUIMode"]) {
132  [self setSystemChromeEnabledSystemUIMode:args];
133  result(nil);
134  } else if ([method isEqualToString:@"SystemChrome.restoreSystemUIOverlays"]) {
135  [self restoreSystemChromeSystemUIOverlays];
136  result(nil);
137  } else if ([method isEqualToString:@"SystemChrome.setSystemUIOverlayStyle"]) {
138  [self setSystemChromeSystemUIOverlayStyle:args];
139  result(nil);
140  } else if ([method isEqualToString:@"SystemNavigator.pop"]) {
141  NSNumber* isAnimated = args;
142  [self popSystemNavigator:isAnimated.boolValue];
143  result(nil);
144  } else if ([method isEqualToString:@"Clipboard.getData"]) {
145  result([self getClipboardData:args]);
146  } else if ([method isEqualToString:@"Clipboard.setData"]) {
147  [self setClipboardData:args];
148  result(nil);
149  } else if ([method isEqualToString:@"Clipboard.hasStrings"]) {
150  result([self clipboardHasStrings]);
151  } else if ([method isEqualToString:@"LiveText.isLiveTextInputAvailable"]) {
152  result(@([self isLiveTextInputAvailable]));
153  } else if ([method isEqualToString:@"SearchWeb.invoke"]) {
154  [self searchWeb:args];
155  result(nil);
156  } else if ([method isEqualToString:@"LookUp.invoke"]) {
157  [self showLookUpViewController:args];
158  result(nil);
159  } else if ([method isEqualToString:@"Translate.invoke"]) {
160  if (@available(iOS 17.4, *)) {
161  [self showTranslateViewControllerForTerm:args];
162  result(nil);
163  } else {
165  }
166  } else if ([method isEqualToString:@"Share.invoke"]) {
167  [self showShareViewController:args];
168  result(nil);
169  } else if ([method isEqualToString:@"ContextMenu.showSystemContextMenu"]) {
170  [self showSystemContextMenu:args];
171  result(nil);
172  } else if ([method isEqualToString:@"ContextMenu.hideSystemContextMenu"]) {
173  [self hideSystemContextMenu];
174  result(nil);
175  } else {
177  }
178 }
179 
180 - (void)showSystemContextMenu:(NSDictionary*)args {
181  if (@available(iOS 16.0, *)) {
182  FlutterTextInputPlugin* textInputPlugin = [self.engine textInputPlugin];
183  BOOL shownEditMenu = [textInputPlugin showEditMenu:args];
184  if (!shownEditMenu) {
185  [FlutterLogger logError:@"Only text input supports system context menu for now. Ensure the "
186  "system context menu is shown with an active text input connection. "
187  "See https://github.com/flutter/flutter/issues/143033."];
188  }
189  }
190 }
191 
192 - (void)hideSystemContextMenu {
193  if (@available(iOS 16.0, *)) {
194  FlutterTextInputPlugin* textInputPlugin = [self.engine textInputPlugin];
195  [textInputPlugin hideEditMenu];
196  }
197 }
198 
199 - (void)showShareViewController:(NSString*)content {
200  UIViewController* engineViewController = [self.engine viewController];
201 
202  NSArray* itemsToShare = @[ content ?: [NSNull null] ];
203  UIActivityViewController* activityViewController =
204  [[UIActivityViewController alloc] initWithActivityItems:itemsToShare
205  applicationActivities:nil];
206 
207  if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
208  // On iPad, the share screen is presented in a popover view, and requires a
209  // sourceView and sourceRect
210  FlutterTextInputPlugin* _textInputPlugin = [self.engine textInputPlugin];
211  UITextRange* range = _textInputPlugin.textInputView.selectedTextRange;
212 
213  // firstRectForRange cannot be used here as its current implementation does
214  // not always return the full rect of the range.
215  CGRect firstRect = [(FlutterTextInputView*)_textInputPlugin.textInputView
216  caretRectForPosition:(FlutterTextPosition*)range.start];
217  CGRect transformedFirstRect = [(FlutterTextInputView*)_textInputPlugin.textInputView
218  localRectFromFrameworkTransform:firstRect];
219  CGRect lastRect = [(FlutterTextInputView*)_textInputPlugin.textInputView
220  caretRectForPosition:(FlutterTextPosition*)range.end];
221  CGRect transformedLastRect = [(FlutterTextInputView*)_textInputPlugin.textInputView
222  localRectFromFrameworkTransform:lastRect];
223 
224  activityViewController.popoverPresentationController.sourceView = engineViewController.view;
225  // In case of RTL Language, get the minimum x coordinate
226  activityViewController.popoverPresentationController.sourceRect =
227  CGRectMake(fmin(transformedFirstRect.origin.x, transformedLastRect.origin.x),
228  transformedFirstRect.origin.y,
229  abs(transformedLastRect.origin.x - transformedFirstRect.origin.x),
230  transformedFirstRect.size.height);
231  }
232 
233  [engineViewController presentViewController:activityViewController animated:YES completion:nil];
234 }
235 
236 - (void)searchWeb:(NSString*)searchTerm {
237  UIApplication* flutterApplication = FlutterSharedApplication.application;
238  if (flutterApplication == nil) {
239  [FlutterLogger logWarning:@"SearchWeb.invoke is not availabe in app extension."];
240  return;
241  }
242 
243  NSString* escapedText = [searchTerm
244  stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet
245  URLHostAllowedCharacterSet]];
246  NSString* searchURL = [NSString stringWithFormat:@"%@%@", kSearchURLPrefix, escapedText];
247 
248  [flutterApplication openURL:[NSURL URLWithString:searchURL] options:@{} completionHandler:nil];
249 }
250 
251 - (void)playSystemSound:(NSString*)soundType {
252  if ([soundType isEqualToString:@"SystemSoundType.click"]) {
253  // All feedback types are specific to Android and are treated as equal on
254  // iOS.
255  AudioServicesPlaySystemSound(kKeyPressClickSoundId);
256  } else if ([soundType isEqualToString:@"SystemSoundType.tick"]) {
257  AudioServicesPlaySystemSound(kWheelsOfTimeSoundId);
258  }
259 }
260 
261 - (void)vibrateHapticFeedback:(NSString*)feedbackType {
262  if (!feedbackType) {
263  AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
264  return;
265  }
266 
267  if ([@"HapticFeedbackType.lightImpact" isEqualToString:feedbackType]) {
268  [[[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleLight] impactOccurred];
269  } else if ([@"HapticFeedbackType.mediumImpact" isEqualToString:feedbackType]) {
270  [[[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleMedium] impactOccurred];
271  } else if ([@"HapticFeedbackType.heavyImpact" isEqualToString:feedbackType]) {
272  [[[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleHeavy] impactOccurred];
273  } else if ([@"HapticFeedbackType.selectionClick" isEqualToString:feedbackType]) {
274  [[[UISelectionFeedbackGenerator alloc] init] selectionChanged];
275  } else if ([@"HapticFeedbackType.successNotification" isEqualToString:feedbackType]) {
276  [[[UINotificationFeedbackGenerator alloc] init]
277  notificationOccurred:UINotificationFeedbackTypeSuccess];
278  } else if ([@"HapticFeedbackType.warningNotification" isEqualToString:feedbackType]) {
279  [[[UINotificationFeedbackGenerator alloc] init]
280  notificationOccurred:UINotificationFeedbackTypeWarning];
281  } else if ([@"HapticFeedbackType.errorNotification" isEqualToString:feedbackType]) {
282  [[[UINotificationFeedbackGenerator alloc] init]
283  notificationOccurred:UINotificationFeedbackTypeError];
284  }
285 }
286 
287 - (void)setSystemChromePreferredOrientations:(NSArray*)orientations {
288  UIInterfaceOrientationMask mask = 0;
289 
290  if (orientations.count == 0) {
291  mask |= UIInterfaceOrientationMaskAll;
292  } else {
293  for (NSString* orientation in orientations) {
294  if ([orientation isEqualToString:@"DeviceOrientation.portraitUp"]) {
295  mask |= UIInterfaceOrientationMaskPortrait;
296  } else if ([orientation isEqualToString:@"DeviceOrientation.portraitDown"]) {
297  mask |= UIInterfaceOrientationMaskPortraitUpsideDown;
298  } else if ([orientation isEqualToString:@"DeviceOrientation.landscapeLeft"]) {
299  mask |= UIInterfaceOrientationMaskLandscapeLeft;
300  } else if ([orientation isEqualToString:@"DeviceOrientation.landscapeRight"]) {
301  mask |= UIInterfaceOrientationMaskLandscapeRight;
302  }
303  }
304  }
305 
306  if (!mask) {
307  return;
308  }
309  [[NSNotificationCenter defaultCenter]
310  postNotificationName:@(kOrientationUpdateNotificationName)
311  object:nil
312  userInfo:@{@(kOrientationUpdateNotificationKey) : @(mask)}];
313 }
314 
315 - (void)setSystemChromeApplicationSwitcherDescription:(NSDictionary*)object {
316  // No counterpart on iOS but is a benign operation. So no asserts.
317 }
318 
319 - (void)setSystemChromeEnabledSystemUIOverlays:(NSArray*)overlays {
320  BOOL statusBarShouldBeHidden = ![overlays containsObject:@"SystemUiOverlay.top"];
321  if ([overlays containsObject:@"SystemUiOverlay.bottom"]) {
322  [[NSNotificationCenter defaultCenter]
323  postNotificationName:FlutterViewControllerShowHomeIndicator
324  object:nil];
325  } else {
326  [[NSNotificationCenter defaultCenter]
327  postNotificationName:FlutterViewControllerHideHomeIndicator
328  object:nil];
329  }
330  if (self.enableViewControllerBasedStatusBarAppearance) {
331  [self.engine viewController].prefersStatusBarHidden = statusBarShouldBeHidden;
332  } else {
333  // Checks if the top status bar should be visible. This platform ignores all
334  // other overlays
335 
336  // We opt out of view controller based status bar visibility since we want
337  // to be able to modify this on the fly. The key used is
338  // UIViewControllerBasedStatusBarAppearance.
339  SetStatusBarHiddenForSharedApplication(statusBarShouldBeHidden);
340  }
341 }
342 
343 - (void)setSystemChromeEnabledSystemUIMode:(NSString*)mode {
344  BOOL edgeToEdge = [mode isEqualToString:@"SystemUiMode.edgeToEdge"];
345  if (self.enableViewControllerBasedStatusBarAppearance) {
346  [self.engine viewController].prefersStatusBarHidden = !edgeToEdge;
347  } else {
348  // Checks if the top status bar should be visible, reflected by edge to edge setting. This
349  // platform ignores all other system ui modes.
350 
351  // We opt out of view controller based status bar visibility since we want
352  // to be able to modify this on the fly. The key used is
353  // UIViewControllerBasedStatusBarAppearance.
355  }
356  [[NSNotificationCenter defaultCenter]
357  postNotificationName:edgeToEdge ? FlutterViewControllerShowHomeIndicator
358  : FlutterViewControllerHideHomeIndicator
359  object:nil];
360 }
361 
362 - (void)restoreSystemChromeSystemUIOverlays {
363  // Nothing to do on iOS.
364 }
365 
366 - (void)setSystemChromeSystemUIOverlayStyle:(NSDictionary*)message {
367  NSString* brightness = message[@"statusBarBrightness"];
368  if (brightness == (id)[NSNull null]) {
369  return;
370  }
371 
372  UIStatusBarStyle statusBarStyle;
373  if ([brightness isEqualToString:@"Brightness.dark"]) {
374  statusBarStyle = UIStatusBarStyleLightContent;
375  } else if ([brightness isEqualToString:@"Brightness.light"]) {
376  statusBarStyle = UIStatusBarStyleDarkContent;
377  } else {
378  return;
379  }
380 
381  if (self.enableViewControllerBasedStatusBarAppearance) {
382  // This notification is respected by the iOS embedder.
383  [[NSNotificationCenter defaultCenter]
384  postNotificationName:@(kOverlayStyleUpdateNotificationName)
385  object:nil
386  userInfo:@{@(kOverlayStyleUpdateNotificationKey) : @(statusBarStyle)}];
387  } else {
389  }
390 }
391 
392 - (void)popSystemNavigator:(BOOL)isAnimated {
393  // Apple's human user guidelines say not to terminate iOS applications. However, if the
394  // root view of the app is a navigation controller, it is instructed to back up a level
395  // in the navigation hierarchy.
396  // It's also possible in an Add2App scenario that the FlutterViewController was presented
397  // outside the context of a UINavigationController, and still wants to be popped.
398 
399  FlutterViewController* engineViewController = [self.engine viewController];
400  UINavigationController* navigationController = [engineViewController navigationController];
401  if (navigationController) {
402  [navigationController popViewControllerAnimated:isAnimated];
403  } else {
404  UIViewController* rootViewController = nil;
405  UIApplication* flutterApplication = FlutterSharedApplication.application;
406  if (flutterApplication) {
407  rootViewController = flutterApplication.keyWindow.rootViewController;
408  } else {
409  rootViewController =
410  [engineViewController flutterWindowSceneIfViewLoaded].keyWindow.rootViewController;
411  }
412 
413  if (engineViewController != rootViewController) {
414  [engineViewController dismissViewControllerAnimated:isAnimated completion:nil];
415  }
416  }
417 }
418 
419 - (NSDictionary*)getClipboardData:(NSString*)format {
420  UIPasteboard* pasteboard = [UIPasteboard generalPasteboard];
421  if (!format || [format isEqualToString:@(kTextPlainFormat)]) {
422  NSString* stringInPasteboard = pasteboard.string;
423  // The pasteboard may contain an item but it may not be a string (an image for instance).
424  return stringInPasteboard == nil ? nil : @{@"text" : stringInPasteboard};
425  }
426  return nil;
427 }
428 
429 - (void)setClipboardData:(NSDictionary*)data {
430  UIPasteboard* pasteboard = [UIPasteboard generalPasteboard];
431  id copyText = data[@"text"];
432  if ([copyText isKindOfClass:[NSString class]]) {
433  pasteboard.string = copyText;
434  } else {
435  pasteboard.string = @"null";
436  }
437 }
438 
439 - (NSDictionary*)clipboardHasStrings {
440  return @{@"value" : @([UIPasteboard generalPasteboard].hasStrings)};
441 }
442 
443 - (BOOL)isLiveTextInputAvailable {
444  return [[self textField] canPerformAction:@selector(captureTextFromCamera:) withSender:nil];
445 }
446 
447 - (void)showLookUpViewController:(NSString*)term {
448  UIViewController* engineViewController = [self.engine viewController];
449  UIReferenceLibraryViewController* referenceLibraryViewController =
450  [[UIReferenceLibraryViewController alloc] initWithTerm:term];
451  [engineViewController presentViewController:referenceLibraryViewController
452  animated:YES
453  completion:nil];
454 }
455 
456 - (CGRect)popoverSourceRectForCurrentSelection {
457  FlutterTextInputPlugin* textInputPlugin = [self.engine textInputPlugin];
458  UITextRange* range = textInputPlugin.textInputView.selectedTextRange;
460 
461  // firstRectForRange cannot be used here as its current implementation does
462  // not always return the full rect of the range.
463  CGRect firstRect = [textInputView caretRectForPosition:range.start];
464  CGRect transformedFirstRect = [textInputView localRectFromFrameworkTransform:firstRect];
465  CGRect lastRect = [textInputView caretRectForPosition:range.end];
466  CGRect transformedLastRect = [textInputView localRectFromFrameworkTransform:lastRect];
467 
468  // In case of RTL Language, get the minimum x coordinate too
469  return CGRectMake(fmin(transformedFirstRect.origin.x, transformedLastRect.origin.x),
470  transformedFirstRect.origin.y,
471  fabs(transformedLastRect.origin.x - transformedFirstRect.origin.x),
472  transformedFirstRect.size.height);
473 }
474 
475 - (void)showTranslateViewControllerForTerm:(NSString*)term {
476  if (@available(iOS 17.4, *)) {
477  if (term.length == 0) {
478  return;
479  }
480  UIViewController* flutterViewController = [self.engine viewController];
481  if (!flutterViewController) {
482  return;
483  }
484  FlutterTranslateViewController* translateViewController;
485 
486  if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
487  // On iPad, the translate screen is presented in a popover view, and requires a rect to use as
488  // source rect
489  CGRect popoverSourceRect = [self popoverSourceRectForCurrentSelection];
490  translateViewController =
491  [[FlutterTranslateViewController alloc] initWithTerm:term
492  popoverSourceRect:popoverSourceRect];
493  } else {
494  translateViewController = [[FlutterTranslateViewController alloc] initWithTerm:term];
495  }
496 
497  translateViewController.view.frame = flutterViewController.view.bounds;
498  [flutterViewController addChildViewController:translateViewController];
499  [flutterViewController.view addSubview:translateViewController.view];
500  [translateViewController didMoveToParentViewController:flutterViewController];
501  }
502 }
503 
504 - (UITextField*)textField {
505  if (_textField == nil) {
506  _textField = [[UITextField alloc] init];
507  }
508  return _textField;
509 }
510 
511 @end
void(^ FlutterResult)(id _Nullable result)
FLUTTER_DARWIN_EXPORT NSObject const * FlutterMethodNotImplemented
static void SetStatusBarStyleForSharedApplication(UIStatusBarStyle style)
static void SetStatusBarHiddenForSharedApplication(BOOL hidden)
CGRect localRectFromFrameworkTransform
CGRect caretRectForPosition
FlutterTextInputPlugin * textInputPlugin
UIView< UITextInput > * textInputView()
BOOL showEditMenu:(ios(16.0) API_AVAILABLE)
constexpr char kTextPlainFormat[]
const UInt32 kKeyPressClickSoundId
NSString *const kSearchURLPrefix
const UInt32 kWheelsOfTimeSoundId
const char *const kOrientationUpdateNotificationKey
const char *const kOverlayStyleUpdateNotificationName
const char *const kOverlayStyleUpdateNotificationKey
const char *const kOrientationUpdateNotificationName