FlutterViewController.mm 18.2 KB
Newer Older
1
// Copyright 2016 The Chromium Authors. All rights reserved.
C
Chinmay Garde 已提交
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h"
C
Chinmay Garde 已提交
6

A
Adam Barth 已提交
7 8
#include <memory>

9 10 11
#include "base/mac/scoped_block.h"
#include "base/mac/scoped_nsobject.h"
#include "base/strings/sys_string_conversions.h"
A
Adam Barth 已提交
12
#include "flutter/common/threads.h"
13 14 15
#include "flutter/shell/gpu/gpu_rasterizer.h"
#include "flutter/shell/gpu/gpu_surface_gl.h"
#include "flutter/shell/platform/darwin/common/platform_mac.h"
16
#include "flutter/shell/platform/darwin/common/string_conversions.h"
A
Adam Barth 已提交
17
#include "flutter/shell/platform/darwin/ios/framework/Source/flutter_touch_mapper.h"
18
#include "flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h"
19
#include "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformPlugin.h"
20 21
#include "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputDelegate.h"
#include "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h"
22
#include "flutter/shell/platform/darwin/ios/platform_view_ios.h"
A
Adam Barth 已提交
23
#include "lib/ftl/functional/make_copyable.h"
24
#include "lib/ftl/time/time_delta.h"
25

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
namespace {

typedef void (^PlatformMessageResponseCallback)(NSString*);

class PlatformMessageResponseDarwin : public blink::PlatformMessageResponse {
  FRIEND_MAKE_REF_COUNTED(PlatformMessageResponseDarwin);

 public:
  void Complete(std::vector<uint8_t> data) override {
    ftl::RefPtr<PlatformMessageResponseDarwin> self(this);
    blink::Threads::Platform()->PostTask(
        ftl::MakeCopyable([ self, data = std::move(data) ]() mutable {
          self->callback_.get()(shell::GetNSStringFromVector(data));
        }));
  }

  void CompleteWithError() override { Complete(std::vector<uint8_t>()); }

 private:
45 46
  explicit PlatformMessageResponseDarwin(
      PlatformMessageResponseCallback callback)
47 48 49 50 51 52 53
      : callback_(callback, base::scoped_policy::RETAIN) {}

  base::mac::ScopedBlock<PlatformMessageResponseCallback> callback_;
};

}  // namespace

54 55
@interface FlutterViewController ()<UIAlertViewDelegate,
                                    FlutterTextInputDelegate>
56 57
@end

58 59 60
void FlutterInit(int argc, const char* argv[]) {
  NSBundle* bundle = [NSBundle bundleForClass:[FlutterViewController class]];
  NSString* icuDataPath = [bundle pathForResource:@"icudtl" ofType:@"dat"];
61
  shell::PlatformMacMain(argc, argv, icuDataPath.UTF8String);
62 63
}

64
@implementation FlutterViewController {
65
  base::scoped_nsprotocol<FlutterDartProject*> _dartProject;
66
  UIInterfaceOrientationMask _orientationPreferences;
67
  UIStatusBarStyle _statusBarStyle;
68
  blink::ViewportMetrics _viewportMetrics;
69 70
  shell::TouchMapper _touchMapper;
  std::unique_ptr<shell::PlatformViewIOS> _platformView;
71
  base::scoped_nsprotocol<FlutterPlatformPlugin*> _platformPlugin;
72
  base::scoped_nsprotocol<FlutterTextInputPlugin*> _textInputPlugin;
73

74
  BOOL _initialized;
75 76
}

77 78
#pragma mark - Manage and override all designated initializers

79 80 81 82
- (instancetype)initWithProject:(FlutterDartProject*)project
                        nibName:(NSString*)nibNameOrNil
                         bundle:(NSBundle*)nibBundleOrNil {
  self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
83

84
  if (self) {
85
    if (project == nil)
86 87
      _dartProject.reset(
          [[FlutterDartProject alloc] initFromDefaultSourceForConfiguration]);
88 89
    else
      _dartProject.reset([project retain]);
90 91

    [self performCommonViewControllerInitialization];
92
  }
93

94
  return self;
C
Chinmay Garde 已提交
95 96
}

97 98
- (instancetype)initWithNibName:(NSString*)nibNameOrNil
                         bundle:(NSBundle*)nibBundleOrNil {
99
  return [self initWithProject:nil nibName:nil bundle:nil];
C
Chinmay Garde 已提交
100 101
}

102
- (instancetype)initWithCoder:(NSCoder*)aDecoder {
103
  return [self initWithProject:nil nibName:nil bundle:nil];
104 105
}

