dsh-eplan 0.0.0-stage → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +219 -3
  3. package/cordis.patch.yml +182 -0
  4. package/docs/INSTALL.md +86 -0
  5. package/docs/LESSONS.md +224 -0
  6. package/docs/interfaces.md +183 -0
  7. package/docs/merged-skills/eplan-setup.md +63 -0
  8. package/docs/merged-skills/eplan-troubleshooting.md +149 -0
  9. package/icon.png +0 -0
  10. package/icon.svg +13 -0
  11. package/knowledge/KNOWLEDGE.md +413 -0
  12. package/knowledge/symbols/BP.png +0 -0
  13. package/knowledge/symbols/CDPST.png +0 -0
  14. package/knowledge/symbols/CO.png +0 -0
  15. package/knowledge/symbols/FA3.png +0 -0
  16. package/knowledge/symbols/TLRO.png +0 -0
  17. package/knowledge/symbols/TLRU.png +0 -0
  18. package/knowledge/symbols/TOUL.png +0 -0
  19. package/knowledge/symbols/TOUR.png +0 -0
  20. package/knowledge/symbols/manifest.json +91 -0
  21. package/locale/en.json +6 -0
  22. package/locale/zh.json +6 -0
  23. package/native/bridge/build.ps1 +73 -0
  24. package/native/bridge/src/Json.cs +383 -0
  25. package/native/bridge/src/Program.cs +1133 -0
  26. package/native/host/build.ps1 +74 -0
  27. package/native/host/src/ActionsTool.cs +225 -0
  28. package/native/host/src/BoxTool.cs +196 -0
  29. package/native/host/src/CheckTool.cs +186 -0
  30. package/native/host/src/Context.cs +169 -0
  31. package/native/host/src/DarkScheme.cs +111 -0
  32. package/native/host/src/DiagnoseTool.cs +115 -0
  33. package/native/host/src/Dispatcher.cs +51 -0
  34. package/native/host/src/DrawTool.cs +316 -0
  35. package/native/host/src/Entry.cs +111 -0
  36. package/native/host/src/ExportTool.cs +213 -0
  37. package/native/host/src/InspectTool.cs +367 -0
  38. package/native/host/src/KnowledgeTool.cs +166 -0
  39. package/native/host/src/LookTool.cs +257 -0
  40. package/native/host/src/OpLog.cs +289 -0
  41. package/native/host/src/PageCreateTool.cs +521 -0
  42. package/native/host/src/PageOpenTool.cs +62 -0
  43. package/native/host/src/PagesTool.cs +95 -0
  44. package/native/host/src/Paths.cs +91 -0
  45. package/native/host/src/PlacementEditTool.cs +234 -0
  46. package/native/host/src/ProbePropsTool.cs +152 -0
  47. package/native/host/src/ProjectCreateTool.cs +176 -0
  48. package/native/host/src/ProjectTool.cs +167 -0
  49. package/native/host/src/PropWriter.cs +70 -0
  50. package/native/host/src/PropsTool.cs +257 -0
  51. package/native/host/src/StatusTool.cs +168 -0
  52. package/native/host/src/SymbolInfoTool.cs +144 -0
  53. package/native/host/src/SymbolInsertTool.cs +261 -0
  54. package/native/host/src/SymbolsTool.cs +94 -0
  55. package/native/host/src/TagLocTool.cs +108 -0
  56. package/native/script/EplanMcpBootstrap.cs +221 -0
  57. package/native/script/build-symbol-gallery.mjs +231 -0
  58. package/native/script/prepare-install.ps1 +57 -0
  59. package/native/script/prune.mjs +132 -0
  60. package/native/script/verify-bootstrap.ps1 +62 -0
  61. package/package.json +53 -4
  62. package/preset/bootstrap.js +498 -0
  63. package/preset/experience-nudge.js +47 -0
  64. package/preset/image-budget.js +175 -0
  65. package/preset/knowledge-tool.js +180 -0
  66. package/preset/mcp-link.js +100 -0
  67. package/preset/prompt-surface.js +76 -0
  68. package/preset/restrict-tools.js +141 -0
  69. package/preset/skill-docs.js +181 -0
  70. package/preset/video-digest.js +294 -0
  71. package/preset/video-tool.js +92 -0
  72. package/server/compact.mjs +623 -0
  73. package/server/edit-args.mjs +67 -0
  74. package/server/fuzzy.mjs +57 -0
  75. package/server/launch-decision.mjs +26 -0
  76. package/server/measure.mjs +320 -0
  77. package/server/pdf.mjs +185 -0
  78. package/server/pdf2png.ps1 +99 -0
  79. package/server/server.mjs +3797 -0
  80. package/server/video.mjs +857 -0
  81. package/setup.mjs +223 -0
  82. package/skills/eplan-annotations/SKILL.md +55 -0
  83. package/skills/eplan-drawing/SKILL.md +206 -0
  84. package/skills/eplan-project/SKILL.md +41 -0
  85. package/skills/eplan-review/SKILL.md +80 -0
  86. package/skills/eplan-symbols/SKILL.md +142 -0
  87. package/test/check-docs.mjs +106 -0
  88. package/test/foreground.ps1 +21 -0
  89. package/test/smoke-all.mjs +229 -0
