FlutterViewController.mm 16.3 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
#include "flutter/services/platform/ios/system_chrome_impl.h"
14 15 16
#include "flutter/shell/gpu/gpu_rasterizer.h"
#include "flutter/shell/gpu/gpu_surface_gl.h"
#include "flutter/shell/platform/darwin/common/platform_mac.h"
17
#include "flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h"
18
#include "flutter/shell/platform/darwin/ios/framework/Source/flutter_touch_mapper.h"
19
#include "flutter/shell/platform/darwin/ios/platform_view_ios.h"
A
Adam Barth 已提交
20
#include "lib/ftl/functional/make_copyable.h"
21
#include "lib/ftl/time/time_delta.h"
22

23
@interface FlutterViewController ()<UIAlertViewDelegate>
24 25
@end

26 27 28
void FlutterInit(int argc, const char* argv[]) {
  NSBundle* bundle = [NSBundle bundleForClass:[FlutterViewController class]];
  NSString* icuDataPath = [bundle pathForResource:@"icudtl" ofType:@"dat"];
29
  shell::PlatformMacMain(argc, argv, icuDataPath.UTF8String);
30 31
}

32
@implementation FlutterViewController {
33
  base::scoped_nsprotocol<FlutterDartProject*> _dartProject;
34
  UIInterfaceOrientationMask _orientationPreferences;
35
  UIStatusBarStyle _statusBarStyle;
36
  sky::ViewportMetricsPtr _viewportMetrics;
37 38
  shell::TouchMapper _touchMapper;
  std::unique_ptr<shell::PlatformViewIOS> _platformView;
39

40
  BOOL _initialized;
41 42
}

43 44
#pragma mark - Manage and override all designated initializers

45 46 47 48
- (instancetype)initWithProject:(FlutterDartProject*)project
                        nibName:(NSString*)nibNameOrNil
                         bundle:(NSBundle*)nibBundleOrNil {
  self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
49

50
  if (self) {
51
    if (project == nil)
52 53
      _dartProject.reset(
          [[FlutterDartProject alloc] initFromDefaultSourceForConfiguration]);
54 55
    else
      _dartProject.reset([project retain]);
56 57

    [self performCommonViewControllerInitialization];
58
  }
59

60
  return self;
C
Chinmay Garde 已提交
61 62
}

63 64
- (instancetype)initWithNibName:(NSString*)nibNameOrNil
                         bundle:(NSBundle*)nibBundleOrNil {
65
  return [self initWithProject:nil nibName:nil bundle:nil];
C
Chinmay Garde 已提交
66 67
}

68
- (instancetype)initWithCoder:(NSCoder*)aDecoder {
69
  return [self initWithProject:nil nibName:nil bundle:nil];
70 71
}

72
#pragma mark - Common view controller initialization tasks
C
Chinmay Garde 已提交
73

74
- (void)performCommonViewControllerInitialization {
75
  if (_initialized)
76 77
    return;
  _initialized = YES;
C
Chinmay Garde 已提交
78

79
  _orientationPreferences = UIInterfaceOrientationMaskAll;
80
  _statusBarStyle = UIStatusBarStyleDefault;
81
  _viewportMetrics = sky::ViewportMetrics::New();
A
Adam Barth 已提交
82
  _platformView = std::make_unique<shell::PlatformViewIOS>(
83 84
      reinterpret_cast<CAEAGLLayer*>(self.view.layer));
  _platformView->SetupResourceContextOnIOThread();
C
Chinmay Garde 已提交
85

86
  [self setupNotificationCenterObservers];
C
Chinmay Garde 已提交
87

88
  [self connectToEngineAndLoad];
C
Chinmay Garde 已提交
89 90
}

