Compare commits

...

21 Commits

Author SHA1 Message Date
YHH
a801e4f50e Merge pull request #150 from esengine/issue-149-编辑器支持设置字体大小
支持字体设置大小
2025-10-17 23:47:42 +08:00
YHH
a9f9ad9b94 支持字体设置大小 2025-10-17 23:47:04 +08:00
YHH
3cf1dab5b9 Merge pull request #148 from esengine/issue-147-Scene的构造函数不应该由用户传入性能分析器
performancemonitor由内部框架维护
2025-10-17 22:19:53 +08:00
YHH
63165bbbfc performancemonitor由内部框架维护 2025-10-17 22:13:32 +08:00
YHH
61caad2bef Merge pull request #146 from esengine/issue-132-场景序列化系统
更新图标及场景序列化系统
2025-10-17 18:17:56 +08:00
YHH
b826bbc4c7 更新图标及场景序列化系统 2025-10-17 18:13:31 +08:00
YHH
2ce7dad8d8 Merge pull request #131 from esengine/release/editor-v1.0.3
chore(editor): Release v1.0.3
2025-10-16 23:53:37 +08:00
esengine
dff400bf22 chore(editor): bump version to 1.0.3 2025-10-16 15:52:45 +00:00
YHH
27ce902344 配置createUpdaterArtifacts生成sig 2025-10-16 23:38:11 +08:00
YHH
33ee0a04c6 升级tauri-action 2025-10-16 23:20:55 +08:00
YHH
d68f6922f8 Merge pull request #129 from esengine/release/editor-v1.0.1
chore(editor): Release v1.0.1
2025-10-16 23:09:26 +08:00
esengine
f8539d7958 chore(editor): bump version to 1.0.1 2025-10-16 15:08:22 +00:00
YHH
14dc911e0a Merge branch 'master' of https://github.com/esengine/ecs-framework 2025-10-16 22:55:09 +08:00
YHH
deccb6bf84 修复editor再ci上版本冲突问题 2025-10-16 22:54:58 +08:00
YHH
dacbfcae95 Merge pull request #127 from esengine/imgbot
[ImgBot] Optimize images
2025-10-16 22:49:51 +08:00
ImgBotApp
1b69ed17b7 [ImgBot] Optimize images
*Total -- 496.42kb -> 376.40kb (24.18%)

/screenshots/main_screetshot.png -- 179.18kb -> 121.90kb (31.97%)
/screenshots/performance_profiler.png -- 59.99kb -> 41.74kb (30.43%)
/screenshots/port_manager.png -- 22.70kb -> 16.86kb (25.72%)
/screenshots/about.png -- 38.75kb -> 29.00kb (25.17%)
/screenshots/plugin_manager.png -- 38.49kb -> 29.16kb (24.25%)
/packages/editor-app/src-tauri/icons/icon.svg -- 3.52kb -> 2.76kb (21.6%)
/screenshots/settings.png -- 53.78kb -> 44.90kb (16.51%)
/packages/editor-app/src-tauri/icons/icon.png -- 33.45kb -> 29.78kb (10.98%)
/packages/editor-app/src-tauri/icons/512x512.png -- 33.45kb -> 29.78kb (10.98%)
/packages/editor-app/src-tauri/icons/256x256.png -- 13.97kb -> 12.76kb (8.68%)
/packages/editor-app/src-tauri/icons/128x128@2x.png -- 13.97kb -> 12.76kb (8.68%)
/packages/editor-app/src-tauri/icons/128x128.png -- 5.17kb -> 5.03kb (2.89%)

Signed-off-by: ImgBotApp <ImgBotHelp@gmail.com>
2025-10-16 14:45:32 +00:00
YHH
241acc9050 更新文档 2025-10-16 22:45:08 +08:00
YHH
8fa921930c Merge pull request #126 from esengine/issue-125-编辑器热更新
热更新配置
2025-10-16 22:31:26 +08:00
YHH
011e43811a 热更新配置 2025-10-16 22:26:50 +08:00
YHH
9f16debd75 新增rust编译缓存和ts构建缓存 2025-10-16 20:54:33 +08:00
YHH
92c56c439b 移除过时的工作流 2025-10-16 20:50:32 +08:00
102 changed files with 2647 additions and 919 deletions

View File

