FlutterViewController.mm 16.1 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 13 14
#include "lib/ftl/time/time_delta.h"
#include "lib/ftl/functional/wrap_lambda.h"
#include "flutter/common/threads.h"
15
#include "flutter/services/platform/ios/system_chrome_impl.h"
16 17 18 19
#include "flutter/shell/platform/darwin/ios/framework/Source/flutter_touch_mapper.h"
#include "flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h"
#include "flutter/shell/platform/darwin/ios/platform_view_ios.h"
#include "flutter/shell/platform/darwin/common/platform_mac.h"
20

21
@interface FlutterViewController ()<UIAlertViewDelegate>
22 23
@end

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

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

38
  BOOL _initialized;
39 40
}

41 42
#pragma mark - Manage and override all designated initializers

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

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

    [self performCommonViewControllerInitialization];
56
  }
57

58
  return self;
C
Chinmay Garde 已提交
59 60
}

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

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

70
#pragma mark - Common view controller initialization tasks
C
Chinmay Garde 已提交
71

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

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

84
  [self setupNotificationCenterObservers];
C
Chinmay Garde 已提交
85

86
  [self connectToEngineAndLoad];
C
Chinmay Garde 已提交
87 88
}

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

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

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

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

132
#pragma mark - Initializing the engine
133

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

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

142
  _platformView->ConnectToEngineAndSetupServices();
143

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

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

#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 {
180 181 182
  auto& engine = _platformView->engineProxy();
  if (engine) {
    engine->OnAppLifecycleStateChanged(sky::AppLifecycleState::RESUMED);
183 184 185 186
  }
}

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

#pragma mark - Touch event handling

enum MapperPhase {
  Accessed,
  Added,
  Removed,
};

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

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

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

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

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

247
    DCHECK(touch_identifier != 0);
C
Chinmay Garde 已提交
248
    CGPoint windowCoordinates = [touch locationInView:nil];
249 250

    auto pointer_time =
A
Adam Barth 已提交
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
        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 已提交
266
  }
267

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

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

293
#pragma mark - Handle view resizing
294

295 296 297 298 299 300 301 302 303 304
- (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;

305 306
  _platformView->engineProxy()->OnViewportMetricsChanged(
      _viewportMetrics.Clone());
307 308
}

309
#pragma mark - Keyboard events
310

311 312 313 314 315 316
- (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;
317 318
  _platformView->engineProxy()->OnViewportMetricsChanged(
      _viewportMetrics.Clone());
319 320
}

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

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

350 351
- (BOOL)shouldAutorotate {
  return YES;
352 353
}

354 355 356 357
- (NSUInteger)supportedInterfaceOrientations {
  return _orientationPreferences;
}

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

372 373 374 375 376 377
#pragma mark - Locale updates

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

#pragma mark - Surface creation and teardown updates

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

  if (appeared) {
388
    _platformView->NotifyCreated();
389
  } else {
390
    _platformView->NotifyDestroyed();
391 392 393
  }
}

394 395
- (void)viewDidAppear:(BOOL)animated {
  [self surfaceUpdated:YES];
396 397
  [self onLocaleUpdated:nil];
  [self onVoiceOverChanged:nil];
398 399

  [super viewWillAppear:animated];
400
}
C
Chinmay Garde 已提交
401

402 403
- (void)viewWillDisappear:(BOOL)animated {
  [self surfaceUpdated:NO];
404 405

  [super viewWillDisappear:animated];
406 407
}

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

413 414 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
#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];
    }
  });
}

440
#pragma mark - Application Messages
441

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

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

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

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

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

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

@end