106
#pragma mark - Common view controller initialization tasks
C
Chinmay Garde 已提交
107

108
- (void)performCommonViewControllerInitialization {
109
  if (_initialized)
110 111
    return;
  _initialized = YES;
C
Chinmay Garde 已提交
112

113
  _orientationPreferences = UIInterfaceOrientationMaskAll;
114
  _statusBarStyle = UIStatusBarStyleDefault;
A
Adam Barth 已提交
115
  _platformView = std::make_unique<shell::PlatformViewIOS>(
116 117
      reinterpret_cast<CAEAGLLayer*>(self.view.layer));
  _platformView->SetupResourceContextOnIOThread();
C
Chinmay Garde 已提交
118

119 120 121
  _platformPlugin.reset([[FlutterPlatformPlugin alloc] init]);
  [self addMessageListener:_platformPlugin.get()];

122 123 124 125
  _textInputPlugin.reset([[FlutterTextInputPlugin alloc] init]);
  _textInputPlugin.get().textInputDelegate = self;
  [self addMessageListener:_textInputPlugin.get()];

126
  [self setupNotificationCenterObservers];
C
Chinmay Garde 已提交
127

128
  [self connectToEngineAndLoad];
C
Chinmay Garde 已提交
129 130
}

131 132 133 134
- (void)setupNotificationCenterObservers {
  NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  [center addObserver:self
             selector:@selector(onOrientationPreferencesUpdated:)
A
Adam Barth 已提交
135
                 name:@(shell::kOrientationUpdateNotificationName)
136 137
               object:nil];

138 139
  [center addObserver:self
             selector:@selector(onPreferredStatusBarStyleUpdated:)
A
Adam Barth 已提交
140
                 name:@(shell::kOverlayStyleUpdateNotificationName)
141 142
               object:nil];

143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
  [center addObserver:self
             selector:@selector(applicationBecameActive:)
                 name:UIApplicationDidBecomeActiveNotification
               object:nil];

  [center addObserver:self
             selector:@selector(applicationWillResignActive:)
                 name:UIApplicationWillResignActiveNotification
               object:nil];

  [center addObserver:self
             selector:@selector(keyboardWasShown:)
                 name:UIKeyboardDidShowNotification
               object:nil];

  [center addObserver:self
             selector:@selector(keyboardWillBeHidden:)
                 name:UIKeyboardWillHideNotification
               object:nil];

  [center addObserver:self
             selector:@selector(onLocaleUpdated:)
                 name:NSCurrentLocaleDidChangeNotification
               object:nil];
167 168 169 170 171

  [center addObserver:self
             selector:@selector(onVoiceOverChanged:)
                 name:UIAccessibilityVoiceOverStatusChanged
               object:nil];
C
Chinmay Garde 已提交
172 173
}

174
#pragma mark - Initializing the engine
175

176
- (void)alertView:(UIAlertView*)alertView
177
    clickedButtonAtIndex:(NSInteger)buttonIndex {
178 179 180
  exit(0);
}

181
- (void)connectToEngineAndLoad {
C
Chinmay Garde 已提交
182
  TRACE_EVENT0("flutter", "connectToEngineAndLoad");
183

184
  _platformView->ConnectToEngineAndSetupServices();
185

186
  // We ask the VM to check what it supports.
187 188
  const enum VMType type =
      Dart_IsPrecompiledRuntime() ? VMTypePrecompilation : VMTypeInterpreter;
189

190
  [_dartProject launchInEngine:_platformView->engineProxy()
191 192 193 194 195 196
                embedderVMType:type
                        result:^(BOOL success, NSString* message) {
                          if (!success) {
                            UIAlertView* alert = [[UIAlertView alloc]
                                    initWithTitle:@"Launch Error"
                                          message:message
197
                                         delegate:self
198 199 200 201 202 203
                                cancelButtonTitle:@"OK"
                                otherButtonTitles:nil];
                            [alert show];
                            [alert release];
                          }
                        }];
204 205 206 207 208
}

#pragma mark - Loading the view

- (void)loadView {
209
  FlutterView* view = [[FlutterView alloc] init];
210

211
  self.view = view;
212 213 214 215
  self.view.multipleTouchEnabled = YES;
  self.view.autoresizingMask =
      UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

216
  [view release];
217 218 219 220 221
}

#pragma mark - Application lifecycle notifications

- (void)applicationBecameActive:(NSNotification*)notification {
222 223
  [self sendString:@"AppLifecycleState.resumed"
      withMessageName:@"flutter/lifecycle"];
224 225 226
}

