Feature/tilemap editor (#237)
* feat: 添加 Tilemap 编辑器插件和组件生命周期支持 * feat(editor-core): 添加声明式插件注册 API * feat(editor-core): 改进tiledmap结构合并tileset进tiledmapeditor * feat: 添加 editor-runtime SDK 和插件系统改进 * fix(ci): 修复SceneResourceManager里变量未使用问题
This commit is contained in:
@@ -3,12 +3,21 @@
|
||||
* 管理Rust引擎生命周期的服务。
|
||||
*/
|
||||
|
||||
import { EngineBridge, EngineRenderSystem, CameraConfig } from '@esengine/ecs-engine-bindgen';
|
||||
import { EngineBridge, EngineRenderSystem, CameraConfig, GizmoDataProviderFn, HasGizmoProviderFn } from '@esengine/ecs-engine-bindgen';
|
||||
import { GizmoRegistry } from '@esengine/editor-core';
|
||||
import { Core, Scene, Entity, SceneSerializer } from '@esengine/ecs-framework';
|
||||
import { TransformComponent, SpriteComponent, SpriteAnimatorSystem, SpriteAnimatorComponent } from '@esengine/ecs-components';
|
||||
import { EntityStoreService, MessageHub } from '@esengine/editor-core';
|
||||
import { TilemapComponent, TilemapRenderingSystem } from '@esengine/tilemap';
|
||||
import { EntityStoreService, MessageHub, SceneManagerService, ProjectService } from '@esengine/editor-core';
|
||||
import * as esEngine from '@esengine/engine';
|
||||
import { AssetManager, EngineIntegration, AssetPathResolver, AssetPlatform } from '@esengine/asset-system';
|
||||
import {
|
||||
AssetManager,
|
||||
EngineIntegration,
|
||||
AssetPathResolver,
|
||||
AssetPlatform,
|
||||
globalPathResolver,
|
||||
SceneResourceManager
|
||||
} from '@esengine/asset-system';
|
||||
import { convertFileSrc } from '@tauri-apps/api/core';
|
||||
import { IdGenerator } from '../utils/idGenerator';
|
||||
|
||||
@@ -23,6 +32,7 @@ export class EngineService {
|
||||
private scene: Scene | null = null;
|
||||
private renderSystem: EngineRenderSystem | null = null;
|
||||
private animatorSystem: SpriteAnimatorSystem | null = null;
|
||||
private tilemapSystem: TilemapRenderingSystem | null = null;
|
||||
private initialized = false;
|
||||
private running = false;
|
||||
private animationFrameId: number | null = null;
|
||||
@@ -30,6 +40,7 @@ export class EngineService {
|
||||
private sceneSnapshot: string | null = null;
|
||||
private assetManager: AssetManager | null = null;
|
||||
private engineIntegration: EngineIntegration | null = null;
|
||||
private sceneResourceManager: SceneResourceManager | null = null;
|
||||
private assetPathResolver: AssetPathResolver | null = null;
|
||||
private assetSystemInitialized = false;
|
||||
private initializationError: Error | null = null;
|
||||
@@ -97,10 +108,28 @@ export class EngineService {
|
||||
this.animatorSystem.enabled = false;
|
||||
this.scene!.addSystem(this.animatorSystem);
|
||||
|
||||
// Add tilemap rendering system
|
||||
// 添加瓦片地图渲染系统
|
||||
this.tilemapSystem = new TilemapRenderingSystem();
|
||||
this.scene!.addSystem(this.tilemapSystem);
|
||||
|
||||
// Add render system to the scene | 将渲染系统添加到场景
|
||||
this.renderSystem = new EngineRenderSystem(this.bridge, TransformComponent);
|
||||
this.scene!.addSystem(this.renderSystem);
|
||||
|
||||
// Register tilemap system as render data provider
|
||||
// 将瓦片地图系统注册为渲染数据提供者
|
||||
this.renderSystem.addRenderDataProvider(this.tilemapSystem);
|
||||
|
||||
// Inject GizmoRegistry into render system
|
||||
// 将 GizmoRegistry 注入渲染系统
|
||||
this.renderSystem.setGizmoRegistry(
|
||||
((component, entity, isSelected) =>
|
||||
GizmoRegistry.getGizmoData(component, entity, isSelected)) as GizmoDataProviderFn,
|
||||
((component) =>
|
||||
GizmoRegistry.hasProvider(component.constructor as any)) as HasGizmoProviderFn
|
||||
);
|
||||
|
||||
// Initialize asset system | 初始化资产系统
|
||||
await this.initializeAssetSystem();
|
||||
|
||||
@@ -349,21 +378,55 @@ export class EngineService {
|
||||
this.assetManager = new AssetManager();
|
||||
|
||||
// 创建路径解析器 / Create path resolver
|
||||
const pathTransformerFn = (path: string) => {
|
||||
// 编辑器平台使用Tauri的convertFileSrc
|
||||
// Use Tauri's convertFileSrc for editor platform
|
||||
if (!path.startsWith('http://') && !path.startsWith('https://') && !path.startsWith('data:') && !path.startsWith('asset://')) {
|
||||
// 如果是相对路径,需要先转换为绝对路径
|
||||
// If it's a relative path, convert to absolute path first
|
||||
if (!path.startsWith('/') && !path.match(/^[a-zA-Z]:/)) {
|
||||
const projectService = Core.services.tryResolve<ProjectService>(ProjectService);
|
||||
if (projectService && projectService.isProjectOpen()) {
|
||||
const projectInfo = projectService.getCurrentProject();
|
||||
if (projectInfo) {
|
||||
const projectPath = projectInfo.path;
|
||||
// 规范化路径分隔符 / Normalize path separators
|
||||
const separator = projectPath.includes('\\') ? '\\' : '/';
|
||||
path = `${projectPath}${separator}${path.replace(/\//g, separator)}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
return convertFileSrc(path);
|
||||
}
|
||||
return path;
|
||||
};
|
||||
|
||||
this.assetPathResolver = new AssetPathResolver({
|
||||
platform: AssetPlatform.Editor,
|
||||
pathTransformer: (path: string) => {
|
||||
// 编辑器平台使用Tauri的convertFileSrc
|
||||
// Use Tauri's convertFileSrc for editor platform
|
||||
if (!path.startsWith('http://') && !path.startsWith('https://') && !path.startsWith('data:')) {
|
||||
return convertFileSrc(path);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
pathTransformer: pathTransformerFn
|
||||
});
|
||||
|
||||
// 配置全局路径解析器,供组件使用
|
||||
// Configure global path resolver for components to use
|
||||
globalPathResolver.updateConfig({
|
||||
platform: AssetPlatform.Editor,
|
||||
pathTransformer: pathTransformerFn
|
||||
});
|
||||
|
||||
// 创建引擎集成 / Create engine integration
|
||||
if (this.bridge) {
|
||||
this.engineIntegration = new EngineIntegration(this.assetManager, this.bridge);
|
||||
|
||||
// 创建场景资源管理器 / Create scene resource manager
|
||||
this.sceneResourceManager = new SceneResourceManager();
|
||||
this.sceneResourceManager.setResourceLoader(this.engineIntegration);
|
||||
|
||||
// 将 SceneResourceManager 设置到 SceneManagerService
|
||||
// Set SceneResourceManager to SceneManagerService
|
||||
const sceneManagerService = Core.services.tryResolve<SceneManagerService>(SceneManagerService);
|
||||
if (sceneManagerService) {
|
||||
sceneManagerService.setSceneResourceManager(this.sceneResourceManager);
|
||||
}
|
||||
}
|
||||
|
||||
this.assetSystemInitialized = true;
|
||||
@@ -625,18 +688,34 @@ export class EngineService {
|
||||
* Restore scene state from saved snapshot.
|
||||
* 从保存的快照恢复场景状态。
|
||||
*/
|
||||
restoreSceneSnapshot(): boolean {
|
||||
async restoreSceneSnapshot(): Promise<boolean> {
|
||||
if (!this.scene || !this.sceneSnapshot) {
|
||||
console.warn('Cannot restore snapshot: no scene or snapshot available');
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
// Clear tilemap rendering cache before restoring
|
||||
// 恢复前清除瓦片地图渲染缓存
|
||||
if (this.tilemapSystem) {
|
||||
console.log('[EngineService] Clearing tilemap cache before restore');
|
||||
this.tilemapSystem.clearCache();
|
||||
}
|
||||
|
||||
// Use SceneSerializer from core library
|
||||
console.log('[EngineService] Deserializing scene snapshot');
|
||||
SceneSerializer.deserialize(this.scene, this.sceneSnapshot, {
|
||||
strategy: 'replace',
|
||||
preserveIds: true
|
||||
});
|
||||
console.log('[EngineService] Scene deserialized, entities:', this.scene.entities.buffer.length);
|
||||
|
||||
// 加载场景资源 / Load scene resources
|
||||
if (this.sceneResourceManager) {
|
||||
await this.sceneResourceManager.loadSceneResources(this.scene);
|
||||
} else {
|
||||
console.warn('[EngineService] SceneResourceManager not available, skipping resource loading');
|
||||
}
|
||||
|
||||
// Sync EntityStore with restored scene entities
|
||||
const entityStore = Core.services.tryResolve(EntityStoreService);
|
||||
@@ -663,6 +742,7 @@ export class EngineService {
|
||||
}
|
||||
|
||||
// Notify UI to refresh
|
||||
console.log('[EngineService] Publishing scene:restored event');
|
||||
messageHub.publish('scene:restored', {});
|
||||
}
|
||||
|
||||
|
||||
73
packages/editor-app/src/services/ImportMapManager.ts
Normal file
73
packages/editor-app/src/services/ImportMapManager.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
interface ImportMap {
|
||||
imports: Record<string, string>;
|
||||
scopes?: Record<string, Record<string, string>>;
|
||||
}
|
||||
|
||||
const SDK_MODULES: Record<string, string> = {
|
||||
'@esengine/editor-runtime': 'editor-runtime.js',
|
||||
'@esengine/behavior-tree': 'behavior-tree.js',
|
||||
};
|
||||
|
||||
class ImportMapManager {
|
||||
private initialized = false;
|
||||
private importMap: ImportMap = { imports: {} };
|
||||
|
||||
async initialize(): Promise<void> {
|
||||
if (this.initialized) {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.buildImportMap();
|
||||
this.injectImportMap();
|
||||
|
||||
this.initialized = true;
|
||||
console.log('[ImportMapManager] Import Map initialized:', this.importMap);
|
||||
}
|
||||
|
||||
private async buildImportMap(): Promise<void> {
|
||||
const baseUrl = this.getBaseUrl();
|
||||
|
||||
for (const [moduleName, fileName] of Object.entries(SDK_MODULES)) {
|
||||
this.importMap.imports[moduleName] = `${baseUrl}assets/${fileName}`;
|
||||
}
|
||||
}
|
||||
|
||||
private getBaseUrl(): string {
|
||||
return window.location.origin + '/';
|
||||
}
|
||||
|
||||
private injectImportMap(): void {
|
||||
const existingMap = document.querySelector('script[type="importmap"]');
|
||||
if (existingMap) {
|
||||
try {
|
||||
const existing = JSON.parse(existingMap.textContent || '{}');
|
||||
this.importMap.imports = { ...existing.imports, ...this.importMap.imports };
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
existingMap.remove();
|
||||
}
|
||||
|
||||
const script = document.createElement('script');
|
||||
script.type = 'importmap';
|
||||
script.textContent = JSON.stringify(this.importMap, null, 2);
|
||||
|
||||
const head = document.head;
|
||||
const firstScript = head.querySelector('script');
|
||||
if (firstScript) {
|
||||
head.insertBefore(script, firstScript);
|
||||
} else {
|
||||
head.appendChild(script);
|
||||
}
|
||||
}
|
||||
|
||||
getImportMap(): ImportMap {
|
||||
return { ...this.importMap };
|
||||
}
|
||||
|
||||
isInitialized(): boolean {
|
||||
return this.initialized;
|
||||
}
|
||||
}
|
||||
|
||||
export const importMapManager = new ImportMapManager();
|
||||
@@ -2,6 +2,7 @@ import { EditorPluginManager, LocaleService, MessageHub } from '@esengine/editor
|
||||
import type { IEditorPlugin } from '@esengine/editor-core';
|
||||
import { Core } from '@esengine/ecs-framework';
|
||||
import { TauriAPI } from '../api/tauri';
|
||||
import { importMapManager } from './ImportMapManager';
|
||||
|
||||
interface PluginPackageJson {
|
||||
name: string;
|
||||
@@ -12,31 +13,41 @@ interface PluginPackageJson {
|
||||
'.': {
|
||||
import?: string;
|
||||
require?: string;
|
||||
development?: {
|
||||
types?: string;
|
||||
import?: string;
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 插件加载器
|
||||
*
|
||||
* 负责从项目的 plugins 目录加载用户插件。
|
||||
* 统一使用 project:// 协议加载预编译的 JS 文件。
|
||||
*/
|
||||
export class PluginLoader {
|
||||
private loadedPluginNames: Set<string> = new Set();
|
||||
private moduleVersions: Map<string, number> = new Map();
|
||||
private loadedModuleUrls: Set<string> = new Set();
|
||||
|
||||
/**
|
||||
* 加载项目中的所有插件
|
||||
*/
|
||||
async loadProjectPlugins(projectPath: string, pluginManager: EditorPluginManager): Promise<void> {
|
||||
// 确保 Import Map 已初始化
|
||||
await importMapManager.initialize();
|
||||
|
||||
const pluginsPath = `${projectPath}/plugins`;
|
||||
|
||||
try {
|
||||
const exists = await TauriAPI.pathExists(pluginsPath);
|
||||
if (!exists) {
|
||||
console.log('[PluginLoader] No plugins directory found');
|
||||
return;
|
||||
}
|
||||
|
||||
const entries = await TauriAPI.listDirectory(pluginsPath);
|
||||
const pluginDirs = entries.filter((entry) => entry.is_dir && !entry.name.startsWith('.'));
|
||||
|
||||
console.log(`[PluginLoader] Found ${pluginDirs.length} plugin(s)`);
|
||||
|
||||
for (const entry of pluginDirs) {
|
||||
const pluginPath = `${pluginsPath}/${entry.name}`;
|
||||
await this.loadPlugin(pluginPath, entry.name, pluginManager);
|
||||
@@ -46,114 +57,130 @@ export class PluginLoader {
|
||||
}
|
||||
}
|
||||
|
||||
private async loadPlugin(pluginPath: string, pluginDirName: string, pluginManager: EditorPluginManager): Promise<void> {
|
||||
/**
|
||||
* 加载单个插件
|
||||
*/
|
||||
private async loadPlugin(
|
||||
pluginPath: string,
|
||||
pluginDirName: string,
|
||||
pluginManager: EditorPluginManager
|
||||
): Promise<void> {
|
||||
try {
|
||||
const packageJsonPath = `${pluginPath}/package.json`;
|
||||
const packageJsonExists = await TauriAPI.pathExists(packageJsonPath);
|
||||
|
||||
if (!packageJsonExists) {
|
||||
console.warn(`[PluginLoader] No package.json found in ${pluginPath}`);
|
||||
// 1. 读取 package.json
|
||||
const packageJson = await this.readPackageJson(pluginPath);
|
||||
if (!packageJson) {
|
||||
return;
|
||||
}
|
||||
|
||||
const packageJsonContent = await TauriAPI.readFileContent(packageJsonPath);
|
||||
const packageJson: PluginPackageJson = JSON.parse(packageJsonContent);
|
||||
|
||||
// 2. 如果插件已加载,先卸载
|
||||
if (this.loadedPluginNames.has(packageJson.name)) {
|
||||
try {
|
||||
await pluginManager.uninstallEditor(packageJson.name);
|
||||
this.loadedPluginNames.delete(packageJson.name);
|
||||
} catch (error) {
|
||||
console.error(`[PluginLoader] Failed to uninstall existing plugin ${packageJson.name}:`, error);
|
||||
}
|
||||
await this.unloadPlugin(packageJson.name, pluginManager);
|
||||
}
|
||||
|
||||
let entryPoint = 'src/index.ts';
|
||||
// 3. 确定入口文件(必须是编译后的 JS)
|
||||
const entryPoint = this.resolveEntryPoint(packageJson);
|
||||
|
||||
if (packageJson.exports?.['.']?.development?.import) {
|
||||
entryPoint = packageJson.exports['.'].development.import;
|
||||
} else if (packageJson.exports?.['.']?.import) {
|
||||
const importPath = packageJson.exports['.'].import;
|
||||
if (importPath.startsWith('src/')) {
|
||||
entryPoint = importPath;
|
||||
} else {
|
||||
const srcPath = importPath.replace('dist/', 'src/').replace('.js', '.ts');
|
||||
const srcExists = await TauriAPI.pathExists(`${pluginPath}/${srcPath}`);
|
||||
entryPoint = srcExists ? srcPath : importPath;
|
||||
}
|
||||
} else if (packageJson.module) {
|
||||
const srcPath = packageJson.module.replace('dist/', 'src/').replace('.js', '.ts');
|
||||
const srcExists = await TauriAPI.pathExists(`${pluginPath}/${srcPath}`);
|
||||
entryPoint = srcExists ? srcPath : packageJson.module;
|
||||
} else if (packageJson.main) {
|
||||
const srcPath = packageJson.main.replace('dist/', 'src/').replace('.js', '.ts');
|
||||
const srcExists = await TauriAPI.pathExists(`${pluginPath}/${srcPath}`);
|
||||
entryPoint = srcExists ? srcPath : packageJson.main;
|
||||
// 4. 验证文件存在
|
||||
const fullPath = `${pluginPath}/${entryPoint}`;
|
||||
const exists = await TauriAPI.pathExists(fullPath);
|
||||
if (!exists) {
|
||||
console.error(`[PluginLoader] Plugin not built: ${fullPath}`);
|
||||
console.error(`[PluginLoader] Run: cd ${pluginPath} && npm run build`);
|
||||
return;
|
||||
}
|
||||
|
||||
// 移除开头的 ./
|
||||
entryPoint = entryPoint.replace(/^\.\//, '');
|
||||
|
||||
// 使用版本号+时间戳确保每次加载都是唯一URL
|
||||
const currentVersion = (this.moduleVersions.get(packageJson.name) || 0) + 1;
|
||||
this.moduleVersions.set(packageJson.name, currentVersion);
|
||||
const timestamp = Date.now();
|
||||
const moduleUrl = `/@user-project/plugins/${pluginDirName}/${entryPoint}?v=${currentVersion}&t=${timestamp}`;
|
||||
|
||||
// 清除可能存在的旧模块缓存
|
||||
this.loadedModuleUrls.add(moduleUrl);
|
||||
// 5. 构建模块 URL(使用 project:// 协议)
|
||||
const moduleUrl = this.buildModuleUrl(pluginDirName, entryPoint, packageJson.name);
|
||||
console.log(`[PluginLoader] Loading: ${packageJson.name} from ${moduleUrl}`);
|
||||
|
||||
// 6. 动态导入模块
|
||||
const module = await import(/* @vite-ignore */ moduleUrl);
|
||||
|
||||
let pluginInstance: IEditorPlugin | null = null;
|
||||
try {
|
||||
pluginInstance = this.findPluginInstance(module);
|
||||
} catch (findError) {
|
||||
console.error('[PluginLoader] Error finding plugin instance:', findError);
|
||||
console.error('[PluginLoader] Module object:', module);
|
||||
return;
|
||||
}
|
||||
|
||||
// 7. 查找并验证插件实例
|
||||
const pluginInstance = this.findPluginInstance(module);
|
||||
if (!pluginInstance) {
|
||||
console.error(`[PluginLoader] No plugin instance found in ${packageJson.name}`);
|
||||
console.error(`[PluginLoader] No valid plugin instance found in ${packageJson.name}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// 8. 安装插件
|
||||
await pluginManager.installEditor(pluginInstance);
|
||||
this.loadedPluginNames.add(packageJson.name);
|
||||
console.log(`[PluginLoader] Successfully loaded: ${packageJson.name}`);
|
||||
|
||||
// 同步插件的语言设置
|
||||
try {
|
||||
const localeService = Core.services.resolve(LocaleService);
|
||||
const currentLocale = localeService.getCurrentLocale();
|
||||
if (pluginInstance.setLocale) {
|
||||
pluginInstance.setLocale(currentLocale);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`[PluginLoader] Failed to set locale for plugin ${packageJson.name}:`, error);
|
||||
}
|
||||
// 9. 同步语言设置
|
||||
this.syncPluginLocale(pluginInstance, packageJson.name);
|
||||
|
||||
// 通知节点面板重新加载模板
|
||||
try {
|
||||
const messageHub = Core.services.resolve(MessageHub);
|
||||
const localeService = Core.services.resolve(LocaleService);
|
||||
messageHub.publish('locale:changed', { locale: localeService.getCurrentLocale() });
|
||||
} catch (error) {
|
||||
console.warn('[PluginLoader] Failed to publish locale:changed event:', error);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`[PluginLoader] Failed to load plugin from ${pluginPath}:`, error);
|
||||
if (error instanceof Error) {
|
||||
console.error('[PluginLoader] Error stack:', error.stack);
|
||||
console.error('[PluginLoader] Stack:', error.stack);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取插件的 package.json
|
||||
*/
|
||||
private async readPackageJson(pluginPath: string): Promise<PluginPackageJson | null> {
|
||||
const packageJsonPath = `${pluginPath}/package.json`;
|
||||
const exists = await TauriAPI.pathExists(packageJsonPath);
|
||||
|
||||
if (!exists) {
|
||||
console.warn(`[PluginLoader] No package.json found in ${pluginPath}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
const content = await TauriAPI.readFileContent(packageJsonPath);
|
||||
return JSON.parse(content);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析插件入口文件路径(始终使用编译后的 JS)
|
||||
*/
|
||||
private resolveEntryPoint(packageJson: PluginPackageJson): string {
|
||||
const entry = (
|
||||
packageJson.exports?.['.']?.import ||
|
||||
packageJson.module ||
|
||||
packageJson.main ||
|
||||
'dist/index.js'
|
||||
);
|
||||
return entry.replace(/^\.\//, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建模块 URL(使用 project:// 协议)
|
||||
*
|
||||
* Windows 上需要用 http://project.localhost/ 格式
|
||||
* macOS/Linux 上用 project://localhost/ 格式
|
||||
*/
|
||||
private buildModuleUrl(pluginDirName: string, entryPoint: string, pluginName: string): string {
|
||||
// 版本号 + 时间戳确保每次加载都是新模块(绕过浏览器缓存)
|
||||
const version = (this.moduleVersions.get(pluginName) || 0) + 1;
|
||||
this.moduleVersions.set(pluginName, version);
|
||||
const timestamp = Date.now();
|
||||
|
||||
const path = `/plugins/${pluginDirName}/${entryPoint}?v=${version}&t=${timestamp}`;
|
||||
|
||||
// Windows 使用 http://scheme.localhost 格式
|
||||
// macOS/Linux 使用 scheme://localhost 格式
|
||||
const isWindows = navigator.userAgent.includes('Windows');
|
||||
if (isWindows) {
|
||||
return `http://project.localhost${path}`;
|
||||
}
|
||||
return `project://localhost${path}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找模块中的插件实例
|
||||
*/
|
||||
private findPluginInstance(module: any): IEditorPlugin | null {
|
||||
// 优先检查 default 导出
|
||||
if (module.default && this.isPluginInstance(module.default)) {
|
||||
return module.default;
|
||||
}
|
||||
|
||||
// 检查命名导出
|
||||
for (const key of Object.keys(module)) {
|
||||
const value = module[key];
|
||||
if (value && this.isPluginInstance(value)) {
|
||||
@@ -161,69 +188,74 @@ export class PluginLoader {
|
||||
}
|
||||
}
|
||||
|
||||
console.error('[PluginLoader] No valid plugin instance found. Exports:', module);
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证对象是否为有效的插件实例
|
||||
*/
|
||||
private isPluginInstance(obj: any): obj is IEditorPlugin {
|
||||
try {
|
||||
if (!obj || typeof obj !== 'object') {
|
||||
return false;
|
||||
}
|
||||
|
||||
const hasRequiredProperties =
|
||||
typeof obj.name === 'string' &&
|
||||
typeof obj.version === 'string' &&
|
||||
typeof obj.displayName === 'string' &&
|
||||
typeof obj.category === 'string' &&
|
||||
typeof obj.install === 'function' &&
|
||||
typeof obj.uninstall === 'function';
|
||||
|
||||
return hasRequiredProperties;
|
||||
} catch (error) {
|
||||
console.error('[PluginLoader] Error in isPluginInstance:', error);
|
||||
if (!obj || typeof obj !== 'object') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (
|
||||
typeof obj.name === 'string' &&
|
||||
typeof obj.version === 'string' &&
|
||||
typeof obj.displayName === 'string' &&
|
||||
typeof obj.category === 'string' &&
|
||||
typeof obj.install === 'function' &&
|
||||
typeof obj.uninstall === 'function'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步插件语言设置
|
||||
*/
|
||||
private syncPluginLocale(plugin: IEditorPlugin, pluginName: string): void {
|
||||
try {
|
||||
const localeService = Core.services.resolve(LocaleService);
|
||||
const currentLocale = localeService.getCurrentLocale();
|
||||
|
||||
if (plugin.setLocale) {
|
||||
plugin.setLocale(currentLocale);
|
||||
}
|
||||
|
||||
// 通知 UI 刷新
|
||||
const messageHub = Core.services.resolve(MessageHub);
|
||||
messageHub.publish('locale:changed', { locale: currentLocale });
|
||||
} catch (error) {
|
||||
console.warn(`[PluginLoader] Failed to sync locale for ${pluginName}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 卸载单个插件
|
||||
*/
|
||||
private async unloadPlugin(pluginName: string, pluginManager: EditorPluginManager): Promise<void> {
|
||||
try {
|
||||
await pluginManager.uninstallEditor(pluginName);
|
||||
this.loadedPluginNames.delete(pluginName);
|
||||
console.log(`[PluginLoader] Unloaded: ${pluginName}`);
|
||||
} catch (error) {
|
||||
console.error(`[PluginLoader] Failed to unload ${pluginName}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 卸载所有已加载的插件
|
||||
*/
|
||||
async unloadProjectPlugins(pluginManager: EditorPluginManager): Promise<void> {
|
||||
for (const pluginName of this.loadedPluginNames) {
|
||||
try {
|
||||
await pluginManager.uninstallEditor(pluginName);
|
||||
} catch (error) {
|
||||
console.error(`[PluginLoader] Failed to unload plugin ${pluginName}:`, error);
|
||||
}
|
||||
await this.unloadPlugin(pluginName, pluginManager);
|
||||
}
|
||||
|
||||
// 清除Vite模块缓存(如果HMR可用)
|
||||
this.invalidateModuleCache();
|
||||
|
||||
this.loadedPluginNames.clear();
|
||||
this.loadedModuleUrls.clear();
|
||||
}
|
||||
|
||||
private invalidateModuleCache(): void {
|
||||
try {
|
||||
// 尝试使用Vite HMR API无效化模块
|
||||
if (import.meta.hot) {
|
||||
import.meta.hot.invalidate();
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('[PluginLoader] Failed to invalidate module cache:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取已加载的插件名称列表
|
||||
*/
|
||||
getLoadedPluginNames(): string[] {
|
||||
return Array.from(this.loadedPluginNames);
|
||||
}
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface ImportMeta {
|
||||
hot?: {
|
||||
invalidate(): void;
|
||||
accept(callback?: () => void): void;
|
||||
dispose(callback: () => void): void;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,6 +21,10 @@ export class TauriDialogService implements IDialogExtended {
|
||||
private showConfirmCallback?: (data: ConfirmDialogData) => void;
|
||||
private locale: string = 'zh';
|
||||
|
||||
dispose(): void {
|
||||
this.showConfirmCallback = undefined;
|
||||
}
|
||||
|
||||
setConfirmCallback(callback: (data: ConfirmDialogData) => void): void {
|
||||
this.showConfirmCallback = callback;
|
||||
}
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
import { singleton } from 'tsyringe';
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
import { invoke, convertFileSrc } from '@tauri-apps/api/core';
|
||||
import type { IFileSystem, FileEntry } from '@esengine/editor-core';
|
||||
|
||||
@singleton()
|
||||
export class TauriFileSystemService implements IFileSystem {
|
||||
dispose(): void {
|
||||
// No cleanup needed
|
||||
}
|
||||
|
||||
async readFile(path: string): Promise<string> {
|
||||
return await invoke<string>('read_file_content', { path });
|
||||
}
|
||||
@@ -49,4 +53,8 @@ export class TauriFileSystemService implements IFileSystem {
|
||||
async scanFiles(basePath: string, pattern: string): Promise<string[]> {
|
||||
return await invoke<string[]>('scan_files', { basePath, pattern });
|
||||
}
|
||||
|
||||
convertToAssetUrl(filePath: string): string {
|
||||
return convertFileSrc(filePath);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user