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