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
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
// ControlWave 插件加载器
class PluginLoader {
    constructor() {
        this.plugins = new Map();
        this.installedPlugins = new Set();
        this.availablePlugins = new Map(); // 官方推荐插件
        this.pluginOrder = [];
        
        // 初始化官方推荐插件列表
        this.initOfficialPlugins();
    }

    // 初始化官方插件
    initOfficialPlugins() {
        // 不再硬编码插件列表,而是从服务器动态获取
        console.log('🔧 插件列表将从服务器动态加载');
    }

    // 注册插件
    async registerPlugin(pluginConfig) {
        const { id, name, path, icon, order = 999 } = pluginConfig;
        
        if (this.plugins.has(id)) {
            console.warn(`插件 ${id} 已存在,跳过注册`);
            return false;
        }

        this.plugins.set(id, {
            id,
            name,
            path,
            icon,
            order,
            loaded: false,
            instance: null,
            installed: this.installedPlugins.has(id)
        });

        // 按order排序插件
        this.pluginOrder = Array.from(this.plugins.keys()).sort((a, b) => {
            return this.plugins.get(a).order - this.plugins.get(b).order;
        });

        console.log(`✅ 注册插件: ${name} (${id})`);
        return true;
    }

    // 加载插件
    async loadPlugin(pluginId) {
        const plugin = this.plugins.get(pluginId);
        if (!plugin) {
            console.error(`插件 ${pluginId} 未在注册列表中找到`);
            console.log('已注册插件:', Array.from(this.plugins.keys()));
            return null;
        }

        // 检查插件是否已安装
        if (!this.installedPlugins.has(pluginId)) {
            console.error(`插件 ${pluginId} 未安装`);
            return null;
        }

        if (plugin.loaded) {
            return plugin.instance;
        }

        try {
            console.log(`🔄 正在加载插件: ${plugin.name} from ${plugin.path}`);
            
            // 动态导入插件模块
            const module = await import(plugin.path);
            if (!module.default) {
                throw new Error('插件文件没有默认导出');
            }
            
            plugin.instance = new module.default();
            plugin.loaded = true;
            
            console.log(`✅ 加载插件成功: ${plugin.name}`);
            return plugin.instance;
        } catch (error) {
            console.error(`❌ 加载插件失败: ${plugin.name}`, error);
            return null;
        }
    }

    // 获取所有已注册的插件
    getPlugins() {
        return this.pluginOrder.map(id => this.plugins.get(id));
    }

    // 创建插件选项卡
    createPluginTabs(container) {
        const tabButtons = container.querySelector('.tab-buttons');
        const mainContent = container.querySelector('.main-content');
        
        console.log('🔧 创建插件选项卡...');
        console.log('📝 所有注册插件:', this.pluginOrder);
        console.log('📦 已安装插件:', Array.from(this.installedPlugins));
        
        // 清空现有选项卡(除了插件管理)
        const existingTabs = tabButtons.querySelectorAll('.tab-button:not([data-tab="plugin-management"])');
        existingTabs.forEach(tab => tab.remove());
        
        // 获取保存的插件顺序
        const savedOrder = this.getSavedPluginOrder();
        
        // 获取所有已安装的插件
        const installedPluginsMap = new Map();
        this.pluginOrder.forEach(pluginId => {
            const plugin = this.plugins.get(pluginId);
            if (plugin && plugin.installed) {
                installedPluginsMap.set(pluginId, plugin);
            }
        });
        
        // 按照保存的顺序创建选项卡
        let tabIndex = 0;
        
        // 先创建在保存顺序中的插件
        savedOrder.forEach(pluginId => {
            const plugin = installedPluginsMap.get(pluginId);
            if (plugin) {
                const tabButton = this.createTabButton(plugin, tabIndex === 0);
                const pluginMgmtBtn = tabButtons.querySelector('[data-tab="plugin-management"]');
                tabButtons.insertBefore(tabButton, pluginMgmtBtn);
                installedPluginsMap.delete(pluginId); // 从map中移除已处理的插件
                tabIndex++;
            }
        });
        
        // 然后创建不在保存顺序中的插件
        installedPluginsMap.forEach((plugin, pluginId) => {
            const tabButton = this.createTabButton(plugin, tabIndex === 0);
            const pluginMgmtBtn = tabButtons.querySelector('[data-tab="plugin-management"]');
            tabButtons.insertBefore(tabButton, pluginMgmtBtn);
            tabIndex++;
        });
        
        // 如果没有已安装的插件,则激活插件管理选项卡
        if (tabIndex === 0) {
            const pluginMgmtBtn = tabButtons.querySelector('[data-tab="plugin-management"]');
            pluginMgmtBtn.classList.add('active');
        }
        
        // 为选项卡启用拖拽功能
        this.enableTabDragAndDrop(tabButtons);
    }
    
