VSCode源码分析 - 主启动流程

    git仓库地址: https://github.com/microsoft/vscode

    通过Eletron集成了桌面应用,可以跨平台使用,开发语言主要采用微软自家的TypeScript。 整个项目结构比较清晰,方便阅读代码理解。成为了最流行跨平台的桌面IDE应用

    微软希望VSCode在保持核心轻量级的基础上,增加项目支持,智能感知,编译调试。

    下载最新版本,目前我用的是1.37.1版本 官方的wiki中有编译安装的说明

    Linux, Window, MacOS三个系统编译时有些差别,参考官方文档, 在编译安装依赖时如果遇到connect timeout, 需要进行科学上网。

    技术架构

    img

    Monaco Editor

    核心层

    • base: 提供通用服务和构建用户界面
    • platform: 注入服务和基础服务代码
    • editor: 微软Monaco编辑器,也可独立运行使用
    • wrokbench: 配合Monaco并且给viewlets提供框架:如:浏览器状态栏,菜单栏利用electron实现桌面程序

    整个项目完全使用typescript实现,electron中运行主进程和渲染进程,使用的api有所不同,所以在core中每个目录组织也是按照使用的api来安排, 运行的环境分为几类:

    • common: 只使用javascritp api的代码,能在任何环境下运行
    • browser: 浏览器api, 如操作dom; 可以调用common
    • node: 需要使用node的api,比如文件io操作
    • electron-brower: 渲染进程api, 可以调用common, brower, node, 依赖
    • electron-main: 主进程api, 可以调用: common, node 依赖于electron main-process AP

    Electron通过package.json中的main字段来定义应用入口。

    main.js是vscode的入口。

    • src/main.js
      • vs/code/electron-main/main.ts
      • vs/code/electron-main/app.ts
      • vs/code/electron-main/windows.ts
      • vs/workbench/electron-browser/desktop.main.ts
      • vs/workbench/browser/workbench.ts
    1. //启动追踪,后面会讲到,跟性能检测优化相关。
    2. if (args['trace']) {
    3. // @ts-ignore
    4. const contentTracing = require('electron').contentTracing;
    5. const traceOptions = {
    6. categoryFilter: args['trace-category-filter'] || '*',
    7. traceOptions: args['trace-options'] || 'record-until-full,enable-sampling'
    8. };
    9. contentTracing.startRecording(traceOptions, () => onReady());
    10. } else {
    11. onReady();
    12. }
    13. });
    14. function onReady() {
    15. perf.mark('main:appReady');
    16. Promise.all([nodeCachedDataDir.ensureExists(), userDefinedLocale]).then(([cachedDataDir, locale]) => {
    17. //1. 这里尝试获取本地配置信息,如果有的话会传递到startup
    18. if (locale && !nlsConfiguration) {
    19. nlsConfiguration = lp.getNLSConfiguration(product.commit, userDataPath, metaDataFile, locale);
    20. }
    21. if (!nlsConfiguration) {
    22. nlsConfiguration = Promise.resolve(undefined);
    23. }
    24. nlsConfiguration.then(nlsConfig => {
    25. //4. 首先会检查用户语言环境配置,如果没有设置默认使用英语
    26. const startup = nlsConfig => {
    27. nlsConfig._languagePackSupport = true;
    28. process.env['VSCODE_NLS_CONFIG'] = JSON.stringify(nlsConfig);
    29. process.env['VSCODE_NODE_CACHED_DATA_DIR'] = cachedDataDir || '';
    30. perf.mark('willLoadMainBundle');
    31. //使用微软的loader组件加载electron-main/main文件
    32. require('./bootstrap-amd').load('vs/code/electron-main/main', () => {
    33. perf.mark('didLoadMainBundle');
    34. });
    35. };
    36. // 2. 接收到有效的配置传入是其生效,调用startup
    37. if (nlsConfig) {
    38. startup(nlsConfig);
    39. }
    40. // 3. 这里尝试使用本地的应用程序
    41. // 应用程序设置区域在ready事件后才有效
    42. else {
    43. let appLocale = app.getLocale();
    44. if (!appLocale) {
    45. startup({ locale: 'en', availableLanguages: {} });
    46. } else {
    47. appLocale = appLocale.toLowerCase();
    48. // 这里就会调用config服务,把本地配置加载进来再调用startup
    49. lp.getNLSConfiguration(product.commit, userDataPath, metaDataFile, appLocale).then(nlsConfig => {
    50. if (!nlsConfig) {
    51. nlsConfig = { locale: appLocale, availableLanguages: {} };
    52. }
    53. startup(nlsConfig);
    54. });
    55. }
    56. }
    57. });
    58. }, console.error);
    59. }

    electron-main/main 是程序真正启动的入口,进入main process初始化流程.

    这里主要做了两件事情:

    1. 初始化Service
    2. 启动主实例

    直接看startup方法的实现,基础服务初始化完成后会加载 CodeApplication, mainIpcServer, instanceEnvironment,调用 startup 方法启动APP

    1. private async startup(args: ParsedArgs): Promise<void> {
    2. //spdlog 日志服务
    3. const bufferLogService = new BufferLogService();
    4. // 1. 调用 createServices
    5. const [instantiationService, instanceEnvironment] = this.createServices(args, bufferLogService);
    6. try {
    7. // 1.1 初始化Service服务
    8. await instantiationService.invokeFunction(async accessor => {
    9. const environmentService = accessor.get(IEnvironmentService);
    10. // 配置服务
    11. const configurationService = accessor.get(IConfigurationService);
    12. // 持久化数据
    13. const stateService = accessor.get(IStateService);
    14. try {
    15. await this.initServices(environmentService, configurationService as ConfigurationService, stateService as StateService);
    16. } catch (error) {
    17. // 抛出错误对话框
    18. this.handleStartupDataDirError(environmentService, error);
    19. throw error;
    20. }
    21. });
    22. // 1.2 启动实例
    23. await instantiationService.invokeFunction(async accessor => {
    24. const environmentService = accessor.get(IEnvironmentService);
    25. const logService = accessor.get(ILogService);
    26. const lifecycleService = accessor.get(ILifecycleService);
    27. const configurationService = accessor.get(IConfigurationService);
    28. const mainIpcServer = await this.doStartup(logService, environmentService, lifecycleService, instantiationService, true);
    29. bufferLogService.logger = new SpdLogService('main', environmentService.logsPath, bufferLogService.getLevel());
    30. once(lifecycleService.onWillShutdown)(() => (configurationService as ConfigurationService).dispose());
    31. return instantiationService.createInstance(CodeApplication, mainIpcServer, instanceEnvironment).startup();
    32. });
    33. } catch (error) {
    34. instantiationService.invokeFunction(this.quit, error);
    35. }
    36. }

    vs/code/electron-main/app.ts

    openFirstWindow 主要实现 CodeApplication.openFirstWindow 首次开启窗口时,创建 Electron 的 IPC,使主进程和渲染进程间通信。 window会被注册到sharedProcessClient,主进程和共享进程通信 根据 environmentService 提供的参数(path,uri)调用windowsMainService.open 方法打开窗口

    1. private openFirstWindow(accessor: ServicesAccessor, electronIpcServer: ElectronIPCServer, sharedProcessClient: Promise<Client<string>>): ICodeWindow[] {
    2. ...
    3. // 1. 注入Electron IPC Service, windows窗口管理,菜单栏等服务
    4. // 2. 根据environmentService进行参数配置
    5. const macOpenFiles: string[] = (<any>global).macOpenFiles;
    6. const context = !!process.env['VSCODE_CLI'] ? OpenContext.CLI : OpenContext.DESKTOP;
    7. const hasCliArgs = hasArgs(args._);
    8. const hasFolderURIs = hasArgs(args['folder-uri']);
    9. const hasFileURIs = hasArgs(args['file-uri']);
    10. const noRecentEntry = args['skip-add-to-recently-opened'] === true;
    11. const waitMarkerFileURI = args.wait && args.waitMarkerFilePath ? URI.file(args.waitMarkerFilePath) : undefined;
    12. ...
    13. // 打开主窗口,默认从执行命令行中读取参数
    14. return windowsMainService.open({
    15. context,
    16. cli: args,
    17. forceNewWindow: args['new-window'] || (!hasCliArgs && args['unity-launch']),
    18. diffMode: args.diff,
    19. noRecentEntry,
    20. waitMarkerFileURI,
    21. gotoLineMode: args.goto,
    22. initialStartup: true
    23. });
    24. }

    vs/code/electron-main/windows.ts

    接下来到了electron的windows窗口,open方法在doOpen中执行窗口配置初始化,最终调用openInBrowserWindow -> 执行doOpenInBrowserWindow是其打开window,主要步骤如下:

    1. private openInBrowserWindow(options: IOpenBrowserWindowOptions): ICodeWindow {
    2. ...
    3. // New window
    4. if (!window) {
    5. //1.判断是否全屏创建窗口
    6. // 2. 创建实例窗口
    7. window = this.instantiationService.createInstance(CodeWindow, {
    8. state,
    9. extensionDevelopmentPath: configuration.extensionDevelopmentPath,
    10. isExtensionTestHost: !!configuration.extensionTestsPath
    11. });
    12. // 3.添加到当前窗口控制器
    13. WindowsManager.WINDOWS.push(window);
    14. // 4.窗口监听器
    15. window.win.webContents.removeAllListeners('devtools-reload-page'); // remove built in listener so we can handle this on our own
    16. window.win.webContents.on('devtools-reload-page', () => this.reload(window!));
    17. window.win.on('unresponsive', () => this.onWindowError(window!, WindowError.UNRESPONSIVE));
    18. window.win.on('closed', () => this.onWindowClosed(window!));
    19. // 5.注册窗口生命周期
    20. (this.lifecycleService as LifecycleService).registerWindow(window);
    21. }
    22. ...
    23. return window;
    24. }

    doOpenInBrowserWindow会调用window.load方法 在window.ts中实现

    main process的使命完成, 主界面进行构建布局。

    在workbench.html中加载了workbench.js, 这里调用return require(‘vs/workbench/electron-browser/desktop.main’).main(configuration);实现对主界面的展示

    vs/workbench/electron-browser/desktop.main.ts

    创建工作区,调用workbench.startup()方法,构建主界面展示布局

    1. ...
    2. async open(): Promise<void> {
    3. const services = await this.initServices();
    4. await domContentLoaded();
    5. mark('willStartWorkbench');
    6. // 1.创建工作区
    7. const workbench = new Workbench(document.body, services.serviceCollection, services.logService);
    8. // 2.监听窗口变化
    9. this._register(addDisposableListener(window, EventType.RESIZE, e => this.onWindowResize(e, true, workbench)));
    10. // 3.工作台生命周期
    11. this._register(workbench.onShutdown(() => this.dispose()));
    12. this._register(workbench.onWillShutdown(event => event.join(services.storageService.close())));
    13. // 3.启动工作区
    14. const instantiationService = workbench.startup();
    15. ...
    16. }
    17. ...

    vs/workbench/browser/workbench.ts

    工作区继承自layout类,主要作用是构建工作区,创建界面布局。

    1. export class Workbench extends Layout {
    2. ...
    3. startup(): IInstantiationService {
    4. try {
    5. ...
    6. // Services
    7. const instantiationService = this.initServices(this.serviceCollection);
    8. instantiationService.invokeFunction(async accessor => {
    9. const lifecycleService = accessor.get(ILifecycleService);
    10. const storageService = accessor.get(IStorageService);
    11. const configurationService = accessor.get(IConfigurationService);
    12. // Layout
    13. this.initLayout(accessor);
    14. // Registries
    15. this.startRegistries(accessor);
    16. // Context Keys
    17. this._register(instantiationService.createInstance(WorkbenchContextKeysHandler));
    18. // 注册监听事件
    19. this.registerListeners(lifecycleService, storageService, configurationService);
    20. // 渲染工作区
    21. this.renderWorkbench(instantiationService, accessor.get(INotificationService) as NotificationService, storageService, configurationService);
    22. // 创建工作区布局
    23. this.createWorkbenchLayout(instantiationService);
    24. // 布局构建
    25. this.layout();
    26. // Restore
    27. try {
    28. await this.restoreWorkbench(accessor.get(IEditorService), accessor.get(IEditorGroupsService), accessor.get(IViewletService), accessor.get(IPanelService), accessor.get(ILogService), lifecycleService);
    29. } catch (error) {
    30. onUnexpectedError(error);
    31. }
    32. });
    33. return instantiationService;
    34. } catch (error) {
    35. onUnexpectedError(error);
    36. throw error; // rethrow because this is a critical issue we cannot handle properly here
    37. }
    38. }
    39. }