@@ -12,28 +12,7 @@ on:
default: '1.0.0' default: '1.0.0'
jobs: jobs:
create-release:
runs-on: ubuntu-latest
outputs:
release_id: ${{ steps.create-release.outputs.id }}
release_upload_url: ${{ steps.create-release.outputs.upload_url }}
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Create Release
id: create-release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ github.event.inputs.version || github.ref_name }}
release_name: ECS Editor ${{ github.event.inputs.version || github.ref_name }}
draft: true
prerelease: false
build-tauri: build-tauri:
needs: create-release
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
@@ -65,6 +44,12 @@ jobs:
with: with:
targets: ${{ matrix.target }} targets: ${{ matrix.target }}
- name: Rust cache
uses: Swatinem/rust-cache@v2
with:
workspaces: packages/editor-app/src-tauri
cache-on-failure: true
- name: Install dependencies (Ubuntu) - name: Install dependencies (Ubuntu)
if: matrix.platform == 'ubuntu-latest' if: matrix.platform == 'ubuntu-latest'
run: | run: |
@@ -74,6 +59,24 @@ jobs:
- name: Install frontend dependencies - name: Install frontend dependencies
run: npm ci run: npm ci
- name: Update version in config files (for manual trigger)
if: github.event_name == 'workflow_dispatch'
run: |
cd packages/editor-app
# 临时更新版本号用于构建(不提交到仓库)
npm version ${{ github.event.inputs.version }} --no-git-tag-version
node scripts/sync-version.js
- name: Cache TypeScript build
uses: actions/cache@v4
with:
path: |
packages/core/bin
packages/editor-core/dist
key: ${{ runner.os }}-ts-build-${{ hashFiles('packages/core/src/**', 'packages/editor-core/src/**') }}
restore-keys: |
${{ runner.os }}-ts-build-
- name: Build core package - name: Build core package
run: npm run build:core run: npm run build:core
@@ -83,31 +86,66 @@ jobs:
npm run build npm run build
- name: Build Tauri app - name: Build Tauri app
uses: tauri-apps/tauri-action@v0 uses: tauri-apps/tauri-action@v0.5
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
with: with:
projectPath: packages/editor-app projectPath: packages/editor-app
tagName: ${{ github.event.inputs.version || github.ref_name }} tagName: ${{ github.event_name == 'workflow_dispatch' && format('editor-v{0}', github.event.inputs.version) || github.ref_name }}
releaseName: 'ECS Editor ${{ github.event.inputs.version || github.ref_name }}' releaseName: 'ECS Editor v${{ github.event.inputs.version || github.ref_name }}'
releaseBody: 'See the assets to download this version and install.' releaseBody: 'See the assets to download this version and install.'
releaseDraft: true releaseDraft: false
prerelease: false prerelease: false
includeUpdaterJson: true
updaterJsonKeepUniversal: false
args: ${{ matrix.platform == 'macos-latest' && format('--target {0}', matrix.target) || '' }} args: ${{ matrix.platform == 'macos-latest' && format('--target {0}', matrix.target) || '' }}
publish-release: # 构建成功后,创建 PR 更新版本号
update-version-pr:
needs: build-tauri needs: build-tauri
if: github.event_name == 'workflow_dispatch' && success()
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Publish Release - name: Checkout code
uses: actions/github-script@v7 uses: actions/checkout@v4
env:
RELEASE_ID: ${{ needs.create-release.outputs.release_id }} - name: Setup Node.js
uses: actions/setup-node@v4
with: with:
script: | node-version: '20.x'
github.rest.repos.updateRelease({
owner: context.repo.owner, - name: Update version files
repo: context.repo.repo, run: |
release_id: process.env.RELEASE_ID, cd packages/editor-app
draft: false npm version ${{ github.event.inputs.version }} --no-git-tag-version
}) node scripts/sync-version.js
- name: Create Pull Request
uses: peter-evans/create-pull-request@v6
with:
token: ${{ secrets.GITHUB_TOKEN }}
commit-message: "chore(editor): bump version to ${{ github.event.inputs.version }}"
branch: release/editor-v${{ github.event.inputs.version }}
delete-branch: true
title: "chore(editor): Release v${{ github.event.inputs.version }}"
body: |
## 🚀 Release v${{ github.event.inputs.version }}
This PR updates the editor version after successful release build.
### Changes
- ✅ Updated `packages/editor-app/package.json` → `${{ github.event.inputs.version }}`
- ✅ Updated `packages/editor-app/src-tauri/tauri.conf.json` → `${{ github.event.inputs.version }}`
### Release
- 📦 [GitHub Release](https://github.com/${{ github.repository }}/releases/tag/editor-v${{ github.event.inputs.version }})
---
*This PR was automatically created by the release workflow.*
labels: |
release
editor
automated pr

View File

@@ -95,11 +95,47 @@ function gameLoop(deltaTime: number) {
支持主流游戏引擎和 Web 平台: 支持主流游戏引擎和 Web 平台:
- **Cocos Creator** - 内置引擎集成支持,提供[专用调试插件](https://store.cocos.com/app/detail/7823) - **Cocos Creator**
- **Laya 引擎** - 完整的生命周期管理 - **Laya 引擎**
- **原生 Web** - 浏览器环境直接运行 - **原生 Web** - 浏览器环境直接运行
- **小游戏平台** - 微信、支付宝等小游戏 - **小游戏平台** - 微信、支付宝等小游戏
## ECS Framework Editor
跨平台桌面编辑器,提供可视化开发和调试工具。
### 主要功能
- **场景管理** - 可视化场景层级和实体管理
- **组件检视** - 实时查看和编辑实体组件
- **性能分析** - 内置 Profiler 监控系统性能
- **插件系统** - 可扩展的插件架构
- **远程调试** - 连接运行中的游戏进行实时调试
- **自动更新** - 支持热更新,自动获取最新版本
### 下载
[![Latest Release](https://img.shields.io/github/v/release/esengine/ecs-framework?label=下载最新版本&style=for-the-badge)](https://github.com/esengine/ecs-framework/releases/latest)
支持 Windows、macOS (Intel & Apple Silicon)
### 截图
<img src="screenshots/main_screetshot.png" alt="ECS Framework Editor" width="800">
<details>
<summary>查看更多截图</summary>
**性能分析器**
<img src="screenshots/performance_profiler.png" alt="Performance Profiler" width="600">
**插件管理**
<img src="screenshots/plugin_manager.png" alt="Plugin Manager" width="600">
**设置界面**
<img src="screenshots/settings.png" alt="Settings" width="600">
</details>
## 示例项目 ## 示例项目

23
package-lock.json generated
View File

@@ -6031,6 +6031,15 @@
"node": ">= 10" "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": { "node_modules/@tauri-apps/plugin-shell": {
"version": "2.3.1", "version": "2.3.1",
"resolved": "https://registry.npmjs.org/@tauri-apps/plugin-shell/-/plugin-shell-2.3.1.tgz", "resolved": "https://registry.npmjs.org/@tauri-apps/plugin-shell/-/plugin-shell-2.3.1.tgz",
@@ -6040,6 +6049,16 @@
"@tauri-apps/api": "^2.8.0" "@tauri-apps/api": "^2.8.0"
} }
}, },
"node_modules/@tauri-apps/plugin-updater": {
"version": "2.9.0",
"resolved": "https://registry.npmjs.org/@tauri-apps/plugin-updater/-/plugin-updater-2.9.0.tgz",
"integrity": "sha512-j++sgY8XpeDvzImTrzWA08OqqGqgkNyxczLD7FjNJJx/uXxMZFz5nDcfkyoI/rCjYuj2101Tci/r/HFmOmoxCg==",
"dev": true,
"license": "MIT OR Apache-2.0",
"dependencies": {
"@tauri-apps/api": "^2.6.0"
}
},
"node_modules/@tootallnate/once": { "node_modules/@tootallnate/once": {
"version": "2.0.0", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-2.0.0.tgz", "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-2.0.0.tgz",
@@ -17654,11 +17673,12 @@
}, },
"packages/editor-app": { "packages/editor-app": {
"name": "@esengine/editor-app", "name": "@esengine/editor-app",
"version": "1.0.0", "version": "1.0.3",
"dependencies": { "dependencies": {
"@esengine/ecs-framework": "file:../core", "@esengine/ecs-framework": "file:../core",
"@esengine/editor-core": "file:../editor-core", "@esengine/editor-core": "file:../editor-core",
"@tauri-apps/api": "^2.2.0", "@tauri-apps/api": "^2.2.0",
"@tauri-apps/plugin-dialog": "^2.4.0",
"@tauri-apps/plugin-shell": "^2.0.0", "@tauri-apps/plugin-shell": "^2.0.0",
"json5": "^2.2.3", "json5": "^2.2.3",
"lucide-react": "^0.545.0", "lucide-react": "^0.545.0",
@@ -17667,6 +17687,7 @@
}, },
"devDependencies": { "devDependencies": {
"@tauri-apps/cli": "^2.2.0", "@tauri-apps/cli": "^2.2.0",
"@tauri-apps/plugin-updater": "^2.9.0",
"@types/react": "^18.3.12", "@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1", "@types/react-dom": "^18.3.1",
"@vitejs/plugin-react": "^4.3.4", "@vitejs/plugin-react": "^4.3.4",

View File

@@ -180,7 +180,7 @@ export class Core {
this._serviceContainer.registerInstance(PoolManager, this._poolManager); this._serviceContainer.registerInstance(PoolManager, this._poolManager);
// 初始化场景管理器 // 初始化场景管理器
this._sceneManager = new SceneManager(); this._sceneManager = new SceneManager(this._performanceMonitor);
this._serviceContainer.registerInstance(SceneManager, this._sceneManager); this._serviceContainer.registerInstance(SceneManager, this._sceneManager);
// 设置场景切换回调,通知调试管理器 // 设置场景切换回调,通知调试管理器

View File

@@ -6,6 +6,7 @@ import { ComponentStorageManager } from './Core/ComponentStorage';
import { QuerySystem } from './Core/QuerySystem'; import { QuerySystem } from './Core/QuerySystem';
import { TypeSafeEventSystem } from './Core/EventSystem'; import { TypeSafeEventSystem } from './Core/EventSystem';
import type { ReferenceTracker } from './Core/ReferenceTracker'; import type { ReferenceTracker } from './Core/ReferenceTracker';
import type { ServiceContainer } from '../Core/ServiceContainer';
/** /**
* 场景接口定义 * 场景接口定义
@@ -67,6 +68,13 @@ export interface IScene {
*/ */
readonly referenceTracker: ReferenceTracker; readonly referenceTracker: ReferenceTracker;
/**
* 服务容器
*
* 场景级别的依赖注入容器,用于管理服务的生命周期。
*/
readonly services: ServiceContainer;
/** /**
* 获取系统列表 * 获取系统列表
*/ */
@@ -171,12 +179,4 @@ export interface ISceneConfig {
* 场景名称 * 场景名称
*/ */
name?: string; name?: string;
/**
* 性能监控器实例(可选)
*
* 如果不提供Scene会自动从Core.services获取全局PerformanceMonitor。
* 提供此参数可以实现场景级别的独立性能监控。
*/
performanceMonitor?: any;
} }

View File

@@ -21,7 +21,7 @@ import { createLogger } from '../Utils/Logger';
/** /**
* 游戏场景默认实现类 * 游戏场景默认实现类
* *
* 实现IScene接口提供场景的基础功能。 * 实现IScene接口提供场景的基础功能。
* 推荐使用组合而非继承的方式来构建自定义场景。 * 推荐使用组合而非继承的方式来构建自定义场景。
*/ */
@@ -97,11 +97,11 @@ export class Scene implements IScene {
private readonly logger: ReturnType<typeof createLogger>; private readonly logger: ReturnType<typeof createLogger>;
/** /**
* 性能监控器 * 性能监控器缓存
* *
* 用于监控场景和系统的性能。可以在构造函数中注入如果不提供则从Core获取。 * 用于监控场景和系统的性能。从 ServiceContainer 获取。
*/ */
private readonly _performanceMonitor: PerformanceMonitor; private _performanceMonitor: PerformanceMonitor | null = null;
/** /**
* 场景是否已开始运行 * 场景是否已开始运行
@@ -182,10 +182,6 @@ export class Scene implements IScene {
this._services = new ServiceContainer(); this._services = new ServiceContainer();
this.logger = createLogger('Scene'); this.logger = createLogger('Scene');
// 从配置获取 PerformanceMonitor如果未提供则创建一个新实例
// Scene 应该是独立的,不依赖于 Core通过构造函数参数明确依赖关系
this._performanceMonitor = config?.performanceMonitor || new PerformanceMonitor();
if (config?.name) { if (config?.name) {
this.name = config.name; this.name = config.name;
} }
@@ -201,6 +197,19 @@ export class Scene implements IScene {
} }
} }
/**
* 获取性能监控器
*
* 从 ServiceContainer 获取,如果未注册则创建默认实例(向后兼容)
*/
private get performanceMonitor(): PerformanceMonitor {
if (!this._performanceMonitor) {
this._performanceMonitor = this._services.tryResolve(PerformanceMonitor)
?? new PerformanceMonitor();
}
return this._performanceMonitor;
}
/** /**
* 初始化场景 * 初始化场景
* *
@@ -578,7 +587,7 @@ export class Scene implements IScene {
system.scene = this; system.scene = this;
system.setPerformanceMonitor(this._performanceMonitor); system.setPerformanceMonitor(this.performanceMonitor);
const metadata = getSystemMetadata(constructor); const metadata = getSystemMetadata(constructor);
if (metadata?.updateOrder !== undefined) { if (metadata?.updateOrder !== undefined) {

View File

@@ -4,6 +4,7 @@ import { Time } from '../Utils/Time';
import { createLogger } from '../Utils/Logger'; import { createLogger } from '../Utils/Logger';
import type { IService } from '../Core/ServiceContainer'; import type { IService } from '../Core/ServiceContainer';
import { World } from './World'; import { World } from './World';
import { PerformanceMonitor } from '../Utils/PerformanceMonitor';
/** /**
* 单场景管理器 * 单场景管理器
@@ -73,14 +74,20 @@ export class SceneManager implements IService {
*/ */
private _onSceneChangedCallback?: () => void; private _onSceneChangedCallback?: () => void;
/**
* 性能监控器(从 Core 注入)
*/
private _performanceMonitor: PerformanceMonitor | null = null;
/** /**
* 默认场景ID * 默认场景ID
*/ */
private static readonly DEFAULT_SCENE_ID = '__main__'; private static readonly DEFAULT_SCENE_ID = '__main__';
constructor() { constructor(performanceMonitor?: PerformanceMonitor) {
this._defaultWorld = new World({ name: '__default__' }); this._defaultWorld = new World({ name: '__default__' });
this._defaultWorld.start(); this._defaultWorld.start();
this._performanceMonitor = performanceMonitor || null;
} }
/** /**
@@ -111,6 +118,11 @@ export class SceneManager implements IService {
// 移除旧场景 // 移除旧场景
this._defaultWorld.removeAllScenes(); this._defaultWorld.removeAllScenes();
// 注册全局 PerformanceMonitor 到 Scene 的 ServiceContainer
if (this._performanceMonitor) {
scene.services.registerInstance(PerformanceMonitor, this._performanceMonitor);
}
// 通过 World 创建新场景 // 通过 World 创建新场景
this._defaultWorld.createScene(SceneManager.DEFAULT_SCENE_ID, scene); this._defaultWorld.createScene(SceneManager.DEFAULT_SCENE_ID, scene);
this._defaultWorld.setSceneActive(SceneManager.DEFAULT_SCENE_ID, true); this._defaultWorld.setSceneActive(SceneManager.DEFAULT_SCENE_ID, true);

View File

@@ -589,25 +589,10 @@ describe('Scene - 场景管理系统测试', () => {
}); });
}); });
describe('依赖注入优化', () => { describe('性能监控', () => {
test('应该支持注入自定义PerformanceMonitor', () => { test('Scene应该自动创建PerformanceMonitor', () => {
const mockPerfMonitor = {
startMeasure: jest.fn(),
endMeasure: jest.fn(),
recordSystemData: jest.fn(),
recordEntityCount: jest.fn(),
recordComponentCount: jest.fn(),
update: jest.fn(),
getSystemData: jest.fn(),
getSystemStats: jest.fn(),
resetSystem: jest.fn(),
reset: jest.fn(),
dispose: jest.fn()
};
const customScene = new Scene({ const customScene = new Scene({
name: 'CustomScene', name: 'CustomScene'
performanceMonitor: mockPerfMonitor as any
}); });
class TestSystem extends EntitySystem { class TestSystem extends EntitySystem {
@@ -619,13 +604,14 @@ describe('Scene - 场景管理系统测试', () => {
const system = new TestSystem(); const system = new TestSystem();
customScene.addEntityProcessor(system); customScene.addEntityProcessor(system);
expect(mockPerfMonitor).toBeDefined(); expect(customScene).toBeDefined();
customScene.end(); customScene.end();
}); });
test('未提供PerformanceMonitor时应该从Core获取', () => { test('每个Scene应该有独立的PerformanceMonitor', () => {
const defaultScene = new Scene({ name: 'DefaultScene' }); const scene1 = new Scene({ name: 'Scene1' });
const scene2 = new Scene({ name: 'Scene2' });
class TestSystem extends EntitySystem { class TestSystem extends EntitySystem {
constructor() { constructor() {
@@ -633,12 +619,14 @@ describe('Scene - 场景管理系统测试', () => {
} }
} }
const system = new TestSystem(); scene1.addEntityProcessor(new TestSystem());
defaultScene.addEntityProcessor(system); scene2.addEntityProcessor(new TestSystem());
expect(defaultScene).toBeDefined(); expect(scene1).toBeDefined();
expect(scene2).toBeDefined();
defaultScene.end(); scene1.end();
scene2.end();
}); });
}); });
}); });

View File

@@ -1,6 +1,6 @@
{ {
"name": "@esengine/editor-app", "name": "@esengine/editor-app",
"version": "1.0.0", "version": "1.0.3",
"description": "ECS Framework Editor Application - Cross-platform desktop editor", "description": "ECS Framework Editor Application - Cross-platform desktop editor",
"type": "module", "type": "module",
"private": true, "private": true,
@@ -10,12 +10,14 @@
"preview": "vite preview", "preview": "vite preview",
"tauri": "tauri", "tauri": "tauri",
"tauri:dev": "tauri dev", "tauri:dev": "tauri dev",
"tauri:build": "tauri build" "tauri:build": "tauri build",
"version": "node scripts/sync-version.js && git add src-tauri/tauri.conf.json"
}, },
"dependencies": { "dependencies": {
"@esengine/ecs-framework": "file:../core", "@esengine/ecs-framework": "file:../core",
"@esengine/editor-core": "file:../editor-core", "@esengine/editor-core": "file:../editor-core",
"@tauri-apps/api": "^2.2.0", "@tauri-apps/api": "^2.2.0",
"@tauri-apps/plugin-dialog": "^2.4.0",
"@tauri-apps/plugin-shell": "^2.0.0", "@tauri-apps/plugin-shell": "^2.0.0",
"json5": "^2.2.3", "json5": "^2.2.3",
"lucide-react": "^0.545.0", "lucide-react": "^0.545.0",
@@ -24,6 +26,7 @@
}, },
"devDependencies": { "devDependencies": {
"@tauri-apps/cli": "^2.2.0", "@tauri-apps/cli": "^2.2.0",
"@tauri-apps/plugin-updater": "^2.9.0",
"@types/react": "^18.3.12", "@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1", "@types/react-dom": "^18.3.1",
"@vitejs/plugin-react": "^4.3.4", "@vitejs/plugin-react": "^4.3.4",

View File

@@ -0,0 +1,33 @@
#!/usr/bin/env node
/**
* 同步 package.json 和 tauri.conf.json 的版本号
* 在 npm version 命令执行后自动运行
*/
import { readFileSync, writeFileSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// 读取 package.json
const packageJsonPath = join(__dirname, '../package.json');
const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf8'));
const newVersion = packageJson.version;
// 读取 tauri.conf.json
const tauriConfigPath = join(__dirname, '../src-tauri/tauri.conf.json');
const tauriConfig = JSON.parse(readFileSync(tauriConfigPath, 'utf8'));
// 更新 tauri.conf.json 的版本号
const oldVersion = tauriConfig.version;
tauriConfig.version = newVersion;
// 写回文件(保持格式)
writeFileSync(tauriConfigPath, JSON.stringify(tauriConfig, null, 2) + '\n', 'utf8');
console.log(`✓ Version synced: ${oldVersion}${newVersion}`);
console.log(` - package.json: ${newVersion}`);
console.log(` - tauri.conf.json: ${newVersion}`);

View File

@@ -47,6 +47,15 @@ version = "1.0.100"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61" checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61"
[[package]]
name = "arbitrary"
version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1"
dependencies = [
"derive_arbitrary",
]
[[package]] [[package]]
name = "ashpd" name = "ashpd"
version = "0.11.0" version = "0.11.0"
@@ -575,6 +584,17 @@ dependencies = [
"serde_core", "serde_core",
] ]
[[package]]
name = "derive_arbitrary"
version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.106",
]
[[package]] [[package]]
name = "derive_more" name = "derive_more"
version = "0.99.20" version = "0.99.20"
@@ -735,6 +755,7 @@ dependencies = [
"tauri-build", "tauri-build",
"tauri-plugin-dialog", "tauri-plugin-dialog",
"tauri-plugin-shell", "tauri-plugin-shell",
"tauri-plugin-updater",
"tokio", "tokio",
"tokio-tungstenite", "tokio-tungstenite",
] ]
@@ -868,6 +889,18 @@ dependencies = [
"rustc_version", "rustc_version",
] ]
[[package]]
name = "filetime"
version = "0.2.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc0505cd1b6fa6580283f6bdf70a73fcf4aba1184038c90902b92b3dd0df63ed"
dependencies = [
"cfg-if",
"libc",
"libredox",
"windows-sys 0.60.2",
]
[[package]] [[package]]
name = "find-msvc-tools" name = "find-msvc-tools"
version = "0.1.4" version = "0.1.4"
@@ -1157,8 +1190,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592" checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"js-sys",
"libc", "libc",
"wasi 0.11.1+wasi-snapshot-preview1", "wasi 0.11.1+wasi-snapshot-preview1",
"wasm-bindgen",
] ]
[[package]] [[package]]
@@ -1168,9 +1203,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4" checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"js-sys",
"libc", "libc",
"r-efi", "r-efi",
"wasi 0.14.7+wasi-0.2.4", "wasi 0.14.7+wasi-0.2.4",
"wasm-bindgen",
] ]
[[package]] [[package]]
@@ -1430,6 +1467,23 @@ dependencies = [
"want", "want",
] ]
[[package]]
name = "hyper-rustls"
version = "0.27.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3c93eb611681b207e1fe55d5a71ecf91572ec8a6705cdb6857f7d8d5242cf58"
dependencies = [
"http",
"hyper",
"hyper-util",
"rustls",
"rustls-pki-types",
"tokio",
"tokio-rustls",
"tower-service",
"webpki-roots",
]
[[package]] [[package]]
name = "hyper-util" name = "hyper-util"
version = "0.1.17" version = "0.1.17"
@@ -1828,6 +1882,7 @@ checksum = "416f7e718bdb06000964960ffa43b4335ad4012ae8b99060261aa4a8088d5ccb"
dependencies = [ dependencies = [
"bitflags 2.9.4", "bitflags 2.9.4",
"libc", "libc",
"redox_syscall",
] ]
[[package]] [[package]]
@@ -1857,6 +1912,12 @@ version = "0.4.28"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34080505efa8e45a4b816c349525ebe327ceaa8559756f0356cba97ef3bf7432" checksum = "34080505efa8e45a4b816c349525ebe327ceaa8559756f0356cba97ef3bf7432"
[[package]]
name = "lru-slab"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
[[package]] [[package]]
name = "mac" name = "mac"
version = "0.1.1" version = "0.1.1"
@@ -1915,6 +1976,12 @@ version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
[[package]]
name = "minisign-verify"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e856fdd13623a2f5f2f54676a4ee49502a96a80ef4a62bcedd23d52427c44d43"
[[package]] [[package]]
name = "miniz_oxide" name = "miniz_oxide"
version = "0.8.9" version = "0.8.9"
@@ -2250,6 +2317,18 @@ dependencies = [
"objc2-foundation 0.2.2", "objc2-foundation 0.2.2",
] ]
[[package]]
name = "objc2-osa-kit"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f112d1746737b0da274ef79a23aac283376f335f4095a083a267a082f21db0c0"
dependencies = [
"bitflags 2.9.4",
"objc2 0.6.3",
"objc2-app-kit",
"objc2-foundation 0.3.2",
]
[[package]] [[package]]
name = "objc2-quartz-core" name = "objc2-quartz-core"
version = "0.2.2" version = "0.2.2"
@@ -2357,6 +2436,20 @@ dependencies = [
"windows-sys 0.61.2", "windows-sys 0.61.2",
] ]
[[package]]
name = "osakit"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "732c71caeaa72c065bb69d7ea08717bd3f4863a4f451402fc9513e29dbd5261b"
dependencies = [
"objc2 0.6.3",
"objc2-foundation 0.3.2",
"objc2-osa-kit",
"serde",
"serde_json",
"thiserror 2.0.17",
]
[[package]] [[package]]
name = "pango" name = "pango"
version = "0.18.3" version = "0.18.3"
@@ -2717,6 +2810,61 @@ dependencies = [
"memchr", "memchr",
] ]
[[package]]
name = "quinn"
version = "0.11.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20"
dependencies = [
"bytes",
"cfg_aliases",
"pin-project-lite",
"quinn-proto",
"quinn-udp",
"rustc-hash",
"rustls",
"socket2",
"thiserror 2.0.17",
"tokio",
"tracing",
"web-time",
]
[[package]]
name = "quinn-proto"
version = "0.11.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1906b49b0c3bc04b5fe5d86a77925ae6524a19b816ae38ce1e426255f1d8a31"
dependencies = [
"bytes",
"getrandom 0.3.3",
"lru-slab",
"rand 0.9.2",
"ring",
"rustc-hash",
"rustls",
"rustls-pki-types",
"slab",
"thiserror 2.0.17",
"tinyvec",
"tracing",
"web-time",
]
[[package]]
name = "quinn-udp"
version = "0.5.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd"
dependencies = [
"cfg_aliases",
"libc",
"once_cell",
"socket2",
"tracing",
"windows-sys 0.60.2",
]
[[package]] [[package]]
name = "quote" name = "quote"
version = "1.0.41" version = "1.0.41"
@@ -2931,16 +3079,21 @@ dependencies = [
"http-body", "http-body",
"http-body-util", "http-body-util",
"hyper", "hyper",
"hyper-rustls",
"hyper-util", "hyper-util",
"js-sys", "js-sys",
"log", "log",
"percent-encoding", "percent-encoding",
"pin-project-lite", "pin-project-lite",
"quinn",
"rustls",
"rustls-pki-types",
"serde", "serde",
"serde_json", "serde_json",
"serde_urlencoded", "serde_urlencoded",
"sync_wrapper", "sync_wrapper",
"tokio", "tokio",
"tokio-rustls",
"tokio-util", "tokio-util",
"tower", "tower",
"tower-http", "tower-http",
@@ -2950,6 +3103,7 @@ dependencies = [
"wasm-bindgen-futures", "wasm-bindgen-futures",
"wasm-streams", "wasm-streams",
"web-sys", "web-sys",
"webpki-roots",
] ]
[[package]] [[package]]
@@ -2977,6 +3131,26 @@ dependencies = [
"windows-sys 0.59.0", "windows-sys 0.59.0",
] ]
[[package]]
name = "ring"
version = "0.17.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
dependencies = [
"cc",
"cfg-if",
"getrandom 0.2.16",
"libc",
"untrusted",
"windows-sys 0.52.0",
]
[[package]]
name = "rustc-hash"
version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d"
[[package]] [[package]]
name = "rustc_version" name = "rustc_version"
version = "0.4.1" version = "0.4.1"
@@ -2999,6 +3173,41 @@ dependencies = [
"windows-sys 0.61.2", "windows-sys 0.61.2",
] ]
[[package]]
name = "rustls"
version = "0.23.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd3c25631629d034ce7cd9940adc9d45762d46de2b0f57193c4443b92c6d4d40"
dependencies = [
"once_cell",
"ring",
"rustls-pki-types",
"rustls-webpki",
"subtle",
"zeroize",
]
[[package]]
name = "rustls-pki-types"
version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "229a4a4c221013e7e1f1a043678c5cc39fe5171437c88fb47151a21e6f5b5c79"
dependencies = [
"web-time",
"zeroize",
]
[[package]]
name = "rustls-webpki"
version = "0.103.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e10b3f4191e8a80e6b43eebabfac91e5dcecebb27a71f04e820c47ec41d314bf"
dependencies = [
"ring",
"rustls-pki-types",
"untrusted",
]
[[package]] [[package]]
name = "rustversion" name = "rustversion"
version = "1.0.22" version = "1.0.22"
@@ -3481,6 +3690,12 @@ version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "subtle"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]] [[package]]
name = "swift-rs" name = "swift-rs"
version = "1.0.7" version = "1.0.7"
@@ -3598,6 +3813,17 @@ dependencies = [
"syn 2.0.106", "syn 2.0.106",
] ]
[[package]]
name = "tar"
version = "0.4.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d863878d212c87a19c1a610eb53bb01fe12951c0501cf5a0d65f724914a667a"
dependencies = [
"filetime",
"libc",
"xattr",
]
[[package]] [[package]]
name = "target-lexicon" name = "target-lexicon"
version = "0.12.16" version = "0.12.16"
@@ -3798,6 +4024,38 @@ dependencies = [
"tokio", "tokio",
] ]
[[package]]
name = "tauri-plugin-updater"
version = "2.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27cbc31740f4d507712550694749572ec0e43bdd66992db7599b89fbfd6b167b"
dependencies = [
"base64 0.22.1",
"dirs",
"flate2",
"futures-util",
"http",
"infer",
"log",
"minisign-verify",
"osakit",
"percent-encoding",
"reqwest",
"semver",
"serde",
"serde_json",
"tar",
"tauri",
"tauri-plugin",
"tempfile",
"thiserror 2.0.17",
"time",
"tokio",
"url",
"windows-sys 0.60.2",
"zip",
]
[[package]] [[package]]
name = "tauri-runtime" name = "tauri-runtime"
version = "2.8.0" version = "2.8.0"
@@ -4003,6 +4261,21 @@ dependencies = [
"zerovec", "zerovec",
] ]
[[package]]
name = "tinyvec"
version = "1.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bfa5fdc3bce6191a1dbc8c02d5c8bffcf557bafa17c124c5264a458f1b0613fa"
dependencies = [
"tinyvec_macros",
]
[[package]]
name = "tinyvec_macros"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]] [[package]]
name = "tokio" name = "tokio"
version = "1.48.0" version = "1.48.0"
@@ -4032,6 +4305,16 @@ dependencies = [
"syn 2.0.106", "syn 2.0.106",
] ]
[[package]]
name = "tokio-rustls"
version = "0.26.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61"
dependencies = [
"rustls",
"tokio",
]
[[package]] [[package]]
name = "tokio-tungstenite" name = "tokio-tungstenite"
version = "0.21.0" version = "0.21.0"
@@ -4352,6 +4635,12 @@ version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493" checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493"
[[package]]
name = "untrusted"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]] [[package]]
name = "url" name = "url"
version = "2.5.7" version = "2.5.7"
@@ -4636,6 +4925,16 @@ dependencies = [
"wasm-bindgen", "wasm-bindgen",
] ]
[[package]]
name = "web-time"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
dependencies = [
"js-sys",
"wasm-bindgen",
]
[[package]] [[package]]
name = "webkit2gtk" name = "webkit2gtk"
version = "2.0.1" version = "2.0.1"
@@ -4680,6 +4979,15 @@ dependencies = [
"system-deps", "system-deps",
] ]
[[package]]
name = "webpki-roots"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32b130c0d2d49f8b6889abc456e795e82525204f27c42cf767cf0d7734e089b8"
dependencies = [
"rustls-pki-types",
]
[[package]] [[package]]
name = "webview2-com" name = "webview2-com"
version = "0.38.0" version = "0.38.0"
@@ -4910,6 +5218,15 @@ dependencies = [
"windows-targets 0.42.2", "windows-targets 0.42.2",
] ]
[[package]]
name = "windows-sys"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [
"windows-targets 0.52.6",
]
[[package]] [[package]]
name = "windows-sys" name = "windows-sys"
version = "0.59.0" version = "0.59.0"
@@ -5247,6 +5564,16 @@ dependencies = [
"pkg-config", "pkg-config",
] ]
[[package]]
name = "xattr"
version = "1.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
dependencies = [
"libc",
"rustix",
]
[[package]] [[package]]
name = "yoke" name = "yoke"
version = "0.8.0" version = "0.8.0"
@@ -5367,6 +5694,12 @@ dependencies = [
"synstructure", "synstructure",
] ]
[[package]]
name = "zeroize"
version = "1.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0"
[[package]] [[package]]
name = "zerotrie" name = "zerotrie"
version = "0.2.2" version = "0.2.2"
@@ -5400,6 +5733,18 @@ dependencies = [
"syn 2.0.106", "syn 2.0.106",
] ]
[[package]]
name = "zip"
version = "4.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "caa8cd6af31c3b31c6631b8f483848b91589021b28fffe50adada48d4f4d2ed1"
dependencies = [
"arbitrary",
"crc32fast",
"indexmap 2.11.4",
"memchr",
]
[[package]] [[package]]
name = "zvariant" name = "zvariant"
version = "5.7.0" version = "5.7.0"