@@ -0,0 +1,1133 @@
1
+ // 桥接器:Node(MCP 服务) 与 EPLAN 进程之间的那一层。
2
+ //
3
+ // 职责很窄:
4
+ // 1. 从 stdin 按行读 JSON 请求 {id, op, args}
5
+ // 2. 用 .NET Remoting 把请求送进运行中的 EPLAN(ExecuteAction "EplanMcpRun")
6
+ // 3. 把结果按行写回 stdout {id, ok, result} / {id, ok:false, error}
7
+ //
8
+ // 它自己不懂 EPLAN 的数据模型 —— 那边由 EplanMcpHost.dll 在 EPLAN 进程内完成。
9
+ // 这样做的原因见 native/script/EplanMcpBootstrap.cs 的注释:EPLAN 的脚本编译器
10
+ // 引用集里没有 DataModelu.dll,所以真正的逻辑必须是我们自己编译的 DLL。
11
+ using System;
12
+ using System.Collections.Generic;
13
+ using System.Globalization;
14
+ using System.IO;
15
+ using System.Diagnostics;
16
+ using System.Runtime.InteropServices;
17
+ using System.Text;
18
+ using System.Threading;
19
+ using Eplan.EplApi.RemoteClient;
20
+ using Eplan.EplApi.Remoting;
21
+
22
+ namespace EplanMcp.Bridge
23
+ {
24
+ internal static class Program
25
+ {
26
+ private const string ActionName = "EplanMcpRun";
27
+
28
+ /// <summary>一次 IPC 往返最多等多久。EPLAN 的导出类操作会慢一些。</summary>
29
+ private const int DefaultTimeoutMs = 120000;
30
+
31
+ /// <summary>引导脚本和桥接器共用的状态目录。</summary>
32
+ private static readonly string StateDir = @"C:\Users\Public\EPLAN\Data\eplan-mcp";
33
+
34
+ private static readonly object WriteLock = new object();
35
+ private static EplanRemoteClient _client;
36
+
37
+ /// <summary>EPLAN 的安装目录。可通过环境变量 EPLAN_BIN 覆盖(换版本时用)。</summary>
38
+ private static string EplanBin
39
+ {
40
+ get
41
+ {
42
+ string fromEnv = Environment.GetEnvironmentVariable("EPLAN_BIN");
43
+ if (!string.IsNullOrEmpty(fromEnv) && Directory.Exists(fromEnv)) return fromEnv;
44
+ return @"D:\EPLAN\Platform\2.9.4\Bin";
45
+ }
46
+ }
47
+
48
+ private static System.Reflection.Assembly ResolveFromEplan(object sender, ResolveEventArgs e)
49
+ {
50
+ try
51
+ {
52
+ string simpleName = e.Name.Split(',')[0];
53
+ string candidate = Path.Combine(EplanBin, simpleName + ".dll");
54
+ if (File.Exists(candidate)) return System.Reflection.Assembly.LoadFrom(candidate);
55
+
56
+ // 64 位 EPLAN 的程序集名带 u 后缀,个别不带,两边都试。
57
+ if (!simpleName.EndsWith("u", StringComparison.OrdinalIgnoreCase))
58
+ {
59
+ candidate = Path.Combine(EplanBin, simpleName + "u.dll");
60
+ if (File.Exists(candidate)) return System.Reflection.Assembly.LoadFrom(candidate);
61
+ }
62
+ }
63
+ catch { }
64
+ return null;
65
+ }
66
+
67
+ private static int Main(string[] args)
68
+ {
69
+ // 桥接器不在 EPLAN 目录里跑,但 EPLAN 的 Remoting 程序集有一串私有依赖。
70
+ // 运行时从 EPLAN 的 Bin 目录就地解析,避免把几十个 DLL 复制进本仓库。
71
+ AppDomain.CurrentDomain.AssemblyResolve += ResolveFromEplan;
72
+
73
+ // 默认走 stdin/stdout(MCP 服务用);--serve 时行为相同。
74
+ // --once "<json>" 用于人工调试:跑一次就退出。
75
+ string onceJson = null;
76
+ for (int i = 0; i < args.Length; i++)
77
+ {
78
+ if (args[i] == "--once" && i + 1 < args.Length) { onceJson = args[i + 1]; i++; }
79
+ }
80
+
81
+ Console.OutputEncoding = new UTF8Encoding(false);
82
+ Console.InputEncoding = new UTF8Encoding(false);
83
+
84
+ try
85
+ {
86
+ if (onceJson != null)
87
+ {
88
+ JsonValue req = Json.Parse(onceJson);
89
+ JsonValue resp = Handle(req);
90
+ Emit(resp);
91
+ return 0;
92
+ }
93
+
94
+ string line;
95
+ while ((line = Console.In.ReadLine()) != null)
96
+ {
97
+ line = line.Trim();
98
+ if (line.Length == 0) continue;
99
+
100
+ JsonValue req;
101
+ try { req = Json.Parse(line); }
102
+ catch (Exception ex)
103
+ {
104
+ Emit(ErrorResponse(null, "BAD_REQUEST", "请求不是合法 JSON: " + ex.Message, null));
105
+ continue;
106
+ }
107
+
108
+ JsonValue resp = Handle(req);
109
+ Emit(resp);
110
+ }
111
+ }
112
+ catch (Exception ex)
113
+ {
114
+ Emit(ErrorResponse(null, "BRIDGE_FATAL", ex.GetType().Name + ": " + ex.Message, ex.ToString()));
115
+ return 3;
116
+ }
117
+ finally
118
+ {
119
+ Disconnect();
120
+ }
121
+
122
+ return 0;
123
+ }
124
+
125
+ private static void Emit(JsonValue response)
126
+ {
127
+ string text = Json.Write(response);
128
+ lock (WriteLock)
129
+ {
130
+ Console.Out.Write(text);
131
+ Console.Out.Write("\n");
132
+ Console.Out.Flush();
133
+ }
134
+ }
135
+
136
+ private static JsonValue ErrorResponse(JsonValue req, string code, string message, string detail)
137
+ {
138
+ JsonValue resp = JsonValue.NewObject();
139
+ if (req == null) resp.Set("id", (string)null);
140
+ else resp.Set("id", req["id"]);
141
+ resp.Set("ok", false);
142
+
143
+ JsonValue err = JsonValue.NewObject();
144
+ err.Set("code", code);
145
+ err.Set("message", message);
146
+ if (detail != null) err.Set("detail", detail);
147
+ resp.Set("error", err);
148
+ return resp;
149
+ }
150
+
151
+ private static JsonValue Handle(JsonValue req)
152
+ {
153
+ string op = req["op"].AsString("");
154
+ JsonValue args = req["args"];
155
+ if (args == null || !args.IsObject) args = JsonValue.NewObject();
156
+
157
+ try
158
+ {
159
+ JsonValue result = Dispatch(op, args);
160
+ JsonValue resp = JsonValue.NewObject();
161
+ resp.Set("id", req["id"]);
162
+ resp.Set("ok", true);
163
+ resp.Set("result", result);
164
+ return resp;
165
+ }
166
+ catch (EplanBridgeException ex)
167
+ {
168
+ return ErrorResponse(req, ex.Code, ex.Message, ex.Detail);
169
+ }
170
+ catch (Exception ex)
171
+ {
172
+ return ErrorResponse(req, "EPLAN_ERROR",
173
+ ex.GetType().Name + ": " + ex.Message,
174
+ ex.InnerException == null ? null : ex.InnerException.Message);
175
+ }
176
+ }
177
+
178
+ private static JsonValue Dispatch(string op, JsonValue args)
179
+ {
180
+ switch (op)
181
+ {
182
+ case "ping":
183
+ return PingResult();
184
+ case "launch":
185
+ return LaunchEplan(args);
186
+ case "install":
187
+ return InstallHost(args);
188
+ case "dialogs":
189
+ return Dialogs(args);
190
+ default:
191
+ return ForwardToEplan(op, args);
192
+ }
193
+ }
194
+
195
+ /// <summary>
196
+ /// 对话框的自检与处置:默认只报,close=true 才动手。
197
+ /// 排查「EPLAN 为什么不动了」时可以直接 --once 调它。
198
+ /// </summary>
199
+ private static JsonValue Dialogs(JsonValue args)
200
+ {
201
+ bool close = args["close"].AsBool(false);
202
+ JsonValue result = JsonValue.NewObject();
203
+ string before = DescribeBlockingDialog();
204
+ result.Set("blocking", before);
205
+ if (close)
206
+ {
207
+ string acted = SettleKnownDialogs();
208
+ result.Set("settled", acted);
209
+ if (acted != null) AppendDialogLog(acted);
210
+ System.Threading.Thread.Sleep(200);
211
+ result.Set("blockingAfter", DescribeBlockingDialog());
212
+ }
213
+ return result;
214
+ }
215
+
216
+ /// <summary>处置记录落盘:事后能看出「这个框被我关过几次」,不用靠猜。</summary>
217
+ private static void AppendDialogLog(string line)
218
+ {
219
+ try
220
+ {
221
+ Directory.CreateDirectory(StateDir);
222
+ File.AppendAllText(
223
+ Path.Combine(StateDir, "dialog-actions.log"),
224
+ DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture) + " " + line + Environment.NewLine,
225
+ new UTF8Encoding(false));
226
+ }
227
+ catch { }
228
+ }
229
+
230
+ // ---------------------------------------------------------------
231
+ // 安装宿主:用 RegisterScript 动作把引导脚本注册进 EPLAN。
232
+ //
233
+ // 关键区别(用 EPLAN 日志试出来的):
234
+ // ExecuteScript 只执行 [Start],**不注册** [DeclareAction]
235
+ // RegisterScript 才真正注册 [DeclareAction]
236
+ // 之前反复失败就是因为用了 ExecuteScript。
237
+ // ---------------------------------------------------------------
238
+
239
+ private static JsonValue InstallHost(JsonValue args)
240
+ {
241
+ string scriptPath = args["script"].AsString(null);
242
+ if (string.IsNullOrEmpty(scriptPath))
243
+ throw new EplanBridgeException("BAD_ARGUMENT", "缺少 script 参数(引导脚本的绝对路径)。", null);
244
+ if (!File.Exists(scriptPath))
245
+ throw new EplanBridgeException("SCRIPT_MISSING", "找不到引导脚本: " + scriptPath, null);
246
+
247
+ EplanRemoteClient client = Client;
248
+
249
+ JsonValue result = JsonValue.NewObject();
250
+ result.Set("script", scriptPath);
251
+
252
+ // 装之前先探一次:宿主已经在了就直接返回,不重复注册。
253
+ string beforeError = ProbeHost(client);
254
+ result.Set("hostBefore", beforeError == null ? "ready" : beforeError);
255
+ if (beforeError == null)
256
+ {
257
+ result.Set("installed", true);
258
+ result.Set("alreadyInstalled", true);
259
+ return result;
260
+ }
261
+
262
+ CallingContext context = new CallingContext();
263
+ context.Set("ScriptFile", scriptPath);
264
+
265
+ bool registered = client.ExecuteAction("RegisterScript", ref context);
266
+ string message = string.IsNullOrEmpty(context.Message) ? null : context.Message;
267
+ result.Set("registerScriptReturned", registered);
268
+ result.Set("registerScriptSucceed", context.Succeed);
269
+ if (message != null) result.Set("message", message);
270
+
271
+ // 动作注册发生在 EPLAN 主线程上,轮询等它出现。
272
+ string afterError = beforeError;
273
+ for (int attempt = 0; attempt < 24; attempt++)
274
+ {
275
+ System.Threading.Thread.Sleep(250);
276
+ afterError = ProbeHost(client);
277
+ if (afterError == null) break;
278
+ }
279
+
280
+ if (afterError != null)
281
+ {
282
+ throw new EplanBridgeException("INSTALL_FAILED",
283
+ "RegisterScript 执行了,但 EplanMcpRun 仍不可用。" +
284
+ (message == null ? "" : " EPLAN 返回:" + message) +
285
+ @" 请查看 C:\Users\Public\EPLAN\Data\eplan-mcp\bootstrap.log 和 EPLAN 日志(EplLog.eldb)。",
286
+ Json.Write(result));
287
+ }
288
+
289
+ result.Set("installed", true);
290
+ result.Set("alreadyInstalled", false);
291
+ return result;
292
+ }
293
+
294
+ /// <summary>
295
+ /// 探一下宿主是否可用:发一个只读的 diagnose 请求走完整 IPC 链路。
296
+ /// 返回 null 表示可用;否则返回错误描述。
297
+ /// </summary>
298
+ private static string ProbeHost(EplanRemoteClient client)
299
+ {
300
+ try
301
+ {
302
+ JsonValue payload = JsonValue.NewObject();
303
+ payload.Set("op", "diagnose");
304
+ payload.Set("args", JsonValue.NewObject());
305
+ JsonValue reply = SendThroughIpc(client, Json.Write(payload), 8000);
306
+ if (!reply["ok"].AsBool(false))
307
+ {
308
+ JsonValue err = reply["error"];
309
+ return err == null ? "HOST_ERROR" : err["code"].AsString("HOST_ERROR");
310
+ }
311
+ return null;
312
+ }
313
+ catch (Exception ex)
314
+ {
315
+ return ex.Message;
316
+ }
317
+ }
318
+
319
+
320
+ /// <summary>
321
+ /// 探一下宿主是否可用:调用只读的 diagnose。
322
+ /// 返回 null 表示可用;否则返回错误码/文本,供上层判断。
323
+ /// 用 diagnose 而不是别的,是因为它不写任何东西。
324
+ /// </summary>
325
+ private static string ProbeHostLegacy(EplanRemoteClient client)
326
+ {
327
+ try
328
+ {
329
+ JsonValue payload = JsonValue.NewObject();
330
+ payload.Set("op", "diagnose");
331
+ payload.Set("args", JsonValue.NewObject());
332
+
333
+ CallingContext context = new CallingContext();
334
+ context.Set("payload", Json.Write(payload));
335
+
336
+ bool ok = client.ExecuteAction(ActionName, ref context);
337
+ if (!ok)
338
+ {
339
+ string message = context.Message;
340
+ if (string.IsNullOrEmpty(message)) return "ACTION_MISSING";
341
+ if (message.IndexOf("EplanMcpRun", StringComparison.OrdinalIgnoreCase) >= 0) return "ACTION_MISSING";
342
+ return message;
343
+ }
344
+
345
+ object reply = null;
346
+ if (!context.Get("reply", out reply) || reply == null) return "NO_REPLY";
347
+ string text = reply as string;
348
+ if (text == null) return "BAD_REPLY_TYPE";
349
+ JsonValue parsed = Json.Parse(text);
350
+ if (!parsed["ok"].AsBool(false))
351
+ {
352
+ JsonValue err = parsed["error"];
353
+ return err == null ? "HOST_ERROR" : err["code"].AsString("HOST_ERROR");
354
+ }
355
+ return null;
356
+ }
357
+ catch (Exception ex)
358
+ {
359
+ return "PROBE_FAILED: " + ex.Message;
360
+ }
361
+ }
362
+
363
+
364
+ // ---------------------------------------------------------------
365
+ // 与 EPLAN 的连接
366
+ // ---------------------------------------------------------------
367
+
368
+ private static EplanRemoteClient Client
369
+ {
370
+ get
371
+ {
372
+ if (_client != null && _client.Ping()) return _client;
373
+ Disconnect();
374
+ EplanRemoteClient client = new EplanRemoteClient();
375
+ // 必须开同步模式:默认异步时 ExecuteAction 对任何动作名都返回 true,
376
+ // 拿不到真实成败,也没法把结果带回来。
377
+ client.SynchronousMode = true;
378
+
379
+ List<EplanServerData> servers = new List<EplanServerData>();
380
+ client.GetActiveEplanServersOnLocalMachine(out servers);
381
+ if (servers == null || servers.Count == 0)
382
+ {
383
+ throw new EplanBridgeException("EPLAN_NOT_RUNNING",
384
+ "没有检测到正在运行的 EPLAN。请先打开 EPLAN Electric P8 并载入项目后重试。", null);
385
+ }
386
+
387
+ // 多实例时选「真的开着项目」的那个(见 InstanceScore),同分再按 P8 优先。
388
+ EplanServerData chosen = servers[0];
389
+ int bestScore = int.MinValue;
390
+ foreach (EplanServerData s in servers)
391
+ {
392
+ int score = InstanceScore(s);
393
+ if (score > bestScore)
394
+ {
395
+ bestScore = score;
396
+ chosen = s;
397
+ }
398
+ }
399
+
400
+ client.Connect("localhost", chosen.ServerPort.ToString(CultureInfo.InvariantCulture));
401
+ if (!client.Ping())
402
+ {
403
+ throw new EplanBridgeException("EPLAN_CONNECT_FAILED",
404
+ "连接 EPLAN 失败(端口 " + chosen.ServerPort + ")。", null);
405
+ }
406
+ _client = client;
407
+ _clientProcessId = chosen.EplanProcessID;
408
+ _clientVersion = chosen.EplanVersion;
409
+ return _client;
410
+ }
411
+ }
412
+
413
+ private static int _clientProcessId;
414
+ private static string _clientVersion;
415
+
416
+ private static void Disconnect()
417
+ {
418
+ if (_client == null) return;
419
+ try { _client.Disconnect(); } catch { }
420
+ _client = null;
421
+ }
422
+
423
+ private static JsonValue PingResult()
424
+ {
425
+ List<EplanServerData> servers = new List<EplanServerData>();
426
+ EplanRemoteClient probe = new EplanRemoteClient();
427
+ probe.SynchronousMode = true;
428
+ probe.GetActiveEplanServersOnLocalMachine(out servers);
429
+
430
+ JsonValue result = JsonValue.NewObject();
431
+ result.Set("bridgeVersion", "0.1.0");
432
+ JsonValue list = JsonValue.NewArray();
433
+ if (servers != null)
434
+ {
435
+ foreach (EplanServerData s in servers)
436
+ {
437
+ JsonValue item = JsonValue.NewObject();
438
+ item.Set("serverName", s.ServerName);
439
+ item.Set("port", s.ServerPort);
440
+ item.Set("version", s.EplanVersion);
441
+ item.Set("variant", s.EplanVariant);
442
+ item.Set("processId", s.EplanProcessID);
443
+ item.Set("is64Bit", s.Is64Bit);
444
+ list.Add(item);
445
+ }
446
+ }
447
+ result.Set("servers", list);
448
+ result.Set("count", list.Count);
449
+ return result;
450
+ }
451
+
452
+ private static JsonValue LaunchEplan(JsonValue args)
453
+ {
454
+ string path = args["path"].AsString(@"D:\EPLAN\Platform\2.9.4\Bin\Eplan.exe");
455
+ string variant = args["variant"].AsString("Electric P8");
456
+ string project = args["project"].AsString(null);
457
+
458
+ // variant 和项目都通过命令行参数传。
459
+ string arguments = "/Variant:\"" + variant + "\"";
460
+ if (!string.IsNullOrEmpty(project)) arguments += " \"" + project + "\"";
461
+
462
+ // 关键:必须用 UseShellExecute 走壳启动,让 EPLAN 成为**独立**进程。
463
+ //
464
+ // 如果直接 Process.Start 用 CreateProcess,EPLAN 就是这个桥接器的子进程;
465
+ // 而 DSH 可能在 Job Object 里运行(kill-on-close),DSH 一退,
466
+ // 整个作业对象连带进程树一起被杀 —— 用户的 EPLAN 就这么没了。
467
+ // 走壳之后 EPLAN 挂在 explorer 下,和 DSH 没有任何父子关系。
468
+ try
469
+ {
470
+ ProcessStartInfo info = new ProcessStartInfo();
471
+ info.FileName = path;
472
+ info.Arguments = arguments;
473
+ info.UseShellExecute = true;
474
+ Process.Start(info);
475
+ }
476
+ catch (Exception ex)
477
+ {
478
+ throw new EplanBridgeException("EPLAN_LAUNCH_FAILED",
479
+ "启动 EPLAN 失败: " + ex.Message, path + " " + arguments);
480
+ }
481
+
482
+ // 启动是异步的,轮询等它把 Remoting 端口挂起来。
483
+ EplanServerData started = null;
484
+ int waited = 0;
485
+ while (waited < 60000)
486
+ {
487
+ System.Threading.Thread.Sleep(1000);
488
+ waited += 1000;
489
+ try
490
+ {
491
+ List<EplanServerData> servers = new List<EplanServerData>();
492
+ EplanRemoteClient probe = new EplanRemoteClient();
493
+ probe.GetActiveEplanServersOnLocalMachine(out servers);
494
+ if (servers != null && servers.Count > 0) { started = servers[servers.Count - 1]; break; }
495
+ }
496
+ catch { }
497
+ }
498
+
499
+ JsonValue result = JsonValue.NewObject();
500
+ result.Set("started", started != null);
501
+ result.Set("detached", true);
502
+ if (started != null)
503
+ {
504
+ result.Set("port", started.ServerPort);
505
+ result.Set("processId", started.EplanProcessID);
506
+ result.Set("version", started.EplanVersion);
507
+ }
508
+ else
509
+ {
510
+ result.Set("note", "EPLAN 已启动但没有在 60 秒内挂上 Remoting 端口,可能还在加载,或者弹出了启动对话框。");
511
+ }
512
+ return result;
513
+ }
514
+
515
+
516
+ // ---------------------------------------------------------------
517
+ // 把请求转发进 EPLAN 进程
518
+ //
519
+ // 走文件交换而不是 CallingContext:DeclareAction 必须是无参 void,
520
+ // 带 ActionCallingContext 参数时 ExecuteAction 返回 false 且
521
+ // context.GetContextParameter() 返回 null,参数根本传不进去。
522
+ // 详见 native/script/EplanMcpBootstrap.cs 顶部的注释。
523
+ // ---------------------------------------------------------------
524
+
525
+ private static JsonValue ForwardToEplan(string op, JsonValue args)
526
+ {
527
+ EplanRemoteClient client = Client;
528
+
529
+ JsonValue payload = JsonValue.NewObject();
530
+ payload.Set("op", op);
531
+ payload.Set("args", args);
532
+
533
+ // 命令里显式指定的超时覆盖默认值。
534
+ int timeoutMs = args["timeoutMs"].AsInt(DefaultTimeoutMs);
535
+
536
+ JsonValue reply = SendThroughIpc(client, Json.Write(payload), timeoutMs);
537
+
538
+ bool replyOk = reply["ok"].AsBool(false);
539
+ if (!replyOk)
540
+ {
541
+ JsonValue error = reply["error"];
542
+ string code = error == null ? "EPLAN_ERROR" : error["code"].AsString("EPLAN_ERROR");
543
+ string message = error == null ? "EPLAN 宿主报告失败" : error["message"].AsString("EPLAN 宿主报告失败");
544
+ string detail = error == null ? null : error["detail"].AsString(null);
545
+ throw new EplanBridgeException(code, message, detail);
546
+ }
547
+
548
+ JsonValue result = reply["result"];
549
+ if (result == null) result = JsonValue.NewObject();
550
+
551
+ // page_open 的成败不能只看宿主有没有把动作执行掉 —— 得看界面到底切没切。
552
+ // 等待放在这一层做:宿主跑在 EPLAN 主线程上,它 Sleep 会把界面锁死,
553
+ // 标题永远刷不出来。桥接器是独立进程,睡多久都不影响 EPLAN。
554
+ //
555
+ // 窗口状态一律不动(2026-11-27 用户要求):
556
+ // 切页只切「软件内的当前页」。不最大化、不置顶、不抢前台、不改尺寸位置。
557
+ // 以前的 Activate/SetWindowPos 那一套整个去掉了 —— 它会把用户正在看的
558
+ // 别的程序顶掉,并且把 EPLAN 拉到最大化,盖住整个屏幕。
559
+ // 渲染的正确比例不靠窗口,靠 EPLAN 自己的 GraphicPageEx:那条路径与窗口
560
+ // 是否可见、是否最大化完全无关(见 LookTool.cs 顶部注释)。
561
+ if (op == "page_open")
562
+ {
563
+ string pageName = result["page"].AsString(null);
564
+ if (!string.IsNullOrEmpty(pageName))
565
+ {
566
+ bool shown = WaitWindowTitle(pageName, 4000);
567
+ result.Set("visibleInTitle", shown);
568
+ // 只在 EPLAN 被最小化时还原,其它窗口状态一概不碰。
569
+ RestoreIfMinimized(FindEplanWindow());
570
+ result.Set("windowStateChanged", false);
571
+ }
572
+ }
573
+
574
+ return result;
575
+ }
576
+
577
+ [DllImport("user32.dll")]
578
+ private static extern bool IsIconic(IntPtr hWnd);
579
+
580
+ [DllImport("user32.dll")]
581
+ private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
582
+
583
+ private const int SW_RESTORE = 9;
584
+
585
+ /// <summary>
586
+ /// 窗口只在**最小化**时才还原 —— 因为最小化的窗口里看不到图纸,还原不等于抢焦点。
587
+ ///
588
+ /// 除此之外一律不动窗口:不最大化(SW_MAXIMIZE 已经从这套代码里删掉了)、
589
+ /// 不置顶(HWND_TOPMOST)、不改尺寸位置(SetWindowPos)、不抢前台
590
+ /// (SetForegroundWindow / AttachThreadInput / BringWindowToTop 全部移除)。
591
+ ///
592
+ /// 为什么这么严:用户明确要求「不要最大化,而是在软件内切换到最新在画的图纸页」,
593
+ /// 并且只在子代理派遣时才最后切一次。原来那一整套前台劫持会把用户正在用的
594
+ /// 其它程序顶掉,而渲染的正确比例本来就不依赖窗口大小 —— LookTool 走的是
595
+ /// EPLAN 自己的导出引擎,与窗口是否可见、是否最大化无关。
596
+ /// </summary>
597
+ private static void RestoreIfMinimized(IntPtr handle)
598
+ {
599
+ try
600
+ {
601
+ if (handle != IntPtr.Zero && IsIconic(handle)) ShowWindow(handle, SW_RESTORE);
602
+ }
603
+ catch { }
604
+ }
605
+
606
+ /// <summary>轮询 EPLAN 主窗口标题,直到里面出现目标页名或超时。</summary>
607
+ private static bool WaitWindowTitle(string needle, int timeoutMs)
608
+ {
609
+ DateTime deadline = DateTime.UtcNow.AddMilliseconds(timeoutMs);
610
+ while (DateTime.UtcNow < deadline)
611
+ {
612
+ string title = WindowTitleOf(FindEplanWindow());
613
+ if (title.IndexOf(needle, StringComparison.OrdinalIgnoreCase) >= 0) return true;
614
+ Thread.Sleep(120);
615
+ }
616
+ return false;
617
+ }
618
+
619
+ private static IntPtr FindEplanWindow()
620
+ {
621
+ foreach (Process process in Process.GetProcesses())
622
+ {
623
+ try
624
+ {
625
+ if (process.MainWindowHandle == IntPtr.Zero) continue;
626
+ string title = process.MainWindowTitle;
627
+ if (title != null && title.StartsWith("EPLAN Electric", StringComparison.OrdinalIgnoreCase))
628
+ return process.MainWindowHandle;
629
+ }
630
+ catch { }
631
+ finally { process.Dispose(); }
632
+ }
633
+ return IntPtr.Zero;
634
+ }
635
+
636
+ private static string WindowTitleOf(IntPtr handle)
637
+ {
638
+ if (handle == IntPtr.Zero) return string.Empty;
639
+ foreach (Process process in Process.GetProcesses())
640
+ {
641
+ try
642
+ {
643
+ if (process.MainWindowHandle == handle) return process.MainWindowTitle ?? string.Empty;
644
+ }
645
+ catch { }
646
+ finally { process.Dispose(); }
647
+ }
648
+ return string.Empty;
649
+ }
650
+
651
+ /// <summary>建一个命名互斥量;名字没权限或不可用时返回 null,让调用方降级。</summary>
652
+ private static Mutex CreateGate(string name)
653
+ {
654
+ try { return new Mutex(false, name); }
655
+ catch { return null; }
656
+ }
657
+
658
+ /// <summary>
659
+ /// 文件 IPC 的独占闸门。
660
+ ///
661
+ /// request.json 是固定路径:同一个桥接进程内部本来就是串行的(主循环一行一行读),
662
+ /// 但**两个**桥接进程(两个 DSH 会话、或者 MCP 与调试脚本同时用)会互相覆盖请求文件,
663
+ /// 输的那一方要白等满一个 timeout 才报超时,而且很可能什么都没执行。
664
+ /// 用命名互斥把跨进程的情形也挡住。
665
+ /// </summary>
666
+ private static JsonValue SendThroughIpc(EplanRemoteClient client, string payload, int timeoutMs)
667
+ {
668
+ // Global\ 需要 SeCreateGlobalPrivilege(默认只给管理员和系统账户)。
669
+ // 普通用户可能拿不到,那就退到会话级的 Local\;再不行就退化成不加锁 ——
670
+ // 跨进程竞态只是少见情形,不值得因为它让整个桥接器不能用。
671
+ Mutex gate = CreateGate(@"Global\EplanMcpIpc") ?? CreateGate(@"Local\EplanMcpIpc");
672
+ if (gate == null) return SendThroughIpcCore(client, payload, timeoutMs);
673
+
674
+ bool taken = false;
675
+ try
676
+ {
677
+ try { taken = gate.WaitOne(IpcGateWaitMs, false); }
678
+ catch (AbandonedMutexException)
679
+ {
680
+ // 上一个持有者崩了,互斥量被系统强制释放 —— 这时候通道归我们。
681
+ taken = true;
682
+ }
683
+
684
+ if (!taken)
685
+ {
686
+ throw new EplanBridgeException("IPC_BUSY",
687
+ "另一个调用已经占着 EPLAN 的 IPC 通道超过 " + (IpcGateWaitMs / 1000) + " 秒。",
688
+ "通常是另一个会话正在跑长任务(导出/渲染),或者上一次调用卡在模态框上没退出。等它结束再试。");
689
+ }
690
+
691
+ return SendThroughIpcCore(client, payload, timeoutMs);
692
+ }
693
+ finally
694
+ {
695
+ if (taken)
696
+ {
697
+ try { gate.ReleaseMutex(); } catch { }
698
+ }
699
+ try { gate.Dispose(); } catch { }
700
+ }
701
+ }
702
+
703
+ // 跨进程等待上限。比正常的 120 秒调用超时留一点余量,让排队的调用有机会跑完。
704
+ private const int IpcGateWaitMs = 180000;
705
+
706
+ /// <summary>
707
+ /// 文件 IPC 一次往返:写 request.json → ExecuteAction("EplanMcpRun") → 轮询 reply-&lt;id&gt;.json。
708
+ /// </summary>
709
+ private static JsonValue SendThroughIpcCore(EplanRemoteClient client, string payload, int timeoutMs)
710
+ {
711
+ string ipcDir = Path.Combine(StateDir, "ipc");
712
+ Directory.CreateDirectory(ipcDir);
713
+
714
+ // 发请求之前先看一眼有没有模态框挡着。
715
+ //
716
+ // 只在超时之后才检查是不够的:模态框占住 EPLAN 主线程时 ExecuteAction 永不返回,
717
+ // 每次调用都要白等满一个 timeout(默认 120 秒)才拿到错误 —— 模型会把这段时间当成
718
+ // 「工具坏了」反复重试,用户则在旁边干等。提前检查能把 120 秒变成 100 毫秒,
719
+ // 而且报的是「有个框挡住了,请关掉」这种能直接照做的信息。
720
+ //
721
+ // 先试着自己答掉已知的框(检查相容性 / 系统消息),它们有标准答案,
722
+ // 不该让用户或模型为它们停下来;答完还挡着才报错。
723
+ string settled = SettleKnownDialogs();
724
+ if (settled != null)
725
+ {
726
+ AppendDialogLog(settled);
727
+ System.Threading.Thread.Sleep(200);
728
+ }
729
+
730
+ string blockedBeforeSend = DescribeBlockingDialog();
731
+ if (blockedBeforeSend != null)
732
+ {
733
+ throw new EplanBridgeException("EPLAN_BLOCKED_BY_DIALOG",
734
+ "EPLAN 被一个对话框挡住了:" + blockedBeforeSend + "。把它关掉再重试;这次请求没有发出去,什么都没改。",
735
+ "模态对话框会占住 EPLAN 主线程,所有 API 调用都会一起卡住。");
736
+ }
737
+
738
+ string requestId = Guid.NewGuid().ToString("N");
739
+ string replyPath = Path.Combine(ipcDir, "reply-" + requestId + ".json");
740
+ string requestPath = Path.Combine(ipcDir, "request.json");
741
+
742
+ // 请求文件得带上 id,脚本靠它命名响应文件。
743
+ JsonValue envelope = Json.Parse(payload);
744
+ envelope.Set("id", requestId);
745
+ string requestText = Json.Write(envelope);
746
+
747
+ // 先写临时文件再改名,避免脚本读到半个文件。
748
+ string tempRequest = requestPath + ".tmp";
749
+ File.WriteAllText(tempRequest, requestText, new UTF8Encoding(false));
750
+ if (File.Exists(requestPath)) File.Delete(requestPath);
751
+ File.Move(tempRequest, requestPath);
752
+
753
+ CallingContext context = new CallingContext();
754
+ bool triggered = client.ExecuteAction(ActionName, ref context);
755
+ string actionMessage = context.Message;
756
+
757
+ if (!triggered)
758
+ {
759
+ try { File.Delete(requestPath); } catch { }
760
+
761
+ // 动作不存在时 EPLAN 返回 S085021「无法找到操作…不包含在功能范围内」。
762
+ if (!string.IsNullOrEmpty(actionMessage) &&
763
+ (actionMessage.IndexOf("EplanMcpRun", StringComparison.OrdinalIgnoreCase) >= 0 ||
764
+ actionMessage.IndexOf("S085021", StringComparison.OrdinalIgnoreCase) >= 0 ||
765
+ actionMessage.IndexOf("功能范围", StringComparison.OrdinalIgnoreCase) >= 0))
766
+ {
767
+ throw new EplanBridgeException("HOST_NOT_INSTALLED",
768
+ "EPLAN 里还没有装宿主(找不到动作 EplanMcpRun)。" +
769
+ "请先执行 install 操作注册引导脚本,详见 README。", actionMessage);
770
+ }
771
+ throw new EplanBridgeException("EPLAN_ACTION_FAILED",
772
+ string.IsNullOrEmpty(actionMessage) ? "EPLAN 执行 EplanMcpRun 失败,没有返回错误文本。" : actionMessage, null);
773
+ }
774
+
775
+ // 脚本在主线程上同步处理,正常情况下几百毫秒内就有响应文件。
776
+ DateTime deadline = DateTime.UtcNow.AddMilliseconds(timeoutMs);
777
+ while (DateTime.UtcNow < deadline)
778
+ {
779
+ if (File.Exists(replyPath))
780
+ {
781
+ string text = null;
782
+ for (int attempt = 0; attempt < 10; attempt++)
783
+ {
784
+ try
785
+ {
786
+ text = File.ReadAllText(replyPath, Encoding.UTF8);
787
+ break;
788
+ }
789
+ catch (IOException)
790
+ {
791
+ // 文件可能还占着,等一下再读。
792
+ System.Threading.Thread.Sleep(30);
793
+ }
794
+ }
795
+ try { File.Delete(replyPath); } catch { }
796
+
797
+ if (text == null)
798
+ {
799
+ throw new EplanBridgeException("HOST_BAD_REPLY", "读不到 EPLAN 的响应文件: " + replyPath, null);
800
+ }
801
+
802
+ try { return Json.Parse(text); }
803
+ catch (Exception ex)
804
+ {
805
+ throw new EplanBridgeException("HOST_BAD_REPLY",
806
+ "EPLAN 返回的 JSON 无法解析: " + ex.Message,
807
+ text.Length > 2000 ? text.Substring(0, 2000) : text);
808
+ }
809
+ }
810
+ System.Threading.Thread.Sleep(25);
811
+ }
812
+
813
+ try { File.Delete(requestPath); } catch { }
814
+
815
+ // 超时的第一嫌疑不是脚本,是 EPLAN 被模态对话框挡住了:
816
+ // 模态框占住 EPLAN 主线程,ExecuteAction 就永远不返回,任何 API 调用一起挂死。
817
+ // 与其让用户对着超时瞎猜,不如直接把那个框念出来。
818
+ string dialog = DescribeBlockingDialog();
819
+ if (dialog != null)
820
+ {
821
+ throw new EplanBridgeException("EPLAN_BLOCKED_BY_DIALOG",
822
+ "等了 " + timeoutMs + " 毫秒没有响应,EPLAN 被一个对话框挡住了:" + dialog +
823
+ "。把它关掉再重试即可;之前那次操作很可能没有执行。",
824
+ "模态对话框会占住 EPLAN 主线程,所有 API 调用都会一起卡住。");
825
+ }
826
+
827
+ // 没有对话框,那可能是脚本压根没跑起来。翻一下日志给个更准的提示。
828
+ string hint = BootstrapHint();
829
+ throw new EplanBridgeException("EPLAN_TIMEOUT",
830
+ "等了 " + timeoutMs + " 毫秒,EPLAN 没有返回结果。" + hint,
831
+ "如果重复出现,请检查 C:\\Users\\Public\\EPLAN\\Data\\eplan-mcp\\bootstrap.log 和 EPLAN 日志(EplLog.eldb)。");
832
+ }
833
+
834
+
835
+ // ---------------------------------------------------------------
836
+ // 超时排障:EPLAN 是不是被模态框挡住了。
837
+ //
838
+ // 模态对话框是 EPLAN 最常见的「假死」来源:一点下去,主线程被占住,
839
+ // ExecuteAction 永远不返回,表现就是所有工具调用一起超时。
840
+ // 这里枚举 EPLAN 进程的可见顶层窗口,把不是主窗口的 #32770 报出来。
841
+ // ---------------------------------------------------------------
842
+
843
+ private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
844
+
845
+ [DllImport("user32.dll")]
846
+ private static extern bool EnumWindows(EnumWindowsProc callback, IntPtr lParam);
847
+
848
+ [DllImport("user32.dll")]
849
+ private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId);
850
+
851
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)]
852
+ private static extern int GetWindowTextW(IntPtr hWnd, StringBuilder text, int count);
853
+
854
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)]
855
+ private static extern int GetClassNameW(IntPtr hWnd, StringBuilder text, int count);
856
+
857
+ [DllImport("user32.dll")]
858
+ private static extern bool IsWindowVisible(IntPtr hWnd);
859
+
860
+ /// <summary>列出 EPLAN 进程里挡在前面的对话框;没有就返回 null。</summary>
861
+ private static string DescribeBlockingDialog()
862
+ {
863
+ try
864
+ {
865
+ List<uint> eplanPids = EplanPids();
866
+ if (eplanPids.Count == 0) return null;
867
+
868
+ List<string> found = new List<string>();
869
+ EnumWindows(delegate(IntPtr handle, IntPtr state)
870
+ {
871
+ uint pid;
872
+ GetWindowThreadProcessId(handle, out pid);
873
+ if (!eplanPids.Contains(pid)) return true;
874
+ if (!IsWindowVisible(handle)) return true;
875
+
876
+ StringBuilder cls = new StringBuilder(256);
877
+ GetClassNameW(handle, cls, 256);
878
+ if (cls.ToString() != "#32770") return true;
879
+
880
+ StringBuilder text = new StringBuilder(512);
881
+ GetWindowTextW(handle, text, 512);
882
+ string title = text.ToString().Trim();
883
+ found.Add(title.Length == 0 ? "(无标题对话框)" : "「" + title + "」");
884
+ return true;
885
+ }, IntPtr.Zero);
886
+
887
+ if (found.Count == 0) return null;
888
+ return string.Join("、", found.ToArray());
889
+ }
890
+ catch
891
+ {
892
+ return null;
893
+ }
894
+ }
895
+
896
+ // ---------------------------------------------------------------
897
+ // 已知对话框自动处置
898
+ //
899
+ // EPLAN 每次非正常关闭后重开项目,都会先弹「检查相容性」;现场经常就卡在
900
+ // 这个框上,看起来像工具坏了。这里把「有标准答案的框」直接答掉:
901
+ // 检查相容性 → 点「以后」(先打开,下次再查;只是恢复提示,不动数据)
902
+ // 系统消息 → 关掉(内容是 S046001 一类可以忽略的告警)
903
+ // 不认识的框一律不碰,交给 DescribeBlockingDialog 报出来让人处理。
904
+ // ---------------------------------------------------------------
905
+
906
+ private static readonly string[][] KnownDialogs = new string[][]
907
+ {
908
+ new string[] { "检查相容性", "以后" },
909
+ new string[] { "检查兼容性", "以后" },
910
+ new string[] { "系统消息", null },
911
+ };
912
+
913
+ private delegate bool EnumChildProc(IntPtr hWnd, IntPtr lParam);
914
+
915
+ [DllImport("user32.dll")]
916
+ private static extern bool EnumChildWindows(IntPtr parent, EnumChildProc callback, IntPtr lParam);
917
+
918
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)]
919
+ private static extern IntPtr SendMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
920
+
921
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)]
922
+ private static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
923
+
924
+ private const uint BM_CLICK = 0x00F5;
925
+ private const uint WM_CLOSE = 0x0010;
926
+
927
+ private static uint TargetEplanPid()
928
+ {
929
+ if (_clientProcessId != 0) return (uint)_clientProcessId;
930
+ foreach (Process process in Process.GetProcesses())
931
+ {
932
+ try
933
+ {
934
+ if (process.MainWindowHandle == IntPtr.Zero) continue;
935
+ string title = process.MainWindowTitle;
936
+ if (title != null && title.StartsWith("EPLAN Electric", StringComparison.OrdinalIgnoreCase))
937
+ return (uint)process.Id;
938
+ }
939
+ catch { }
940
+ finally { process.Dispose(); }
941
+ }
942
+ return 0;
943
+ }
944
+
945
+ /// <summary>
946
+ /// 给一个 EPLAN 实例打分:真的载着项目的窗口优先。
947
+ ///
948
+ /// 本机常同时开两个窗口(一个空启动、一个开着项目)。以前固定用 servers[0],
949
+ /// 于是命令对着空实例发 —— 表现是项目打不开、或者报「另一个程序正在使用此文件」。
950
+ /// 有项目时窗口标题是「EPLAN Electric P8 2.9 SP1 - C:\...\项目名 - =XXX/7」,
951
+ /// 至少两个「 - 」并且带页名;空实例只有程序名。
952
+ /// </summary>
953
+ private static int InstanceScore(EplanServerData server)
954
+ {
955
+ int score = 0;
956
+ if (server.EplanVariant != null && server.EplanVariant.IndexOf("P8", StringComparison.OrdinalIgnoreCase) >= 0) score += 100;
957
+ string title = EplanWindowTitle((uint)server.EplanProcessID);
958
+ if (!string.IsNullOrEmpty(title))
959
+ {
960
+ int separators = 0;
961
+ for (int index = 0; index + 2 < title.Length; index++)
962
+ {
963
+ if (title[index] == ' ' && title[index + 1] == '-' && title[index + 2] == ' ') separators++;
964
+ }
965
+ if (separators >= 2) score += 50; // 标题里有项目
966
+ if (title.IndexOf('=') >= 0) score += 25; // 标题里有页名 =XXX/1
967
+ else if (separators <= 1) score -= 20; // 只有程序名,多半是空窗口
968
+ }
969
+ return score;
970
+ }
971
+
972
+ /// <summary>某个进程最长的一条可见顶层窗口标题(找不到返回 null)。</summary>
973
+ private static string EplanWindowTitle(uint pid)
974
+ {
975
+ string best = null;
976
+ EnumWindows(delegate(IntPtr handle, IntPtr state)
977
+ {
978
+ uint windowPid;
979
+ GetWindowThreadProcessId(handle, out windowPid);
980
+ if (windowPid != pid) return true;
981
+ if (!IsWindowVisible(handle)) return true;
982
+ StringBuilder text = new StringBuilder(512);
983
+ int length = GetWindowTextW(handle, text, text.Capacity);
984
+ if (length <= 0) return true;
985
+ string title = text.ToString();
986
+ if (title.Length == 0) return true;
987
+ if (best == null || title.Length > best.Length) best = title;
988
+ return true;
989
+ }, IntPtr.Zero);
990
+ return best;
991
+ }
992
+
993
+ /// <summary>
994
+ /// 本机所有 EPLAN 进程的 pid。
995
+ ///
996
+ /// 多实例是本机的常态(用户会同时开两个窗口),对话框可能出现在**任何一个**
997
+ /// 实例上;只看第一个会漏掉,表现就是「明明屏幕上有个框,工具说没有」。
998
+ /// </summary>
999
+ private static List<uint> EplanPids()
1000
+ {
1001
+ List<uint> pids = new List<uint>();
1002
+ foreach (Process process in Process.GetProcesses())
1003
+ {
1004
+ try
1005
+ {
1006
+ if (process.MainWindowHandle == IntPtr.Zero) continue;
1007
+ string title = process.MainWindowTitle;
1008
+ if (title == null) continue;
1009
+ if (title.StartsWith("EPLAN Electric", StringComparison.OrdinalIgnoreCase))
1010
+ pids.Add((uint)process.Id);
1011
+ }
1012
+ catch { }
1013
+ finally { process.Dispose(); }
1014
+ }
1015
+ return pids;
1016
+ }
1017
+
1018
+ /// <summary>点掉/关掉已知对话框;返回做过的事,没有可做的返回 null。</summary>
1019
+ private static string SettleKnownDialogs()
1020
+ {
1021
+ try
1022
+ {
1023
+ List<uint> pids = EplanPids();
1024
+ if (pids.Count == 0) return null;
1025
+
1026
+ List<string> acted = new List<string>();
1027
+ EnumWindows(delegate(IntPtr handle, IntPtr state)
1028
+ {
1029
+ uint windowPid;
1030
+ GetWindowThreadProcessId(handle, out windowPid);
1031
+ if (!pids.Contains(windowPid)) return true;
1032
+ if (!IsWindowVisible(handle)) return true;
1033
+
1034
+ StringBuilder cls = new StringBuilder(256);
1035
+ GetClassNameW(handle, cls, 256);
1036
+ if (cls.ToString() != "#32770") return true;
1037
+
1038
+ StringBuilder caption = new StringBuilder(512);
1039
+ GetWindowTextW(handle, caption, 512);
1040
+ string title = caption.ToString().Trim();
1041
+ if (title.Length == 0) return true;
1042
+
1043
+ foreach (string[] known in KnownDialogs)
1044
+ {
1045
+ if (title.IndexOf(known[0], StringComparison.OrdinalIgnoreCase) < 0) continue;
1046
+
1047
+ string button = known[1];
1048
+ if (button == null)
1049
+ {
1050
+ PostMessage(handle, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
1051
+ acted.Add("「" + title + "」→ 已关闭");
1052
+ break;
1053
+ }
1054
+
1055
+ IntPtr target = IntPtr.Zero;
1056
+ EnumChildWindows(handle, delegate(IntPtr child, IntPtr childState)
1057
+ {
1058
+ StringBuilder childClass = new StringBuilder(256);
1059
+ GetClassNameW(child, childClass, 256);
1060
+ if (childClass.ToString() != "Button") return true;
1061
+ StringBuilder childText = new StringBuilder(256);
1062
+ GetWindowTextW(child, childText, 256);
1063
+ if (childText.ToString().Trim() == button) { target = child; return false; }
1064
+ return true;
1065
+ }, IntPtr.Zero);
1066
+
1067
+ if (target != IntPtr.Zero)
1068
+ {
1069
+ SendMessage(target, BM_CLICK, IntPtr.Zero, IntPtr.Zero);
1070
+ acted.Add("「" + title + "」→ 已点「" + button + "」");
1071
+ }
1072
+ else
1073
+ {
1074
+ PostMessage(handle, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
1075
+ acted.Add("「" + title + "」→ 没有「" + button + "」,已关闭");
1076
+ }
1077
+ break;
1078
+ }
1079
+ return true;
1080
+ }, IntPtr.Zero);
1081
+
1082
+ if (acted.Count == 0) return null;
1083
+ return string.Join(";", acted.ToArray());
1084
+ }
1085
+ catch
1086
+ {
1087
+ return null;
1088
+ }
1089
+ }
1090
+
1091
+ /// <summary>超时时看一眼引导日志,把「脚本没加载」和「脚本卡住」区分开。</summary>
1092
+ private static string BootstrapHint()
1093
+ {
1094
+ try
1095
+ {
1096
+ string logPath = Path.Combine(StateDir, "bootstrap.log");
1097
+ if (!File.Exists(logPath))
1098
+ return " 引导脚本可能从未加载(找不到 bootstrap.log)。";
1099
+
1100
+ string[] lines = File.ReadAllLines(logPath, Encoding.UTF8);
1101
+ for (int i = lines.Length - 1; i >= 0 && i >= lines.Length - 4; i--)
1102
+ {
1103
+ string line = lines[i] ?? string.Empty;
1104
+ if (line.IndexOf("请求", StringComparison.Ordinal) >= 0 ||
1105
+ line.IndexOf("读取请求失败", StringComparison.Ordinal) >= 0 ||
1106
+ line.IndexOf("写响应失败", StringComparison.Ordinal) >= 0 ||
1107
+ line.IndexOf("HOST_LOAD_FAILED", StringComparison.Ordinal) >= 0)
1108
+ {
1109
+ return " 引导日志最后一条相关记录:" + line.Trim();
1110
+ }
1111
+ }
1112
+ return " 引导脚本已加载,但没有记录到本次请求。";
1113
+ }
1114
+ catch
1115
+ {
1116
+ return string.Empty;
1117
+ }
1118
+ }
1119
+ }
1120
+
1121
+ internal class EplanBridgeException : Exception
1122
+ {
1123
+ public string Code { get; private set; }
1124
+ public string Detail { get; private set; }
1125
+
1126
+ public EplanBridgeException(string code, string message, string detail)
1127
+ : base(message)
1128
+ {
1129
+ Code = code;
1130
+ Detail = detail;
1131
+ }
1132
+ }
1133
+ }