- (void)applicationWillResignActive:(NSNotification*)notification {
227 228
  [self sendString:@"AppLifecycleState.paused"
      withMessageName:@"flutter/lifecycle"];
229 230 231 232 233 234 235 236 237 238
}

#pragma mark - Touch event handling

enum MapperPhase {
  Accessed,
  Added,
  Removed,
};

239 240
using PointerChangeMapperPhase =
    std::pair<blink::PointerData::Change, MapperPhase>;
A
Adam Barth 已提交
241
static inline PointerChangeMapperPhase PointerChangePhaseFromUITouchPhase(
242 243 244
    UITouchPhase phase) {
  switch (phase) {
    case UITouchPhaseBegan:
A
Adam Barth 已提交
245 246
      return PointerChangeMapperPhase(blink::PointerData::Change::kDown,
                                      MapperPhase::Added);
247 248 249 250
    case UITouchPhaseMoved:
    case UITouchPhaseStationary:
      // There is no EVENT_TYPE_POINTER_STATIONARY. So we just pass a move type
      // with the same coordinates
A
Adam Barth 已提交
251 252
      return PointerChangeMapperPhase(blink::PointerData::Change::kMove,
                                      MapperPhase::Accessed);
253
    case UITouchPhaseEnded:
A
Adam Barth 已提交
254 255
      return PointerChangeMapperPhase(blink::PointerData::Change::kUp,
                                      MapperPhase::Removed);
256
    case UITouchPhaseCancelled:
A
Adam Barth 已提交
257 258
      return PointerChangeMapperPhase(blink::PointerData::Change::kCancel,
                                      MapperPhase::Removed);
259 260
  }

A
Adam Barth 已提交
261 262
  return PointerChangeMapperPhase(blink::PointerData::Change::kCancel,
                                  MapperPhase::Accessed);
263
}
C
Chinmay Garde 已提交
264 265

- (void)dispatchTouches:(NSSet*)touches phase:(UITouchPhase)phase {
A
Adam Barth 已提交
266
  auto eventTypePhase = PointerChangePhaseFromUITouchPhase(phase);
C
Chinmay Garde 已提交
267
  const CGFloat scale = [UIScreen mainScreen].scale;
A
Adam Barth 已提交
268
  auto packet = std::make_unique<blink::PointerDataPacket>(touches.count);
C
Chinmay Garde 已提交
269

A
Adam Barth 已提交
270
  int i = 0;
C
Chinmay Garde 已提交
271
  for (UITouch* touch in touches) {
272 273 274 275
    int touch_identifier = 0;

    switch (eventTypePhase.second) {
      case Accessed:
276
        touch_identifier = _touchMapper.identifierOf(touch);
277 278
        break;
      case Added:
279
        touch_identifier = _touchMapper.registerTouch(touch);
280 281
        break;
      case Removed:
282
        touch_identifier = _touchMapper.unregisterTouch(touch);
283 284
        break;
    }
285

286
    DCHECK(touch_identifier != 0);
C
Chinmay Garde 已提交
287
    CGPoint windowCoordinates = [touch locationInView:nil];
288

A
Adam Barth 已提交
289 290 291
    blink::PointerData pointer_data;
    pointer_data.Clear();

292 293
    constexpr int kMicrosecondsPerSecond = 1000 * 1000;
    pointer_data.time_stamp = touch.timestamp * kMicrosecondsPerSecond;
A
Adam Barth 已提交
294 295 296 297 298 299 300 301 302
    pointer_data.change = eventTypePhase.first;
    pointer_data.kind = blink::PointerData::DeviceKind::kTouch;
    pointer_data.pointer = touch_identifier;
    pointer_data.physical_x = windowCoordinates.x * scale;
    pointer_data.physical_y = windowCoordinates.y * scale;
    pointer_data.pressure = 1.0;
    pointer_data.pressure_max = 1.0;

    packet->SetPointerData(i++, pointer_data);
C
Chinmay Garde 已提交
303
  }
304

A
Adam Barth 已提交
305
  blink::Threads::UI()->PostTask(ftl::MakeCopyable([
306 307 308 309 310
    engine = _platformView->engine().GetWeakPtr(), packet = std::move(packet)
  ] {
    if (engine.get())
      engine->DispatchPointerDataPacket(*packet);
  }));
C
Chinmay Garde 已提交
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
}

- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
  [self dispatchTouches:touches phase:UITouchPhaseBegan];
}

- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
  [self dispatchTouches:touches phase:UITouchPhaseMoved];
}

- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event {
  [self dispatchTouches:touches phase:UITouchPhaseEnded];
}

