diff --git a/package-lock.json b/package-lock.json index d1660d9d..72aed70c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -6031,6 +6031,15 @@ "node": ">= 10" } }, + "node_modules/@tauri-apps/plugin-dialog": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@tauri-apps/plugin-dialog/-/plugin-dialog-2.4.0.tgz", + "integrity": "sha512-OvXkrEBfWwtd8tzVCEXIvRfNEX87qs2jv6SqmVPiHcJjBhSF/GUvjqUNIDmKByb5N8nvDqVUM7+g1sXwdC/S9w==", + "license": "MIT OR Apache-2.0", + "dependencies": { + "@tauri-apps/api": "^2.8.0" + } + }, "node_modules/@tauri-apps/plugin-shell": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/@tauri-apps/plugin-shell/-/plugin-shell-2.3.1.tgz", @@ -17669,6 +17678,7 @@ "@esengine/ecs-framework": "file:../core", "@esengine/editor-core": "file:../editor-core", "@tauri-apps/api": "^2.2.0", + "@tauri-apps/plugin-dialog": "^2.4.0", "@tauri-apps/plugin-shell": "^2.0.0", "json5": "^2.2.3", "lucide-react": "^0.545.0", diff --git a/packages/editor-app/package.json b/packages/editor-app/package.json index 2350acc5..bf337ee2 100644 --- a/packages/editor-app/package.json +++ b/packages/editor-app/package.json @@ -17,6 +17,7 @@ "@esengine/ecs-framework": "file:../core", "@esengine/editor-core": "file:../editor-core", "@tauri-apps/api": "^2.2.0", + "@tauri-apps/plugin-dialog": "^2.4.0", "@tauri-apps/plugin-shell": "^2.0.0", "json5": "^2.2.3", "lucide-react": "^0.545.0", diff --git a/packages/editor-app/src-tauri/icons/128x128.png b/packages/editor-app/src-tauri/icons/128x128.png index 8c6b3f7d..af01ecee 100644 Binary files a/packages/editor-app/src-tauri/icons/128x128.png and b/packages/editor-app/src-tauri/icons/128x128.png differ diff --git a/packages/editor-app/src-tauri/icons/128x128@2x.png b/packages/editor-app/src-tauri/icons/128x128@2x.png index cbb08a6b..7aa32e02 100644 Binary files a/packages/editor-app/src-tauri/icons/128x128@2x.png and b/packages/editor-app/src-tauri/icons/128x128@2x.png differ diff --git a/packages/editor-app/src-tauri/icons/32x32.png b/packages/editor-app/src-tauri/icons/32x32.png index cff567a2..9bd71620 100644 Binary files a/packages/editor-app/src-tauri/icons/32x32.png and b/packages/editor-app/src-tauri/icons/32x32.png differ diff --git a/packages/editor-app/src-tauri/icons/64x64.png b/packages/editor-app/src-tauri/icons/64x64.png new file mode 100644 index 00000000..943987ad Binary files /dev/null and b/packages/editor-app/src-tauri/icons/64x64.png differ diff --git a/packages/editor-app/src-tauri/icons/Square107x107Logo.png b/packages/editor-app/src-tauri/icons/Square107x107Logo.png new file mode 100644 index 00000000..a12266e6 Binary files /dev/null and b/packages/editor-app/src-tauri/icons/Square107x107Logo.png differ diff --git a/packages/editor-app/src-tauri/icons/Square142x142Logo.png b/packages/editor-app/src-tauri/icons/Square142x142Logo.png new file mode 100644 index 00000000..abbd010d Binary files /dev/null and b/packages/editor-app/src-tauri/icons/Square142x142Logo.png differ diff --git a/packages/editor-app/src-tauri/icons/Square150x150Logo.png b/packages/editor-app/src-tauri/icons/Square150x150Logo.png new file mode 100644 index 00000000..876efba6 Binary files /dev/null and b/packages/editor-app/src-tauri/icons/Square150x150Logo.png differ diff --git a/packages/editor-app/src-tauri/icons/Square284x284Logo.png b/packages/editor-app/src-tauri/icons/Square284x284Logo.png new file mode 100644 index 00000000..940d5352 Binary files /dev/null and b/packages/editor-app/src-tauri/icons/Square284x284Logo.png differ diff --git a/packages/editor-app/src-tauri/icons/Square30x30Logo.png b/packages/editor-app/src-tauri/icons/Square30x30Logo.png new file mode 100644 index 00000000..776127fb Binary files /dev/null and b/packages/editor-app/src-tauri/icons/Square30x30Logo.png differ diff --git a/packages/editor-app/src-tauri/icons/Square310x310Logo.png b/packages/editor-app/src-tauri/icons/Square310x310Logo.png new file mode 100644 index 00000000..442e7066 Binary files /dev/null and b/packages/editor-app/src-tauri/icons/Square310x310Logo.png differ diff --git a/packages/editor-app/src-tauri/icons/Square44x44Logo.png b/packages/editor-app/src-tauri/icons/Square44x44Logo.png new file mode 100644 index 00000000..8f5fb33c Binary files /dev/null and b/packages/editor-app/src-tauri/icons/Square44x44Logo.png differ diff --git a/packages/editor-app/src-tauri/icons/Square71x71Logo.png b/packages/editor-app/src-tauri/icons/Square71x71Logo.png new file mode 100644 index 00000000..21d46aa8 Binary files /dev/null and b/packages/editor-app/src-tauri/icons/Square71x71Logo.png differ diff --git a/packages/editor-app/src-tauri/icons/Square89x89Logo.png b/packages/editor-app/src-tauri/icons/Square89x89Logo.png new file mode 100644 index 00000000..426e981e Binary files /dev/null and b/packages/editor-app/src-tauri/icons/Square89x89Logo.png differ diff --git a/packages/editor-app/src-tauri/icons/StoreLogo.png b/packages/editor-app/src-tauri/icons/StoreLogo.png new file mode 100644 index 00000000..54b69403 Binary files /dev/null and b/packages/editor-app/src-tauri/icons/StoreLogo.png differ diff --git a/packages/editor-app/src-tauri/icons/android/mipmap-hdpi/ic_launcher.png b/packages/editor-app/src-tauri/icons/android/mipmap-hdpi/ic_launcher.png new file mode 100644 index 00000000..5711d505 Binary files /dev/null and b/packages/editor-app/src-tauri/icons/android/mipmap-hdpi/ic_launcher.png differ diff --git a/packages/editor-app/src-tauri/icons/android/mipmap-hdpi/ic_launcher_foreground.png b/packages/editor-app/src-tauri/icons/android/mipmap-hdpi/ic_launcher_foreground.png new file mode 100644 index 00000000..988fd001 Binary files /dev/null and b/packages/editor-app/src-tauri/icons/android/mipmap-hdpi/ic_launcher_foreground.png differ diff --git a/packages/editor-app/src-tauri/icons/android/mipmap-hdpi/ic_launcher_round.png b/packages/editor-app/src-tauri/icons/android/mipmap-hdpi/ic_launcher_round.png new file mode 100644 index 00000000..5711d505 Binary files /dev/null and b/packages/editor-app/src-tauri/icons/android/mipmap-hdpi/ic_launcher_round.png differ diff --git a/packages/editor-app/src-tauri/icons/android/mipmap-mdpi/ic_launcher.png b/packages/editor-app/src-tauri/icons/android/mipmap-mdpi/ic_launcher.png new file mode 100644 index 00000000..298ff05a Binary files /dev/null and b/packages/editor-app/src-tauri/icons/android/mipmap-mdpi/ic_launcher.png differ diff --git a/packages/editor-app/src-tauri/icons/android/mipmap-mdpi/ic_launcher_foreground.png b/packages/editor-app/src-tauri/icons/android/mipmap-mdpi/ic_launcher_foreground.png new file mode 100644 index 00000000..6158a80a Binary files /dev/null and b/packages/editor-app/src-tauri/icons/android/mipmap-mdpi/ic_launcher_foreground.png differ diff --git a/packages/editor-app/src-tauri/icons/android/mipmap-mdpi/ic_launcher_round.png b/packages/editor-app/src-tauri/icons/android/mipmap-mdpi/ic_launcher_round.png new file mode 100644 index 00000000..298ff05a Binary files /dev/null and b/packages/editor-app/src-tauri/icons/android/mipmap-mdpi/ic_launcher_round.png differ diff --git a/packages/editor-app/src-tauri/icons/android/mipmap-xhdpi/ic_launcher.png b/packages/editor-app/src-tauri/icons/android/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 00000000..79d398e4 Binary files /dev/null and b/packages/editor-app/src-tauri/icons/android/mipmap-xhdpi/ic_launcher.png differ diff --git a/packages/editor-app/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_foreground.png b/packages/editor-app/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_foreground.png new file mode 100644 index 00000000..2a008518 Binary files /dev/null and b/packages/editor-app/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_foreground.png differ diff --git a/packages/editor-app/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_round.png b/packages/editor-app/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_round.png new file mode 100644 index 00000000..79d398e4 Binary files /dev/null and b/packages/editor-app/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_round.png differ diff --git a/packages/editor-app/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher.png b/packages/editor-app/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 00000000..2268c7e2 Binary files /dev/null and b/packages/editor-app/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher.png differ diff --git a/packages/editor-app/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_foreground.png b/packages/editor-app/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_foreground.png new file mode 100644 index 00000000..f55c0538 Binary files /dev/null and b/packages/editor-app/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_foreground.png differ diff --git a/packages/editor-app/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_round.png b/packages/editor-app/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_round.png new file mode 100644 index 00000000..2268c7e2 Binary files /dev/null and b/packages/editor-app/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_round.png differ diff --git a/packages/editor-app/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher.png b/packages/editor-app/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 00000000..d588ebe6 Binary files /dev/null and b/packages/editor-app/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/packages/editor-app/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_foreground.png b/packages/editor-app/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_foreground.png new file mode 100644 index 00000000..76591991 Binary files /dev/null and b/packages/editor-app/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_foreground.png differ diff --git a/packages/editor-app/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_round.png b/packages/editor-app/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_round.png new file mode 100644 index 00000000..d588ebe6 Binary files /dev/null and b/packages/editor-app/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_round.png differ diff --git a/packages/editor-app/src-tauri/icons/icon.icns b/packages/editor-app/src-tauri/icons/icon.icns new file mode 100644 index 00000000..c07f4991 Binary files /dev/null and b/packages/editor-app/src-tauri/icons/icon.icns differ diff --git a/packages/editor-app/src-tauri/icons/icon.ico b/packages/editor-app/src-tauri/icons/icon.ico index 5511df84..8587ee9f 100644 Binary files a/packages/editor-app/src-tauri/icons/icon.ico and b/packages/editor-app/src-tauri/icons/icon.ico differ diff --git a/packages/editor-app/src-tauri/icons/icon.png b/packages/editor-app/src-tauri/icons/icon.png index 9a0b2558..db4212fe 100644 Binary files a/packages/editor-app/src-tauri/icons/icon.png and b/packages/editor-app/src-tauri/icons/icon.png differ diff --git a/packages/editor-app/src-tauri/icons/ios/AppIcon-20x20@1x.png b/packages/editor-app/src-tauri/icons/ios/AppIcon-20x20@1x.png new file mode 100644 index 00000000..11f3ca49 Binary files /dev/null and b/packages/editor-app/src-tauri/icons/ios/AppIcon-20x20@1x.png differ diff --git a/packages/editor-app/src-tauri/icons/ios/AppIcon-20x20@2x-1.png b/packages/editor-app/src-tauri/icons/ios/AppIcon-20x20@2x-1.png new file mode 100644 index 00000000..47c1145a Binary files /dev/null and b/packages/editor-app/src-tauri/icons/ios/AppIcon-20x20@2x-1.png differ diff --git a/packages/editor-app/src-tauri/icons/ios/AppIcon-20x20@2x.png b/packages/editor-app/src-tauri/icons/ios/AppIcon-20x20@2x.png new file mode 100644 index 00000000..47c1145a Binary files /dev/null and b/packages/editor-app/src-tauri/icons/ios/AppIcon-20x20@2x.png differ diff --git a/packages/editor-app/src-tauri/icons/ios/AppIcon-20x20@3x.png b/packages/editor-app/src-tauri/icons/ios/AppIcon-20x20@3x.png new file mode 100644 index 00000000..7932fa3e Binary files /dev/null and b/packages/editor-app/src-tauri/icons/ios/AppIcon-20x20@3x.png differ diff --git a/packages/editor-app/src-tauri/icons/ios/AppIcon-29x29@1x.png b/packages/editor-app/src-tauri/icons/ios/AppIcon-29x29@1x.png new file mode 100644 index 00000000..2e2cbaab Binary files /dev/null and b/packages/editor-app/src-tauri/icons/ios/AppIcon-29x29@1x.png differ diff --git a/packages/editor-app/src-tauri/icons/ios/AppIcon-29x29@2x-1.png b/packages/editor-app/src-tauri/icons/ios/AppIcon-29x29@2x-1.png new file mode 100644 index 00000000..b1179cbc Binary files /dev/null and b/packages/editor-app/src-tauri/icons/ios/AppIcon-29x29@2x-1.png differ diff --git a/packages/editor-app/src-tauri/icons/ios/AppIcon-29x29@2x.png b/packages/editor-app/src-tauri/icons/ios/AppIcon-29x29@2x.png new file mode 100644 index 00000000..b1179cbc Binary files /dev/null and b/packages/editor-app/src-tauri/icons/ios/AppIcon-29x29@2x.png differ diff --git a/packages/editor-app/src-tauri/icons/ios/AppIcon-29x29@3x.png b/packages/editor-app/src-tauri/icons/ios/AppIcon-29x29@3x.png new file mode 100644 index 00000000..28acd15d Binary files /dev/null and b/packages/editor-app/src-tauri/icons/ios/AppIcon-29x29@3x.png differ diff --git a/packages/editor-app/src-tauri/icons/ios/AppIcon-40x40@1x.png b/packages/editor-app/src-tauri/icons/ios/AppIcon-40x40@1x.png new file mode 100644 index 00000000..47c1145a Binary files /dev/null and b/packages/editor-app/src-tauri/icons/ios/AppIcon-40x40@1x.png differ diff --git a/packages/editor-app/src-tauri/icons/ios/AppIcon-40x40@2x-1.png b/packages/editor-app/src-tauri/icons/ios/AppIcon-40x40@2x-1.png new file mode 100644 index 00000000..7a72796e Binary files /dev/null and b/packages/editor-app/src-tauri/icons/ios/AppIcon-40x40@2x-1.png differ diff --git a/packages/editor-app/src-tauri/icons/ios/AppIcon-40x40@2x.png b/packages/editor-app/src-tauri/icons/ios/AppIcon-40x40@2x.png new file mode 100644 index 00000000..7a72796e Binary files /dev/null and b/packages/editor-app/src-tauri/icons/ios/AppIcon-40x40@2x.png differ diff --git a/packages/editor-app/src-tauri/icons/ios/AppIcon-40x40@3x.png b/packages/editor-app/src-tauri/icons/ios/AppIcon-40x40@3x.png new file mode 100644 index 00000000..6e09eadd Binary files /dev/null and b/packages/editor-app/src-tauri/icons/ios/AppIcon-40x40@3x.png differ diff --git a/packages/editor-app/src-tauri/icons/ios/AppIcon-512@2x.png b/packages/editor-app/src-tauri/icons/ios/AppIcon-512@2x.png new file mode 100644 index 00000000..c98fd6c6 Binary files /dev/null and b/packages/editor-app/src-tauri/icons/ios/AppIcon-512@2x.png differ diff --git a/packages/editor-app/src-tauri/icons/ios/AppIcon-60x60@2x.png b/packages/editor-app/src-tauri/icons/ios/AppIcon-60x60@2x.png new file mode 100644 index 00000000..6e09eadd Binary files /dev/null and b/packages/editor-app/src-tauri/icons/ios/AppIcon-60x60@2x.png differ diff --git a/packages/editor-app/src-tauri/icons/ios/AppIcon-60x60@3x.png b/packages/editor-app/src-tauri/icons/ios/AppIcon-60x60@3x.png new file mode 100644 index 00000000..63ee56d5 Binary files /dev/null and b/packages/editor-app/src-tauri/icons/ios/AppIcon-60x60@3x.png differ diff --git a/packages/editor-app/src-tauri/icons/ios/AppIcon-76x76@1x.png b/packages/editor-app/src-tauri/icons/ios/AppIcon-76x76@1x.png new file mode 100644 index 00000000..2773b130 Binary files /dev/null and b/packages/editor-app/src-tauri/icons/ios/AppIcon-76x76@1x.png differ diff --git a/packages/editor-app/src-tauri/icons/ios/AppIcon-76x76@2x.png b/packages/editor-app/src-tauri/icons/ios/AppIcon-76x76@2x.png new file mode 100644 index 00000000..82f51a70 Binary files /dev/null and b/packages/editor-app/src-tauri/icons/ios/AppIcon-76x76@2x.png differ diff --git a/packages/editor-app/src-tauri/icons/ios/AppIcon-83.5x83.5@2x.png b/packages/editor-app/src-tauri/icons/ios/AppIcon-83.5x83.5@2x.png new file mode 100644 index 00000000..1f5a2857 Binary files /dev/null and b/packages/editor-app/src-tauri/icons/ios/AppIcon-83.5x83.5@2x.png differ diff --git a/packages/editor-app/src-tauri/src/main.rs b/packages/editor-app/src-tauri/src/main.rs index 25cb067e..34e7e7e1 100644 --- a/packages/editor-app/src-tauri/src/main.rs +++ b/packages/editor-app/src-tauri/src/main.rs @@ -34,6 +34,26 @@ fn export_binary(data: Vec, output_path: String) -> Result<(), String> { Ok(()) } +#[tauri::command] +fn create_directory(path: String) -> Result<(), String> { + std::fs::create_dir_all(&path) + .map_err(|e| format!("Failed to create directory: {}", e))?; + Ok(()) +} + +#[tauri::command] +fn write_file_content(path: String, content: String) -> Result<(), String> { + std::fs::write(&path, content) + .map_err(|e| format!("Failed to write file: {}", e))?; + Ok(()) +} + +#[tauri::command] +fn path_exists(path: String) -> Result { + use std::path::Path; + Ok(Path::new(&path).exists()) +} + #[tauri::command] async fn open_project_dialog(app: AppHandle) -> Result, String> { use tauri_plugin_dialog::DialogExt; @@ -46,6 +66,37 @@ async fn open_project_dialog(app: AppHandle) -> Result, String> { Ok(folder.map(|path| path.to_string())) } +#[tauri::command] +async fn save_scene_dialog(app: AppHandle, default_name: Option) -> Result, String> { + use tauri_plugin_dialog::DialogExt; + + let mut dialog = app.dialog() + .file() + .set_title("Save ECS Scene") + .add_filter("ECS Scene Files", &["ecs"]); + + if let Some(name) = default_name { + dialog = dialog.set_file_name(&name); + } + + let file = dialog.blocking_save_file(); + + Ok(file.map(|path| path.to_string())) +} + +#[tauri::command] +async fn open_scene_dialog(app: AppHandle) -> Result, String> { + use tauri_plugin_dialog::DialogExt; + + let file = app.dialog() + .file() + .set_title("Open ECS Scene") + .add_filter("ECS Scene Files", &["ecs"]) + .blocking_pick_file(); + + Ok(file.map(|path| path.to_string())) +} + #[tauri::command] fn scan_directory(path: String, pattern: String) -> Result, String> { use glob::glob; @@ -300,7 +351,12 @@ fn main() { open_project, save_project, export_binary, + create_directory, + write_file_content, + path_exists, open_project_dialog, + save_scene_dialog, + open_scene_dialog, scan_directory, read_file_content, list_directory, diff --git a/packages/editor-app/src/App.tsx b/packages/editor-app/src/App.tsx index 09b58363..0e5ebf9e 100644 --- a/packages/editor-app/src/App.tsx +++ b/packages/editor-app/src/App.tsx @@ -1,6 +1,6 @@ -import { useState, useEffect, useRef } from 'react'; +import { useState, useEffect, useRef, useCallback } from 'react'; import { Core, Scene } from '@esengine/ecs-framework'; -import { EditorPluginManager, UIRegistry, MessageHub, SerializerRegistry, EntityStoreService, ComponentRegistry, LocaleService, ProjectService, ComponentDiscoveryService, ComponentLoaderService, PropertyMetadataService, LogService, SettingsRegistry } from '@esengine/editor-core'; +import { EditorPluginManager, UIRegistry, MessageHub, SerializerRegistry, EntityStoreService, ComponentRegistry, LocaleService, ProjectService, ComponentDiscoveryService, PropertyMetadataService, LogService, SettingsRegistry, SceneManagerService } from '@esengine/editor-core'; import { SceneInspectorPlugin } from './plugins/SceneInspectorPlugin'; import { ProfilerPlugin } from './plugins/ProfilerPlugin'; import { StartupPage } from './components/StartupPage'; @@ -13,10 +13,13 @@ import { ProfilerWindow } from './components/ProfilerWindow'; import { PortManager } from './components/PortManager'; import { SettingsWindow } from './components/SettingsWindow'; import { AboutDialog } from './components/AboutDialog'; +import { ErrorDialog } from './components/ErrorDialog'; +import { ConfirmDialog } from './components/ConfirmDialog'; import { Viewport } from './components/Viewport'; import { MenuBar } from './components/MenuBar'; import { DockContainer, DockablePanel } from './components/DockContainer'; import { TauriAPI } from './api/tauri'; +import { TauriFileAPI } from './adapters/TauriFileAPI'; import { SettingsService } from './services/SettingsService'; import { checkForUpdatesOnStartup } from './utils/updater'; import { useLocale } from './hooks/useLocale'; @@ -44,6 +47,7 @@ function App() { const [logService, setLogService] = useState(null); const [uiRegistry, setUiRegistry] = useState(null); const [settingsRegistry, setSettingsRegistry] = useState(null); + const [sceneManager, setSceneManager] = useState(null); const { t, locale, changeLocale } = useLocale(); const [status, setStatus] = useState(t('header.status.initializing')); const [panels, setPanels] = useState([]); @@ -55,6 +59,14 @@ function App() { const [pluginUpdateTrigger, setPluginUpdateTrigger] = useState(0); const [isRemoteConnected, setIsRemoteConnected] = useState(false); const [isProfilerMode, setIsProfilerMode] = useState(false); + const [errorDialog, setErrorDialog] = useState<{ title: string; message: string } | null>(null); + const [confirmDialog, setConfirmDialog] = useState<{ + title: string; + message: string; + confirmText: string; + cancelText: string; + onConfirm: () => void; + } | null>(null); useEffect(() => { // 禁用默认右键菜单 @@ -72,12 +84,10 @@ function App() { useEffect(() => { if (messageHub) { const unsubscribeEnabled = messageHub.subscribe('plugin:enabled', () => { - console.log('[App] Plugin enabled, updating panels'); setPluginUpdateTrigger(prev => prev + 1); }); const unsubscribeDisabled = messageHub.subscribe('plugin:disabled', () => { - console.log('[App] Plugin disabled, updating panels'); setPluginUpdateTrigger(prev => prev + 1); }); @@ -94,13 +104,11 @@ function App() { const profilerService = (window as any).__PROFILER_SERVICE__; if (profilerService && profilerService.isConnected()) { if (!isRemoteConnected) { - console.log('[App] Remote game connected'); setIsRemoteConnected(true); setStatus(t('header.status.remoteConnected')); } } else { if (isRemoteConnected) { - console.log('[App] Remote game disconnected'); setIsRemoteConnected(false); if (projectLoaded) { const componentRegistry = Core.services.resolve(ComponentRegistry); @@ -123,13 +131,11 @@ function App() { const initializeEditor = async () => { // 使用 ref 防止 React StrictMode 的双重调用 if (initRef.current) { - console.log('[App] Already initialized via ref, skipping second initialization'); return; } initRef.current = true; try { - console.log('[App] Starting editor initialization...'); (window as any).__ECS_FRAMEWORK__ = await import('@esengine/ecs-framework'); const editorScene = new Scene(); @@ -140,12 +146,13 @@ function App() { const serializerRegistry = new SerializerRegistry(); const entityStore = new EntityStoreService(messageHub); const componentRegistry = new ComponentRegistry(); - const projectService = new ProjectService(messageHub); + const fileAPI = new TauriFileAPI(); + const projectService = new ProjectService(messageHub, fileAPI); const componentDiscovery = new ComponentDiscoveryService(messageHub); - const componentLoader = new ComponentLoaderService(messageHub, componentRegistry); const propertyMetadata = new PropertyMetadataService(); const logService = new LogService(); const settingsRegistry = new SettingsRegistry(); + const sceneManagerService = new SceneManagerService(messageHub, fileAPI, projectService); // 监听远程日志事件 window.addEventListener('profiler:remote-log', ((event: CustomEvent) => { @@ -160,10 +167,10 @@ function App() { Core.services.registerInstance(ComponentRegistry, componentRegistry); Core.services.registerInstance(ProjectService, projectService); Core.services.registerInstance(ComponentDiscoveryService, componentDiscovery); - Core.services.registerInstance(ComponentLoaderService, componentLoader); Core.services.registerInstance(PropertyMetadataService, propertyMetadata); Core.services.registerInstance(LogService, logService); Core.services.registerInstance(SettingsRegistry, settingsRegistry); + Core.services.registerInstance(SceneManagerService, sceneManagerService); const pluginMgr = new EditorPluginManager(); pluginMgr.initialize(coreInstance, Core.services); @@ -172,11 +179,6 @@ function App() { await pluginMgr.installEditor(new SceneInspectorPlugin()); await pluginMgr.installEditor(new ProfilerPlugin()); - console.log('[App] All plugins installed'); - console.log('[App] UIRegistry menu count:', uiRegistry.getAllMenus().length); - console.log('[App] UIRegistry all menus:', uiRegistry.getAllMenus()); - console.log('[App] UIRegistry window menus:', uiRegistry.getChildMenus('window')); - messageHub.subscribe('ui:openWindow', (data: any) => { if (data.windowId === 'profiler') { setShowProfiler(true); @@ -185,8 +187,7 @@ function App() { } }); - const greeting = await TauriAPI.greet('Developer'); - console.log(greeting); + await TauriAPI.greet('Developer'); setInitialized(true); setPluginManager(pluginMgr); @@ -195,6 +196,7 @@ function App() { setLogService(logService); setUiRegistry(uiRegistry); setSettingsRegistry(settingsRegistry); + setSceneManager(sceneManagerService); setStatus(t('header.status.ready')); // Check for updates on startup (after 3 seconds) @@ -211,13 +213,11 @@ function App() { const handleOpenRecentProject = async (projectPath: string) => { try { setIsLoading(true); - setLoadingMessage(locale === 'zh' ? '正在打开项目...' : 'Opening project...'); + setLoadingMessage(locale === 'zh' ? '步骤 1/2: 打开项目配置...' : 'Step 1/2: Opening project config...'); const projectService = Core.services.resolve(ProjectService); - const discoveryService = Core.services.resolve(ComponentDiscoveryService); - const loaderService = Core.services.resolve(ComponentLoaderService); - if (!projectService || !discoveryService || !loaderService) { + if (!projectService) { console.error('Required services not available'); setIsLoading(false); return; @@ -231,31 +231,27 @@ function App() { body: JSON.stringify({ path: projectPath }) }); - setLoadingMessage(locale === 'zh' ? '正在扫描组件...' : 'Scanning components...'); - setStatus('Scanning components...'); + setStatus(t('header.status.projectOpened')); - const componentsPath = projectService.getComponentsPath(); - if (componentsPath) { - const componentInfos = await discoveryService.scanComponents({ - basePath: componentsPath, - pattern: '**/*.ts', - scanFunction: TauriAPI.scanDirectory, - readFunction: TauriAPI.readFileContent - }); + setLoadingMessage(locale === 'zh' ? '步骤 2/2: 加载场景...' : 'Step 2/2: Loading scene...'); - setLoadingMessage(locale === 'zh' ? `正在加载 ${componentInfos.length} 个组件...` : `Loading ${componentInfos.length} components...`); - setStatus(`Loading ${componentInfos.length} components...`); + const sceneManagerService = Core.services.resolve(SceneManagerService); + const scenesPath = projectService.getScenesPath(); + if (scenesPath && sceneManagerService) { + try { + const sceneFiles = await TauriAPI.scanDirectory(scenesPath, '*.ecs'); - const modulePathTransform = (filePath: string) => { - const relativePath = filePath.replace(projectPath, '').replace(/\\/g, '/'); - return `/@user-project${relativePath}`; - }; + if (sceneFiles.length > 0) { + const defaultScenePath = projectService.getDefaultScenePath(); + const sceneToLoad = sceneFiles.find(f => f === defaultScenePath) || sceneFiles[0]; - await loaderService.loadComponents(componentInfos, modulePathTransform); - - setStatus(t('header.status.projectOpened') + ` (${componentInfos.length} components registered)`); - } else { - setStatus(t('header.status.projectOpened')); + await sceneManagerService.openScene(sceneToLoad); + } else { + await sceneManagerService.newScene(); + } + } catch (error) { + await sceneManagerService.newScene(); + } } const settings = SettingsService.getInstance(); @@ -268,6 +264,14 @@ function App() { console.error('Failed to open project:', error); setStatus(t('header.status.failed')); setIsLoading(false); + + const errorMessage = error instanceof Error ? error.message : String(error); + setErrorDialog({ + title: locale === 'zh' ? '打开项目失败' : 'Failed to Open Project', + message: locale === 'zh' + ? `无法打开项目:\n${errorMessage}` + : `Failed to open project:\n${errorMessage}` + }); } }; @@ -283,7 +287,72 @@ function App() { }; const handleCreateProject = async () => { - console.log('Create project not implemented yet'); + let selectedProjectPath: string | null = null; + + try { + selectedProjectPath = await TauriAPI.openProjectDialog(); + if (!selectedProjectPath) return; + + setIsLoading(true); + setLoadingMessage(locale === 'zh' ? '正在创建项目...' : 'Creating project...'); + + const projectService = Core.services.resolve(ProjectService); + if (!projectService) { + console.error('ProjectService not available'); + setIsLoading(false); + setErrorDialog({ + title: locale === 'zh' ? '创建项目失败' : 'Failed to Create Project', + message: locale === 'zh' ? '项目服务不可用,请重启编辑器' : 'Project service is not available. Please restart the editor.' + }); + return; + } + + await projectService.createProject(selectedProjectPath); + + setLoadingMessage(locale === 'zh' ? '项目创建成功,正在打开...' : 'Project created, opening...'); + + await handleOpenRecentProject(selectedProjectPath); + } catch (error) { + console.error('Failed to create project:', error); + setIsLoading(false); + + const errorMessage = error instanceof Error ? error.message : String(error); + const pathToOpen = selectedProjectPath; + + if (errorMessage.includes('already exists') && pathToOpen) { + setConfirmDialog({ + title: locale === 'zh' ? '项目已存在' : 'Project Already Exists', + message: locale === 'zh' + ? '该目录下已存在 ECS 项目,是否要打开该项目?' + : 'An ECS project already exists in this directory. Do you want to open it?', + confirmText: locale === 'zh' ? '打开项目' : 'Open Project', + cancelText: locale === 'zh' ? '取消' : 'Cancel', + onConfirm: () => { + setConfirmDialog(null); + setIsLoading(true); + setLoadingMessage(locale === 'zh' ? '正在打开项目...' : 'Opening project...'); + handleOpenRecentProject(pathToOpen).catch((err) => { + console.error('Failed to open project:', err); + setIsLoading(false); + setErrorDialog({ + title: locale === 'zh' ? '打开项目失败' : 'Failed to Open Project', + message: locale === 'zh' + ? `无法打开项目:\n${err instanceof Error ? err.message : String(err)}` + : `Failed to open project:\n${err instanceof Error ? err.message : String(err)}` + }); + }); + } + }); + } else { + setStatus(locale === 'zh' ? '创建项目失败' : 'Failed to create project'); + setErrorDialog({ + title: locale === 'zh' ? '创建项目失败' : 'Failed to Create Project', + message: locale === 'zh' + ? `无法创建项目:\n${errorMessage}` + : `Failed to create project:\n${errorMessage}` + }); + } + } }; const handleProfilerMode = async () => { @@ -292,20 +361,109 @@ function App() { setStatus(t('header.status.profilerMode') || 'Profiler Mode - Waiting for connection...'); }; - const handleNewScene = () => { - console.log('New scene not implemented yet'); + const handleNewScene = async () => { + if (!sceneManager) { + console.error('SceneManagerService not available'); + return; + } + + try { + await sceneManager.newScene(); + setStatus(locale === 'zh' ? '已创建新场景' : 'New scene created'); + } catch (error) { + console.error('Failed to create new scene:', error); + setStatus(locale === 'zh' ? '创建场景失败' : 'Failed to create scene'); + } }; - const handleOpenScene = () => { - console.log('Open scene not implemented yet'); + const handleOpenScene = async () => { + if (!sceneManager) { + console.error('SceneManagerService not available'); + return; + } + + try { + await sceneManager.openScene(); + const sceneState = sceneManager.getSceneState(); + setStatus(locale === 'zh' ? `已打开场景: ${sceneState.sceneName}` : `Scene opened: ${sceneState.sceneName}`); + } catch (error) { + console.error('Failed to open scene:', error); + setStatus(locale === 'zh' ? '打开场景失败' : 'Failed to open scene'); + } }; - const handleSaveScene = () => { - console.log('Save scene not implemented yet'); + const handleOpenSceneByPath = useCallback(async (scenePath: string) => { + console.log('[App] handleOpenSceneByPath called with:', scenePath); + + if (!sceneManager) { + console.error('SceneManagerService not available'); + return; + } + + try { + console.log('[App] Opening scene:', scenePath); + await sceneManager.openScene(scenePath); + const sceneState = sceneManager.getSceneState(); + console.log('[App] Scene opened, state:', sceneState); + setStatus(locale === 'zh' ? `已打开场景: ${sceneState.sceneName}` : `Scene opened: ${sceneState.sceneName}`); + } catch (error) { + console.error('Failed to open scene:', error); + setStatus(locale === 'zh' ? '打开场景失败' : 'Failed to open scene'); + setErrorDialog({ + title: locale === 'zh' ? '打开场景失败' : 'Failed to Open Scene', + message: locale === 'zh' + ? `无法打开场景:\n${error instanceof Error ? error.message : String(error)}` + : `Failed to open scene:\n${error instanceof Error ? error.message : String(error)}` + }); + } + }, [sceneManager, locale]); + + const handleSaveScene = async () => { + if (!sceneManager) { + console.error('SceneManagerService not available'); + return; + } + + try { + await sceneManager.saveScene(); + const sceneState = sceneManager.getSceneState(); + setStatus(locale === 'zh' ? `已保存场景: ${sceneState.sceneName}` : `Scene saved: ${sceneState.sceneName}`); + } catch (error) { + console.error('Failed to save scene:', error); + setStatus(locale === 'zh' ? '保存场景失败' : 'Failed to save scene'); + } }; - const handleSaveSceneAs = () => { - console.log('Save scene as not implemented yet'); + const handleSaveSceneAs = async () => { + if (!sceneManager) { + console.error('SceneManagerService not available'); + return; + } + + try { + await sceneManager.saveSceneAs(); + const sceneState = sceneManager.getSceneState(); + setStatus(locale === 'zh' ? `已保存场景: ${sceneState.sceneName}` : `Scene saved: ${sceneState.sceneName}`); + } catch (error) { + console.error('Failed to save scene as:', error); + setStatus(locale === 'zh' ? '另存场景失败' : 'Failed to save scene as'); + } + }; + + const handleExportScene = async () => { + if (!sceneManager) { + console.error('SceneManagerService not available'); + return; + } + + try { + await sceneManager.exportScene(); + const sceneState = sceneManager.getSceneState(); + setStatus(locale === 'zh' ? `已导出场景: ${sceneState.sceneName}` : `Scene exported: ${sceneState.sceneName}`); + } catch (error) { + console.error('Failed to export scene:', error); + setStatus(locale === 'zh' ? '导出场景失败' : 'Failed to export scene'); + } }; const handleCloseProject = () => { @@ -391,7 +549,7 @@ function App() { id: 'assets', title: locale === 'zh' ? '资产' : 'Assets', position: 'bottom', - content: , + content: , closable: false }, { @@ -436,7 +594,7 @@ function App() { console.log('[App] Loading plugin panels:', pluginPanels); setPanels([...corePanels, ...pluginPanels]); } - }, [projectLoaded, entityStore, messageHub, logService, uiRegistry, pluginManager, locale, currentProjectPath, t, pluginUpdateTrigger, isProfilerMode]); + }, [projectLoaded, entityStore, messageHub, logService, uiRegistry, pluginManager, locale, currentProjectPath, t, pluginUpdateTrigger, isProfilerMode, handleOpenSceneByPath]); const handlePanelMove = (panelId: string, newPosition: any) => { setPanels(prevPanels => @@ -477,6 +635,23 @@ function App() { )} + {errorDialog && ( + setErrorDialog(null)} + /> + )} + {confirmDialog && ( + setConfirmDialog(null)} + /> + )} ); } @@ -543,6 +718,14 @@ function App() { {showAbout && ( setShowAbout(false)} locale={locale} /> )} + + {errorDialog && ( + setErrorDialog(null)} + /> + )} ); } diff --git a/packages/editor-app/src/adapters/TauriFileAPI.ts b/packages/editor-app/src/adapters/TauriFileAPI.ts new file mode 100644 index 00000000..29083604 --- /dev/null +++ b/packages/editor-app/src/adapters/TauriFileAPI.ts @@ -0,0 +1,41 @@ +import type { IFileAPI } from '@esengine/editor-core'; +import { TauriAPI } from '../api/tauri'; + +/** + * Tauri 文件 API 适配器 + * + * 实现 IFileAPI 接口,连接 editor-core 和 Tauri 后端 + */ +export class TauriFileAPI implements IFileAPI { + public async openSceneDialog(): Promise { + return await TauriAPI.openSceneDialog(); + } + + public async saveSceneDialog(defaultName?: string): Promise { + return await TauriAPI.saveSceneDialog(defaultName); + } + + public async readFileContent(path: string): Promise { + return await TauriAPI.readFileContent(path); + } + + public async saveProject(path: string, data: string): Promise { + return await TauriAPI.saveProject(path, data); + } + + public async exportBinary(data: Uint8Array, path: string): Promise { + return await TauriAPI.exportBinary(data, path); + } + + public async createDirectory(path: string): Promise { + return await TauriAPI.createDirectory(path); + } + + public async writeFileContent(path: string, content: string): Promise { + return await TauriAPI.writeFileContent(path, content); + } + + public async pathExists(path: string): Promise { + return await TauriAPI.pathExists(path); + } +} diff --git a/packages/editor-app/src/api/tauri.ts b/packages/editor-app/src/api/tauri.ts index cc7fc80d..0fd0b54c 100644 --- a/packages/editor-app/src/api/tauri.ts +++ b/packages/editor-app/src/api/tauri.ts @@ -70,6 +70,49 @@ export class TauriAPI { static async toggleDevtools(): Promise { return await invoke('toggle_devtools'); } + + /** + * 打开保存场景对话框 + * @param defaultName 默认文件名(可选) + * @returns 用户选择的文件路径,取消则返回 null + */ + static async saveSceneDialog(defaultName?: string): Promise { + return await invoke('save_scene_dialog', { defaultName }); + } + + /** + * 打开场景文件选择对话框 + * @returns 用户选择的文件路径,取消则返回 null + */ + static async openSceneDialog(): Promise { + return await invoke('open_scene_dialog'); + } + + /** + * 创建目录 + * @param path 目录路径 + */ + static async createDirectory(path: string): Promise { + return await invoke('create_directory', { path }); + } + + /** + * 写入文件内容 + * @param path 文件路径 + * @param content 文件内容 + */ + static async writeFileContent(path: string, content: string): Promise { + return await invoke('write_file_content', { path, content }); + } + + /** + * 检查路径是否存在 + * @param path 文件或目录路径 + * @returns 路径是否存在 + */ + static async pathExists(path: string): Promise { + return await invoke('path_exists', { path }); + } } export interface DirectoryEntry { diff --git a/packages/editor-app/src/components/AddComponent.css b/packages/editor-app/src/components/AddComponent.css deleted file mode 100644 index c0985b9d..00000000 --- a/packages/editor-app/src/components/AddComponent.css +++ /dev/null @@ -1,175 +0,0 @@ -.modal-overlay { - position: fixed; - top: 0; - left: 0; - right: 0; - bottom: 0; - background-color: rgba(0, 0, 0, 0.5); - display: flex; - align-items: center; - justify-content: center; - z-index: 1000; -} - -.add-component-dialog { - background-color: #2d2d2d; - border-radius: 8px; - width: 500px; - max-width: 90%; - max-height: 80vh; - display: flex; - flex-direction: column; - box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3); -} - -.dialog-header { - display: flex; - justify-content: space-between; - align-items: center; - padding: 16px 20px; - border-bottom: 1px solid #404040; -} - -.dialog-header h3 { - margin: 0; - font-size: 16px; - color: #fff; -} - -.close-btn { - background: none; - border: none; - color: #aaa; - font-size: 24px; - cursor: pointer; - padding: 0; - width: 24px; - height: 24px; - line-height: 20px; - transition: color 0.2s; -} - -.close-btn:hover { - color: #fff; -} - -.dialog-content { - flex: 1; - display: flex; - flex-direction: column; - overflow: hidden; - padding: 16px 20px; -} - -.component-filter { - width: 100%; - padding: 8px 12px; - background-color: #1e1e1e; - border: 1px solid #404040; - border-radius: 4px; - color: #fff; - font-size: 14px; - margin-bottom: 12px; -} - -.component-filter:focus { - outline: none; - border-color: #007acc; -} - -.component-list { - flex: 1; - overflow-y: auto; - min-height: 200px; - max-height: 400px; -} - -.component-category { - margin-bottom: 16px; -} - -.category-header { - font-size: 12px; - font-weight: 600; - color: #888; - text-transform: uppercase; - margin-bottom: 8px; - padding-bottom: 4px; - border-bottom: 1px solid #404040; -} - -.component-option { - padding: 10px 12px; - cursor: pointer; - border-radius: 4px; - margin-bottom: 4px; - transition: background-color 0.2s; -} - -.component-option:hover { - background-color: #3a3a3a; -} - -.component-option.selected { - background-color: #094771; - border: 1px solid #007acc; -} - -.component-name { - font-size: 14px; - color: #fff; - font-weight: 500; - margin-bottom: 2px; -} - -.component-description { - font-size: 12px; - color: #aaa; -} - -.empty-message { - color: #888; - text-align: center; - padding: 40px 20px; - font-size: 14px; -} - -.dialog-footer { - display: flex; - justify-content: flex-end; - gap: 8px; - padding: 16px 20px; - border-top: 1px solid #404040; -} - -.btn { - padding: 8px 16px; - border-radius: 4px; - border: none; - cursor: pointer; - font-size: 14px; - transition: all 0.2s; -} - -.btn:disabled { - opacity: 0.5; - cursor: not-allowed; -} - -.btn-cancel { - background-color: #3a3a3a; - color: #fff; -} - -.btn-cancel:hover:not(:disabled) { - background-color: #4a4a4a; -} - -.btn-primary { - background-color: #007acc; - color: #fff; -} - -.btn-primary:hover:not(:disabled) { - background-color: #0098ff; -} diff --git a/packages/editor-app/src/components/AddComponent.tsx b/packages/editor-app/src/components/AddComponent.tsx deleted file mode 100644 index 086cbe13..00000000 --- a/packages/editor-app/src/components/AddComponent.tsx +++ /dev/null @@ -1,121 +0,0 @@ -import { useState, useEffect } from 'react'; -import { Entity } from '@esengine/ecs-framework'; -import { ComponentRegistry, ComponentTypeInfo } from '@esengine/editor-core'; -import './AddComponent.css'; - -interface AddComponentProps { - entity: Entity; - componentRegistry: ComponentRegistry; - onAdd: (componentName: string) => void; - onCancel: () => void; -} - -export function AddComponent({ entity, componentRegistry, onAdd, onCancel }: AddComponentProps) { - const [components, setComponents] = useState([]); - const [selectedComponent, setSelectedComponent] = useState(null); - const [filter, setFilter] = useState(''); - - useEffect(() => { - if (!componentRegistry) { - console.error('ComponentRegistry is null'); - return; - } - - const allComponents = componentRegistry.getAllComponents(); - console.log('All registered components:', allComponents); - - allComponents.forEach(comp => { - console.log(`Component ${comp.name}: has type = ${!!comp.type}`); - }); - - const existingComponentNames = entity.components.map(c => c.constructor.name); - - const availableComponents = allComponents.filter( - comp => comp.type && !existingComponentNames.includes(comp.name) - ); - - console.log('Available components to add:', availableComponents); - console.log('Components filtered out:', allComponents.filter(comp => !comp.type).map(c => c.name)); - setComponents(availableComponents); - }, [entity, componentRegistry]); - - const filteredComponents = components.filter(comp => - comp.name.toLowerCase().includes(filter.toLowerCase()) || - comp.category?.toLowerCase().includes(filter.toLowerCase()) - ); - - const handleAdd = () => { - if (selectedComponent) { - onAdd(selectedComponent); - } - }; - - const groupedComponents = filteredComponents.reduce((groups, comp) => { - const category = comp.category || 'Other'; - if (!groups[category]) { - groups[category] = []; - } - groups[category].push(comp); - return groups; - }, {} as Record); - - return ( -
-
e.stopPropagation()}> -
-

