C3031
2026-01-30 065674f3eea53cd84244dbb7ba1a994f86dde1ab
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using System.Text;
using System.Threading.Tasks;
 
namespace LB_VisionProcesses
{
    public class PluginManager
    {
        private static readonly List<Assembly> _loadedAssemblies = new List<Assembly>();
        private static readonly Dictionary<string, AssemblyLoadContext> _loadContexts =
            new Dictionary<string, AssemblyLoadContext>();
        private static readonly object _lock = new object();
 
        /// <summary>
        /// 已加载的工具字典(键:显示名称,值:类型完全限定名)
        /// </summary>
        public static Dictionary<string, string> LoadedProcesses { get; } = new Dictionary<string, string>();
 
        /// <summary>
        /// 按分类组织的工具
        /// </summary>
        public static Dictionary<string, Dictionary<string, string>> CategorizedProcesses { get; } =
            new Dictionary<string, Dictionary<string, string>>();
 
        /// <summary>
        /// 插件信息
        /// </summary>
        public static List<PluginInfo> PluginInfos { get; } = new List<PluginInfo>();
 
        /// <summary>
        /// 插件目录路径
        /// </summary>
        public static string PluginDirectory { get; set; } = "Plugins";
 
        /// <summary>
        /// 插件加载事件
        /// </summary>
        public static event EventHandler<PluginEventArgs> PluginLoaded;
        public static event EventHandler<PluginEventArgs> PluginUnloaded;
 
        static PluginManager()
        {
            // 确保插件目录存在
            if (!Directory.Exists(PluginDirectory))
            {
                Directory.CreateDirectory(PluginDirectory);
            }
        }
 
        /// <summary>
        /// 加载所有插件
        /// </summary>
        public static void LoadAllPlugins()
        {
            lock (_lock)
            {
                ClearLoadedAssemblies();
 
                // 加载主程序集的工具
                ScanAssemblyForProcesses(Assembly.GetExecutingAssembly(), "LB_VisionProcesses");
 
                // 加载插件目录的DLL
                LoadAssembliesFromDirectory(PluginDirectory);
 
                // 加载配置文件指定的插件
                LoadFromConfig();
            }
        }
 
        /// <summary>
        /// 加载指定程序集
        /// </summary>
        public static bool LoadAssembly(string assemblyPath, string pluginName = null)
        {
            lock (_lock)
            {
                try
                {
                    if (!File.Exists(assemblyPath))
                    {
                        Debug.WriteLine($"程序集文件不存在: {assemblyPath}");
                        return false;
                    }
 
                    // 检查是否已加载
                    var fileName = Path.GetFileName(assemblyPath);
                    if (_loadContexts.ContainsKey(fileName))
                    {
                        Debug.WriteLine($"程序集已加载: {fileName}");
                        return false;
                    }
 
                    // 创建隔离的加载上下文
                    var context = new PluginLoadContext(assemblyPath);
                    var assembly = context.LoadFromAssemblyPath(assemblyPath);
 
                    _loadedAssemblies.Add(assembly);
                    _loadContexts[fileName] = context;
 
                    // 扫描工具类
                    var pluginInfo = ScanAssemblyForProcesses(assembly, pluginName ?? Path.GetFileNameWithoutExtension(assemblyPath));
                    PluginInfos.Add(pluginInfo);
 
                    // 触发事件
                    PluginLoaded?.Invoke(null, new PluginEventArgs(pluginInfo));
 
                    return true;
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"加载程序集失败: {assemblyPath}, 错误: {ex.Message}");
                    return false;
                }
            }
        }
 