    // 创建选项卡按钮
    createTabButton(plugin, isActive) {
        const tabButton = document.createElement('button');
        // 初始创建时不设置 active,让 loadPlugin 来控制
        tabButton.className = 'tab-button draggable';
        tabButton.dataset.tab = plugin.id;
        tabButton.innerHTML = plugin.name;
        tabButton.draggable = true;
        return tabButton;
    }
    
    // 获取保存的插件顺序
    getSavedPluginOrder() {
        const saved = localStorage.getItem('controlwave_plugin_order');
        if (saved) {
            try {
                return JSON.parse(saved);
            } catch (e) {
                console.error('解析保存的插件顺序失败:', e);
            }
        }
        // 返回默认顺序
        return ['wave-space', 'preview', 'full-render', 'training-visualization-v2'];
    }
    
    // 启用选项卡拖拽功能
    enableTabDragAndDrop(tabButtons) {
        let draggedTab = null;
        
        tabButtons.addEventListener('dragstart', (e) => {
            if (e.target.classList.contains('draggable')) {
                draggedTab = e.target;
                e.target.classList.add('dragging');
                e.dataTransfer.effectAllowed = 'move';
            }
        });
        
        tabButtons.addEventListener('dragend', (e) => {
            if (e.target.classList.contains('draggable')) {
                e.target.classList.remove('dragging');
            }
        });
        
        tabButtons.addEventListener('dragover', (e) => {
            e.preventDefault();
            const afterElement = this.getDragAfterElement(tabButtons, e.clientX);
            
            if (afterElement == null) {
                // 插入到插件管理按钮之前
                const pluginMgmtBtn = tabButtons.querySelector('[data-tab="plugin-management"]');
                tabButtons.insertBefore(draggedTab, pluginMgmtBtn);
            } else if (afterElement !== draggedTab) {
                tabButtons.insertBefore(draggedTab, afterElement);
            }
        });
        
        tabButtons.addEventListener('drop', (e) => {
            e.preventDefault();
            
            // 获取新的顺序
            const tabs = [...tabButtons.querySelectorAll('.tab-button.draggable')];
            const newOrder = tabs.map(tab => tab.dataset.tab);
            
            // 保存顺序
            localStorage.setItem('controlwave_plugin_order', JSON.stringify(newOrder));
            console.log('选项卡顺序已更新:', newOrder);
            
            // 同步更新插件管理界面的顺序列表
            const updateEvent = new CustomEvent('plugin-order-changed', { detail: newOrder });
            window.dispatchEvent(updateEvent);
        });
    }
    
    // 获取拖拽后的位置(水平方向)
    getDragAfterElement(container, x) {
        const draggableElements = [...container.querySelectorAll('.tab-button.draggable:not(.dragging)')];
        
        return draggableElements.reduce((closest, child) => {
            const box = child.getBoundingClientRect();
            const offset = x - box.left - box.width / 2;
            
            if (offset < 0 && offset > closest.offset) {
                return { offset: offset, element: child };
            } else {
                return closest;
            }
        }, { offset: Number.NEGATIVE_INFINITY }).element;
    }

    // 安装插件
    async installPlugin(pluginId) {
        this.installedPlugins.add(pluginId);
        
        // 更新已注册插件状态
        if (this.plugins.has(pluginId)) {
            this.plugins.get(pluginId).installed = true;
        }
        
        console.log(`✅ 插件 ${pluginId} 已安装`);
        return true;
    }

    // 卸载插件
    async uninstallPlugin(pluginId) {
        this.installedPlugins.delete(pluginId);
        
        // 更新已注册插件状态
        if (this.plugins.has(pluginId)) {
            const plugin = this.plugins.get(pluginId);
            plugin.installed = false;
            plugin.loaded = false;
            plugin.instance = null;
        }
        
        // 移除插件内容容器
        const container = document.getElementById(pluginId);
        if (container) {
            container.remove();
        }
        
        console.log(`❌ 插件 ${pluginId} 已卸载`);
        return true;
    }

    // 获取所有可用插件(包括未安装的)
    getAllAvailablePlugins() {
        return Array.from(this.availablePlugins.values());
    }

    // 获取已安装插件
    getInstalledPlugins() {
        return this.pluginOrder
            .filter(id => this.installedPlugins.has(id))
            .map(id => this.plugins.get(id) || this.availablePlugins.get(id));
    }

    // 扫描本地插件文件夹
    async scanLocalPlugins() {
        try {
            // 调用服务器API扫描插件文件夹
            const response = await fetch('/api/plugins/scan');
            const data = await response.json();
            
            if (!response.ok) {
                throw new Error('Failed to scan plugins');
            }
            
            const { plugins, duplicates } = data;
            
            // 显示重复插件警告
            if (duplicates && duplicates.length > 0) {
                this.showDuplicateWarnings(duplicates);
            }
            
            // 更新可用插件列表和已安装状态
            plugins.forEach(plugin => {
                this.availablePlugins.set(plugin.id, plugin);
                // 本地插件自动标记为已安装(因为文件夹存在即已安装)
                this.installedPlugins.add(plugin.id);
            });
            
            console.log(`🔍 扫描到 ${plugins.length} 个本地插件`);
            console.log(`📦 已安装插件:`, Array.from(this.installedPlugins));
            
            if (duplicates.length > 0) {
                console.warn(`⚠️ 发现 ${duplicates.length} 个重复ID的插件`);
            }
            
            return plugins;
            
        } catch (error) {
            console.error('扫描本地插件失败:', error);
            return [];
        }
    }
    
