Flutter是如何在iOS上執行起來的原始碼解讀

稻子_Aadan發表於2020-05-06

摘要

本文主要是針對 Flutter 在 iOS 上是如何執行起來的原始碼進行串聯,總結大致的執行流程。

涉及到的關鍵類有以下幾個:

  • FlutterViewController
  • FlutterView
  • FlutterEngine
  • DartIsolate

FlutterViewController

Flutter 嵌入原生應用必須有個載體,從這個點入手,在 Flutter Engine 原始碼中的 API 的入口點是 FlutterViewController,對其標頭檔案原始碼做精簡,大致如下

@interface FlutterViewController : UIViewController <FlutterTextureRegistry, FlutterPluginRegistry>

- (instancetype)initWithEngine:(FlutterEngine*)engine
                       nibName:(nullable NSString*)nibName
                        bundle:(nullable NSBundle*)nibBundle NS_DESIGNATED_INITIALIZER;

- (instancetype)initWithProject:(nullable FlutterDartProject*)project
                        nibName:(nullable NSString*)nibName
                         bundle:(nullable NSBundle*)nibBundle NS_DESIGNATED_INITIALIZER;

- (void)handleStatusBarTouches:(UIEvent*)event;

- (void)setFlutterViewDidRenderCallback:(void (^)(void))callback;

- (NSString*)lookupKeyForAsset:(NSString*)asset;