91 92 93 94 95 96 97
- (void)setupNotificationCenterObservers {
  NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  [center addObserver:self
             selector:@selector(onOrientationPreferencesUpdated:)
                 name:@(flutter::platform::kOrientationUpdateNotificationName)
               object:nil];

98 99 100 101 102
  [center addObserver:self
             selector:@selector(onPreferredStatusBarStyleUpdated:)
                 name:@(flutter::platform::kOverlayStyleUpdateNotificationName)
               object:nil];

103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
  [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];
127 128 129 130 131

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

134
#pragma mark - Initializing the engine
135

136
- (void)alertView:(UIAlertView*)alertView
137
    clickedButtonAtIndex:(NSInteger)buttonIndex {
138 139 140
  exit(0);
}

141
- (void)connectToEngineAndLoad {
C
Chinmay Garde 已提交
142
  TRACE_EVENT0("flutter", "connectToEngineAndLoad");
143

144
  _platformView->ConnectToEngineAndSetupServices();
145

146
  // We ask the VM to check what it supports.
147 148
  const enum VMType type =
      Dart_IsPrecompiledRuntime() ? VMTypePrecompilation : VMTypeInterpreter;
149

150
  [_dartProject launchInEngine:_platformView->engineProxy()
151 152 153 154 155 156
                embedderVMType:type
                        result:^(BOOL success, NSString* message) {
                          if (!success) {
                            UIAlertView* alert = [[UIAlertView alloc]
                                    initWithTitle:@"Launch Error"
                                          message:message
157
                                         delegate:self
158 159 160 161 162 163
                                cancelButtonTitle:@"OK"
                                otherButtonTitles:nil];
                            [alert show];
                            [alert release];
                          }
                        }];
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
}

#pragma mark - Loading the view

- (void)loadView {
  FlutterView* surface = [[FlutterView alloc] init];

  self.view = surface;
  self.view.multipleTouchEnabled = YES;
  self.view.autoresizingMask =
      UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

  [surface release];
}

#pragma mark - Application lifecycle notifications

- (void)applicationBecameActive:(NSNotification*)notification {
182 183 184
  auto& engine = _platformView->engineProxy();
  if (engine) {
    engine->OnAppLifecycleStateChanged(sky::AppLifecycleState::RESUMED);
185 186 187 188
  }
}

- (void)applicationWillResignActive:(NSNotification*)notification {
189 190 191
  auto& engine = _platformView->engineProxy();
  if (engine) {
    engine->OnAppLifecycleStateChanged(sky::AppLifecycleState::PAUSED);
192 193 194 195 196 197 198 199 200 201 202
  }
}

#pragma mark - Touch event handling

enum MapperPhase {
  Accessed,
  Added,
  Removed,
};

203 204
using PointerChangeMapperPhase =
    std::pair<blink::PointerData::Change, MapperPhase>;
A
Adam Barth 已提交
205
static inline PointerChangeMapperPhase PointerChangePhaseFromUITouchPhase(
206 207 208
    UITouchPhase phase) {
  switch (phase) {
    case UITouchPhaseBegan:
A
Adam Barth 已提交
209 210
      return PointerChangeMapperPhase(blink::PointerData::Change::kDown,
                                      MapperPhase::Added);
211 212 213 214
    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 已提交
215 216
      return PointerChangeMapperPhase(blink::PointerData::Change::kMove,
                                      MapperPhase::Accessed);
217
    case UITouchPhaseEnded:
A
Adam Barth 已提交
218 219
      return PointerChangeMapperPhase(blink::PointerData::Change::kUp,
                                      MapperPhase::Removed);
220
    case UITouchPhaseCancelled:
A
Adam Barth 已提交
221 222
      return PointerChangeMapperPhase(blink::PointerData::Change::kCancel,
                                      MapperPhase::Removed);
223 224
  }

A
Adam Barth 已提交
225 226
  return PointerChangeMapperPhase(blink::PointerData::Change::kCancel,
                                  MapperPhase::Accessed);
227
}
C
Chinmay Garde 已提交
228 229

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

A
Adam Barth 已提交
234
  int i = 0;
C
Chinmay Garde 已提交
235
  for (UITouch* touch in touches) {
236 237 238 239
    int touch_identifier = 0;

    switch (eventTypePhase.second) {
      case Accessed:
240
        touch_identifier = _touchMapper.identifierOf(touch);
241 242
        break;
      case Added:
243
        touch_identifier = _touchMapper.registerTouch(touch);
244 245
        break;
      case Removed:
246
        touch_identifier = _touchMapper.unregisterTouch(touch);
247 248
        break;
    }
249

250
    DCHECK(touch_identifier != 0);
C
Chinmay Garde 已提交
251
    CGPoint windowCoordinates = [touch locationInView:nil];
252 253

    auto pointer_time =
A
Adam Barth 已提交
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
        ftl::TimeDelta::FromSeconds(touch.timestamp).ToMicroseconds();

    blink::PointerData pointer_data;
    pointer_data.Clear();

    pointer_data.time_stamp = pointer_time;
    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 已提交
269
  }
270

A
Adam Barth 已提交
271
  blink::Threads::UI()->PostTask(ftl::MakeCopyable([
272 273 274 275 276
    engine = _platformView->engine().GetWeakPtr(), packet = std::move(packet)
  ] {
    if (engine.get())
      engine->DispatchPointerDataPacket(*packet);
  }));
C
Chinmay Garde 已提交
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
}