        /// <summary>
        /// 加载指定目录下所有DLL
        /// </summary>
        public static void LoadAssembliesFromDirectory(string directoryPath)
        {
            if (!Directory.Exists(directoryPath))
            {
                Debug.WriteLine($"插件目录不存在: {directoryPath}");
                return;
            }
 
            // 加载主DLL
            var dllFiles = Directory.GetFiles(directoryPath, "*.dll")
                .Where(f => !f.EndsWith(".resources.dll") &&
                           !f.Contains("\\ref\\") &&
                           !Path.GetFileName(f).StartsWith("System.") &&
                           !Path.GetFileName(f).StartsWith("Microsoft."))
                .ToList();
 
            // 先加载没有依赖的,再加载可能有依赖的
            var orderedFiles = dllFiles.OrderBy(f =>
                File.ReadAllBytes(f).Length).ToList(); // 按文件大小排序,小的先加载
 
            foreach (var dllFile in orderedFiles)
            {
                try
                {
                    LoadAssembly(dllFile);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"加载DLL失败: {dllFile}, 错误: {ex.Message}");
                }
            }
        }
 
        /// <summary>
        /// 卸载指定插件
        /// </summary>
        public static bool UnloadPlugin(string pluginName)
        {
            lock (_lock)
            {
                var pluginInfo = PluginInfos.FirstOrDefault(p => p.Name == pluginName);
                if (pluginInfo == null)
                    return false;
 
                try
                {
                    // 从工具字典中移除
                    foreach (var process in pluginInfo.Processes)
                    {
                        LoadedProcesses.Remove(process.Key);
 
                        // 从分类字典中移除
                        if (CategorizedProcesses.ContainsKey(process.Value.Category))
                        {
                            CategorizedProcesses[process.Value.Category].Remove(process.Key);
                        }
                    }
 
                    // 触发事件
                    PluginUnloaded?.Invoke(null, new PluginEventArgs(pluginInfo));
 
                    // 从列表中移除
                    PluginInfos.Remove(pluginInfo);
 
                    // 尝试卸载程序集(需要.NET Core 3.0+)
                    var fileName = Path.GetFileName(pluginInfo.AssemblyPath);
                    if (_loadContexts.TryGetValue(fileName, out var context))
                    {
                        _loadContexts.Remove(fileName);
                        if (context.IsCollectible)
                        {
                            context.Unload();
                        }
                    }
 
                    return true;
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"卸载插件失败: {pluginName}, 错误: {ex.Message}");
                    return false;
                }
            }
        }
 
        /// <summary>
        /// 扫描程序集中的工具类
        /// </summary>
        private static PluginInfo ScanAssemblyForProcesses(Assembly assembly, string pluginName)
        {
            var pluginInfo = new PluginInfo
            {
                Name = pluginName,
                AssemblyPath = assembly.Location,
                Version = assembly.GetName().Version?.ToString() ?? "1.0.0",
                LoadedTime = DateTime.Now
            };
 
            try
            {
                var processTypes = assembly.GetTypes()
                    .Where(t => t.IsClass && !t.IsAbstract &&
                               typeof(IProcess).IsAssignableFrom(t))
                    .ToList();
                foreach (var type in processTypes)
                {
                    try
                    {
                        if (type.IsDefined(typeof(ProcessAttribute), false) || type.IsDefined(typeof(CategoryAttribute), false))
                        {
                            // 使用特性获取元数据,避免实例化
                            var processAttr = type.GetCustomAttribute<ProcessAttribute>();
                            var categoryAttr = type.GetCustomAttribute<CategoryAttribute>();
 
                            string displayName;
                            string category = "其他";
                            string description = "";
                            int order = 0;
 
                            if (processAttr != null)
                            {
                                displayName = processAttr.DisplayName;
                                category = processAttr.Category;
                                description = processAttr.Description;
                                order = processAttr.Order;
                            }
                            else
                            {
                                // 如果没有特性,使用类型名称
                                displayName = type.Name;
                            }
 
                            if (categoryAttr != null)
                            {
                                category = categoryAttr.Category;
                            }
 
                            // 避免重复名称
                            int suffix = 1;
                            string originalName = displayName;
                            while (LoadedProcesses.ContainsKey(displayName))
                            {
                                displayName = $"{originalName}_{suffix}";
                                suffix++;
                            }
 
                            string fullName = type.AssemblyQualifiedName;
 
                            // 添加到总字典
                            LoadedProcesses[displayName] = fullName;
 
                            // 按分类组织
                            if (!CategorizedProcesses.ContainsKey(category))
                            {
                                CategorizedProcesses[category] = new Dictionary<string, string>();
                            }
                            CategorizedProcesses[category][displayName] = fullName;
 
                            // 添加到插件信息
                            pluginInfo.Processes[displayName] = new ProcessInfo
                            {
                                TypeName = fullName,
                                DisplayName = displayName,
                                Category = category,
                                Description = description,
                                Order = order
                            };
 
                            Debug.WriteLine($"注册工具: {displayName} ({category})");
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine($"注册工具类型 {type.Name} 失败: {ex.Message}");
                    }
                }
            }
            catch (ReflectionTypeLoadException ex)
            {
                Debug.WriteLine($"扫描程序集 {assembly.FullName} 时类型加载失败: {ex.Message}");
                foreach (var loaderEx in ex.LoaderExceptions)
                {
                    Debug.WriteLine($"加载异常: {loaderEx?.Message}");
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"扫描程序集 {assembly.FullName} 失败: {ex.Message}");
            }
 
            return pluginInfo;
        }
 
        /// <summary>
        /// 从配置文件加载插件
        /// </summary>
        private static void LoadFromConfig()
        {
            var configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "plugin.config.json");
            if (File.Exists(configPath))
            {
                try
                {
                    var config = File.ReadAllText(configPath);
                    var pluginConfigs = JsonConvert.DeserializeObject<List<PluginConfig>>(config);
 
                    foreach (var pluginConfig in pluginConfigs)
                    {
                        if (pluginConfig.Enabled)
                        {
                            var pluginPath = Path.Combine(PluginDirectory, pluginConfig.AssemblyName);
                            LoadAssembly(pluginPath, pluginConfig.Name);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"读取插件配置失败: {ex.Message}");
                }
            }
        }
 
        /// <summary>
        /// 清空已加载的程序集
        /// </summary>
        private static void ClearLoadedAssemblies()
        {
            lock (_lock)
            {
                _loadedAssemblies.Clear();
                _loadContexts.Clear();
                LoadedProcesses.Clear();
                CategorizedProcesses.Clear();
                PluginInfos.Clear();
            }
        }
 
        /// <summary>
        /// 重新加载所有插件
        /// </summary>
        public static void ReloadPlugins()
        {
            lock (_lock)
            {
                ClearLoadedAssemblies();
                LoadAllPlugins();
            }
        }
 
        /// <summary>
        /// 获取所有分类
        /// </summary>
        public static List<string> GetCategories()
        {
            return CategorizedProcesses.Keys.OrderBy(k => k).ToList();
        }
 
        /// <summary>
        /// 获取指定分类的工具
        /// </summary>
        public static Dictionary<string, string> GetProcessesByCategory(string category)
        {
            return CategorizedProcesses.ContainsKey(category)
                ? CategorizedProcesses[category]
                : new Dictionary<string, string>();
        }
 
        /// <summary>
        /// 创建工具实例
        /// </summary>
        public static IProcess CreateProcess(string displayName)
        {
            lock (_lock)
            {
                if (!LoadedProcesses.TryGetValue(displayName, out string typeName))
                {
                    throw new KeyNotFoundException($"未找到工具: {displayName}");
                }
 
                try
                {
                    var type = Type.GetType(typeName);
                    if (type == null)
                    {
                        // 尝试从已加载的程序集中查找
                        foreach (var assembly in _loadedAssemblies)
                        {
                            type = assembly.GetType(typeName.Split(',')[0]);
                            if (type != null) break;
                        }
                    }
 
                    if (type == null)
                    {
                        throw new TypeLoadException($"无法加载类型: {typeName}");
                    }
 
                    return Activator.CreateInstance(type) as IProcess;
                }
                catch (Exception ex)
                {
                    throw new ApplicationException($"创建工具实例失败: {displayName}", ex);
                }
            }
        }
    }
}