View File

@@ -16,6 +16,7 @@ tauri-build = { version = "2.0", features = [] }
tauri = { version = "2.0", features = ["protocol-asset"] } tauri = { version = "2.0", features = ["protocol-asset"] }
tauri-plugin-shell = "2.0" tauri-plugin-shell = "2.0"
tauri-plugin-dialog = "2.0" tauri-plugin-dialog = "2.0"
tauri-plugin-updater = "2"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
glob = "0.3" glob = "0.3"

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 KiB

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 865 B

After

Width:  |  Height:  |  Size: 915 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 888 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

After

Width:  |  Height:  |  Size: 26 KiB

View File

@@ -1,88 +1 @@
<svg width="512" height="512" viewBox="0 0 512 512" fill="none" xmlns="http://www.w3.org/2000/svg"> <svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" fill="none" viewBox="0 0 512 512"><rect width="512" height="512" fill="#1E1E1E"/><defs><radialGradient id="glow" cx="50%" cy="50%" r="50%"><stop offset="0%" style="stop-color:#569cd6;stop-opacity:.15"/><stop offset="100%" style="stop-color:#569cd6;stop-opacity:0"/></radialGradient><linearGradient id="cubeGrad1" x1="0%" x2="100%" y1="0%" y2="100%"><stop offset="0%" style="stop-color:#569cd6"/><stop offset="100%" style="stop-color:#4a8bc2"/></linearGradient><linearGradient id="cubeGrad2" x1="0%" x2="0%" y1="0%" y2="100%"><stop offset="0%" style="stop-color:#4ec9b0"/><stop offset="100%" style="stop-color:#3da592"/></linearGradient><filter id="shadow"><feGaussianBlur in="SourceAlpha" stdDeviation="4"/><feOffset dx="2" dy="2" result="offsetblur"/><feComponentTransfer><feFuncA slope=".3" type="linear"/></feComponentTransfer><feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge></filter></defs><circle cx="256" cy="256" r="200" fill="url(#glow)"/><g filter="url(#shadow)"><path fill="none" stroke="url(#cubeGrad1)" stroke-width="6" d="M 180 140 L 332 140 L 332 292 L 180 292 Z" opacity=".4"/><path fill="rgba(86, 156, 214, 0.08)" stroke="url(#cubeGrad1)" stroke-linecap="round" stroke-linejoin="round" stroke-width="8" d="M 140 180 L 292 180 L 292 332 L 140 332 Z"/><line x1="140" x2="180" y1="180" y2="140" stroke="url(#cubeGrad1)" stroke-linecap="round" stroke-width="6" opacity=".6"/><line x1="292" x2="332" y1="180" y2="140" stroke="url(#cubeGrad1)" stroke-linecap="round" stroke-width="6" opacity=".6"/><line x1="292" x2="332" y1="332" y2="292" stroke="url(#cubeGrad1)" stroke-linecap="round" stroke-width="6" opacity=".6"/><line x1="140" x2="180" y1="332" y2="292" stroke="url(#cubeGrad1)" stroke-linecap="round" stroke-width="6" opacity=".6"/><circle cx="216" cy="216" r="14" fill="#CE9178" opacity=".95"><animate attributeName="opacity" dur="2s" repeatCount="indefinite" values="0.95;1;0.95"/></circle><circle cx="256" cy="256" r="14" fill="#4EC9B0" opacity=".95"><animate attributeName="opacity" begin="0.3s" dur="2s" repeatCount="indefinite" values="0.95;1;0.95"/></circle><circle cx="296" cy="296" r="14" fill="#569CD6" opacity=".95"><animate attributeName="opacity" begin="0.6s" dur="2s" repeatCount="indefinite" values="0.95;1;0.95"/></circle><line x1="216" x2="256" y1="216" y2="256" stroke="#4EC9B0" stroke-linecap="round" stroke-width="2" opacity=".5"/><line x1="256" x2="296" y1="256" y2="296" stroke="#569CD6" stroke-linecap="round" stroke-width="2" opacity=".5"/></g><g stroke="#4EC9B0" stroke-linecap="round" stroke-width="3" opacity=".3"><line x1="130" x2="130" y1="170" y2="190"/><line x1="130" x2="150" y1="170" y2="170"/><line x1="302" x2="302" y1="342" y2="322"/><line x1="302" x2="282" y1="342" y2="342"/></g></svg>
<rect width="512" height="512" fill="#1E1E1E"/>
<!-- 背景光晕 -->
<defs>
<radialGradient id="glow" cx="50%" cy="50%" r="50%">
<stop offset="0%" style="stop-color:#569CD6;stop-opacity:0.15" />
<stop offset="100%" style="stop-color:#569CD6;stop-opacity:0" />
</radialGradient>
<linearGradient id="cubeGrad1" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" style="stop-color:#569CD6" />
<stop offset="100%" style="stop-color:#4A8BC2" />
</linearGradient>
<linearGradient id="cubeGrad2" x1="0%" y1="0%" x2="0%" y2="100%">
<stop offset="0%" style="stop-color:#4EC9B0" />
<stop offset="100%" style="stop-color:#3DA592" />
</linearGradient>
<filter id="shadow">
<feGaussianBlur in="SourceAlpha" stdDeviation="4"/>
<feOffset dx="2" dy="2" result="offsetblur"/>
<feComponentTransfer>
<feFuncA type="linear" slope="0.3"/>
</feComponentTransfer>
<feMerge>
<feMergeNode/>
<feMergeNode in="SourceGraphic"/>
</feMerge>
</filter>
</defs>
<!-- 背景光晕效果 -->
<circle cx="256" cy="256" r="200" fill="url(#glow)"/>
<!-- 主立方体框架 -->
<g filter="url(#shadow)">
<!-- 后面的立方体边缘 -->
<path d="M 180 140 L 332 140 L 332 292 L 180 292 Z"
stroke="url(#cubeGrad1)"
stroke-width="6"
fill="none"
opacity="0.4"/>
<!-- 前面的立方体 -->
<path d="M 140 180 L 292 180 L 292 332 L 140 332 Z"
stroke="url(#cubeGrad1)"
stroke-width="8"
fill="rgba(86, 156, 214, 0.08)"
stroke-linecap="round"
stroke-linejoin="round"/>
<!-- 连接线3D效果 -->
<line x1="140" y1="180" x2="180" y2="140" stroke="url(#cubeGrad1)" stroke-width="6" opacity="0.6" stroke-linecap="round"/>
<line x1="292" y1="180" x2="332" y2="140" stroke="url(#cubeGrad1)" stroke-width="6" opacity="0.6" stroke-linecap="round"/>
<line x1="292" y1="332" x2="332" y2="292" stroke="url(#cubeGrad1)" stroke-width="6" opacity="0.6" stroke-linecap="round"/>
<line x1="140" y1="332" x2="180" y2="292" stroke="url(#cubeGrad1)" stroke-width="6" opacity="0.6" stroke-linecap="round"/>
<!-- Entity 点(橙色) -->
<circle cx="216" cy="216" r="14" fill="#CE9178" opacity="0.95">
<animate attributeName="opacity" values="0.95;1;0.95" dur="2s" repeatCount="indefinite"/>
</circle>
<!-- Component 点(青绿色) -->
<circle cx="256" cy="256" r="14" fill="#4EC9B0" opacity="0.95">
<animate attributeName="opacity" values="0.95;1;0.95" dur="2s" begin="0.3s" repeatCount="indefinite"/>
</circle>
<!-- System 点(蓝色) -->
<circle cx="296" cy="296" r="14" fill="#569CD6" opacity="0.95">
<animate attributeName="opacity" values="0.95;1;0.95" dur="2s" begin="0.6s" repeatCount="indefinite"/>
</circle>
<!-- 点之间的连接线 -->
<line x1="216" y1="216" x2="256" y2="256" stroke="#4EC9B0" stroke-width="2" opacity="0.5" stroke-linecap="round"/>
<line x1="256" y1="256" x2="296" y2="296" stroke="#569CD6" stroke-width="2" opacity="0.5" stroke-linecap="round"/>
</g>
<!-- 角落装饰线 -->
<g stroke="#4EC9B0" stroke-width="3" opacity="0.3" stroke-linecap="round">
<line x1="130" y1="170" x2="130" y2="190"/>
<line x1="130" y1="170" x2="150" y2="170"/>
<line x1="302" y1="342" x2="302" y2="322"/>
<line x1="302" y1="342" x2="282" y2="342"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 3.5 KiB

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 512 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 847 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