Add Component

- -
- -
- setFilter(e.target.value)} - autoFocus - /> - -
- {Object.keys(groupedComponents).length === 0 ? ( -
No available components
- ) : ( - Object.entries(groupedComponents).map(([category, comps]) => ( -
-
{category}
- {comps.map(comp => ( -
setSelectedComponent(comp.name)} - onDoubleClick={handleAdd} - > -
{comp.name}
- {comp.description && ( -
{comp.description}
- )} -
- ))} -
- )) - )} -
-
- -
- - -
-
-
- ); -} diff --git a/packages/editor-app/src/components/AssetBrowser.tsx b/packages/editor-app/src/components/AssetBrowser.tsx index 1c1f57d3..8387a067 100644 --- a/packages/editor-app/src/components/AssetBrowser.tsx +++ b/packages/editor-app/src/components/AssetBrowser.tsx @@ -1,4 +1,6 @@ import { useState, useEffect } from 'react'; +import { Core } from '@esengine/ecs-framework'; +import { MessageHub } from '@esengine/editor-core'; import { TauriAPI, DirectoryEntry } from '../api/tauri'; import { FileTree } from './FileTree'; import { ResizablePanel } from './ResizablePanel'; @@ -14,11 +16,12 @@ interface AssetItem { interface AssetBrowserProps { projectPath: string | null; locale: string; + onOpenScene?: (scenePath: string) => void; } type ViewMode = 'tree-split' | 'tree-only'; -export function AssetBrowser({ projectPath, locale }: AssetBrowserProps) { +export function AssetBrowser({ projectPath, locale, onOpenScene }: AssetBrowserProps) { const [viewMode, setViewMode] = useState('tree-split'); const [selectedPath, setSelectedPath] = useState(null); const [assets, setAssets] = useState([]); @@ -67,6 +70,29 @@ export function AssetBrowser({ projectPath, locale }: AssetBrowserProps) { } }, [projectPath, viewMode]); + // Listen for asset reveal requests + useEffect(() => { + const messageHub = Core.services.resolve(MessageHub); + if (!messageHub) return; + + const unsubscribe = messageHub.subscribe('asset:reveal', (data: any) => { + const filePath = data.path; + if (filePath) { + setSelectedPath(filePath); + + if (viewMode === 'tree-split') { + const lastSlashIndex = Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\')); + const dirPath = lastSlashIndex > 0 ? filePath.substring(0, lastSlashIndex) : null; + if (dirPath) { + loadAssets(dirPath); + } + } + } + }); + + return () => unsubscribe(); + }, [viewMode]); + const loadAssets = async (path: string) => { setLoading(true); try { @@ -105,7 +131,11 @@ export function AssetBrowser({ projectPath, locale }: AssetBrowserProps) { }; const handleAssetDoubleClick = (asset: AssetItem) => { - console.log('Open asset:', asset); + if (asset.type === 'file' && asset.extension === 'ecs') { + if (onOpenScene) { + onOpenScene(asset.path); + } + } }; const filteredAssets = searchQuery diff --git a/packages/editor-app/src/components/ConfirmDialog.tsx b/packages/editor-app/src/components/ConfirmDialog.tsx new file mode 100644 index 00000000..b73c7efd --- /dev/null +++ b/packages/editor-app/src/components/ConfirmDialog.tsx @@ -0,0 +1,37 @@ +import { X } from 'lucide-react'; +import '../styles/ConfirmDialog.css'; + +interface ConfirmDialogProps { + title: string; + message: string; + confirmText: string; + cancelText: string; + onConfirm: () => void; + onCancel: () => void; +} + +export function ConfirmDialog({ title, message, confirmText, cancelText, onConfirm, onCancel }: ConfirmDialogProps) { + return ( +
+
e.stopPropagation()}> +
+