    // 显示重复插件警告
    showDuplicateWarnings(duplicates) {
        // 检查是否已有警告区域
        let warningArea = document.getElementById('plugin-warnings');
        
        if (!warningArea) {
            // 创建警告区域
            warningArea = document.createElement('div');
            warningArea.id = 'plugin-warnings';
            warningArea.style.cssText = `
                position: fixed;
                top: 10px;
                right: 10px;
                width: 350px;
                max-height: 300px;
                overflow-y: auto;
                background: #fff;
                border: 1px solid #ffc107;
                border-radius: 4px;
                box-shadow: 0 2px 10px rgba(0,0,0,0.1);
                z-index: 10000;
                font-size: 14px;
            `;
            
            const header = document.createElement('div');
            header.style.cssText = `
                background: #ffc107;
                color: #000;
                padding: 10px 15px;
                font-weight: bold;
                display: flex;
                justify-content: space-between;
                align-items: center;
            `;
            header.innerHTML = `
                <span>⚠️ 插件警告</span>
                <button onclick="document.getElementById('plugin-warnings').remove()" style="
                    background: none;
                    border: none;
                    font-size: 18px;
                    cursor: pointer;
                    padding: 0;
                    width: 24px;
                    height: 24px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                ">×</button>
            `;
            
            warningArea.appendChild(header);
            
            const content = document.createElement('div');
            content.id = 'plugin-warnings-content';
            content.style.cssText = 'padding: 15px;';
            warningArea.appendChild(content);
            
            document.body.appendChild(warningArea);
        }
        
        // 更新警告内容
        const content = document.getElementById('plugin-warnings-content');
        content.innerHTML = '';
        
        duplicates.forEach(dup => {
            const warning = document.createElement('div');
            warning.style.cssText = 'margin-bottom: 10px; padding-bottom: 10px; border-bottom: 1px solid #eee;';
            warning.innerHTML = `
                <strong>重复ID: ${dup.id}</strong><br>
                <small>文件夹: ${dup.folders.join(', ')}</small><br>
                <small style="color: #666;">只加载了第一个插件</small>
            `;
            content.appendChild(warning);
        });
        
        // 10秒后自动关闭
        setTimeout(() => {
            const area = document.getElementById('plugin-warnings');
            if (area) {
                area.style.transition = 'opacity 0.3s';
                area.style.opacity = '0';
                setTimeout(() => area.remove(), 300);
            }
        }, 10000);
    }

    // 获取所有插件(包括本地和远程)
    async getAllPluginsWithLocal() {
        await this.scanLocalPlugins();
        return Array.from(this.availablePlugins.values());
    }

    // 获取特定插件的实例和信息
    getPlugin(pluginId) {
        return this.plugins.get(pluginId);
    }

    // 初始化插件内容
    async initializePluginContent(pluginId, container) {
        const plugin = await this.loadPlugin(pluginId);
        if (!plugin) {
            console.error(`插件 ${pluginId} 加载失败`);
            container.innerHTML = `
                <div class="error-message" style="padding: 50px; text-align: center;">
                    <h3>❌ 插件加载失败</h3>
                    <p>插件 ${pluginId} 无法加载</p>
                </div>
            `;
            return;
        }

        // 渲染插件内容到容器
        try {
            await plugin.render(container);
            console.log(`✅ 插件 ${pluginId} 渲染成功`);
        } catch (error) {
            console.error(`渲染插件失败: ${pluginId}`, error);
            container.innerHTML = `
                <div class="error-message" style="padding: 50px; text-align: center;">
                    <h3>❌ 插件渲染失败</h3>
                    <p>${error.message}</p>
                </div>
            `;
        }
    }
}

// 插件基类
export class ControlWavePlugin {
    constructor(config) {
        this.id = config.id;
        this.name = config.name;
        this.version = config.version || '1.0.0';
        this.author = config.author || 'Unknown';
        this.description = config.description || '';
        // 新增:插件是否需要Viser可视化(默认false)
        this.needsViser = config.needsViser || false;
    }

    // 渲染插件界面(子类需要重写)
    async render(container) {
        throw new Error('render() 方法必须被子类实现');
    }

    // 插件初始化(可选)
    async initialize() {
        // 子类可以重写此方法进行初始化
    }

    // 插件销毁(可选)
    async destroy() {
        // 子类可以重写此方法进行清理
    }
}

// 导出全局插件加载器实例
export const pluginLoader = new PluginLoader();