View File

@@ -34,6 +34,26 @@ fn export_binary(data: Vec<u8>, output_path: String) -> Result<(), String> {
Ok(()) 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<bool, String> {
use std::path::Path;
Ok(Path::new(&path).exists())
}
#[tauri::command] #[tauri::command]
async fn open_project_dialog(app: AppHandle) -> Result<Option<String>, String> { async fn open_project_dialog(app: AppHandle) -> Result<Option<String>, String> {
use tauri_plugin_dialog::DialogExt; use tauri_plugin_dialog::DialogExt;
@@ -46,6 +66,37 @@ async fn open_project_dialog(app: AppHandle) -> Result<Option<String>, String> {
Ok(folder.map(|path| path.to_string())) Ok(folder.map(|path| path.to_string()))
} }
#[tauri::command]
async fn save_scene_dialog(app: AppHandle, default_name: Option<String>) -> Result<Option<String>, 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<Option<String>, 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] #[tauri::command]
fn scan_directory(path: String, pattern: String) -> Result<Vec<String>, String> { fn scan_directory(path: String, pattern: String) -> Result<Vec<String>, String> {
use glob::glob; use glob::glob;
@@ -243,6 +294,7 @@ fn main() {
tauri::Builder::default() tauri::Builder::default()
.plugin(tauri_plugin_shell::init()) .plugin(tauri_plugin_shell::init())
.plugin(tauri_plugin_dialog::init()) .plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_updater::Builder::new().build())
.register_uri_scheme_protocol("project", move |_app, request| { .register_uri_scheme_protocol("project", move |_app, request| {
let project_paths = Arc::clone(&project_paths_clone); let project_paths = Arc::clone(&project_paths_clone);
@@ -299,7 +351,12 @@ fn main() {
open_project, open_project,
save_project, save_project,
export_binary, export_binary,
create_directory,
write_file_content,
path_exists,
open_project_dialog, open_project_dialog,
save_scene_dialog,
open_scene_dialog,
scan_directory, scan_directory,
read_file_content, read_file_content,
list_directory, list_directory,

View File

@@ -1,6 +1,6 @@
{ {
"productName": "ECS Framework Editor", "productName": "ECS Framework Editor",
"version": "1.0.0", "version": "1.0.3",
"identifier": "com.esengine.editor", "identifier": "com.esengine.editor",
"build": { "build": {
"beforeDevCommand": "npm run dev", "beforeDevCommand": "npm run dev",
@@ -11,6 +11,7 @@
"bundle": { "bundle": {
"active": true, "active": true,
"targets": "all", "targets": "all",
"createUpdaterArtifacts": true,
"icon": [ "icon": [
"icons/32x32.png", "icons/32x32.png",
"icons/128x128.png", "icons/128x128.png",
@@ -53,14 +54,41 @@
"assetProtocol": { "assetProtocol": {
"enable": true, "enable": true,
"scope": { "scope": {
"allow": ["**"] "allow": [
"**"
]
} }
} },
"capabilities": [
{
"identifier": "main",
"windows": [
"main"
],
"permissions": [
"core:default",
"shell:default",
"dialog:default",
"updater:default",
"updater:allow-check",
"updater:allow-download",
"updater:allow-install"
]
}
]
} }
}, },
"plugins": { "plugins": {
"shell": { "shell": {
"open": true "open": true
},
"updater": {
"active": true,
"endpoints": [
"https://github.com/esengine/ecs-framework/releases/latest/download/latest.json"
],
"dialog": true,
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDFDQjNFNDIxREFBODNDNkMKUldSc1BLamFJZVN6SEJIRXRWWEovVXRta08yNWFkZmtKNnZoSHFmbi9ZdGxubUMzSHJaN3J0VEcK"
} }
} }
} }

View File

@@ -1,8 +1,9 @@
import { useState, useEffect, useRef } from 'react'; import { useState, useEffect, useRef, useCallback } from 'react';
import { Core, Scene } from '@esengine/ecs-framework'; 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 { SceneInspectorPlugin } from './plugins/SceneInspectorPlugin';
import { ProfilerPlugin } from './plugins/ProfilerPlugin'; import { ProfilerPlugin } from './plugins/ProfilerPlugin';
import { EditorAppearancePlugin } from './plugins/EditorAppearancePlugin';
import { StartupPage } from './components/StartupPage'; import { StartupPage } from './components/StartupPage';
import { SceneHierarchy } from './components/SceneHierarchy'; import { SceneHierarchy } from './components/SceneHierarchy';
import { EntityInspector } from './components/EntityInspector'; import { EntityInspector } from './components/EntityInspector';
@@ -12,11 +13,16 @@ import { PluginManagerWindow } from './components/PluginManagerWindow';
import { ProfilerWindow } from './components/ProfilerWindow'; import { ProfilerWindow } from './components/ProfilerWindow';
import { PortManager } from './components/PortManager'; import { PortManager } from './components/PortManager';
import { SettingsWindow } from './components/SettingsWindow'; 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 { Viewport } from './components/Viewport';
import { MenuBar } from './components/MenuBar'; import { MenuBar } from './components/MenuBar';
import { DockContainer, DockablePanel } from './components/DockContainer'; import { DockContainer, DockablePanel } from './components/DockContainer';
import { TauriAPI } from './api/tauri'; import { TauriAPI } from './api/tauri';
import { TauriFileAPI } from './adapters/TauriFileAPI';
import { SettingsService } from './services/SettingsService'; import { SettingsService } from './services/SettingsService';
import { checkForUpdatesOnStartup } from './utils/updater';
import { useLocale } from './hooks/useLocale'; import { useLocale } from './hooks/useLocale';
import { en, zh } from './locales'; import { en, zh } from './locales';
import { Loader2, Globe } from 'lucide-react'; import { Loader2, Globe } from 'lucide-react';
@@ -42,6 +48,7 @@ function App() {
const [logService, setLogService] = useState<LogService | null>(null); const [logService, setLogService] = useState<LogService | null>(null);
const [uiRegistry, setUiRegistry] = useState<UIRegistry | null>(null); const [uiRegistry, setUiRegistry] = useState<UIRegistry | null>(null);
const [settingsRegistry, setSettingsRegistry] = useState<SettingsRegistry | null>(null); const [settingsRegistry, setSettingsRegistry] = useState<SettingsRegistry | null>(null);
const [sceneManager, setSceneManager] = useState<SceneManagerService | null>(null);
const { t, locale, changeLocale } = useLocale(); const { t, locale, changeLocale } = useLocale();
const [status, setStatus] = useState(t('header.status.initializing')); const [status, setStatus] = useState(t('header.status.initializing'));
const [panels, setPanels] = useState<DockablePanel[]>([]); const [panels, setPanels] = useState<DockablePanel[]>([]);
@@ -49,9 +56,18 @@ function App() {
const [showProfiler, setShowProfiler] = useState(false); const [showProfiler, setShowProfiler] = useState(false);
const [showPortManager, setShowPortManager] = useState(false); const [showPortManager, setShowPortManager] = useState(false);
const [showSettings, setShowSettings] = useState(false); const [showSettings, setShowSettings] = useState(false);
const [showAbout, setShowAbout] = useState(false);
const [pluginUpdateTrigger, setPluginUpdateTrigger] = useState(0); const [pluginUpdateTrigger, setPluginUpdateTrigger] = useState(0);
const [isRemoteConnected, setIsRemoteConnected] = useState(false); const [isRemoteConnected, setIsRemoteConnected] = useState(false);
const [isProfilerMode, setIsProfilerMode] = 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(() => { useEffect(() => {
// 禁用默认右键菜单 // 禁用默认右键菜单
@@ -69,12 +85,10 @@ function App() {
useEffect(() => { useEffect(() => {
if (messageHub) { if (messageHub) {
const unsubscribeEnabled = messageHub.subscribe('plugin:enabled', () => { const unsubscribeEnabled = messageHub.subscribe('plugin:enabled', () => {
console.log('[App] Plugin enabled, updating panels');
setPluginUpdateTrigger(prev => prev + 1); setPluginUpdateTrigger(prev => prev + 1);
}); });
const unsubscribeDisabled = messageHub.subscribe('plugin:disabled', () => { const unsubscribeDisabled = messageHub.subscribe('plugin:disabled', () => {
console.log('[App] Plugin disabled, updating panels');
setPluginUpdateTrigger(prev => prev + 1); setPluginUpdateTrigger(prev => prev + 1);
}); });
@@ -91,13 +105,11 @@ function App() {
const profilerService = (window as any).__PROFILER_SERVICE__; const profilerService = (window as any).__PROFILER_SERVICE__;
if (profilerService && profilerService.isConnected()) { if (profilerService && profilerService.isConnected()) {
if (!isRemoteConnected) { if (!isRemoteConnected) {
console.log('[App] Remote game connected');
setIsRemoteConnected(true); setIsRemoteConnected(true);
setStatus(t('header.status.remoteConnected')); setStatus(t('header.status.remoteConnected'));
} }
} else { } else {
if (isRemoteConnected) { if (isRemoteConnected) {
console.log('[App] Remote game disconnected');
setIsRemoteConnected(false); setIsRemoteConnected(false);
if (projectLoaded) { if (projectLoaded) {
const componentRegistry = Core.services.resolve(ComponentRegistry); const componentRegistry = Core.services.resolve(ComponentRegistry);
@@ -120,13 +132,11 @@ function App() {
const initializeEditor = async () => { const initializeEditor = async () => {
// 使用 ref 防止 React StrictMode 的双重调用 // 使用 ref 防止 React StrictMode 的双重调用
if (initRef.current) { if (initRef.current) {
console.log('[App] Already initialized via ref, skipping second initialization');
return; return;
} }
initRef.current = true; initRef.current = true;
try { try {
console.log('[App] Starting editor initialization...');
(window as any).__ECS_FRAMEWORK__ = await import('@esengine/ecs-framework'); (window as any).__ECS_FRAMEWORK__ = await import('@esengine/ecs-framework');
const editorScene = new Scene(); const editorScene = new Scene();
@@ -137,12 +147,13 @@ function App() {
const serializerRegistry = new SerializerRegistry(); const serializerRegistry = new SerializerRegistry();
const entityStore = new EntityStoreService(messageHub); const entityStore = new EntityStoreService(messageHub);
const componentRegistry = new ComponentRegistry(); 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 componentDiscovery = new ComponentDiscoveryService(messageHub);
const componentLoader = new ComponentLoaderService(messageHub, componentRegistry);
const propertyMetadata = new PropertyMetadataService(); const propertyMetadata = new PropertyMetadataService();
const logService = new LogService(); const logService = new LogService();
const settingsRegistry = new SettingsRegistry(); const settingsRegistry = new SettingsRegistry();
const sceneManagerService = new SceneManagerService(messageHub, fileAPI, projectService);
// 监听远程日志事件 // 监听远程日志事件
window.addEventListener('profiler:remote-log', ((event: CustomEvent) => { window.addEventListener('profiler:remote-log', ((event: CustomEvent) => {
@@ -157,10 +168,10 @@ function App() {
Core.services.registerInstance(ComponentRegistry, componentRegistry); Core.services.registerInstance(ComponentRegistry, componentRegistry);
Core.services.registerInstance(ProjectService, projectService); Core.services.registerInstance(ProjectService, projectService);
Core.services.registerInstance(ComponentDiscoveryService, componentDiscovery); Core.services.registerInstance(ComponentDiscoveryService, componentDiscovery);
Core.services.registerInstance(ComponentLoaderService, componentLoader);
Core.services.registerInstance(PropertyMetadataService, propertyMetadata); Core.services.registerInstance(PropertyMetadataService, propertyMetadata);
Core.services.registerInstance(LogService, logService); Core.services.registerInstance(LogService, logService);
Core.services.registerInstance(SettingsRegistry, settingsRegistry); Core.services.registerInstance(SettingsRegistry, settingsRegistry);
Core.services.registerInstance(SceneManagerService, sceneManagerService);
const pluginMgr = new EditorPluginManager(); const pluginMgr = new EditorPluginManager();
pluginMgr.initialize(coreInstance, Core.services); pluginMgr.initialize(coreInstance, Core.services);
@@ -168,11 +179,7 @@ function App() {
await pluginMgr.installEditor(new SceneInspectorPlugin()); await pluginMgr.installEditor(new SceneInspectorPlugin());
await pluginMgr.installEditor(new ProfilerPlugin()); await pluginMgr.installEditor(new ProfilerPlugin());
await pluginMgr.installEditor(new EditorAppearancePlugin());
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) => { messageHub.subscribe('ui:openWindow', (data: any) => {
if (data.windowId === 'profiler') { if (data.windowId === 'profiler') {
@@ -182,8 +189,7 @@ function App() {
} }
}); });
const greeting = await TauriAPI.greet('Developer'); await TauriAPI.greet('Developer');
console.log(greeting);
setInitialized(true); setInitialized(true);
setPluginManager(pluginMgr); setPluginManager(pluginMgr);
@@ -192,7 +198,11 @@ function App() {
setLogService(logService); setLogService(logService);
setUiRegistry(uiRegistry); setUiRegistry(uiRegistry);
setSettingsRegistry(settingsRegistry); setSettingsRegistry(settingsRegistry);
setSceneManager(sceneManagerService);
setStatus(t('header.status.ready')); setStatus(t('header.status.ready'));
// Check for updates on startup (after 3 seconds)
checkForUpdatesOnStartup();
} catch (error) { } catch (error) {
console.error('Failed to initialize editor:', error); console.error('Failed to initialize editor:', error);
setStatus(t('header.status.failed')); setStatus(t('header.status.failed'));
@@ -205,13 +215,11 @@ function App() {
const handleOpenRecentProject = async (projectPath: string) => { const handleOpenRecentProject = async (projectPath: string) => {
try { try {
setIsLoading(true); 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 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'); console.error('Required services not available');
setIsLoading(false); setIsLoading(false);
return; return;
@@ -225,31 +233,27 @@ function App() {
body: JSON.stringify({ path: projectPath }) body: JSON.stringify({ path: projectPath })
}); });
setLoadingMessage(locale === 'zh' ? '正在扫描组件...' : 'Scanning components...'); setStatus(t('header.status.projectOpened'));
setStatus('Scanning components...');
const componentsPath = projectService.getComponentsPath(); setLoadingMessage(locale === 'zh' ? '步骤 2/2: 加载场景...' : 'Step 2/2: Loading scene...');
if (componentsPath) {
const componentInfos = await discoveryService.scanComponents({
basePath: componentsPath,
pattern: '**/*.ts',
scanFunction: TauriAPI.scanDirectory,
readFunction: TauriAPI.readFileContent
});
setLoadingMessage(locale === 'zh' ? `正在加载 ${componentInfos.length} 个组件...` : `Loading ${componentInfos.length} components...`); const sceneManagerService = Core.services.resolve(SceneManagerService);
setStatus(`Loading ${componentInfos.length} components...`); const scenesPath = projectService.getScenesPath();
if (scenesPath && sceneManagerService) {
try {
const sceneFiles = await TauriAPI.scanDirectory(scenesPath, '*.ecs');
const modulePathTransform = (filePath: string) => { if (sceneFiles.length > 0) {
const relativePath = filePath.replace(projectPath, '').replace(/\\/g, '/'); const defaultScenePath = projectService.getDefaultScenePath();
return `/@user-project${relativePath}`; const sceneToLoad = sceneFiles.find(f => f === defaultScenePath) || sceneFiles[0];
};
await loaderService.loadComponents(componentInfos, modulePathTransform); await sceneManagerService.openScene(sceneToLoad);
} else {
setStatus(t('header.status.projectOpened') + ` (${componentInfos.length} components registered)`); await sceneManagerService.newScene();
} else { }
setStatus(t('header.status.projectOpened')); } catch (error) {
await sceneManagerService.newScene();
}
} }
const settings = SettingsService.getInstance(); const settings = SettingsService.getInstance();
@@ -262,6 +266,14 @@ function App() {
console.error('Failed to open project:', error); console.error('Failed to open project:', error);
setStatus(t('header.status.failed')); setStatus(t('header.status.failed'));
setIsLoading(false); 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}`
});
} }
}; };
@@ -277,7 +289,72 @@ function App() {
}; };
const handleCreateProject = async () => { 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 () => { const handleProfilerMode = async () => {
@@ -286,20 +363,109 @@ function App() {
setStatus(t('header.status.profilerMode') || 'Profiler Mode - Waiting for connection...'); setStatus(t('header.status.profilerMode') || 'Profiler Mode - Waiting for connection...');
}; };
const handleNewScene = () => { const handleNewScene = async () => {
console.log('New scene not implemented yet'); 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 = () => { const handleOpenScene = async () => {
console.log('Open scene not implemented yet'); 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 = () => { const handleOpenSceneByPath = useCallback(async (scenePath: string) => {
console.log('Save scene not implemented yet'); 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 = () => { const handleSaveSceneAs = async () => {
console.log('Save scene as not implemented yet'); 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 = () => { const handleCloseProject = () => {
@@ -326,6 +492,10 @@ function App() {
} }
}; };
const handleOpenAbout = () => {
setShowAbout(true);
};
useEffect(() => { useEffect(() => {
if (projectLoaded && entityStore && messageHub && logService && uiRegistry && pluginManager) { if (projectLoaded && entityStore && messageHub && logService && uiRegistry && pluginManager) {
let corePanels: DockablePanel[]; let corePanels: DockablePanel[];
@@ -381,7 +551,7 @@ function App() {
id: 'assets', id: 'assets',
title: locale === 'zh' ? '资产' : 'Assets', title: locale === 'zh' ? '资产' : 'Assets',
position: 'bottom', position: 'bottom',
content: <AssetBrowser projectPath={currentProjectPath} locale={locale} />, content: <AssetBrowser projectPath={currentProjectPath} locale={locale} onOpenScene={handleOpenSceneByPath} />,
closable: false closable: false
}, },
{ {
@@ -426,7 +596,7 @@ function App() {
console.log('[App] Loading plugin panels:', pluginPanels); console.log('[App] Loading plugin panels:', pluginPanels);
setPanels([...corePanels, ...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) => { const handlePanelMove = (panelId: string, newPosition: any) => {
setPanels(prevPanels => setPanels(prevPanels =>
@@ -467,6 +637,23 @@ function App() {
</div> </div>
</div> </div>
)} )}
{errorDialog && (
<ErrorDialog
title={errorDialog.title}
message={errorDialog.message}
onClose={() => setErrorDialog(null)}
/>
)}
{confirmDialog && (
<ConfirmDialog
title={confirmDialog.title}
message={confirmDialog.message}
confirmText={confirmDialog.confirmText}
cancelText={confirmDialog.cancelText}
onConfirm={confirmDialog.onConfirm}
onCancel={() => setConfirmDialog(null)}
/>
)}
</> </>
); );
} }
@@ -491,6 +678,7 @@ function App() {
onOpenPortManager={() => setShowPortManager(true)} onOpenPortManager={() => setShowPortManager(true)}
onOpenSettings={() => setShowSettings(true)} onOpenSettings={() => setShowSettings(true)}
onToggleDevtools={handleToggleDevtools} onToggleDevtools={handleToggleDevtools}
onOpenAbout={handleOpenAbout}
/> />
<div className="header-right"> <div className="header-right">
<button onClick={handleLocaleChange} className="toolbar-btn locale-btn" title={locale === 'en' ? '切换到中文' : 'Switch to English'}> <button onClick={handleLocaleChange} className="toolbar-btn locale-btn" title={locale === 'en' ? '切换到中文' : 'Switch to English'}>
@@ -528,6 +716,18 @@ function App() {
{showSettings && settingsRegistry && ( {showSettings && settingsRegistry && (
<SettingsWindow onClose={() => setShowSettings(false)} settingsRegistry={settingsRegistry} /> <SettingsWindow onClose={() => setShowSettings(false)} settingsRegistry={settingsRegistry} />
)} )}
{showAbout && (
<AboutDialog onClose={() => setShowAbout(false)} locale={locale} />
)}
{errorDialog && (
<ErrorDialog
title={errorDialog.title}
message={errorDialog.message}
onClose={() => setErrorDialog(null)}
/>
)}
</div> </div>
); );
} }

View File

@@ -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<string | null> {
return await TauriAPI.openSceneDialog();
}
public async saveSceneDialog(defaultName?: string): Promise<string | null> {
return await TauriAPI.saveSceneDialog(defaultName);
}
public async readFileContent(path: string): Promise<string> {
return await TauriAPI.readFileContent(path);
}
public async saveProject(path: string, data: string): Promise<void> {
return await TauriAPI.saveProject(path, data);
}
public async exportBinary(data: Uint8Array, path: string): Promise<void> {
return await TauriAPI.exportBinary(data, path);
}
public async createDirectory(path: string): Promise<void> {
return await TauriAPI.createDirectory(path);
}
public async writeFileContent(path: string, content: string): Promise<void> {
return await TauriAPI.writeFileContent(path, content);
}
public async pathExists(path: string): Promise<boolean> {
return await TauriAPI.pathExists(path);
}
}

View File

@@ -70,6 +70,49 @@ export class TauriAPI {
static async toggleDevtools(): Promise<void> { static async toggleDevtools(): Promise<void> {
return await invoke<void>('toggle_devtools'); return await invoke<void>('toggle_devtools');
} }
/**
* 打开保存场景对话框
* @param defaultName 默认文件名(可选)
* @returns 用户选择的文件路径,取消则返回 null
*/
static async saveSceneDialog(defaultName?: string): Promise<string | null> {
return await invoke<string | null>('save_scene_dialog', { defaultName });
}
/**
* 打开场景文件选择对话框
* @returns 用户选择的文件路径,取消则返回 null
*/
static async openSceneDialog(): Promise<string | null> {
return await invoke<string | null>('open_scene_dialog');
}
/**
* 创建目录
* @param path 目录路径
*/
static async createDirectory(path: string): Promise<void> {
return await invoke<void>('create_directory', { path });
}
/**
* 写入文件内容
* @param path 文件路径
* @param content 文件内容
*/
static async writeFileContent(path: string, content: string): Promise<void> {
return await invoke<void>('write_file_content', { path, content });
}
/**
* 检查路径是否存在
* @param path 文件或目录路径
* @returns 路径是否存在
*/
static async pathExists(path: string): Promise<boolean> {
return await invoke<boolean>('path_exists', { path });
}
} }
export interface DirectoryEntry { export interface DirectoryEntry {

View File

@@ -0,0 +1,213 @@
import { useState, useEffect } from 'react';
import { X, RefreshCw, Check, AlertCircle, Download } from 'lucide-react';
import { checkForUpdates } from '../utils/updater';
import { getVersion } from '@tauri-apps/api/app';
import { open } from '@tauri-apps/plugin-shell';
import '../styles/AboutDialog.css';
interface AboutDialogProps {
onClose: () => void;
locale?: string;
}
export function AboutDialog({ onClose, locale = 'en' }: AboutDialogProps) {
const [checking, setChecking] = useState(false);
const [updateStatus, setUpdateStatus] = useState<'idle' | 'checking' | 'available' | 'latest' | 'error'>('idle');
const [version, setVersion] = useState<string>('1.0.0');
const [newVersion, setNewVersion] = useState<string>('');
useEffect(() => {
// Fetch version on mount
const fetchVersion = async () => {
try {
const currentVersion = await getVersion();
setVersion(currentVersion);
} catch (error) {
console.error('Failed to get version:', error);
}
};
fetchVersion();
}, []);
const t = (key: string) => {
const translations: Record<string, Record<string, string>> = {
en: {
title: 'About ECS Framework Editor',
version: 'Version',
description: 'High-performance ECS framework editor for game development',
checkUpdate: 'Check for Updates',
checking: 'Checking...',
updateAvailable: 'New version available',
latest: 'You are using the latest version',
error: 'Failed to check for updates',
download: 'Download Update',
close: 'Close',
copyright: '© 2025 ESEngine. All rights reserved.',
website: 'Website',
github: 'GitHub'
},
zh: {
title: '关于 ECS Framework Editor',
version: '版本',
description: '高性能 ECS 框架编辑器,用于游戏开发',
checkUpdate: '检查更新',
checking: '检查中...',
updateAvailable: '发现新版本',
latest: '您正在使用最新版本',
error: '检查更新失败',
download: '下载更新',
close: '关闭',
copyright: '© 2025 ESEngine. 保留所有权利。',
website: '官网',
github: 'GitHub'
}
};
return translations[locale]?.[key] || key;
};
const handleCheckUpdate = async () => {
setChecking(true);
setUpdateStatus('checking');
try {
const currentVersion = await getVersion();
setVersion(currentVersion);
// 使用我们的 updater 工具检查更新
const result = await checkForUpdates(false);
if (result.error) {
setUpdateStatus('error');
} else if (result.available) {
setUpdateStatus('available');
if (result.version) {
setNewVersion(result.version);
}
} else {
setUpdateStatus('latest');
}
} catch (error: any) {
console.error('Check update failed:', error);
setUpdateStatus('error');
} finally {
setChecking(false);
}
};
const getStatusIcon = () => {
switch (updateStatus) {
case 'checking':
return <RefreshCw size={16} className="animate-spin" />;
case 'available':
return <Download size={16} className="status-available" />;
case 'latest':
return <Check size={16} className="status-latest" />;
case 'error':
return <AlertCircle size={16} className="status-error" />;
default:
return null;
}
};
const getStatusText = () => {
switch (updateStatus) {
case 'checking':
return t('checking');
case 'available':
return `${t('updateAvailable')} (v${newVersion})`;
case 'latest':
return t('latest');
case 'error':
return t('error');
default:
return '';
}
};
const handleOpenGithub = async () => {
try {
await open('https://github.com/esengine/ecs-framework');
} catch (error) {
console.error('Failed to open GitHub link:', error);
}
};
return (
<div className="modal-overlay" onClick={onClose}>
<div className="about-dialog" onClick={(e) => e.stopPropagation()}>
<div className="about-header">
<h2>{t('title')}</h2>
<button className="close-btn" onClick={onClose}>
<X size={20} />
</button>
</div>
<div className="about-content">
<div className="about-logo">
<div className="logo-placeholder">ECS</div>
</div>
<div className="about-info">
<h3>ECS Framework Editor</h3>
<p className="about-version">
{t('version')}: Editor {version}
</p>
<p className="about-description">
{t('description')}
</p>
</div>
<div className="about-update">
<button
className="update-btn"
onClick={handleCheckUpdate}
disabled={checking}
>
{checking ? (
<>
<RefreshCw size={16} className="animate-spin" />
<span>{t('checking')}</span>
</>
) : (
<>
<RefreshCw size={16} />
<span>{t('checkUpdate')}</span>
</>
)}
</button>
{updateStatus !== 'idle' && (
<div className={`update-status status-${updateStatus}`}>
{getStatusIcon()}
<span>{getStatusText()}</span>
</div>
)}
</div>
<div className="about-links">
<a
href="#"
onClick={(e) => {
e.preventDefault();
handleOpenGithub();
}}
className="about-link"
>
{t('github')}
</a>
</div>
<div className="about-footer">
<p>{t('copyright')}</p>
</div>
</div>
<div className="about-actions">
<button className="btn-primary" onClick={onClose}>
{t('close')}
</button>
</div>
</div>
</div>
);
}

View File

@@ -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;
}

View File

@@ -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<ComponentTypeInfo[]>([]);
const [selectedComponent, setSelectedComponent] = useState<string | null>(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<string, ComponentTypeInfo[]>);
return (
<div className="modal-overlay" onClick={onCancel}>
<div className="add-component-dialog" onClick={(e) => e.stopPropagation()}>
<div className="dialog-header">
<h3>Add Component</h3>
<button className="close-btn" onClick={onCancel}>&times;</button>
</div>
<div className="dialog-content">
<input
type="text"
className="component-filter"
placeholder="Search components..."
value={filter}
onChange={(e) => setFilter(e.target.value)}
autoFocus
/>
<div className="component-list">
{Object.keys(groupedComponents).length === 0 ? (
<div className="empty-message">No available components</div>
) : (
Object.entries(groupedComponents).map(([category, comps]) => (
<div key={category} className="component-category">
<div className="category-header">{category}</div>
{comps.map(comp => (
<div
key={comp.name}
className={`component-option ${selectedComponent === comp.name ? 'selected' : ''}`}
onClick={() => setSelectedComponent(comp.name)}
onDoubleClick={handleAdd}
>
<div className="component-name">{comp.name}</div>
{comp.description && (
<div className="component-description">{comp.description}</div>
)}
</div>
))}
</div>
))
)}
</div>
</div>
<div className="dialog-footer">
<button className="btn btn-cancel" onClick={onCancel}>
Cancel
</button>
<button
className="btn btn-primary"
onClick={handleAdd}
disabled={!selectedComponent}
>
Add Component
</button>
</div>
</div>
</div>
);
}

View File

@@ -1,4 +1,6 @@
import { useState, useEffect } from 'react'; import { useState, useEffect } from 'react';
import { Core } from '@esengine/ecs-framework';
import { MessageHub } from '@esengine/editor-core';
import { TauriAPI, DirectoryEntry } from '../api/tauri'; import { TauriAPI, DirectoryEntry } from '../api/tauri';
import { FileTree } from './FileTree'; import { FileTree } from './FileTree';
import { ResizablePanel } from './ResizablePanel'; import { ResizablePanel } from './ResizablePanel';
@@ -14,11 +16,12 @@ interface AssetItem {
interface AssetBrowserProps { interface AssetBrowserProps {
projectPath: string | null; projectPath: string | null;
locale: string; locale: string;
onOpenScene?: (scenePath: string) => void;
} }
type ViewMode = 'tree-split' | 'tree-only'; type ViewMode = 'tree-split' | 'tree-only';
export function AssetBrowser({ projectPath, locale }: AssetBrowserProps) { export function AssetBrowser({ projectPath, locale, onOpenScene }: AssetBrowserProps) {
const [viewMode, setViewMode] = useState<ViewMode>('tree-split'); const [viewMode, setViewMode] = useState<ViewMode>('tree-split');
const [selectedPath, setSelectedPath] = useState<string | null>(null); const [selectedPath, setSelectedPath] = useState<string | null>(null);
const [assets, setAssets] = useState<AssetItem[]>([]); const [assets, setAssets] = useState<AssetItem[]>([]);
@@ -67,6 +70,29 @@ export function AssetBrowser({ projectPath, locale }: AssetBrowserProps) {
} }
}, [projectPath, viewMode]); }, [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) => { const loadAssets = async (path: string) => {
setLoading(true); setLoading(true);
try { try {
@@ -105,7 +131,11 @@ export function AssetBrowser({ projectPath, locale }: AssetBrowserProps) {
}; };
const handleAssetDoubleClick = (asset: AssetItem) => { const handleAssetDoubleClick = (asset: AssetItem) => {
console.log('Open asset:', asset); if (asset.type === 'file' && asset.extension === 'ecs') {
if (onOpenScene) {
onOpenScene(asset.path);
}
}
}; };
const filteredAssets = searchQuery const filteredAssets = searchQuery

View File

@@ -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 (
<div className="confirm-dialog-overlay" onClick={onCancel}>
<div className="confirm-dialog" onClick={(e) => e.stopPropagation()}>
<div className="confirm-dialog-header">
<h2>{title}</h2>
<button className="close-btn" onClick={onCancel}>
<X size={16} />
</button>
</div>
<div className="confirm-dialog-content">
<p>{message}</p>
</div>
<div className="confirm-dialog-footer">
<button className="confirm-dialog-btn cancel" onClick={onCancel}>
{cancelText}
</button>
<button className="confirm-dialog-btn confirm" onClick={onConfirm}>
{confirmText}
</button>
</div>
</div>
</div>
);
}

View File

@@ -1,9 +1,8 @@
import { useState, useEffect } from 'react'; import { useState, useEffect } from 'react';
import { Entity, Core } from '@esengine/ecs-framework'; import { Entity, Core } from '@esengine/ecs-framework';
import { EntityStoreService, MessageHub, ComponentRegistry } from '@esengine/editor-core'; import { EntityStoreService, MessageHub, ComponentRegistry } from '@esengine/editor-core';
import { AddComponent } from './AddComponent';
import { PropertyInspector } from './PropertyInspector'; 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'; import '../styles/EntityInspector.css';
interface EntityInspectorProps { interface EntityInspectorProps {
@@ -15,22 +14,21 @@ export function EntityInspector({ entityStore: _entityStore, messageHub }: Entit
const [selectedEntity, setSelectedEntity] = useState<Entity | null>(null); const [selectedEntity, setSelectedEntity] = useState<Entity | null>(null);
const [remoteEntity, setRemoteEntity] = useState<any | null>(null); const [remoteEntity, setRemoteEntity] = useState<any | null>(null);
const [remoteEntityDetails, setRemoteEntityDetails] = useState<any | null>(null); const [remoteEntityDetails, setRemoteEntityDetails] = useState<any | null>(null);
const [showAddComponent, setShowAddComponent] = useState(false);
const [expandedComponents, setExpandedComponents] = useState<Set<number>>(new Set()); const [expandedComponents, setExpandedComponents] = useState<Set<number>>(new Set());
const [componentVersion, setComponentVersion] = useState(0);
useEffect(() => { useEffect(() => {
const handleSelection = (data: { entity: Entity | null }) => { const handleSelection = (data: { entity: Entity | null }) => {
setSelectedEntity(data.entity); setSelectedEntity(data.entity);
setRemoteEntity(null); setRemoteEntity(null);
setRemoteEntityDetails(null); setRemoteEntityDetails(null);
setShowAddComponent(false); setComponentVersion(0);
}; };
const handleRemoteSelection = (data: { entity: any }) => { const handleRemoteSelection = (data: { entity: any }) => {
setRemoteEntity(data.entity); setRemoteEntity(data.entity);
setRemoteEntityDetails(null); setRemoteEntityDetails(null);
setSelectedEntity(null); setSelectedEntity(null);
setShowAddComponent(false);
}; };
const handleEntityDetails = (event: Event) => { const handleEntityDetails = (event: Event) => {
@@ -39,38 +37,26 @@ export function EntityInspector({ entityStore: _entityStore, messageHub }: Entit
setRemoteEntityDetails(details); setRemoteEntityDetails(details);
}; };
const handleComponentChange = () => {
setComponentVersion(prev => prev + 1);
};
const unsubSelect = messageHub.subscribe('entity:selected', handleSelection); const unsubSelect = messageHub.subscribe('entity:selected', handleSelection);
const unsubRemoteSelect = messageHub.subscribe('remote-entity:selected', handleRemoteSelection); 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); window.addEventListener('profiler:entity-details', handleEntityDetails);
return () => { return () => {
unsubSelect(); unsubSelect();
unsubRemoteSelect(); unsubRemoteSelect();
unsubComponentAdded();
unsubComponentRemoved();
window.removeEventListener('profiler:entity-details', handleEntityDetails); window.removeEventListener('profiler:entity-details', handleEntityDetails);
}; };
}, [messageHub]); }, [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) => { const handleRemoveComponent = (index: number) => {
if (!selectedEntity) return; if (!selectedEntity) return;
const component = selectedEntity.components[index]; const component = selectedEntity.components[index];
@@ -481,19 +467,12 @@ export function EntityInspector({ entityStore: _entityStore, messageHub }: Entit
<div className="section-header"> <div className="section-header">
<Settings size={12} className="section-icon" /> <Settings size={12} className="section-icon" />
<span>Components ({components.length})</span> <span>Components ({components.length})</span>
<button
className="add-component-btn"
onClick={() => setShowAddComponent(true)}
title="Add Component"
>
<Plus size={12} />
</button>
</div> </div>
<div className="section-content"> <div className="section-content">
{components.length === 0 ? ( {components.length === 0 ? (
<div className="empty-state-small">No components</div> <div className="empty-state-small">No components</div>
) : ( ) : (
<ul className="component-list"> <ul className="component-list" key={componentVersion}>
{components.map((component, index) => { {components.map((component, index) => {
const isExpanded = expandedComponents.has(index); const isExpanded = expandedComponents.has(index);
return ( return (
@@ -534,15 +513,6 @@ export function EntityInspector({ entityStore: _entityStore, messageHub }: Entit
</div> </div>
</div> </div>
</div> </div>
{showAddComponent && selectedEntity && (
<AddComponent
entity={selectedEntity}
componentRegistry={Core.services.resolve(ComponentRegistry)}
onAdd={handleAddComponent}
onCancel={() => setShowAddComponent(false)}
/>
)}
</div> </div>
); );
} }

View File

@@ -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 (
<div className="error-dialog-overlay" onClick={onClose}>
<div className="error-dialog" onClick={(e) => e.stopPropagation()}>
<div className="error-dialog-header">
<h2>{title}</h2>
<button className="close-btn" onClick={onClose}>
<X size={16} />
</button>
</div>
<div className="error-dialog-content">
<p>{message}</p>
</div>
<div className="error-dialog-footer">
<button className="error-dialog-btn" onClick={onClose}>
</button>
</div>
</div>
</div>
);
}

View File

@@ -29,6 +29,7 @@ interface MenuBarProps {
onOpenPortManager?: () => void; onOpenPortManager?: () => void;
onOpenSettings?: () => void; onOpenSettings?: () => void;
onToggleDevtools?: () => void; onToggleDevtools?: () => void;
onOpenAbout?: () => void;
} }
export function MenuBar({ export function MenuBar({
@@ -47,7 +48,8 @@ export function MenuBar({
onOpenProfiler, onOpenProfiler,
onOpenPortManager, onOpenPortManager,
onOpenSettings, onOpenSettings,
onToggleDevtools onToggleDevtools,
onOpenAbout
}: MenuBarProps) { }: MenuBarProps) {
const [openMenu, setOpenMenu] = useState<string | null>(null); const [openMenu, setOpenMenu] = useState<string | null>(null);
const [pluginMenuItems, setPluginMenuItems] = useState<PluginMenuItem[]>([]); const [pluginMenuItems, setPluginMenuItems] = useState<PluginMenuItem[]>([]);
@@ -144,6 +146,7 @@ export function MenuBar({
settings: 'Settings', settings: 'Settings',
help: 'Help', help: 'Help',
documentation: 'Documentation', documentation: 'Documentation',
checkForUpdates: 'Check for Updates',
about: 'About', about: 'About',
devtools: 'Developer Tools' devtools: 'Developer Tools'
}, },
@@ -176,6 +179,7 @@ export function MenuBar({
settings: '设置', settings: '设置',
help: '帮助', help: '帮助',
documentation: '文档', documentation: '文档',
checkForUpdates: '检查更新',
about: '关于', about: '关于',
devtools: '开发者工具' devtools: '开发者工具'
} }
@@ -233,7 +237,8 @@ export function MenuBar({
help: [ help: [
{ label: t('documentation'), disabled: true }, { label: t('documentation'), disabled: true },
{ separator: true }, { separator: true },
{ label: t('about'), disabled: true } { label: t('checkForUpdates'), onClick: onOpenAbout },
{ label: t('about'), onClick: onOpenAbout }
] ]
}; };

View File

@@ -1,9 +1,10 @@
import { useState, useEffect } from 'react'; import { useState, useEffect } from 'react';
import { Entity } from '@esengine/ecs-framework'; import { Entity, Core } from '@esengine/ecs-framework';
import { EntityStoreService, MessageHub } from '@esengine/editor-core'; import { EntityStoreService, MessageHub, SceneManagerService } from '@esengine/editor-core';
import { useLocale } from '../hooks/useLocale'; 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 { ProfilerService, RemoteEntity } from '../services/ProfilerService';
import { confirm } from '@tauri-apps/plugin-dialog';
import '../styles/SceneHierarchy.css'; import '../styles/SceneHierarchy.css';
interface SceneHierarchyProps { interface SceneHierarchyProps {
@@ -17,7 +18,51 @@ export function SceneHierarchy({ entityStore, messageHub }: SceneHierarchyProps)
const [isRemoteConnected, setIsRemoteConnected] = useState(false); const [isRemoteConnected, setIsRemoteConnected] = useState(false);
const [selectedId, setSelectedId] = useState<number | null>(null); const [selectedId, setSelectedId] = useState<number | null>(null);
const [searchQuery, setSearchQuery] = useState(''); const [searchQuery, setSearchQuery] = useState('');
const { t } = useLocale(); const [sceneName, setSceneName] = useState<string>('Untitled');
const [sceneFilePath, setSceneFilePath] = useState<string | null>(null);
const [isSceneModified, setIsSceneModified] = useState<boolean>(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 // Subscribe to local entity changes
useEffect(() => { 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 // Filter entities based on search query
const filterRemoteEntities = (entityList: RemoteEntity[]): RemoteEntity[] => { const filterRemoteEntities = (entityList: RemoteEntity[]): RemoteEntity[] => {
if (!searchQuery.trim()) return entityList; if (!searchQuery.trim()) return entityList;
@@ -153,6 +249,15 @@ export function SceneHierarchy({ entityStore, messageHub }: SceneHierarchyProps)
<div className="hierarchy-header"> <div className="hierarchy-header">
<Layers size={16} className="hierarchy-header-icon" /> <Layers size={16} className="hierarchy-header-icon" />
<h3>{t('hierarchy.title')}</h3> <h3>{t('hierarchy.title')}</h3>
<div
className="scene-name-container clickable"
onClick={handleSceneNameClick}
title={sceneFilePath ? `${sceneName} - 点击跳转到文件` : sceneName}
>
<span className="scene-name">
{sceneName}{isSceneModified ? '*' : ''}
</span>
</div>
{showRemoteIndicator && ( {showRemoteIndicator && (
<div className="remote-indicator" title="Showing remote entities"> <div className="remote-indicator" title="Showing remote entities">
<Wifi size={12} /> <Wifi size={12} />
@@ -168,6 +273,26 @@ export function SceneHierarchy({ entityStore, messageHub }: SceneHierarchyProps)
onChange={(e) => setSearchQuery(e.target.value)} onChange={(e) => setSearchQuery(e.target.value)}
/> />
</div> </div>
{!isRemoteConnected && (
<div className="hierarchy-toolbar">
<button
className="toolbar-btn"
onClick={handleCreateEntity}
title={locale === 'zh' ? '创建实体' : 'Create Entity'}
>
<Plus size={14} />
<span>{locale === 'zh' ? '创建实体' : 'Create Entity'}</span>
</button>
<button
className="toolbar-btn"
onClick={handleDeleteEntity}
disabled={!selectedId}
title={locale === 'zh' ? '删除实体' : 'Delete Entity'}
>
<Trash2 size={14} />
</button>
</div>
)}
<div className="hierarchy-content scrollable"> <div className="hierarchy-content scrollable">
{displayEntities.length === 0 ? ( {displayEntities.length === 0 ? (
<div className="empty-state"> <div className="empty-state">

View File

@@ -18,7 +18,7 @@ export function StartupPage({ onOpenProject, onCreateProject, onOpenRecentProjec
title: 'ECS Framework Editor', title: 'ECS Framework Editor',
subtitle: 'Professional Game Development Tool', subtitle: 'Professional Game Development Tool',
openProject: 'Open Project', openProject: 'Open Project',
createProject: 'Create New Project', createProject: 'Create Project',
profilerMode: 'Profiler Mode', profilerMode: 'Profiler Mode',
recentProjects: 'Recent Projects', recentProjects: 'Recent Projects',
noRecentProjects: 'No recent projects', noRecentProjects: 'No recent projects',
@@ -49,19 +49,25 @@ export function StartupPage({ onOpenProject, onCreateProject, onOpenRecentProjec
<div className="startup-content"> <div className="startup-content">
<div className="startup-actions"> <div className="startup-actions">
<button className="startup-action-btn primary" onClick={onProfilerMode}> <button className="startup-action-btn primary" onClick={onOpenProject}>
<svg className="btn-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor"> <svg className="btn-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<path d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/> <path d="M3 7V17C3 18.1046 3.89543 19 5 19H19C20.1046 19 21 18.1046 21 17V9C21 7.89543 20.1046 7 19 7H13L11 5H5C3.89543 5 3 5.89543 3 7Z" strokeWidth="2"/>
</svg> </svg>
<span>{t.profilerMode}</span> <span>{t.openProject}</span>
</button> </button>
<button className="startup-action-btn disabled" disabled title={t.comingSoon}> <button className="startup-action-btn" onClick={onCreateProject}>
<svg className="btn-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor"> <svg className="btn-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<path d="M12 5V19M5 12H19" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/> <path d="M12 5V19M5 12H19" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
</svg> </svg>
<span>{t.createProject}</span> <span>{t.createProject}</span>
<span className="badge-coming-soon">{t.comingSoon}</span> </button>
<button className="startup-action-btn" onClick={onProfilerMode}>
<svg className="btn-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<path d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
</svg>
<span>{t.profilerMode}</span>
</button> </button>
</div> </div>

View File

@@ -0,0 +1,97 @@
import type { Core, ServiceContainer } from '@esengine/ecs-framework';
import { createLogger } from '@esengine/ecs-framework';
import { IEditorPlugin, EditorPluginCategory, SettingsRegistry } from '@esengine/editor-core';
import { SettingsService } from '../services/SettingsService';
const logger = createLogger('EditorAppearancePlugin');
/**
* Editor Appearance Plugin
*
* Manages editor appearance settings like font size
*/
export class EditorAppearancePlugin implements IEditorPlugin {
readonly name = '@esengine/editor-appearance';
readonly version = '1.0.0';
readonly displayName = 'Editor Appearance';
readonly category = EditorPluginCategory.System;
readonly description = 'Configure editor appearance settings';
readonly icon = '🎨';
async install(_core: Core, services: ServiceContainer): Promise<void> {
const settingsRegistry = services.resolve(SettingsRegistry);
settingsRegistry.registerCategory({
id: 'appearance',
title: '外观',
description: '配置编辑器的外观设置',
sections: [
{
id: 'font',
title: '字体设置',
description: '配置编辑器字体样式',
settings: [
{
key: 'editor.fontSize',
label: '字体大小 (px)',
type: 'range',
defaultValue: 13,
description: '编辑器界面的字体大小',
min: 11,
max: 18,
step: 1
}
]
}
]
});
this.applyFontSettings();
this.setupSettingsListener();
logger.info('Installed');
}
async uninstall(): Promise<void> {
logger.info('Uninstalled');
}
async onEditorReady(): Promise<void> {
logger.info('Editor is ready');
}
/**
* Apply font settings from settings
*/
private applyFontSettings(): void {
const settings = SettingsService.getInstance();
const baseFontSize = settings.get<number>('editor.fontSize', 13);
logger.info(`Applying font size: ${baseFontSize}px`);
const root = document.documentElement;
// Apply font sizes
root.style.setProperty('--font-size-xs', `${baseFontSize - 2}px`);
root.style.setProperty('--font-size-sm', `${baseFontSize - 1}px`);
root.style.setProperty('--font-size-base', `${baseFontSize}px`);
root.style.setProperty('--font-size-md', `${baseFontSize + 1}px`);
root.style.setProperty('--font-size-lg', `${baseFontSize + 3}px`);
root.style.setProperty('--font-size-xl', `${baseFontSize + 5}px`);
}
/**
* Listen for settings changes
*/
private setupSettingsListener(): void {
window.addEventListener('settings:changed', ((event: CustomEvent) => {
const changedSettings = event.detail;
logger.info('Settings changed event received', changedSettings);
if ('editor.fontSize' in changedSettings) {
logger.info('Font size changed, applying...');
this.applyFontSettings();
}
}) as EventListener);
}
}

View File

@@ -0,0 +1,258 @@
.modal-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;
backdrop-filter: blur(4px);
}
.about-dialog {
background: var(--color-bg-elevated);
border-radius: 8px;
padding: 0;
width: 500px;
max-width: 90vw;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
animation: slideIn 0.2s ease-out;
}
@keyframes slideIn {
from {
opacity: 0;
transform: translateY(-20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.about-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 20px 24px;
border-bottom: 1px solid var(--color-border-default);
}
.about-header h2 {
margin: 0;
font-size: 18px;
font-weight: 600;
color: var(--color-text-primary);
}
.about-header .close-btn {
background: none;
border: none;
color: var(--color-text-secondary);
cursor: pointer;
padding: 4px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 4px;
transition: all 0.2s;
}
.about-header .close-btn:hover {
background: var(--color-bg-hover);
color: var(--color-text-primary);
}
.about-content {
padding: 32px 24px;
display: flex;
flex-direction: column;
align-items: center;
gap: 24px;
}
.about-logo {
width: 80px;
height: 80px;
}
.logo-placeholder {
width: 100%;
height: 100%;
background: linear-gradient(135deg, #569CD6, #4EC9B0);
border-radius: 16px;
display: flex;
align-items: center;
justify-content: center;
font-size: 28px;
font-weight: bold;
color: white;
box-shadow: 0 4px 12px rgba(86, 156, 214, 0.3);
}
.about-info {
text-align: center;
}
.about-info h3 {
margin: 0 0 8px 0;
font-size: 20px;
font-weight: 600;
color: var(--color-text-primary);
}
.about-version {
margin: 0 0 12px 0;
font-size: 14px;
color: var(--color-text-secondary);
}
.about-description {
margin: 0;
font-size: 14px;
color: var(--color-text-secondary);
line-height: 1.5;
max-width: 400px;
}
.about-update {
width: 100%;
display: flex;
flex-direction: column;
gap: 12px;
align-items: center;
}
.update-btn {
display: flex;
align-items: center;
gap: 8px;
padding: 10px 24px;
background: var(--color-bg-overlay);
border: 1px solid var(--color-border-default);
border-radius: 6px;
color: var(--color-text-primary);
font-size: 14px;
cursor: pointer;
transition: all 0.2s;
}
.update-btn:hover:not(:disabled) {
background: var(--color-bg-hover);
border-color: var(--color-primary);
}
.update-btn:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.update-status {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 16px;
border-radius: 6px;
font-size: 13px;
}
.update-status.status-checking {
background: rgba(86, 156, 214, 0.1);
color: #569CD6;
}
.update-status.status-available {
background: rgba(78, 201, 176, 0.1);
color: #4EC9B0;
}
.update-status.status-latest {
background: rgba(78, 201, 176, 0.1);
color: #4EC9B0;
}
.update-status.status-error {
background: rgba(206, 145, 120, 0.1);
color: #CE9178;
}
.update-status .status-available {
color: #4EC9B0;
}
.update-status .status-latest {
color: #4EC9B0;
}
.update-status .status-error {
color: #CE9178;
}
.about-links {
display: flex;
gap: 16px;
margin-top: 8px;
}
.about-link {
color: var(--color-primary);
text-decoration: none;
font-size: 14px;
transition: color 0.2s;
}
.about-link:hover {
color: var(--color-primary-hover);
text-decoration: underline;
}
.about-footer {
margin-top: 8px;
padding-top: 16px;
border-top: 1px solid var(--color-border-default);
text-align: center;
}
.about-footer p {
margin: 0;
font-size: 12px;
color: var(--color-text-tertiary);
}
.about-actions {
padding: 16px 24px;
border-top: 1px solid var(--color-border-default);
display: flex;
justify-content: flex-end;
}
.btn-primary {
padding: 8px 24px;
background: var(--color-primary);
border: none;
border-radius: 6px;
color: white;
font-size: 14px;
cursor: pointer;
transition: background 0.2s;
}
.btn-primary:hover {
background: var(--color-primary-hover);
}
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
.animate-spin {
animation: spin 1s linear infinite;
}

View File

@@ -14,7 +14,7 @@
.asset-browser-header h3 { .asset-browser-header h3 {
margin: 0; margin: 0;
font-size: 14px; font-size: var(--font-size-md);
font-weight: 600; font-weight: 600;
color: #cccccc; color: #cccccc;
} }
@@ -83,7 +83,7 @@
border: 1px solid #3e3e3e; border: 1px solid #3e3e3e;
border-radius: 3px; border-radius: 3px;
color: #cccccc; color: #cccccc;
font-size: 13px; font-size: var(--font-size-base);
outline: none; outline: none;
} }
@@ -103,7 +103,7 @@
justify-content: center; justify-content: center;
height: 200px; height: 200px;
color: #858585; color: #858585;
font-size: 13px; font-size: var(--font-size-base);
} }
.asset-list { .asset-list {
@@ -152,7 +152,7 @@
} }
.asset-name { .asset-name {
font-size: 12px; font-size: var(--font-size-sm);
color: #cccccc; color: #cccccc;
text-align: center; text-align: center;
width: 100%; width: 100%;
@@ -163,7 +163,7 @@
} }
.asset-type { .asset-type {
font-size: 10px; font-size: var(--font-size-xs);
color: #858585; color: #858585;
text-transform: uppercase; text-transform: uppercase;
} }

View File

@@ -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);
}

View File

@@ -72,7 +72,7 @@
border: none; border: none;
outline: none; outline: none;
color: var(--color-text-primary); color: var(--color-text-primary);
font-size: 11px; font-size: var(--font-size-xs);
font-family: var(--font-family-mono); font-family: var(--font-family-mono);
} }
@@ -89,7 +89,7 @@
border: 1px solid transparent; border: 1px solid transparent;
border-radius: var(--radius-sm); border-radius: var(--radius-sm);
cursor: pointer; cursor: pointer;
font-size: 10px; font-size: var(--font-size-xs);
font-weight: 500; font-weight: 500;
transition: all var(--transition-fast); transition: all var(--transition-fast);
opacity: 0.5; opacity: 0.5;
@@ -152,7 +152,7 @@
} }
.console-filter-btn span { .console-filter-btn span {
font-size: 10px; font-size: var(--font-size-xs);
font-family: var(--font-family-mono); font-family: var(--font-family-mono);
} }
@@ -161,7 +161,7 @@
overflow-y: auto; overflow-y: auto;
overflow-x: hidden; overflow-x: hidden;
font-family: var(--font-family-mono); font-family: var(--font-family-mono);
font-size: 11px; font-size: var(--font-size-xs);
line-height: 1.4; line-height: 1.4;
} }
@@ -177,7 +177,7 @@
.console-empty p { .console-empty p {
margin: 0; margin: 0;
font-size: 12px; font-size: var(--font-size-sm);
} }
.log-entry { .log-entry {
@@ -202,7 +202,7 @@
.log-entry-time { .log-entry-time {
color: var(--color-text-tertiary); color: var(--color-text-tertiary);
font-size: 10px; font-size: var(--font-size-xs);
white-space: nowrap; white-space: nowrap;
padding-top: 2px; padding-top: 2px;
flex-shrink: 0; flex-shrink: 0;
@@ -211,7 +211,7 @@
.log-entry-source { .log-entry-source {
color: var(--color-text-secondary); color: var(--color-text-secondary);
font-size: 10px; font-size: var(--font-size-xs);
white-space: nowrap; white-space: nowrap;
padding-top: 2px; padding-top: 2px;
flex-shrink: 0; flex-shrink: 0;
@@ -226,7 +226,7 @@
.log-entry-client { .log-entry-client {
color: #10b981; color: #10b981;
font-size: 9px; font-size: calc(var(--font-size-xs) - 2px);
white-space: nowrap; white-space: nowrap;
padding: 1px 6px; padding: 1px 6px;
flex-shrink: 0; flex-shrink: 0;
@@ -312,7 +312,7 @@
border-radius: var(--radius-sm); border-radius: var(--radius-sm);
border: 1px solid var(--color-border-default); border: 1px solid var(--color-border-default);
font-family: var(--font-family-mono); font-family: var(--font-family-mono);
font-size: 11px; font-size: var(--font-size-xs);
line-height: 1.5; line-height: 1.5;
overflow: auto; overflow: auto;
white-space: pre; white-space: pre;
@@ -377,7 +377,7 @@
color: var(--color-text-inverse); color: var(--color-text-inverse);
border: none; border: none;
border-radius: var(--radius-sm); border-radius: var(--radius-sm);
font-size: 11px; font-size: var(--font-size-xs);
font-weight: 500; font-weight: 500;
cursor: pointer; cursor: pointer;
box-shadow: var(--shadow-md); box-shadow: var(--shadow-md);

View File

@@ -4,6 +4,7 @@
height: 100%; height: 100%;
background-color: var(--color-bg-base); background-color: var(--color-bg-base);
color: var(--color-text-primary); color: var(--color-text-primary);
position: relative;
} }
.inspector-header { .inspector-header {

View File

@@ -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);
}

View File

@@ -30,7 +30,7 @@
align-items: center; align-items: center;
justify-content: center; justify-content: center;
color: #858585; color: #858585;
font-size: 12px; font-size: var(--font-size-sm);
} }
.tree-node { .tree-node {
@@ -38,7 +38,7 @@
align-items: center; align-items: center;
padding: 4px 8px; padding: 4px 8px;
cursor: pointer; cursor: pointer;
font-size: 13px; font-size: var(--font-size-base);
white-space: nowrap; white-space: nowrap;
transition: background 0.1s ease; transition: background 0.1s ease;
} }
@@ -58,13 +58,13 @@
align-items: center; align-items: center;
justify-content: center; justify-content: center;
margin-right: 4px; margin-right: 4px;
font-size: 10px; font-size: var(--font-size-xs);
color: #cccccc; color: #cccccc;
} }
.tree-icon { .tree-icon {
margin-right: 6px; margin-right: 6px;
font-size: 14px; font-size: var(--font-size-md);
} }
.tree-label { .tree-label {

View File

@@ -29,7 +29,42 @@
color: var(--color-text-primary); color: var(--color-text-primary);
text-transform: uppercase; text-transform: uppercase;
letter-spacing: 0.05em; 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 { .remote-indicator {
@@ -74,6 +109,45 @@
color: var(--color-text-tertiary); 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 { .hierarchy-content {
flex: 1; flex: 1;
overflow-y: auto; overflow-y: auto;

View File

@@ -0,0 +1,60 @@
import { check } from '@tauri-apps/plugin-updater';
export interface UpdateCheckResult {
available: boolean;
version?: string;
currentVersion?: string;
error?: string;
}
/**
* 检查应用更新
*
* 自动检查 GitHub Releases 是否有新版本
* 如果有更新,提示用户并可选择安装
*/
export async function checkForUpdates(silent: boolean = false): Promise<UpdateCheckResult> {
try {
const update = await check();
if (update?.available) {
console.log(`发现新版本: ${update.version}`);
console.log(`当前版本: ${update.currentVersion}`);
console.log(`更新日期: ${update.date}`);
console.log(`更新说明:\n${update.body}`);
if (!silent) {
// Tauri 会自动显示更新对话框(因为配置了 dialog: true
// 用户点击确认后会自动下载并安装,安装完成后会自动重启
await update.downloadAndInstall();
}
return {
available: true,
version: update.version,
currentVersion: update.currentVersion
};
} else {
if (!silent) {
console.log('当前已是最新版本');
}
return { available: false };
}
} catch (error) {
console.error('检查更新失败:', error);
return {
available: false,
error: error instanceof Error ? error.message : '检查更新失败'
};
}
}
/**
* 应用启动时静默检查更新
*/
export async function checkForUpdatesOnStartup(): Promise<void> {
// 延迟 3 秒后检查,避免影响启动速度
setTimeout(() => {
checkForUpdates(true);
}, 3000);
}

View File

@@ -3,15 +3,10 @@ import react from '@vitejs/plugin-react';
import fs from 'fs'; import fs from 'fs';
import path from 'path'; import path from 'path';
import { transformSync } from 'esbuild'; import { transformSync } from 'esbuild';
import JSON5 from 'json5';
const host = process.env.TAURI_DEV_HOST; const host = process.env.TAURI_DEV_HOST;
const userProjectPathMap = new Map<string, string>(); const userProjectPathMap = new Map<string, string>();
const userProjectDependencies = new Map<string, Set<string>>();
const cocosEnginePaths = new Map<string, string>();
const allowedPaths = new Set<string>();
const editorPackageMapping = new Map<string, string>(); const editorPackageMapping = new Map<string, string>();
function loadEditorPackages() { function loadEditorPackages() {
@@ -36,7 +31,6 @@ function loadEditorPackages() {
const entryPath = path.join(packagesDir, dir, mainFile); const entryPath = path.join(packagesDir, dir, mainFile);
if (fs.existsSync(entryPath)) { if (fs.existsSync(entryPath)) {
editorPackageMapping.set(packageJson.name, 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(); 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<string>();
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 = () => ({ const userProjectPlugin = () => ({
name: 'user-project-middleware', name: 'user-project-middleware',
configureServer(server: any) { configureServer(server: any) {
allowedPaths.add(path.resolve(__dirname, '..'));
server.middlewares.use(async (req: any, res: any, next: any) => { server.middlewares.use(async (req: any, res: any, next: any) => {
if (req.url?.startsWith('/@user-project/')) { if (req.url?.startsWith('/@user-project/')) {
console.log('[Vite] Received request:', req.url);
const urlWithoutQuery = req.url.split('?')[0]; const urlWithoutQuery = req.url.split('?')[0];
const relativePath = decodeURIComponent(urlWithoutQuery.substring('/@user-project'.length)); const relativePath = decodeURIComponent(urlWithoutQuery.substring('/@user-project'.length));
console.log('[Vite] Resolved relative path:', relativePath);
let projectPath: string | null = null; let projectPath: string | null = null;
for (const [, path] of userProjectPathMap) { for (const [, path] of userProjectPathMap) {
projectPath = path; projectPath = path;
break; break;
@@ -146,8 +64,6 @@ const userProjectPlugin = () => ({
} }
const filePath = path.join(projectPath, relativePath); 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)) { if (!fs.existsSync(filePath)) {
console.error('[Vite] File not found:', filePath); console.error('[Vite] File not found:', filePath);
@@ -163,7 +79,6 @@ const userProjectPlugin = () => ({
} }
try { try {
console.log('[Vite] Reading and transforming file:', filePath);
let content = fs.readFileSync(filePath, 'utf-8'); let content = fs.readFileSync(filePath, 'utf-8');
editorPackageMapping.forEach((srcPath, packageName) => { 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 fileDir = path.dirname(filePath);
const relativeImportRegex = /from\s+['"](\.\.?\/[^'"]+)['"]/g; const relativeImportRegex = /from\s+['"](\.\.?\/[^'"]+)['"]/g;
content = content.replace(relativeImportRegex, (match, importPath) => { content = content.replace(relativeImportRegex, (match, importPath) => {
@@ -239,7 +117,6 @@ const userProjectPlugin = () => ({
sourcefile: filePath, sourcefile: filePath,
}); });
console.log('[Vite] Successfully transformed file:', filePath);
res.setHeader('Content-Type', 'application/javascript; charset=utf-8'); res.setHeader('Content-Type', 'application/javascript; charset=utf-8');
res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Cache-Control', 'no-cache'); res.setHeader('Cache-Control', 'no-cache');
@@ -253,58 +130,12 @@ const userProjectPlugin = () => ({
} }
if (req.url === '/@ecs-framework-shim') { 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('Content-Type', 'application/javascript; charset=utf-8');
res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Origin', '*');
res.end('export * from "/@fs/' + path.resolve(__dirname, '../core/src/index.ts').replace(/\\/g, '/') + '";'); res.end('export * from "/@fs/' + path.resolve(__dirname, '../core/src/index.ts').replace(/\\/g, '/') + '";');
return; 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') { if (req.url === '/@user-project-set-path') {
let body = ''; let body = '';
req.on('data', (chunk: any) => { req.on('data', (chunk: any) => {
@@ -314,9 +145,6 @@ const userProjectPlugin = () => ({
try { try {
const { path: projectPath } = JSON.parse(body); const { path: projectPath } = JSON.parse(body);
userProjectPathMap.set('current', projectPath); userProjectPathMap.set('current', projectPath);
allowedPaths.add(projectPath);
loadUserProjectDependencies(projectPath);
console.log('[Vite] User project path set to:', projectPath);
res.statusCode = 200; res.statusCode = 200;
res.end('OK'); res.end('OK');
} catch (err) { } catch (err) {

View File

@@ -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<string, LoadedComponentInfo> = 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<LoadedComponentInfo[]> {
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<LoadedComponentInfo | null> {
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();
}
}

View File

@@ -1,7 +1,8 @@
import type { IService } from '@esengine/ecs-framework'; import type { IService } from '@esengine/ecs-framework';
import { Injectable } 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 { MessageHub } from './MessageHub';
import type { IFileAPI } from '../Types/IFileAPI';
const logger = createLogger('ProjectService'); const logger = createLogger('ProjectService');
@@ -19,6 +20,8 @@ export interface ProjectConfig {
componentsPath?: string; componentsPath?: string;
componentPattern?: string; componentPattern?: string;
buildOutput?: string; buildOutput?: string;
scenesPath?: string;
defaultScene?: string;
} }
@Injectable() @Injectable()
@@ -26,9 +29,55 @@ export class ProjectService implements IService {
private currentProject: ProjectInfo | null = null; private currentProject: ProjectInfo | null = null;
private projectConfig: ProjectConfig | null = null; private projectConfig: ProjectConfig | null = null;
private messageHub: MessageHub; private messageHub: MessageHub;
private fileAPI: IFileAPI;
constructor(messageHub: MessageHub) { constructor(messageHub: MessageHub, fileAPI: IFileAPI) {
this.messageHub = messageHub; this.messageHub = messageHub;
this.fileAPI = fileAPI;
}
public async createProject(projectPath: string): Promise<void> {
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<void> { public async openProject(projectPath: string): Promise<void> {
@@ -91,6 +140,28 @@ export class ProjectService implements IService {
return `${this.currentProject.path}${sep}${this.projectConfig.componentsPath}`; 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<ProjectInfo> { private async validateProject(projectPath: string): Promise<ProjectInfo> {
const projectName = projectPath.split(/[\\/]/).pop() || 'Unknown Project'; const projectName = projectPath.split(/[\\/]/).pop() || 'Unknown Project';
@@ -118,7 +189,9 @@ export class ProjectService implements IService {
projectType: 'cocos', projectType: 'cocos',
componentsPath: '', componentsPath: '',
componentPattern: '**/*.ts', componentPattern: '**/*.ts',
buildOutput: 'temp/editor-components' buildOutput: 'temp/editor-components',
scenesPath: 'ecs-scenes',
defaultScene: 'main.ecs'
}; };
} }

View File

@@ -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<void> {
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<void> {
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<void> {
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<void> {
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<void> {
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<boolean> {
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');
}
}

View File

@@ -0,0 +1,61 @@
/**
* 文件 API 接口
*
* 定义编辑器与文件系统交互的抽象接口
* 具体实现由上层应用提供(如 TauriFileAPI
*/
export interface IFileAPI {
/**
* 打开场景文件选择对话框
* @returns 用户选择的文件路径,取消则返回 null
*/
openSceneDialog(): Promise<string | null>;
/**
* 打开保存场景对话框
* @param defaultName 默认文件名
* @returns 用户选择的文件路径,取消则返回 null
*/
saveSceneDialog(defaultName?: string): Promise<string | null>;
/**
* 读取文件内容
* @param path 文件路径
* @returns 文件内容(文本格式)
*/
readFileContent(path: string): Promise<string>;
/**
* 保存项目文件
* @param path 保存路径
* @param data 文件内容(文本格式)
*/
saveProject(path: string, data: string): Promise<void>;
/**
* 导出二进制文件
* @param data 二进制数据
* @param path 保存路径
*/
exportBinary(data: Uint8Array, path: string): Promise<void>;
/**
* 创建目录
* @param path 目录路径
*/
createDirectory(path: string): Promise<void>;
/**
* 写入文件内容
* @param path 文件路径
* @param content 文件内容
*/
writeFileContent(path: string, content: string): Promise<void>;
/**
* 检查路径是否存在
* @param path 文件或目录路径
* @returns 路径是否存在
*/
pathExists(path: string): Promise<boolean>;
}

View File

@@ -16,8 +16,9 @@ export * from './Services/LocaleService';
export * from './Services/PropertyMetadata'; export * from './Services/PropertyMetadata';
export * from './Services/ProjectService'; export * from './Services/ProjectService';
export * from './Services/ComponentDiscoveryService'; export * from './Services/ComponentDiscoveryService';
export * from './Services/ComponentLoaderService';
export * from './Services/LogService'; export * from './Services/LogService';
export * from './Services/SettingsRegistry'; export * from './Services/SettingsRegistry';
export * from './Services/SceneManagerService';
export * from './Types/UITypes'; export * from './Types/UITypes';
export * from './Types/IFileAPI';

BIN
screenshots/about.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 122 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Some files were not shown because too many files have changed in this diff Show More