{title}

+ +
+
+

{message}

+
+
+ + +
+
+
+ ); +} diff --git a/packages/editor-app/src/components/EntityInspector.tsx b/packages/editor-app/src/components/EntityInspector.tsx index 6d49a86b..91d0334d 100644 --- a/packages/editor-app/src/components/EntityInspector.tsx +++ b/packages/editor-app/src/components/EntityInspector.tsx @@ -1,9 +1,8 @@ import { useState, useEffect } from 'react'; import { Entity, Core } from '@esengine/ecs-framework'; import { EntityStoreService, MessageHub, ComponentRegistry } from '@esengine/editor-core'; -import { AddComponent } from './AddComponent'; import { PropertyInspector } from './PropertyInspector'; -import { FileSearch, Plus, ChevronDown, ChevronRight, X, Settings } from 'lucide-react'; +import { FileSearch, ChevronDown, ChevronRight, X, Settings } from 'lucide-react'; import '../styles/EntityInspector.css'; interface EntityInspectorProps { @@ -15,22 +14,21 @@ export function EntityInspector({ entityStore: _entityStore, messageHub }: Entit const [selectedEntity, setSelectedEntity] = useState(null); const [remoteEntity, setRemoteEntity] = useState(null); const [remoteEntityDetails, setRemoteEntityDetails] = useState(null); - const [showAddComponent, setShowAddComponent] = useState(false); const [expandedComponents, setExpandedComponents] = useState>(new Set()); + const [componentVersion, setComponentVersion] = useState(0); useEffect(() => { const handleSelection = (data: { entity: Entity | null }) => { setSelectedEntity(data.entity); setRemoteEntity(null); setRemoteEntityDetails(null); - setShowAddComponent(false); + setComponentVersion(0); }; const handleRemoteSelection = (data: { entity: any }) => { setRemoteEntity(data.entity); setRemoteEntityDetails(null); setSelectedEntity(null); - setShowAddComponent(false); }; const handleEntityDetails = (event: Event) => { @@ -39,38 +37,26 @@ export function EntityInspector({ entityStore: _entityStore, messageHub }: Entit setRemoteEntityDetails(details); }; + const handleComponentChange = () => { + setComponentVersion(prev => prev + 1); + }; + const unsubSelect = messageHub.subscribe('entity:selected', handleSelection); const unsubRemoteSelect = messageHub.subscribe('remote-entity:selected', handleRemoteSelection); + const unsubComponentAdded = messageHub.subscribe('component:added', handleComponentChange); + const unsubComponentRemoved = messageHub.subscribe('component:removed', handleComponentChange); window.addEventListener('profiler:entity-details', handleEntityDetails); return () => { unsubSelect(); unsubRemoteSelect(); + unsubComponentAdded(); + unsubComponentRemoved(); window.removeEventListener('profiler:entity-details', handleEntityDetails); }; }, [messageHub]); - const handleAddComponent = (componentName: string) => { - if (!selectedEntity) return; - - const componentRegistry = Core.services.resolve(ComponentRegistry); - if (!componentRegistry) { - console.error('ComponentRegistry not found'); - return; - } - - const component = componentRegistry.createInstance(componentName); - - if (component) { - selectedEntity.addComponent(component); - messageHub.publish('component:added', { entity: selectedEntity, component }); - setShowAddComponent(false); - } else { - console.error('Failed to create component instance for:', componentName); - } - }; - const handleRemoveComponent = (index: number) => { if (!selectedEntity) return; const component = selectedEntity.components[index]; @@ -481,19 +467,12 @@ export function EntityInspector({ entityStore: _entityStore, messageHub }: Entit
Components ({components.length}) -
{components.length === 0 ? (
No components
) : ( -
    +
      {components.map((component, index) => { const isExpanded = expandedComponents.has(index); return ( @@ -534,15 +513,6 @@ export function EntityInspector({ entityStore: _entityStore, messageHub }: Entit
- - {showAddComponent && selectedEntity && ( - setShowAddComponent(false)} - /> - )} ); } diff --git a/packages/editor-app/src/components/ErrorDialog.tsx b/packages/editor-app/src/components/ErrorDialog.tsx new file mode 100644 index 00000000..0ea6c6d3 --- /dev/null +++ b/packages/editor-app/src/components/ErrorDialog.tsx @@ -0,0 +1,31 @@ +import { X } from 'lucide-react'; +import '../styles/ErrorDialog.css'; + +interface ErrorDialogProps { + title: string; + message: string; + onClose: () => void; +} + +export function ErrorDialog({ title, message, onClose }: ErrorDialogProps) { + return ( +
+
e.stopPropagation()}> +
+

{title}

+ +
+
+

{message}

+
+
+ +
+
+
+ ); +} diff --git a/packages/editor-app/src/components/SceneHierarchy.tsx b/packages/editor-app/src/components/SceneHierarchy.tsx index 206b5d24..9f51784f 100644 --- a/packages/editor-app/src/components/SceneHierarchy.tsx +++ b/packages/editor-app/src/components/SceneHierarchy.tsx @@ -1,9 +1,10 @@ import { useState, useEffect } from 'react'; -import { Entity } from '@esengine/ecs-framework'; -import { EntityStoreService, MessageHub } from '@esengine/editor-core'; +import { Entity, Core } from '@esengine/ecs-framework'; +import { EntityStoreService, MessageHub, SceneManagerService } from '@esengine/editor-core'; import { useLocale } from '../hooks/useLocale'; -import { Box, Layers, Wifi, Search } from 'lucide-react'; +import { Box, Layers, Wifi, Search, Plus, Trash2 } from 'lucide-react'; import { ProfilerService, RemoteEntity } from '../services/ProfilerService'; +import { confirm } from '@tauri-apps/plugin-dialog'; import '../styles/SceneHierarchy.css'; interface SceneHierarchyProps { @@ -17,7 +18,51 @@ export function SceneHierarchy({ entityStore, messageHub }: SceneHierarchyProps) const [isRemoteConnected, setIsRemoteConnected] = useState(false); const [selectedId, setSelectedId] = useState(null); const [searchQuery, setSearchQuery] = useState(''); - const { t } = useLocale(); + const [sceneName, setSceneName] = useState('Untitled'); + const [sceneFilePath, setSceneFilePath] = useState(null); + const [isSceneModified, setIsSceneModified] = useState(false); + const { t, locale } = useLocale(); + + // Subscribe to scene changes + useEffect(() => { + const sceneManager = Core.services.resolve(SceneManagerService); + + const updateSceneInfo = () => { + if (sceneManager) { + const state = sceneManager.getSceneState(); + setSceneName(state.sceneName); + setIsSceneModified(state.isModified); + } + }; + + updateSceneInfo(); + + const unsubLoaded = messageHub.subscribe('scene:loaded', (data: any) => { + if (data.sceneName) { + setSceneName(data.sceneName); + setSceneFilePath(data.path || null); + setIsSceneModified(data.isModified || false); + } else { + updateSceneInfo(); + } + }); + const unsubNew = messageHub.subscribe('scene:new', () => { + updateSceneInfo(); + }); + const unsubSaved = messageHub.subscribe('scene:saved', () => { + updateSceneInfo(); + }); + const unsubModified = messageHub.subscribe('scene:modified', () => { + updateSceneInfo(); + }); + + return () => { + unsubLoaded(); + unsubNew(); + unsubSaved(); + unsubModified(); + }; + }, [messageHub]); // Subscribe to local entity changes useEffect(() => { @@ -107,6 +152,57 @@ export function SceneHierarchy({ entityStore, messageHub }: SceneHierarchyProps) }); }; + const handleSceneNameClick = () => { + if (sceneFilePath) { + messageHub.publish('asset:reveal', { path: sceneFilePath }); + } + }; + + const handleCreateEntity = () => { + const scene = Core.scene; + if (!scene) return; + + const entityCount = entityStore.getAllEntities().length; + const entityName = `Entity ${entityCount + 1}`; + const entity = scene.createEntity(entityName); + entityStore.addEntity(entity); + entityStore.selectEntity(entity); + }; + + const handleDeleteEntity = async () => { + if (!selectedId) return; + + const entity = entityStore.getEntity(selectedId); + if (!entity) return; + + const confirmed = await confirm( + locale === 'zh' + ? `确定要删除实体 "${entity.name}" 吗?此操作无法撤销。` + : `Are you sure you want to delete entity "${entity.name}"? This action cannot be undone.`, + { + title: locale === 'zh' ? '删除实体' : 'Delete Entity', + kind: 'warning' + } + ); + + if (confirmed) { + entity.destroy(); + entityStore.removeEntity(entity); + } + }; + + // Listen for Delete key + useEffect(() => { + const handleKeyDown = (e: KeyboardEvent) => { + if (e.key === 'Delete' && selectedId && !isRemoteConnected) { + handleDeleteEntity(); + } + }; + + window.addEventListener('keydown', handleKeyDown); + return () => window.removeEventListener('keydown', handleKeyDown); + }, [selectedId, isRemoteConnected]); + // Filter entities based on search query const filterRemoteEntities = (entityList: RemoteEntity[]): RemoteEntity[] => { if (!searchQuery.trim()) return entityList; @@ -153,6 +249,15 @@ export function SceneHierarchy({ entityStore, messageHub }: SceneHierarchyProps)

{t('hierarchy.title')}

+
+ + {sceneName}{isSceneModified ? '*' : ''} + +
{showRemoteIndicator && (
@@ -168,6 +273,26 @@ export function SceneHierarchy({ entityStore, messageHub }: SceneHierarchyProps) onChange={(e) => setSearchQuery(e.target.value)} />
+ {!isRemoteConnected && ( +
+ + +
+ )}
{displayEntities.length === 0 ? (
diff --git a/packages/editor-app/src/components/StartupPage.tsx b/packages/editor-app/src/components/StartupPage.tsx index 96762c1c..67035f7c 100644 --- a/packages/editor-app/src/components/StartupPage.tsx +++ b/packages/editor-app/src/components/StartupPage.tsx @@ -18,7 +18,7 @@ export function StartupPage({ onOpenProject, onCreateProject, onOpenRecentProjec title: 'ECS Framework Editor', subtitle: 'Professional Game Development Tool', openProject: 'Open Project', - createProject: 'Create New Project', + createProject: 'Create Project', profilerMode: 'Profiler Mode', recentProjects: 'Recent Projects', noRecentProjects: 'No recent projects', @@ -49,19 +49,25 @@ export function StartupPage({ onOpenProject, onCreateProject, onOpenRecentProjec
- - + +
diff --git a/packages/editor-app/src/styles/ConfirmDialog.css b/packages/editor-app/src/styles/ConfirmDialog.css new file mode 100644 index 00000000..b4a97111 --- /dev/null +++ b/packages/editor-app/src/styles/ConfirmDialog.css @@ -0,0 +1,128 @@ +.confirm-dialog-overlay { + position: fixed; + top: 0; + left: 0; + right: 0; + bottom: 0; + background: rgba(0, 0, 0, 0.6); + display: flex; + align-items: center; + justify-content: center; + z-index: 10000; + animation: fadeIn 0.2s ease-out; +} + +@keyframes fadeIn { + from { + opacity: 0; + } + to { + opacity: 1; + } +} + +.confirm-dialog { + background: var(--bg-secondary, #2a2a2a); + border: 1px solid var(--border-color, #404040); + border-radius: 8px; + min-width: 400px; + max-width: 600px; + box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4); + animation: slideIn 0.2s ease-out; +} + +@keyframes slideIn { + from { + transform: translateY(-20px); + opacity: 0; + } + to { + transform: translateY(0); + opacity: 1; + } +} + +.confirm-dialog-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 16px 20px; + border-bottom: 1px solid var(--border-color, #404040); +} + +.confirm-dialog-header h2 { + margin: 0; + font-size: 16px; + font-weight: 600; + color: var(--text-primary, #e0e0e0); +} + +.confirm-dialog-header .close-btn { + background: none; + border: none; + color: var(--text-secondary, #999); + cursor: pointer; + padding: 4px; + border-radius: 4px; + display: flex; + align-items: center; + justify-content: center; + transition: all 0.2s; +} + +.confirm-dialog-header .close-btn:hover { + background: var(--bg-hover, #3a3a3a); + color: var(--text-primary, #fff); +} + +.confirm-dialog-content { + padding: 20px; + color: var(--text-primary, #e0e0e0); + line-height: 1.6; +} + +.confirm-dialog-content p { + margin: 0; + white-space: pre-wrap; + word-break: break-word; +} + +.confirm-dialog-footer { + padding: 12px 20px; + border-top: 1px solid var(--border-color, #404040); + display: flex; + justify-content: flex-end; + gap: 8px; +} + +.confirm-dialog-btn { + padding: 8px 24px; + border: none; + border-radius: 4px; + cursor: pointer; + font-size: 14px; + font-weight: 500; + transition: all 0.2s; +} + +.confirm-dialog-btn.cancel { + background: var(--bg-hover, #3a3a3a); + color: var(--text-primary, #e0e0e0); +} + +.confirm-dialog-btn.cancel:hover { + background: var(--bg-active, #4a4a4a); +} + +.confirm-dialog-btn.confirm { + background: #4a9eff; + color: white; +} + +.confirm-dialog-btn.confirm:hover { + background: #6bb0ff; +} + +.confirm-dialog-btn:active { + transform: scale(0.98); +} diff --git a/packages/editor-app/src/styles/EntityInspector.css b/packages/editor-app/src/styles/EntityInspector.css index d88961ab..734b2fb8 100644 --- a/packages/editor-app/src/styles/EntityInspector.css +++ b/packages/editor-app/src/styles/EntityInspector.css @@ -4,6 +4,7 @@ height: 100%; background-color: var(--color-bg-base); color: var(--color-text-primary); + position: relative; } .inspector-header { diff --git a/packages/editor-app/src/styles/ErrorDialog.css b/packages/editor-app/src/styles/ErrorDialog.css new file mode 100644 index 00000000..02071ead --- /dev/null +++ b/packages/editor-app/src/styles/ErrorDialog.css @@ -0,0 +1,115 @@ +.error-dialog-overlay { + position: fixed; + top: 0; + left: 0; + right: 0; + bottom: 0; + background: rgba(0, 0, 0, 0.6); + display: flex; + align-items: center; + justify-content: center; + z-index: 10000; + animation: fadeIn 0.2s ease-out; +} + +@keyframes fadeIn { + from { + opacity: 0; + } + to { + opacity: 1; + } +} + +.error-dialog { + background: var(--bg-secondary, #2a2a2a); + border: 1px solid var(--border-color, #404040); + border-radius: 8px; + min-width: 400px; + max-width: 600px; + box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4); + animation: slideIn 0.2s ease-out; +} + +@keyframes slideIn { + from { + transform: translateY(-20px); + opacity: 0; + } + to { + transform: translateY(0); + opacity: 1; + } +} + +.error-dialog-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 16px 20px; + border-bottom: 1px solid var(--border-color, #404040); +} + +.error-dialog-header h2 { + margin: 0; + font-size: 16px; + font-weight: 600; + color: #ff4444; +} + +.error-dialog-header .close-btn { + background: none; + border: none; + color: var(--text-secondary, #999); + cursor: pointer; + padding: 4px; + border-radius: 4px; + display: flex; + align-items: center; + justify-content: center; + transition: all 0.2s; +} + +.error-dialog-header .close-btn:hover { + background: var(--bg-hover, #3a3a3a); + color: var(--text-primary, #fff); +} + +.error-dialog-content { + padding: 20px; + color: var(--text-primary, #e0e0e0); + line-height: 1.6; +} + +.error-dialog-content p { + margin: 0; + white-space: pre-wrap; + word-break: break-word; +} + +.error-dialog-footer { + padding: 12px 20px; + border-top: 1px solid var(--border-color, #404040); + display: flex; + justify-content: flex-end; +} + +.error-dialog-btn { + padding: 8px 24px; + background: #ff4444; + color: white; + border: none; + border-radius: 4px; + cursor: pointer; + font-size: 14px; + font-weight: 500; + transition: all 0.2s; +} + +.error-dialog-btn:hover { + background: #ff6666; +} + +.error-dialog-btn:active { + transform: scale(0.98); +} diff --git a/packages/editor-app/src/styles/SceneHierarchy.css b/packages/editor-app/src/styles/SceneHierarchy.css index 60af5168..709d0b85 100644 --- a/packages/editor-app/src/styles/SceneHierarchy.css +++ b/packages/editor-app/src/styles/SceneHierarchy.css @@ -29,7 +29,42 @@ color: var(--color-text-primary); text-transform: uppercase; letter-spacing: 0.05em; - flex: 1; +} + +.scene-name-container { + display: flex; + align-items: center; + padding: 2px 8px; + background-color: var(--color-bg-base); + border: 1px solid var(--color-border-default); + border-radius: var(--radius-sm); + margin-left: auto; + margin-right: var(--spacing-sm); + transition: all var(--transition-fast); +} + +.scene-name-container.clickable { + cursor: pointer; +} + +.scene-name-container.clickable:hover { + background-color: var(--color-bg-hover); + border-color: var(--color-primary); +} + +.scene-name-container.clickable:hover .scene-name { + color: var(--color-primary); +} + +.scene-name { + font-size: var(--font-size-xs); + color: var(--color-text-secondary); + font-weight: var(--font-weight-medium); + max-width: 120px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + transition: color var(--transition-fast); } .remote-indicator { @@ -74,6 +109,45 @@ color: var(--color-text-tertiary); } +.hierarchy-toolbar { + display: flex; + align-items: center; + gap: var(--spacing-xs); + padding: var(--spacing-sm) var(--spacing-md); + border-bottom: 1px solid var(--color-border-default); + background-color: var(--color-bg-base); + flex-shrink: 0; +} + +.toolbar-btn { + display: flex; + align-items: center; + gap: var(--spacing-xs); + padding: var(--spacing-xs) var(--spacing-sm); + background-color: var(--color-bg-elevated); + border: 1px solid var(--color-border-default); + border-radius: var(--radius-sm); + color: var(--color-text-primary); + font-size: var(--font-size-sm); + cursor: pointer; + transition: all var(--transition-fast); +} + +.toolbar-btn:hover:not(:disabled) { + background-color: var(--color-bg-hover); + border-color: var(--color-primary); + color: var(--color-primary); +} + +.toolbar-btn:active:not(:disabled) { + transform: scale(0.98); +} + +.toolbar-btn:disabled { + opacity: 0.5; + cursor: not-allowed; +} + .hierarchy-content { flex: 1; overflow-y: auto; diff --git a/packages/editor-app/vite.config.ts b/packages/editor-app/vite.config.ts index 8910f565..bef77d96 100644 --- a/packages/editor-app/vite.config.ts +++ b/packages/editor-app/vite.config.ts @@ -3,15 +3,10 @@ import react from '@vitejs/plugin-react'; import fs from 'fs'; import path from 'path'; import { transformSync } from 'esbuild'; -import JSON5 from 'json5'; const host = process.env.TAURI_DEV_HOST; const userProjectPathMap = new Map(); -const userProjectDependencies = new Map>(); -const cocosEnginePaths = new Map(); -const allowedPaths = new Set(); - const editorPackageMapping = new Map(); function loadEditorPackages() { @@ -36,7 +31,6 @@ function loadEditorPackages() { const entryPath = path.join(packagesDir, dir, mainFile); if (fs.existsSync(entryPath)) { editorPackageMapping.set(packageJson.name, entryPath); - console.log(`[Vite] Mapped ${packageJson.name} -> ${entryPath}`); } } } @@ -45,95 +39,19 @@ function loadEditorPackages() { } } } - - console.log(`[Vite] Loaded ${editorPackageMapping.size} editor packages`); } loadEditorPackages(); -function loadCocosEnginePath(projectPath: string) { - try { - const tsconfigPath = path.join(projectPath, 'tsconfig.json'); - if (!fs.existsSync(tsconfigPath)) { - console.log('[Vite] No tsconfig.json found in user project'); - return; - } - - const tsconfigContent = fs.readFileSync(tsconfigPath, 'utf-8'); - const tsconfig = JSON5.parse(tsconfigContent); - - if (tsconfig.extends) { - const extendedPath = path.join(projectPath, tsconfig.extends); - if (fs.existsSync(extendedPath)) { - const extendedContent = fs.readFileSync(extendedPath, 'utf-8'); - const extendedConfig = JSON5.parse(extendedContent); - - if (extendedConfig.compilerOptions?.paths?.['db://internal/*']) { - const cocosInternalPaths = extendedConfig.compilerOptions.paths['db://internal/*']; - if (cocosInternalPaths && cocosInternalPaths.length > 0) { - let cocosEnginePath = cocosInternalPaths[0]; - cocosEnginePath = cocosEnginePath.replace(/[\/\\]\*$/, ''); - cocosEnginePath = cocosEnginePath.replace(/[\/\\]editor[\/\\]assets$/, ''); - - const exportsBasePath = path.join(cocosEnginePath, 'exports', 'base.ts'); - if (fs.existsSync(exportsBasePath)) { - cocosEnginePaths.set(projectPath, exportsBasePath); - allowedPaths.add(cocosEnginePath); - console.log(`[Vite] Found Cocos Creator engine at: ${exportsBasePath}`); - console.log(`[Vite] Added Cocos engine path to allowed paths: ${cocosEnginePath}`); - } else { - console.log(`[Vite] Cocos engine base.ts not found at: ${exportsBasePath}`); - } - } - } - } - } - } catch (error) { - console.error('[Vite] Failed to load Cocos engine path:', error); - } -} - -function loadUserProjectDependencies(projectPath: string) { - try { - const packageJsonPath = path.join(projectPath, 'package.json'); - if (!fs.existsSync(packageJsonPath)) { - console.log('[Vite] No package.json found in user project'); - return; - } - - const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8')); - const deps = new Set(); - - if (packageJson.dependencies) { - Object.keys(packageJson.dependencies).forEach(dep => deps.add(dep)); - } - if (packageJson.devDependencies) { - Object.keys(packageJson.devDependencies).forEach(dep => deps.add(dep)); - } - - userProjectDependencies.set(projectPath, deps); - console.log(`[Vite] Loaded ${deps.size} dependencies from user project`); - - loadCocosEnginePath(projectPath); - } catch (error) { - console.error('[Vite] Failed to load user project dependencies:', error); - } -} - const userProjectPlugin = () => ({ name: 'user-project-middleware', configureServer(server: any) { - allowedPaths.add(path.resolve(__dirname, '..')); - server.middlewares.use(async (req: any, res: any, next: any) => { if (req.url?.startsWith('/@user-project/')) { - console.log('[Vite] Received request:', req.url); const urlWithoutQuery = req.url.split('?')[0]; const relativePath = decodeURIComponent(urlWithoutQuery.substring('/@user-project'.length)); - console.log('[Vite] Resolved relative path:', relativePath); let projectPath: string | null = null; - for (const [, path] of userProjectPathMap) { projectPath = path; break; @@ -146,8 +64,6 @@ const userProjectPlugin = () => ({ } const filePath = path.join(projectPath, relativePath); - console.log('[Vite] Looking for file:', filePath); - console.log('[Vite] File exists:', fs.existsSync(filePath)); if (!fs.existsSync(filePath)) { console.error('[Vite] File not found:', filePath); @@ -163,7 +79,6 @@ const userProjectPlugin = () => ({ } try { - console.log('[Vite] Reading and transforming file:', filePath); let content = fs.readFileSync(filePath, 'utf-8'); editorPackageMapping.forEach((srcPath, packageName) => { @@ -175,43 +90,6 @@ const userProjectPlugin = () => ({ ); }); - const deps = userProjectDependencies.get(projectPath); - if (deps) { - deps.forEach(dep => { - if (editorPackageMapping.has(dep)) { - return; - } - - const depPath = path.join(projectPath, 'node_modules', dep); - if (fs.existsSync(depPath)) { - const packageJsonPath = path.join(depPath, 'package.json'); - if (fs.existsSync(packageJsonPath)) { - try { - const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8')); - const mainFile = pkg.module || pkg.main || 'index.js'; - const entryPath = path.join(depPath, mainFile); - - if (fs.existsSync(entryPath)) { - const escapedDep = dep.replace(/\//g, '\\/').replace(/@/g, '\\@'); - const regex = new RegExp(`from\\s+['"]${escapedDep}['"]`, 'g'); - content = content.replace( - regex, - `from "/@fs/${entryPath.replace(/\\/g, '/')}"` - ); - } - } catch (e) { - // 忽略解析错误 - } - } - } - }); - } - - content = content.replace( - /from\s+['"]cc['"]/g, - 'from "/@cocos-shim"' - ); - const fileDir = path.dirname(filePath); const relativeImportRegex = /from\s+['"](\.\.?\/[^'"]+)['"]/g; content = content.replace(relativeImportRegex, (match, importPath) => { @@ -239,7 +117,6 @@ const userProjectPlugin = () => ({ sourcefile: filePath, }); - console.log('[Vite] Successfully transformed file:', filePath); res.setHeader('Content-Type', 'application/javascript; charset=utf-8'); res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Cache-Control', 'no-cache'); @@ -253,58 +130,12 @@ const userProjectPlugin = () => ({ } if (req.url === '/@ecs-framework-shim') { - let projectPath: string | null = null; - for (const [, p] of userProjectPathMap) { - projectPath = p; - break; - } - - if (projectPath) { - const userFrameworkPath = path.join(projectPath, 'node_modules', '@esengine', 'ecs-framework', 'bin', 'index.js'); - if (fs.existsSync(userFrameworkPath)) { - res.setHeader('Content-Type', 'application/javascript; charset=utf-8'); - res.setHeader('Access-Control-Allow-Origin', '*'); - res.end('export * from "/@fs/' + userFrameworkPath.replace(/\\/g, '/') + '";'); - return; - } - } - res.setHeader('Content-Type', 'application/javascript; charset=utf-8'); res.setHeader('Access-Control-Allow-Origin', '*'); res.end('export * from "/@fs/' + path.resolve(__dirname, '../core/src/index.ts').replace(/\\/g, '/') + '";'); return; } - if (req.url === '/@cocos-shim') { - console.log('[Vite] Using Cocos Creator fallback shim (editor environment)'); - res.setHeader('Content-Type', 'application/javascript; charset=utf-8'); - res.setHeader('Access-Control-Allow-Origin', '*'); - res.end(` - export default {}; - export class Node {} - export class Component {} - export class Vec2 { - constructor(x = 0, y = 0) { this.x = x; this.y = y; } - static distance(a, b) { return Math.sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2); } - length() { return Math.sqrt(this.x ** 2 + this.y ** 2); } - normalize() { const len = this.length(); if (len > 0) { this.x /= len; this.y /= len; } return this; } - set(x, y) { this.x = x; this.y = y; return this; } - } - export class Vec3 { - constructor(x = 0, y = 0, z = 0) { this.x = x; this.y = y; this.z = z; } - static distance(a, b) { return Math.sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2 + (a.z - b.z) ** 2); } - length() { return Math.sqrt(this.x ** 2 + this.y ** 2 + this.z ** 2); } - normalize() { const len = this.length(); if (len > 0) { this.x /= len; this.y /= len; this.z /= len; } return this; } - set(x, y, z) { this.x = x; this.y = y; this.z = z; return this; } - } - export class Color { constructor(r = 255, g = 255, b = 255, a = 255) { this.r = r; this.g = g; this.b = b; this.a = a; } } - export class Quat { constructor(x = 0, y = 0, z = 0, w = 1) { this.x = x; this.y = y; this.z = z; this.w = w; } } - export function tween() { return { to() { return this; }, call() { return this; }, start() {} }; } - export function v3(x, y, z) { return new Vec3(x, y, z); } - `); - return; - } - if (req.url === '/@user-project-set-path') { let body = ''; req.on('data', (chunk: any) => { @@ -314,9 +145,6 @@ const userProjectPlugin = () => ({ try { const { path: projectPath } = JSON.parse(body); userProjectPathMap.set('current', projectPath); - allowedPaths.add(projectPath); - loadUserProjectDependencies(projectPath); - console.log('[Vite] User project path set to:', projectPath); res.statusCode = 200; res.end('OK'); } catch (err) { diff --git a/packages/editor-core/src/Services/ComponentLoaderService.ts b/packages/editor-core/src/Services/ComponentLoaderService.ts deleted file mode 100644 index c20b92fa..00000000 --- a/packages/editor-core/src/Services/ComponentLoaderService.ts +++ /dev/null @@ -1,140 +0,0 @@ -import type { IService } from '@esengine/ecs-framework'; -import { Injectable, Component } from '@esengine/ecs-framework'; -import { createLogger } from '@esengine/ecs-framework'; -import { MessageHub } from './MessageHub'; -import type { ComponentFileInfo } from './ComponentDiscoveryService'; -import { ComponentRegistry } from './ComponentRegistry'; - -const logger = createLogger('ComponentLoaderService'); - -export interface LoadedComponentInfo { - fileInfo: ComponentFileInfo; - componentClass: typeof Component; - loadedAt: number; -} - -@Injectable() -export class ComponentLoaderService implements IService { - private loadedComponents: Map = new Map(); - private messageHub: MessageHub; - private componentRegistry: ComponentRegistry; - - constructor(messageHub: MessageHub, componentRegistry: ComponentRegistry) { - this.messageHub = messageHub; - this.componentRegistry = componentRegistry; - } - - public async loadComponents( - componentInfos: ComponentFileInfo[], - modulePathTransform?: (filePath: string) => string - ): Promise { - const loadedComponents: LoadedComponentInfo[] = []; - - for (const componentInfo of componentInfos) { - try { - const loadedComponent = await this.loadComponent(componentInfo, modulePathTransform); - if (loadedComponent) { - loadedComponents.push(loadedComponent); - } - } catch (error) { - logger.error(`Failed to load component: ${componentInfo.fileName}`, error); - } - } - - await this.messageHub.publish('components:loaded', { - count: loadedComponents.length, - components: loadedComponents - }); - - return loadedComponents; - } - - public async loadComponent( - componentInfo: ComponentFileInfo, - modulePathTransform?: (filePath: string) => string - ): Promise { - try { - if (!componentInfo.className) { - logger.warn(`No class name found for component: ${componentInfo.fileName}`); - return null; - } - - let componentClass: typeof Component | undefined; - - if (modulePathTransform) { - const modulePath = modulePathTransform(componentInfo.path); - - try { - const module = await import(/* @vite-ignore */ modulePath); - - componentClass = module[componentInfo.className] || module.default; - - if (!componentClass) { - logger.warn(`Component class ${componentInfo.className} not found in module exports`); - logger.warn(`Available exports: ${Object.keys(module).join(', ')}`); - } - } catch (error) { - logger.error(`Failed to import component module: ${modulePath}`, error); - } - } - - this.componentRegistry.register({ - name: componentInfo.className, - type: componentClass as any, - category: componentInfo.className.includes('Transform') ? 'Transform' : - componentInfo.className.includes('Render') || componentInfo.className.includes('Sprite') ? 'Rendering' : - componentInfo.className.includes('Physics') || componentInfo.className.includes('RigidBody') ? 'Physics' : - 'Custom', - description: `Component from ${componentInfo.fileName}`, - metadata: { - path: componentInfo.path, - fileName: componentInfo.fileName - } - }); - - const loadedInfo: LoadedComponentInfo = { - fileInfo: componentInfo, - componentClass: (componentClass || Component) as any, - loadedAt: Date.now() - }; - - this.loadedComponents.set(componentInfo.path, loadedInfo); - - return loadedInfo; - } catch (error) { - logger.error(`Failed to load component: ${componentInfo.fileName}`, error); - return null; - } - } - - public getLoadedComponents(): LoadedComponentInfo[] { - return Array.from(this.loadedComponents.values()); - } - - public unloadComponent(filePath: string): boolean { - const loadedComponent = this.loadedComponents.get(filePath); - - if (!loadedComponent || !loadedComponent.fileInfo.className) { - return false; - } - - this.componentRegistry.unregister(loadedComponent.fileInfo.className); - this.loadedComponents.delete(filePath); - - return true; - } - - public clearLoadedComponents(): void { - for (const [filePath] of this.loadedComponents) { - this.unloadComponent(filePath); - } - } - - private convertToModulePath(filePath: string): string { - return filePath; - } - - public dispose(): void { - this.clearLoadedComponents(); - } -} diff --git a/packages/editor-core/src/Services/ProjectService.ts b/packages/editor-core/src/Services/ProjectService.ts index 446e06da..4d30a465 100644 --- a/packages/editor-core/src/Services/ProjectService.ts +++ b/packages/editor-core/src/Services/ProjectService.ts @@ -1,7 +1,8 @@ import type { IService } from '@esengine/ecs-framework'; import { Injectable } from '@esengine/ecs-framework'; -import { createLogger } from '@esengine/ecs-framework'; +import { createLogger, Scene } from '@esengine/ecs-framework'; import { MessageHub } from './MessageHub'; +import type { IFileAPI } from '../Types/IFileAPI'; const logger = createLogger('ProjectService'); @@ -19,6 +20,8 @@ export interface ProjectConfig { componentsPath?: string; componentPattern?: string; buildOutput?: string; + scenesPath?: string; + defaultScene?: string; } @Injectable() @@ -26,9 +29,55 @@ export class ProjectService implements IService { private currentProject: ProjectInfo | null = null; private projectConfig: ProjectConfig | null = null; private messageHub: MessageHub; + private fileAPI: IFileAPI; - constructor(messageHub: MessageHub) { + constructor(messageHub: MessageHub, fileAPI: IFileAPI) { this.messageHub = messageHub; + this.fileAPI = fileAPI; + } + + public async createProject(projectPath: string): Promise { + try { + const sep = projectPath.includes('\\') ? '\\' : '/'; + const configPath = `${projectPath}${sep}ecs-editor.config.json`; + + const configExists = await this.fileAPI.pathExists(configPath); + if (configExists) { + throw new Error('ECS project already exists in this directory'); + } + + const config: ProjectConfig = { + projectType: 'cocos', + componentsPath: 'components', + componentPattern: '**/*.ts', + buildOutput: 'temp/editor-components', + scenesPath: 'ecs-scenes', + defaultScene: 'main.ecs' + }; + + await this.fileAPI.writeFileContent(configPath, JSON.stringify(config, null, 2)); + + const scenesPath = `${projectPath}${sep}${config.scenesPath}`; + await this.fileAPI.createDirectory(scenesPath); + + const defaultScenePath = `${scenesPath}${sep}${config.defaultScene}`; + const emptyScene = new Scene(); + const sceneData = emptyScene.serialize({ + format: 'json', + pretty: true, + includeMetadata: true + }) as string; + await this.fileAPI.writeFileContent(defaultScenePath, sceneData); + + await this.messageHub.publish('project:created', { + path: projectPath + }); + + logger.info('Project created', { path: projectPath }); + } catch (error) { + logger.error('Failed to create project', error); + throw error; + } } public async openProject(projectPath: string): Promise { @@ -91,6 +140,28 @@ export class ProjectService implements IService { return `${this.currentProject.path}${sep}${this.projectConfig.componentsPath}`; } + public getScenesPath(): string | null { + if (!this.currentProject) { + return null; + } + const scenesPath = this.projectConfig?.scenesPath || 'assets/scenes'; + const sep = this.currentProject.path.includes('\\') ? '\\' : '/'; + return `${this.currentProject.path}${sep}${scenesPath}`; + } + + public getDefaultScenePath(): string | null { + if (!this.currentProject) { + return null; + } + const scenesPath = this.getScenesPath(); + if (!scenesPath) { + return null; + } + const defaultScene = this.projectConfig?.defaultScene || 'main.scene'; + const sep = this.currentProject.path.includes('\\') ? '\\' : '/'; + return `${scenesPath}${sep}${defaultScene}`; + } + private async validateProject(projectPath: string): Promise { const projectName = projectPath.split(/[\\/]/).pop() || 'Unknown Project'; @@ -118,7 +189,9 @@ export class ProjectService implements IService { projectType: 'cocos', componentsPath: '', componentPattern: '**/*.ts', - buildOutput: 'temp/editor-components' + buildOutput: 'temp/editor-components', + scenesPath: 'ecs-scenes', + defaultScene: 'main.ecs' }; } diff --git a/packages/editor-core/src/Services/SceneManagerService.ts b/packages/editor-core/src/Services/SceneManagerService.ts new file mode 100644 index 00000000..3ee80d73 --- /dev/null +++ b/packages/editor-core/src/Services/SceneManagerService.ts @@ -0,0 +1,283 @@ +import type { IService } from '@esengine/ecs-framework'; +import { Injectable, Core, createLogger, SceneSerializer, Scene } from '@esengine/ecs-framework'; +import type { MessageHub } from './MessageHub'; +import type { IFileAPI } from '../Types/IFileAPI'; +import type { ProjectService } from './ProjectService'; + +const logger = createLogger('SceneManagerService'); + +export interface SceneState { + currentScenePath: string | null; + sceneName: string; + isModified: boolean; + isSaved: boolean; +} + +@Injectable() +export class SceneManagerService implements IService { + private sceneState: SceneState = { + currentScenePath: null, + sceneName: 'Untitled', + isModified: false, + isSaved: false + }; + + private unsubscribeHandlers: Array<() => void> = []; + + constructor( + private messageHub: MessageHub, + private fileAPI: IFileAPI, + private projectService?: ProjectService + ) { + this.setupAutoModificationTracking(); + logger.info('SceneManagerService initialized'); + } + + public async newScene(): Promise { + if (!await this.canClose()) { + return; + } + + const scene = Core.scene as Scene | null; + if (!scene) { + throw new Error('No active scene'); + } + scene.entities.removeAllEntities(); + const systems = [...scene.systems]; + for (const system of systems) { + scene.removeEntityProcessor(system); + } + + this.sceneState = { + currentScenePath: null, + sceneName: 'Untitled', + isModified: false, + isSaved: false + }; + + await this.messageHub.publish('scene:new', {}); + logger.info('New scene created'); + } + + public async openScene(filePath?: string): Promise { + if (!await this.canClose()) { + return; + } + + let path: string | null | undefined = filePath; + if (!path) { + path = await this.fileAPI.openSceneDialog(); + if (!path) { + return; + } + } + + try { + const jsonData = await this.fileAPI.readFileContent(path); + + const validation = SceneSerializer.validate(jsonData); + if (!validation.valid) { + throw new Error(`场景文件损坏: ${validation.errors?.join(', ')}`); + } + + const scene = Core.scene as Scene | null; + if (!scene) { + throw new Error('No active scene'); + } + scene.deserialize(jsonData, { + strategy: 'replace' + }); + + const fileName = path.split(/[/\\]/).pop() || 'Untitled'; + const sceneName = fileName.replace('.ecs', ''); + + this.sceneState = { + currentScenePath: path, + sceneName, + isModified: false, + isSaved: true + }; + + await this.messageHub.publish('scene:loaded', { + path, + sceneName, + isModified: false, + isSaved: true + }); + logger.info(`Scene loaded: ${path}`); + } catch (error) { + logger.error('Failed to load scene:', error); + throw error; + } + } + + public async saveScene(): Promise { + if (!this.sceneState.currentScenePath) { + await this.saveSceneAs(); + return; + } + + try { + const scene = Core.scene as Scene | null; + if (!scene) { + throw new Error('No active scene'); + } + const jsonData = scene.serialize({ + format: 'json', + pretty: true, + includeMetadata: true + }) as string; + + await this.fileAPI.saveProject(this.sceneState.currentScenePath, jsonData); + + this.sceneState.isModified = false; + this.sceneState.isSaved = true; + + await this.messageHub.publish('scene:saved', { + path: this.sceneState.currentScenePath + }); + logger.info(`Scene saved: ${this.sceneState.currentScenePath}`); + } catch (error) { + logger.error('Failed to save scene:', error); + throw error; + } + } + + public async saveSceneAs(filePath?: string): Promise { + let path: string | null | undefined = filePath; + if (!path) { + let defaultName = this.sceneState.sceneName || 'Untitled'; + + if (this.projectService?.isProjectOpen()) { + const scenesPath = this.projectService.getScenesPath(); + if (scenesPath) { + const sep = scenesPath.includes('\\') ? '\\' : '/'; + defaultName = `${scenesPath}${sep}${defaultName}`; + } + } + + path = await this.fileAPI.saveSceneDialog(defaultName); + if (!path) { + return; + } + } + + if (!path.endsWith('.ecs')) { + path += '.ecs'; + } + + try { + const scene = Core.scene as Scene | null; + if (!scene) { + throw new Error('No active scene'); + } + const jsonData = scene.serialize({ + format: 'json', + pretty: true, + includeMetadata: true + }) as string; + + await this.fileAPI.saveProject(path, jsonData); + + const fileName = path.split(/[/\\]/).pop() || 'Untitled'; + const sceneName = fileName.replace('.ecs', ''); + + this.sceneState = { + currentScenePath: path, + sceneName, + isModified: false, + isSaved: true + }; + + await this.messageHub.publish('scene:saved', { path }); + logger.info(`Scene saved as: ${path}`); + } catch (error) { + logger.error('Failed to save scene as:', error); + throw error; + } + } + + public async exportScene(filePath?: string): Promise { + let path: string | null | undefined = filePath; + if (!path) { + let defaultName = (this.sceneState.sceneName || 'Untitled') + '.ecs.bin'; + + if (this.projectService?.isProjectOpen()) { + const scenesPath = this.projectService.getScenesPath(); + if (scenesPath) { + const sep = scenesPath.includes('\\') ? '\\' : '/'; + defaultName = `${scenesPath}${sep}${defaultName}`; + } + } + + path = await this.fileAPI.saveSceneDialog(defaultName); + if (!path) { + return; + } + } + + if (!path.endsWith('.ecs.bin')) { + path += '.ecs.bin'; + } + + try { + const scene = Core.scene as Scene | null; + if (!scene) { + throw new Error('No active scene'); + } + const binaryData = scene.serialize({ + format: 'binary' + }) as Uint8Array; + + await this.fileAPI.exportBinary(binaryData, path); + + await this.messageHub.publish('scene:exported', { path }); + logger.info(`Scene exported: ${path}`); + } catch (error) { + logger.error('Failed to export scene:', error); + throw error; + } + } + + public getSceneState(): SceneState { + return { ...this.sceneState }; + } + + public markAsModified(): void { + if (!this.sceneState.isModified) { + this.sceneState.isModified = true; + this.messageHub.publishSync('scene:modified', {}); + logger.debug('Scene marked as modified'); + } + } + + public async canClose(): Promise { + if (!this.sceneState.isModified) { + return true; + } + + return true; + } + + private setupAutoModificationTracking(): void { + const unsubscribeEntityAdded = this.messageHub.subscribe('entity:added', () => { + this.markAsModified(); + }); + + const unsubscribeEntityRemoved = this.messageHub.subscribe('entity:removed', () => { + this.markAsModified(); + }); + + this.unsubscribeHandlers.push(unsubscribeEntityAdded, unsubscribeEntityRemoved); + + logger.debug('Auto modification tracking setup complete'); + } + + public dispose(): void { + for (const unsubscribe of this.unsubscribeHandlers) { + unsubscribe(); + } + this.unsubscribeHandlers = []; + logger.info('SceneManagerService disposed'); + } +} diff --git a/packages/editor-core/src/Types/IFileAPI.ts b/packages/editor-core/src/Types/IFileAPI.ts new file mode 100644 index 00000000..15be5847 --- /dev/null +++ b/packages/editor-core/src/Types/IFileAPI.ts @@ -0,0 +1,61 @@ +/** + * 文件 API 接口 + * + * 定义编辑器与文件系统交互的抽象接口 + * 具体实现由上层应用提供(如 TauriFileAPI) + */ +export interface IFileAPI { + /** + * 打开场景文件选择对话框 + * @returns 用户选择的文件路径,取消则返回 null + */ + openSceneDialog(): Promise; + + /** + * 打开保存场景对话框 + * @param defaultName 默认文件名 + * @returns 用户选择的文件路径,取消则返回 null + */ + saveSceneDialog(defaultName?: string): Promise; + + /** + * 读取文件内容 + * @param path 文件路径 + * @returns 文件内容(文本格式) + */ + readFileContent(path: string): Promise; + + /** + * 保存项目文件 + * @param path 保存路径 + * @param data 文件内容(文本格式) + */ + saveProject(path: string, data: string): Promise; + + /** + * 导出二进制文件 + * @param data 二进制数据 + * @param path 保存路径 + */ + exportBinary(data: Uint8Array, path: string): Promise; + + /** + * 创建目录 + * @param path 目录路径 + */ + createDirectory(path: string): Promise; + + /** + * 写入文件内容 + * @param path 文件路径 + * @param content 文件内容 + */ + writeFileContent(path: string, content: string): Promise; + + /** + * 检查路径是否存在 + * @param path 文件或目录路径 + * @returns 路径是否存在 + */ + pathExists(path: string): Promise; +} diff --git a/packages/editor-core/src/index.ts b/packages/editor-core/src/index.ts index 91f551b7..2b538b11 100644 --- a/packages/editor-core/src/index.ts +++ b/packages/editor-core/src/index.ts @@ -16,8 +16,9 @@ export * from './Services/LocaleService'; export * from './Services/PropertyMetadata'; export * from './Services/ProjectService'; export * from './Services/ComponentDiscoveryService'; -export * from './Services/ComponentLoaderService'; export * from './Services/LogService'; export * from './Services/SettingsRegistry'; +export * from './Services/SceneManagerService'; export * from './Types/UITypes'; +export * from './Types/IFileAPI';