- (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];
}

295
#pragma mark - Handle view resizing
296

297 298 299 300 301 302 303 304 305 306
- (void)viewDidLayoutSubviews {
  CGSize size = self.view.bounds.size;
  CGFloat scale = [UIScreen mainScreen].scale;

  _viewportMetrics->device_pixel_ratio = scale;
  _viewportMetrics->physical_width = size.width * scale;
  _viewportMetrics->physical_height = size.height * scale;
  _viewportMetrics->physical_padding_top =
      [UIApplication sharedApplication].statusBarFrame.size.height * scale;

307 308
  _platformView->engineProxy()->OnViewportMetricsChanged(
      _viewportMetrics.Clone());
309 310
}

311
#pragma mark - Keyboard events
312

313 314 315 316 317 318
- (void)keyboardWasShown:(NSNotification*)notification {
  NSDictionary* info = [notification userInfo];
  CGFloat bottom = CGRectGetHeight(
      [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue]);
  CGFloat scale = [UIScreen mainScreen].scale;
  _viewportMetrics->physical_padding_bottom = bottom * scale;
319 320
  _platformView->engineProxy()->OnViewportMetricsChanged(
      _viewportMetrics.Clone());
321 322
}

323 324
- (void)keyboardWillBeHidden:(NSNotification*)notification {
  _viewportMetrics->physical_padding_bottom = 0.0;
325 326
  _platformView->engineProxy()->OnViewportMetricsChanged(
      _viewportMetrics.Clone());
327 328
}

329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
#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;

    NSNumber* update =
        info[@(flutter::platform::kOrientationUpdateNotificationKey)];

    if (update == nil) {
      return;
    }

    NSUInteger new_preferences = update.unsignedIntegerValue;

    if (new_preferences != _orientationPreferences) {
      _orientationPreferences = new_preferences;
      [UIViewController attemptRotationToDeviceOrientation];
    }
  });
350 351
}

352 353
- (BOOL)shouldAutorotate {
  return YES;
354 355
}

356 357 358 359
- (NSUInteger)supportedInterfaceOrientations {
  return _orientationPreferences;
}

360 361 362 363 364 365 366
#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.
367
  bool enabled = true;
368
#else
369
  bool enabled = UIAccessibilityIsVoiceOverRunning();
370
#endif
371
  _platformView->ToggleAccessibility(self.view, enabled);
372 373
}

374 375 376 377 378 379
#pragma mark - Locale updates

- (void)onLocaleUpdated:(NSNotification*)notification {
  NSLocale* currentLocale = [NSLocale currentLocale];
  NSString* languageCode = [currentLocale objectForKey:NSLocaleLanguageCode];
  NSString* countryCode = [currentLocale objectForKey:NSLocaleCountryCode];
380 381
  _platformView->engineProxy()->OnLocaleChanged(languageCode.UTF8String,
                                                countryCode.UTF8String);
382 383 384 385 386
}

#pragma mark - Surface creation and teardown updates