- (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event {
  [self dispatchTouches:touches phase:UITouchPhaseCancelled];
}

329
#pragma mark - Handle view resizing
330

331 332 333 334 335 336 337 338 339
- (void)updateViewportMetrics {
  blink::Threads::UI()->PostTask([
    engine = _platformView->engine().GetWeakPtr(), metrics = _viewportMetrics
  ] {
    if (engine.get())
      engine->SetViewportMetrics(metrics);
  });
}

340 341 342 343
- (void)viewDidLayoutSubviews {
  CGSize size = self.view.bounds.size;
  CGFloat scale = [UIScreen mainScreen].scale;

344 345 346 347
  _viewportMetrics.device_pixel_ratio = scale;
  _viewportMetrics.physical_width = size.width * scale;
  _viewportMetrics.physical_height = size.height * scale;
  _viewportMetrics.physical_padding_top =
348
      [UIApplication sharedApplication].statusBarFrame.size.height * scale;
349
  [self updateViewportMetrics];
350 351
}

352
#pragma mark - Keyboard events
353

354 355 356 357 358
- (void)keyboardWasShown:(NSNotification*)notification {
  NSDictionary* info = [notification userInfo];
  CGFloat bottom = CGRectGetHeight(
      [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue]);
  CGFloat scale = [UIScreen mainScreen].scale;
359 360
  _viewportMetrics.physical_padding_bottom = bottom * scale;
  [self updateViewportMetrics];
361 362
}

363
- (void)keyboardWillBeHidden:(NSNotification*)notification {
364 365
  _viewportMetrics.physical_padding_bottom = 0;
  [self updateViewportMetrics];
366 367
}

368 369 370
#pragma mark - Text input delegate

- (void)updateEditingClient:(int)client withState:(NSDictionary*)state {
371 372 373 374 375
  NSDictionary* message = @{
    @"method" : @"TextInputClient.updateEditingState",
    @"args" : @[ @(client), state ],
  };
  [self sendJSON:message withMessageName:@"flutter/textinputclient"];
376 377
}

378 379 380 381 382 383 384
#pragma mark - Orientation updates

- (void)onOrientationPreferencesUpdated:(NSNotification*)notification {
  // Notifications may not be on the iOS UI thread
  dispatch_async(dispatch_get_main_queue(), ^{
    NSDictionary* info = notification.userInfo;

385
    NSNumber* update = info[@(shell::kOrientationUpdateNotificationKey)];
386 387 388 389 390 391 392 393 394 395 396 397

    if (update == nil) {
      return;
    }

    NSUInteger new_preferences = update.unsignedIntegerValue;

    if (new_preferences != _orientationPreferences) {
      _orientationPreferences = new_preferences;
      [UIViewController attemptRotationToDeviceOrientation];
    }
  });
398 399
}

400 401
- (BOOL)shouldAutorotate {
  return YES;
402 403
}

404 405 406 407
- (NSUInteger)supportedInterfaceOrientations {
  return _orientationPreferences;
}

408 409 410 411 412 413 414
#pragma mark - Accessibility

- (void)onVoiceOverChanged:(NSNotification*)notification {
#if TARGET_OS_SIMULATOR
  // There doesn't appear to be any way to determine whether the accessibility
  // inspector is enabled on the simulator. We conservatively always turn on the
  // accessibility bridge in the simulator.
415
  bool enabled = true;
416
#else
417
  bool enabled = UIAccessibilityIsVoiceOverRunning();
418
#endif
419
  _platformView->ToggleAccessibility(self.view, enabled);
420 421
}

422 423 424 425 426 427
#pragma mark - Locale updates

- (void)onLocaleUpdated:(NSNotification*)notification {
  NSLocale* currentLocale = [NSLocale currentLocale];
  NSString* languageCode = [currentLocale objectForKey:NSLocaleLanguageCode];
  NSString* countryCode = [currentLocale objectForKey:NSLocaleCountryCode];
428 429 430 431
  NSDictionary* message =
      @{ @"method" : @"setLocale",
         @"args" : @[ languageCode, countryCode ] };
  [self sendJSON:message withMessageName:@"flutter/localization"];
432 433 434 435 436
}

#pragma mark - Surface creation and teardown updates

- (void)surfaceUpdated:(BOOL)appeared {
437
  CHECK(_platformView != nullptr);
438 439

  if (appeared) {
440 441
    _platformView->NotifyCreated(
        std::make_unique<shell::GPUSurfaceGL>(_platformView.get()));
442
  } else {
443
    _platformView->NotifyDestroyed();
444 445 446
  }
}

447 448
- (void)viewDidAppear:(BOOL)animated {
  [self surfaceUpdated:YES];
449 450
  [self onLocaleUpdated:nil];
  [self onVoiceOverChanged:nil];
451 452

  [super viewWillAppear:animated];
453
}
C
Chinmay Garde 已提交
454

455 456
- (void)viewWillDisappear:(BOOL)animated {
  [self surfaceUpdated:NO];
457 458

  [super viewWillDisappear:animated];
459 460
}

C
Chinmay Garde 已提交
461
- (void)dealloc {
462
  [[NSNotificationCenter defaultCenter] removeObserver:self];
463 464
  [super dealloc];
}
465

466 467 468 469 470 471 472 473 474 475 476
#pragma mark - Status bar style

- (UIStatusBarStyle)preferredStatusBarStyle {
  return _statusBarStyle;
}

- (void)onPreferredStatusBarStyleUpdated:(NSNotification*)notification {
  // Notifications may not be on the iOS UI thread
  dispatch_async(dispatch_get_main_queue(), ^{
    NSDictionary* info = notification.userInfo;

477
    NSNumber* update = info[@(shell::kOverlayStyleUpdateNotificationKey)];
478 479 480 481 482 483 484 485 486 487 488 489 490 491

    if (update == nil) {
      return;
    }

    NSInteger style = update.integerValue;

    if (style != _statusBarStyle) {
      _statusBarStyle = static_cast<UIStatusBarStyle>(style);
      [self setNeedsStatusBarAppearanceUpdate];
    }
  });
}

492
#pragma mark - Application Messages
493

494
- (void)sendString:(NSString*)message withMessageName:(NSString*)channel {
495
  NSAssert(message, @"The message must not be null");
496 497 498
  NSAssert(channel, @"The channel must not be null");
  _platformView->DispatchPlatformMessage(
      ftl::MakeRefCounted<blink::PlatformMessage>(
499
          channel.UTF8String, shell::GetVectorFromNSString(message), nullptr));
500 501 502
}

- (void)sendString:(NSString*)message
503
    withMessageName:(NSString*)channel
504
           callback:(void (^)(NSString*))callback {
505
  NSAssert(message, @"The message must not be null");
506
  NSAssert(channel, @"The channel must not be null");
507
  NSAssert(callback, @"The callback must not be null");
508 509
  _platformView->DispatchPlatformMessage(
      ftl::MakeRefCounted<blink::PlatformMessage>(
510
          channel.UTF8String, shell::GetVectorFromNSString(message),
511
          ftl::MakeRefCounted<PlatformMessageResponseDarwin>(callback)));
512 513
}

514
- (void)sendJSON:(NSDictionary*)message withMessageName:(NSString*)channel {
515 516
  NSData* data =
      [NSJSONSerialization dataWithJSONObject:message options:0 error:nil];
517 518
  if (!data)
    return;
519
  const uint8_t* bytes = static_cast<const uint8_t*>(data.bytes);
520 521
  _platformView->DispatchPlatformMessage(
      ftl::MakeRefCounted<blink::PlatformMessage>(
522
          channel.UTF8String, std::vector<uint8_t>(bytes, bytes + data.length),
523 524 525
          nullptr));
}

526
- (void)addMessageListener:(NSObject<FlutterMessageListener>*)listener {
527
  NSAssert(listener, @"The listener must not be null");
528 529
  NSString* channel = listener.messageName;
  NSAssert(channel, @"The channel must not be null");
530 531
  _platformView->platform_message_router().SetMessageListener(
      channel.UTF8String, listener);
532 533
}

534
- (void)removeMessageListener:(NSObject<FlutterMessageListener>*)listener {
535
  NSAssert(listener, @"The listener must not be null");
536 537
  NSString* channel = listener.messageName;
  NSAssert(channel, @"The channel must not be null");
538 539
  _platformView->platform_message_router().SetMessageListener(
      channel.UTF8String, nil);
540 541
}

542 543
- (void)addAsyncMessageListener:
    (NSObject<FlutterAsyncMessageListener>*)listener {
544 545 546
  NSAssert(listener, @"The listener must not be null");
  NSString* messageName = listener.messageName;
  NSAssert(messageName, @"The messageName must not be null");
547
  _platformView->platform_message_router().SetAsyncMessageListener(
548
      messageName.UTF8String, listener);
549 550
}

551 552
- (void)removeAsyncMessageListener:
    (NSObject<FlutterAsyncMessageListener>*)listener {
553 554 555
  NSAssert(listener, @"The listener must not be null");
  NSString* messageName = listener.messageName;
  NSAssert(messageName, @"The messageName must not be null");
556
  _platformView->platform_message_router().SetAsyncMessageListener(
557
      messageName.UTF8String, nil);
C
Chinmay Garde 已提交
558 559 560
}

@end