- (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package;

- (void)setInitialRoute:(NSString*)route;

- (void)popRoute;

- (void)pushRoute:(NSString*)route;

- (id<FlutterPluginRegistry>)pluginRegistry;

@property(nonatomic, readonly, getter=isDisplayingFlutterUI) BOOL displayingFlutterUI;

@property(strong, nonatomic) UIView* splashScreenView;

- (BOOL)loadDefaultSplashScreenView;

@property(nonatomic, getter=isViewOpaque) BOOL viewOpaque;

@property(weak, nonatomic, readonly) FlutterEngine* engine;

@property(nonatomic, readonly) NSObject<FlutterBinaryMessenger>* binaryMessenger;

@end
複製程式碼

FlutterViewController 的建構函式

FlutterViewController 有兩個建構函式,本質上是一樣的,第一個建構函式是谷歌為了在存在多個 FlutterViewController 的場景下為了讓使用者能複用 FlutterEngine 而開放的。

- (instancetype)initWithEngine:(FlutterEngine*)engine
                       nibName:(nullable NSString*)nibName
                        bundle:(nullable NSBundle*)nibBundle {
  NSAssert(engine != nil, @"Engine is required");
  self = [super initWithNibName:nibName bundle:nibBundle];
  if (self) {
    _viewOpaque = YES;
    _engine.reset([engine retain]);
    _engineNeedsLaunch = NO;
    _flutterView.reset([[FlutterView alloc] initWithDelegate:_engine opaque:self.isViewOpaque]);
    _weakFactory = std::make_unique<fml::WeakPtrFactory<FlutterViewController>>(self);
    _ongoingTouches = [[NSMutableSet alloc] init];

    [self performCommonViewControllerInitialization];
    [engine setViewController:self];
  }

  return self;
}

- (instancetype)initWithProject:(nullable FlutterDartProject*)project
                        nibName:(nullable NSString*)nibName
                         bundle:(nullable NSBundle*)nibBundle {
  self = [super initWithNibName:nibName bundle:nibBundle];
  if (self) {
    _viewOpaque = YES;
    _weakFactory = std::make_unique<fml::WeakPtrFactory<FlutterViewController>>(self);
    _engine.reset([[FlutterEngine alloc] initWithName:@"io.flutter"
                                              project:project
                               allowHeadlessExecution:NO]);
    _flutterView.reset([[FlutterView alloc] initWithDelegate:_engine opaque:self.isViewOpaque]);
    [_engine.get() createShell:nil libraryURI:nil];
    _engineNeedsLaunch = YES;
    _ongoingTouches = [[NSMutableSet alloc] init];
    [self loadDefaultSplashScreenView];
    [self performCommonViewControllerInitialization];
  }

  return self;
}

複製程式碼

在建構函式中主要做了這麼幾件事情:

  • 初始化或者替換當前的 FlutterEngine

  • 初始化 FlutterView

  • 初始化正在發生的手勢集合

  • 載入閃屏頁,傳入 FlutterEngine 的建構函式沒有這項,應該是考慮了多 FlutterViewController 的場景下不好頻繁載入閃屏頁

  • 設定 UIInterfaceOrientationMaskUIStatusBarStyle

  • 新增一系列的通知,包括 Application 的生命週期,鍵盤事件,Accessibility的事件等

  • FlutterViewController 設定給 FlutterEngine

第二個建構函式中還多了這行程式碼,第一個建構函式把這個呼叫延後了而已

    [_engine.get() createShell:nil libraryURI:nil];
複製程式碼

FlutterViewController 的 loadView

loadView 函式中,設定了 FlutterViewControllerview,並判斷是否需要載入閃屏頁,可以通過重寫 splashScreenView 的 get 方法返回 nil 的方式徹底不載入閃屏頁

- (void)loadView {
  self.view = _flutterView.get();
  self.view.multipleTouchEnabled = YES;
  self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

  [self installSplashScreenViewIfNecessary];
}
複製程式碼

FlutterViewController 對 Navigator 的操作

FlutterViewController 提供了三個介面允許我們在原生端對 dart 的 Navigator 直接進行操作

- (void)setInitialRoute:(NSString*)route {
  [[_engine.get() navigationChannel] invokeMethod:@"setInitialRoute" arguments:route];
}

- (void)popRoute {
  [[_engine.get() navigationChannel] invokeMethod:@"popRoute" arguments:nil];
}

- (void)pushRoute:(NSString*)route {
  [[_engine.get() navigationChannel] invokeMethod:@"pushRoute" arguments:route];
}
複製程式碼

setInitialRoute

setInitialRoute 在 iOS 端通過 navigationChannel 來告訴 dart 具體的 initialRoute,這個過程略微特殊,並不會在 dart 端直接接收 channel 資訊, 而是在引擎層面做了處理,web_ui 不在本文的解析範疇,這裡直接洗跟原生相關的點

setInitialRoute 設定流程如下:

DispatchPlatformMessage -> HandleNavigationPlatformMessage -> initial_route_

void Engine::DispatchPlatformMessage(fml::RefPtr<PlatformMessage> message) {
  if (message->channel() == kLifecycleChannel) {
    if (HandleLifecyclePlatformMessage(message.get()))
      return;
  } else if (message->channel() == kLocalizationChannel) {
    if (HandleLocalizationPlatformMessage(message.get()))
      return;
  } else if (message->channel() == kSettingsChannel) {
    HandleSettingsPlatformMessage(message.get());
    return;
  }

  if (runtime_controller_->IsRootIsolateRunning() &&
      runtime_controller_->DispatchPlatformMessage(std::move(message))) {
    return;
  }

  // If there's no runtime_, we may still need to set the initial route.
  if (message->channel() == kNavigationChannel) {
    HandleNavigationPlatformMessage(std::move(message));
    return;
  }

  FML_DLOG(WARNING) << "Dropping platform message on channel: "
                    << message->channel();
}
複製程式碼
bool Engine::HandleNavigationPlatformMessage(
    fml::RefPtr<PlatformMessage> message) {
  const auto& data = message->data();

  rapidjson::Document document;
  document.Parse(reinterpret_cast<const char*>(data.data()), data.size());
  if (document.HasParseError() || !document.IsObject())
    return false;
  auto root = document.GetObject();
  auto method = root.FindMember("method");
  if (method->value != "setInitialRoute")
    return false;
  auto route = root.FindMember("args");
  initial_route_ = std::move(route->value.GetString());
  return true;
}
複製程式碼

setInitialRoute 最終在 HandleNavigationPlatformMessage 函式中直接被賦值給 initial_route_

setInitialRoute 讀取流程如下:

Window.defaultRouteName -> DefaultRouteName -> Engine::DefaultRouteName -> initial_route_

可以看到,關鍵字 native,這是 dart 為了方便繫結 C/C++ 匯出方法而新增的關鍵字,對應的 key 是 Window_defaultRouteName

class Window {
  String get defaultRouteName => _defaultRouteName();
  String _defaultRouteName() native 'Window_defaultRouteName';
}
複製程式碼

可以找到在引擎層的 flutter 名稱空間下,有下面這個函式,註冊了對應的匯出函式,這裡對應的是 DefaultRouteName

void Window::RegisterNatives(tonic::DartLibraryNatives* natives) {
  natives->Register({
      {"Window_defaultRouteName", DefaultRouteName, 1, true},
      {"Window_scheduleFrame", ScheduleFrame, 1, true},
      {"Window_sendPlatformMessage", _SendPlatformMessage, 4, true},
      {"Window_respondToPlatformMessage", _RespondToPlatformMessage, 3, true},
      {"Window_render", Render, 2, true},
      {"Window_updateSemantics", UpdateSemantics, 2, true},
      {"Window_setIsolateDebugName", SetIsolateDebugName, 2, true},
      {"Window_reportUnhandledException", ReportUnhandledException, 2, true},
      {"Window_setNeedsReportTimings", SetNeedsReportTimings, 2, true},
  });
}
複製程式碼
void DefaultRouteName(Dart_NativeArguments args) {
  std::string routeName =
      UIDartState::Current()->window()->client()->DefaultRouteName();
  Dart_SetReturnValue(args, tonic::StdStringToDart(routeName));
}
複製程式碼

再往下就是到 engine.cc 檔案下面的函式,讀取 initial_route_ 的值

std::string Engine::DefaultRouteName() {
  if (!initial_route_.empty()) {
    return initial_route_;
  }
  return "/";
}
複製程式碼

至此,完成了在原生端設定 defaultRouteName,在 dart 端獲取該值的流程。

pushRoute and popRoute

實現方式主要還是通過引擎內建的 navigationChannel 通知 dart 端,對應的在 dart 端 SystemChannels 類中,存在對應的 channel

static const MethodChannel navigation = MethodChannel(
      'flutter/navigation',
      JSONMethodCodec(),
  );
複製程式碼

最終處理 pushRoutepopRoute 的邏輯在 WidgetsBinding 類中,主要是以下幾個函式

  Future<dynamic> _handleNavigationInvocation(MethodCall methodCall) {
    switch (methodCall.method) {
      case 'popRoute':
        return handlePopRoute();
      case 'pushRoute':
        return handlePushRoute(methodCall.arguments as String);
    }
    return Future<dynamic>.value();
  }

  Future<void> handlePushRoute(String route) async {
    for (final WidgetsBindingObserver observer in List<WidgetsBindingObserver>.from(_observers)) {
      if (await observer.didPushRoute(route))
        return;
    }
  }

  Future<void> handlePopRoute() async {
    for (final WidgetsBindingObserver observer in List<WidgetsBindingObserver>.from(_observers)) {
      if (await observer.didPopRoute())
        return;
    }
    SystemNavigator.pop();
  }
複製程式碼

這段程式碼表示只有呼叫的方法返回 true 時才中斷,每個 handle 函式具體的處理邏輯是通過某個 WidgetsBindingObserver 來實現了,繼續跟進找到如下程式碼

class _WidgetsAppState extends State<WidgetsApp> with WidgetsBindingObserver {

  @override
  Future<bool> didPopRoute() async {
    assert(mounted);
    final NavigatorState navigator = _navigator?.currentState;
    if (navigator == null)
      return false;
    return await navigator.maybePop();
  }

  @override
  Future<bool> didPushRoute(String route) async {
    assert(mounted);
    final NavigatorState navigator = _navigator?.currentState;
    if (navigator == null)
      return false;
    navigator.pushNamed(route);
    return true;
  }
}
複製程式碼

handlePopRoute 函式中,如果沒有任何一個 observer 返回 true,則最終呼叫 SystemNavigator.pop(); 來退出應用程式

class SystemNavigator {
  static Future<void> pop({bool animated}) async {
    await SystemChannels.platform.invokeMethod<void>('SystemNavigator.pop', animated);
  }
}
複製程式碼

FlutterView

FlutterView 並沒有太多功能,主要是兩點:

  • 初始化時傳入 FlutterViewEngineDelegate
  • 建立 flutter::IOSSurface
@protocol FlutterViewEngineDelegate <NSObject>

- (flutter::Rasterizer::Screenshot)takeScreenshot:(flutter::Rasterizer::ScreenshotType)type
                                  asBase64Encoded:(BOOL)base64Encode;

- (flutter::FlutterPlatformViewsController*)platformViewsController;

@end

@interface FlutterView : UIView

- (instancetype)initWithDelegate:(id<FlutterViewEngineDelegate>)delegate
                          opaque:(BOOL)opaque NS_DESIGNATED_INITIALIZER;
- (std::unique_ptr<flutter::IOSSurface>)createSurface:
    (std::shared_ptr<flutter::IOSGLContext>)context;

@end
複製程式碼

takeScreenshot:asBase64Encoded: 應該是 FlutterView 渲染的資料來源,具體參考 drawLayer:inContext: 的原始碼

@implementation FlutterView
- (void)drawLayer:(CALayer*)layer inContext:(CGContextRef)context {
  if (layer != self.layer || context == nullptr) {
    return;
  }

  auto screenshot = [_delegate takeScreenshot:flutter::Rasterizer::ScreenshotType::UncompressedImage
                              asBase64Encoded:NO];

  if (!screenshot.data || screenshot.data->isEmpty() || screenshot.frame_size.isEmpty()) {
    return;
  }

  NSData* data = [NSData dataWithBytes:const_cast<void*>(screenshot.data->data())
                                length:screenshot.data->size()];

  fml::CFRef<CGDataProviderRef> image_data_provider(
      CGDataProviderCreateWithCFData(reinterpret_cast<CFDataRef>(data)));

  fml::CFRef<CGColorSpaceRef> colorspace(CGColorSpaceCreateDeviceRGB());

  fml::CFRef<CGImageRef> image(CGImageCreate(
      screenshot.frame_size.width(),      // size_t width
      screenshot.frame_size.height(),     // size_t height
      8,                                  // size_t bitsPerComponent
      32,                                 // size_t bitsPerPixel,
      4 * screenshot.frame_size.width(),  // size_t bytesPerRow
      colorspace,                         // CGColorSpaceRef space
      static_cast<CGBitmapInfo>(kCGImageAlphaPremultipliedLast |
                                kCGBitmapByteOrder32Big),  // CGBitmapInfo bitmapInfo
      image_data_provider,                                 // CGDataProviderRef provider
      nullptr,                                             // const CGFloat* decode
      false,                                               // bool shouldInterpolate
      kCGRenderingIntentDefault                            // CGColorRenderingIntent intent
      ));

  const CGRect frame_rect =
      CGRectMake(0.0, 0.0, screenshot.frame_size.width(), screenshot.frame_size.height());

  CGContextSaveGState(context);
  CGContextTranslateCTM(context, 0.0, CGBitmapContextGetHeight(context));
  CGContextScaleCTM(context, 1.0, -1.0);
  CGContextDrawImage(context, frame_rect, image);
  CGContextRestoreGState(context);
}
@end
複製程式碼

後面我們會看到 FlutterViewEngineDelegate 實際上是被 FlutterEngine 實現了。

這裡不對 IOSSurface 做過多解析,其是建立在三種 layer 之上的,可以在編譯期選擇使用何種渲染方式

  • 如果是模擬器,則使用正常的 CALayer
  • 使用 Metal 渲染的情形則使用 CAMetalLayer
  • 使用 OpenGL 渲染的情形則使用 CAEAGLLayer
+ (Class)layerClass {
#if TARGET_IPHONE_SIMULATOR
  return [CALayer class];
#else  // TARGET_IPHONE_SIMULATOR
#if FLUTTER_SHELL_ENABLE_METAL
  return [CAMetalLayer class];
#else   // FLUTTER_SHELL_ENABLE_METAL
  return [CAEAGLLayer class];
#endif  //  FLUTTER_SHELL_ENABLE_METAL
#endif  // TARGET_IPHONE_SIMULATOR
}
複製程式碼

createSurface 函式中主要是分別建立三種對應的 IOSSurface

CALayer -> IOSSurfaceSoftware CAEAGLLayer -> IOSSurfaceGL CAMetalLayer -> IOSSurfaceMetal

再往下的渲染實際上就要交給 FlutterEngine 自身了。

FlutterEngine

FlutterEngine 對外暴露的介面不算多,主要就這麼幾點

  • 建構函式,initWithName:project:allowHeadlessExecution,allowHeadlessExecution允許初始化引擎時不強依賴FlutterViewController`
  • 啟動引擎,runWithEntrypoint:libraryURI: 可傳入自定義的 entrypoint
  • 釋放資源,destroyContext
  • 語義樹是否建立,ensureSemanticsEnabled,關於語義樹文件比較少,大概是殘疾人模式下需要用到的東西
  • FlutterViewController 的 get/set
  • 最後是一堆內建的 channel

我們主要關心引擎的構造、啟動、釋放和 FlutterViewController 就差不多了,FlutterTextureRegistry, FlutterPluginRegistry 不在本文關注範圍內

@interface FlutterEngine : NSObject <FlutterTextureRegistry, FlutterPluginRegistry>

- (instancetype)initWithName:(NSString*)labelPrefix
                     project:(nullable FlutterDartProject*)project
      allowHeadlessExecution:(BOOL)allowHeadlessExecution NS_DESIGNATED_INITIALIZER;

- (BOOL)runWithEntrypoint:(nullable NSString*)entrypoint libraryURI:(nullable NSString*)uri;

- (void)destroyContext;

- (void)ensureSemanticsEnabled;

@property(nonatomic, weak) FlutterViewController* viewController;

@property(nonatomic, readonly, nullable) FlutterMethodChannel* localizationChannel;

@property(nonatomic, readonly) FlutterMethodChannel* navigationChannel;

@property(nonatomic, readonly) FlutterMethodChannel* platformChannel;

@property(nonatomic, readonly) FlutterMethodChannel* textInputChannel;

@property(nonatomic, readonly) FlutterBasicMessageChannel* lifecycleChannel;

@property(nonatomic, readonly) FlutterBasicMessageChannel* systemChannel;

@property(nonatomic, readonly) FlutterBasicMessageChannel* settingsChannel;

@property(nonatomic, readonly) NSObject<FlutterBinaryMessenger>* binaryMessenger;

@property(nonatomic, readonly, copy, nullable) NSString* isolateId;

@end
複製程式碼

FlutterEngine 的構造

FlutterEngine在構造時,要關注的有幾下兩點:

  • FlutterDartProject 初始化
  • FlutterPlatformViewsController 的初始化
- (instancetype)initWithName:(NSString*)labelPrefix
                     project:(FlutterDartProject*)project
      allowHeadlessExecution:(BOOL)allowHeadlessExecution {
  self = [super init];
  NSAssert(self, @"Super init cannot be nil");
  NSAssert(labelPrefix, @"labelPrefix is required");

  _allowHeadlessExecution = allowHeadlessExecution;
  _labelPrefix = [labelPrefix copy];

  _weakFactory = std::make_unique<fml::WeakPtrFactory<FlutterEngine>>(self);

  if (project == nil)
    _dartProject.reset([[FlutterDartProject alloc] init]);
  else
    _dartProject.reset([project retain]);

  _pluginPublications = [NSMutableDictionary new];
  _platformViewsController.reset(new flutter::FlutterPlatformViewsController());

  _binaryMessenger = [[FlutterBinaryMessengerRelay alloc] initWithParent:self];

  NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  [center addObserver:self
             selector:@selector(onMemoryWarning:)
                 name:UIApplicationDidReceiveMemoryWarningNotification
               object:nil];

  return self;
}
複製程式碼

FlutterEngine 的啟動

FlutterEngine 層面,需要關注以下一些類:

  • FlutterDartProject
  • flutter::ThreadHost
  • flutter::Shell
  • FlutterObservatoryPublisher
  • FlutterPlatformViewsController

FlutterEngine 的啟動,主要是兩個事情

  • createShell
  • launchEngine
- (BOOL)runWithEntrypoint:(NSString*)entrypoint libraryURI:(NSString*)libraryURI {
  if ([self createShell:entrypoint libraryURI:libraryURI]) {
    [self launchEngine:entrypoint libraryURI:libraryURI];
  }

  return _shell != nullptr;
}
複製程式碼

createShell

createShell 的原始碼比較多,做了下精簡,主要是以下幾點:

  • 初始化 MessageLoop
  • 初始化 ThreadHost
  • 設定 on_create_platform_view 回撥
  • 設定 on_create_rasterizer 回撥
  • 初始化 flutter::TaskRunners,如果開啟 embedded_views_preview 則 使用當前執行緒的 TaskRunner 作為 gpu 執行緒的 TaskRunner
  • 建立 shell,最終是啟動 Isolate
  • 建立 FlutterPlatformViewsController
  • 建立 FlutterObservatoryPublisher
  • 設定 PlatformView channels
- (BOOL)createShell:(NSString*)entrypoint libraryURI:(NSString*)libraryURI {

  // ……

  fml::MessageLoop::EnsureInitializedForCurrentThread();

  _threadHost = {threadLabel.UTF8String, flutter::ThreadHost::Type::UI |
                                         flutter::ThreadHost::Type::GPU |
                                         flutter::ThreadHost::Type::IO};

  flutter::Shell::CreateCallback<flutter::PlatformView> on_create_platform_view =
      [](flutter::Shell& shell) {
        return std::make_unique<flutter::PlatformViewIOS>(shell, shell.GetTaskRunners());
      };

  flutter::Shell::CreateCallback<flutter::Rasterizer> on_create_rasterizer =
      [](flutter::Shell& shell) {
        return std::make_unique<flutter::Rasterizer>(shell, shell.GetTaskRunners());
      };

  if (flutter::IsIosEmbeddedViewsPreviewEnabled()) {
    flutter::TaskRunners task_runners(threadLabel.UTF8String,                          // label
                                      fml::MessageLoop::GetCurrent().GetTaskRunner(),  // platform
                                      fml::MessageLoop::GetCurrent().GetTaskRunner(),  // gpu
                                      _threadHost.ui_thread->GetTaskRunner(),          // ui
                                      _threadHost.io_thread->GetTaskRunner()           // io
    );
    // Create the shell. This is a blocking operation.
    _shell = flutter::Shell::Create(std::move(task_runners),  // task runners
                                    std::move(settings),      // settings
                                    on_create_platform_view,  // platform view creation
                                    on_create_rasterizer      // rasterzier creation
    );
  } else {
    flutter::TaskRunners task_runners(threadLabel.UTF8String,                          // label
                                      fml::MessageLoop::GetCurrent().GetTaskRunner(),  // platform
                                      _threadHost.gpu_thread->GetTaskRunner(),         // gpu
                                      _threadHost.ui_thread->GetTaskRunner(),          // ui
                                      _threadHost.io_thread->GetTaskRunner()           // io
    );
    // Create the shell. This is a blocking operation.
    _shell = flutter::Shell::Create(std::move(task_runners),  // task runners
                                    std::move(settings),      // settings
                                    on_create_platform_view,  // platform view creation
                                    on_create_rasterizer      // rasterzier creation
    );
  }

  if (_shell != nullptr) {
    [self setupChannels];
    if (!_platformViewsController) {
      _platformViewsController.reset(new flutter::FlutterPlatformViewsController());
    }
    _publisher.reset([[FlutterObservatoryPublisher alloc] init]);
    [self maybeSetupPlatformViewChannels];
  }

  return _shell != nullptr;
}
複製程式碼

這裡可以看到會啟動四個 TaskRunner,分別為 platform,gpu, ui,io,但實際上並不一定對應四個執行緒。

launchEngine

launchEngine 實際上還是在 shell 上進行的操作

- (void)launchEngine:(NSString*)entrypoint libraryURI:(NSString*)libraryOrNil {
  // Launch the Dart application with the inferred run configuration.
  self.shell.RunEngine([_dartProject.get() runConfigurationForEntrypoint:entrypoint
                                                            libraryOrNil:libraryOrNil]);
}
複製程式碼
void Shell::RunEngine(RunConfiguration run_configuration) {
  RunEngine(std::move(run_configuration), nullptr);
}

void Shell::RunEngine(RunConfiguration run_configuration,
                      std::function<void(Engine::RunStatus)> result_callback) {
  auto result = [platform_runner = task_runners_.GetPlatformTaskRunner(),
                 result_callback](Engine::RunStatus run_result) {
    if (!result_callback) {
      return;
    }
    platform_runner->PostTask(
        [result_callback, run_result]() { result_callback(run_result); });
  };
  FML_DCHECK(is_setup_);
  FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread());

  if (!weak_engine_) {
    result(Engine::RunStatus::Failure);
  }
  fml::TaskRunner::RunNowOrPostTask(
      task_runners_.GetUITaskRunner(),
      fml::MakeCopyable(
          [run_configuration = std::move(run_configuration),
           weak_engine = weak_engine_, result]() mutable {
            if (!weak_engine) {
              FML_LOG(ERROR)
                  << "Could not launch engine with configuration - no engine.";
              result(Engine::RunStatus::Failure);
              return;
            }
            auto run_result = weak_engine->Run(std::move(run_configuration));
            if (run_result == flutter::Engine::RunStatus::Failure) {
              FML_LOG(ERROR) << "Could not launch engine with configuration.";
            }
            result(run_result);
          }));
}
複製程式碼

再跟下去,最終會到[shell > common > engine.cc] 裡面的 run 函式,最核心的是這行程式碼 PrepareAndLaunchIsolate,最終整個流程跑下來就是為了啟動 Isolate

Engine::RunStatus Engine::Run(RunConfiguration configuration) {
  if (!configuration.IsValid()) {
    FML_LOG(ERROR) << "Engine run configuration was invalid.";
    return RunStatus::Failure;
  }

  auto isolate_launch_status =
      PrepareAndLaunchIsolate(std::move(configuration));
  if (isolate_launch_status == Engine::RunStatus::Failure) {
    FML_LOG(ERROR) << "Engine not prepare and launch isolate.";
    return isolate_launch_status;
  } else if (isolate_launch_status ==
             Engine::RunStatus::FailureAlreadyRunning) {
    return isolate_launch_status;
  }

  std::shared_ptr<DartIsolate> isolate =
      runtime_controller_->GetRootIsolate().lock();

  bool isolate_running =
      isolate && isolate->GetPhase() == DartIsolate::Phase::Running;

  if (isolate_running) {
    tonic::DartState::Scope scope(isolate.get());

    if (settings_.root_isolate_create_callback) {
      settings_.root_isolate_create_callback();
    }

    if (settings_.root_isolate_shutdown_callback) {
      isolate->AddIsolateShutdownCallback(
          settings_.root_isolate_shutdown_callback);
    }

    std::string service_id = isolate->GetServiceId();
    fml::RefPtr<PlatformMessage> service_id_message =
        fml::MakeRefCounted<flutter::PlatformMessage>(
            kIsolateChannel,
            std::vector<uint8_t>(service_id.begin(), service_id.end()),
            nullptr);
    HandlePlatformMessage(service_id_message);
  }

  return isolate_running ? Engine::RunStatus::Success
                         : Engine::RunStatus::Failure;
}
複製程式碼

DartIsolate

PrepareAndLaunchIsolate 函式做下精簡,剩下兩個點

  • PrepareIsolate
  • RunFromLibrary
Engine::RunStatus Engine::PrepareAndLaunchIsolate(RunConfiguration configuration) {
  // ……

  if (!isolate_configuration->PrepareIsolate(*isolate)) {
    return RunStatus::Failure;
  }

  if (!isolate->RunFromLibrary(configuration.GetEntrypointLibrary(),
                               configuration.GetEntrypoint(),
                               settings_.dart_entrypoint_args)) {
    return RunStatus::Failure;
  }

  return RunStatus::Success;
}
複製程式碼

主要看看 RunFromLibrary 做了什麼

  • 查詢 entrypoint
  • 呼叫 entrypoint 的函式,InvokeMainEntrypoint
bool DartIsolate::RunFromLibrary(const std::string& library_name,
                                 const std::string& entrypoint_name,
                                 const std::vector<std::string>& args,
                                 fml::closure on_run) {
  tonic::DartState::Scope scope(this);

  auto user_entrypoint_function =
      Dart_GetField(Dart_LookupLibrary(tonic::ToDart(library_name.c_str())),
                    tonic::ToDart(entrypoint_name.c_str()));

  auto entrypoint_args = tonic::ToDart(args);

  if (!InvokeMainEntrypoint(user_entrypoint_function, entrypoint_args)) {
    return false;
  }
  phase_ = Phase::Running;
  if (on_run) {
    on_run();
  }
  return true;
}
複製程式碼

再看看 InvokeMainEntrypoint 做了什麼,原始碼做了精簡,主要就這兩步,我們可以在 dart 端找到對應的函式

  • _getStartMainIsolateFunction
  • _runMainZoned
static bool InvokeMainEntrypoint(Dart_Handle user_entrypoint_function,
                                 Dart_Handle args) {

  Dart_Handle start_main_isolate_function =
      tonic::DartInvokeField(Dart_LookupLibrary(tonic::ToDart("dart:isolate")),
                             "_getStartMainIsolateFunction", {});

  if (tonic::LogIfError(tonic::DartInvokeField(
          Dart_LookupLibrary(tonic::ToDart("dart:ui")), "_runMainZoned",
          {start_main_isolate_function, user_entrypoint_function, args}))) {
    FML_LOG(ERROR) << "Could not invoke the main entrypoint.";
    return false;
  }

  return true;
}
複製程式碼

再往下就是 tonic 庫,這是 fuchsia 下的庫。

總結

Flutter 執行於 iOS 之上,從原始碼層面看,有以下幾點收穫:

  • 複用了現有的三類 CALayer 來繪製介面,drawLayer 時會呼叫 takeScreenshot 來獲取 Flutter 介面的光柵圖
  • 在原生端不會建立對應的 語義樹,需要額外生成
  • Flutter 自身會起一個完全獨立的執行緒環境來執行,我們需要關注的是四個 TaskRunner,Platform TaskRunner 不一定是獨立的執行緒
  • Platform TaskRunner,原生端跟 Flutter 的所有互動都會在 Platform TaskRunner 進行處理
  • dart 端可以通過 native 關鍵字呼叫 C/C++ 的函式,獲取基本型別的資料返回值,效能比 channel 要好
  • FlutterViewController 將所有的手勢互動相關的都轉發給 FlutterEngine

Flutter 執行流程

對整個 Flutter 執行的流程可以大致總結如下,主要是側重在引擎側,dart 那邊的流程不展開,僅供參考:

  • 尋找 DartLibrary
  • 定位到 Entrypoint
  • 建立 FlutterEngine,傳入 DartLibrary 和 Entrypoint
  • 建立 FlutterViewControllerFlutterView
  • 設定 FlutterEngineviewController
  • 建立 shell,啟動 Dart VM
  • 載入 DartLibrary,執行 dart 的 Entrypoint
  • 擷取 Dart UI 的介面並光柵化並 繪製 CALayer

作者其它文章

Flutter 在哈囉出行 B 端創新業務的實踐

如何無縫的將Flutter引入現有應用?

相關文章