- (void)surfaceUpdated:(BOOL)appeared {
387
  CHECK(_platformView != nullptr);
388 389

  if (appeared) {
390 391
    _platformView->NotifyCreated(
        std::make_unique<shell::GPUSurfaceGL>(_platformView.get()));
392
  } else {
393
    _platformView->NotifyDestroyed();
394 395 396
  }
}

397 398
- (void)viewDidAppear:(BOOL)animated {
  [self surfaceUpdated:YES];
399 400
  [self onLocaleUpdated:nil];
  [self onVoiceOverChanged:nil];
401 402

  [super viewWillAppear:animated];
403
}
C
Chinmay Garde 已提交
404

405 406
- (void)viewWillDisappear:(BOOL)animated {
  [self surfaceUpdated:NO];
407 408

  [super viewWillDisappear:animated];
409 410
}

C
Chinmay Garde 已提交
411
- (void)dealloc {
412
  [[NSNotificationCenter defaultCenter] removeObserver:self];
413 414
  [super dealloc];
}
415

416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
#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;

    NSNumber* update =
        info[@(flutter::platform::kOverlayStyleUpdateNotificationKey)];

    if (update == nil) {
      return;
    }

    NSInteger style = update.integerValue;

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

443
#pragma mark - Application Messages
444

445
- (void)sendString:(NSString*)message withMessageName:(NSString*)messageName {
446 447
  NSAssert(message, @"The message must not be null");
  NSAssert(messageName, @"The messageName must not be null");
448 449 450
  _platformView->AppMessageSender()->SendString(
      messageName.UTF8String, message.UTF8String,
      [](const mojo::String& response) {});
451 452 453
}

- (void)sendString:(NSString*)message
454 455
    withMessageName:(NSString*)messageName
           callback:(void (^)(NSString*))callback {
456 457 458
  NSAssert(message, @"The message must not be null");
  NSAssert(messageName, @"The messageName must not be null");
  NSAssert(callback, @"The callback must not be null");
459
  base::mac::ScopedBlock<void (^)(NSString*)> callback_ptr(
460
      callback, base::scoped_policy::RETAIN);
461
  _platformView->AppMessageSender()->SendString(
462
      messageName.UTF8String, message.UTF8String,
463
      [callback_ptr](const mojo::String& response) {
464 465
        callback_ptr.get()(base::SysUTF8ToNSString(response));
      });
466 467
}

468
- (void)addMessageListener:(NSObject<FlutterMessageListener>*)listener {
469
  NSAssert(listener, @"The listener must not be null");
470
  NSString* messageName = listener.messageName;
471
  NSAssert(messageName, @"The messageName must not be null");
472 473
  _platformView->AppMessageReceiver().SetMessageListener(messageName.UTF8String,
                                                         listener);
474 475
}

476
- (void)removeMessageListener:(NSObject<FlutterMessageListener>*)listener {
477
  NSAssert(listener, @"The listener must not be null");
478
  NSString* messageName = listener.messageName;
479
  NSAssert(messageName, @"The messageName must not be null");
480 481
  _platformView->AppMessageReceiver().SetMessageListener(messageName.UTF8String,
                                                         nil);
482 483
}

484 485
- (void)addAsyncMessageListener:
    (NSObject<FlutterAsyncMessageListener>*)listener {
486 487 488
  NSAssert(listener, @"The listener must not be null");
  NSString* messageName = listener.messageName;
  NSAssert(messageName, @"The messageName must not be null");
489 490
  _platformView->AppMessageReceiver().SetAsyncMessageListener(
      messageName.UTF8String, listener);
491 492
}

493 494
- (void)removeAsyncMessageListener:
    (NSObject<FlutterAsyncMessageListener>*)listener {
495 496 497
  NSAssert(listener, @"The listener must not be null");
  NSString* messageName = listener.messageName;
  NSAssert(messageName, @"The messageName must not be null");
498 499
  _platformView->AppMessageReceiver().SetAsyncMessageListener(
      messageName.UTF8String, nil);
C
Chinmay Garde 已提交
500 501 502
}

@end