wps-multitool-mcp 1.0.1 → 1.0.3

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 (214) hide show
  1. package/dist/bridge/cancellable.d.ts.map +1 -1
  2. package/dist/bridge/cancellable.js +4 -0
  3. package/dist/bridge/cancellable.js.map +1 -1
  4. package/dist/bridge/index.js +109 -18
  5. package/dist/bridge/index.js.map +1 -1
  6. package/dist/bridge/ps-child.d.ts +27 -1
  7. package/dist/bridge/ps-child.d.ts.map +1 -1
  8. package/dist/bridge/ps-child.js +137 -3
  9. package/dist/bridge/ps-child.js.map +1 -1
  10. package/dist/cli/install.d.ts +65 -0
  11. package/dist/cli/install.d.ts.map +1 -0
  12. package/dist/cli/install.js +399 -0
  13. package/dist/cli/install.js.map +1 -0
  14. package/dist/client/action-routes.generated.d.ts +3 -2
  15. package/dist/client/action-routes.generated.d.ts.map +1 -1
  16. package/dist/client/action-routes.generated.js +10 -12
  17. package/dist/client/action-routes.generated.js.map +1 -1
  18. package/dist/client/addon-channel.d.ts +104 -0
  19. package/dist/client/addon-channel.d.ts.map +1 -0
  20. package/dist/client/addon-channel.js +491 -0
  21. package/dist/client/addon-channel.js.map +1 -0
  22. package/dist/client/ps-daemon.d.ts +1 -0
  23. package/dist/client/ps-daemon.d.ts.map +1 -1
  24. package/dist/client/ps-daemon.js +8 -4
  25. package/dist/client/ps-daemon.js.map +1 -1
  26. package/dist/client/wps-client.d.ts +3 -4
  27. package/dist/client/wps-client.d.ts.map +1 -1
  28. package/dist/client/wps-client.js +139 -32
  29. package/dist/client/wps-client.js.map +1 -1
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +57 -4
  32. package/dist/index.js.map +1 -1
  33. package/dist/server/auto-snapshot.d.ts +58 -0
  34. package/dist/server/auto-snapshot.d.ts.map +1 -0
  35. package/dist/server/auto-snapshot.js +150 -0
  36. package/dist/server/auto-snapshot.js.map +1 -0
  37. package/dist/server/backend-selector.d.ts +51 -0
  38. package/dist/server/backend-selector.d.ts.map +1 -0
  39. package/dist/server/backend-selector.js +104 -0
  40. package/dist/server/backend-selector.js.map +1 -0
  41. package/dist/server/mcp-server.d.ts.map +1 -1
  42. package/dist/server/mcp-server.js +8 -141
  43. package/dist/server/mcp-server.js.map +1 -1
  44. package/dist/server/target-context.d.ts +32 -0
  45. package/dist/server/target-context.d.ts.map +1 -0
  46. package/dist/server/target-context.js +47 -0
  47. package/dist/server/target-context.js.map +1 -0
  48. package/dist/server/tool-aliases.generated.d.ts +41 -0
  49. package/dist/server/tool-aliases.generated.d.ts.map +1 -0
  50. package/dist/server/tool-aliases.generated.js +88 -0
  51. package/dist/server/tool-aliases.generated.js.map +1 -0
  52. package/dist/server/tool-annotations.d.ts +3 -0
  53. package/dist/server/tool-annotations.d.ts.map +1 -1
  54. package/dist/server/tool-annotations.generated.d.ts.map +1 -1
  55. package/dist/server/tool-annotations.generated.js +31 -53
  56. package/dist/server/tool-annotations.generated.js.map +1 -1
  57. package/dist/server/tool-annotations.js +95 -7
  58. package/dist/server/tool-annotations.js.map +1 -1
  59. package/dist/server/tool-metadata.d.ts +25 -0
  60. package/dist/server/tool-metadata.d.ts.map +1 -1
  61. package/dist/server/tool-metadata.js +217 -40
  62. package/dist/server/tool-metadata.js.map +1 -1
  63. package/dist/server/tool-registry.d.ts +25 -3
  64. package/dist/server/tool-registry.d.ts.map +1 -1
  65. package/dist/server/tool-registry.js +208 -42
  66. package/dist/server/tool-registry.js.map +1 -1
  67. package/dist/server/tool-tiers.d.ts +28 -8
  68. package/dist/server/tool-tiers.d.ts.map +1 -1
  69. package/dist/server/tool-tiers.js +35 -8
  70. package/dist/server/tool-tiers.js.map +1 -1
  71. package/dist/server/tool-verification.d.ts +35 -0
  72. package/dist/server/tool-verification.d.ts.map +1 -0
  73. package/dist/server/tool-verification.generated.d.ts +17 -0
  74. package/dist/server/tool-verification.generated.d.ts.map +1 -0
  75. package/dist/server/tool-verification.generated.js +293 -0
  76. package/dist/server/tool-verification.generated.js.map +1 -0
  77. package/dist/server/tool-verification.js +43 -0
  78. package/dist/server/tool-verification.js.map +1 -0
  79. package/dist/tools/common/batch.d.ts.map +1 -1
  80. package/dist/tools/common/batch.js +79 -1
  81. package/dist/tools/common/batch.js.map +1 -1
  82. package/dist/tools/common/general.d.ts +0 -3
  83. package/dist/tools/common/general.d.ts.map +1 -1
  84. package/dist/tools/common/general.js +28 -66
  85. package/dist/tools/common/general.js.map +1 -1
  86. package/dist/tools/common/index.d.ts +4 -2
  87. package/dist/tools/common/index.d.ts.map +1 -1
  88. package/dist/tools/common/index.js +18 -4
  89. package/dist/tools/common/index.js.map +1 -1
  90. package/dist/tools/common/snapshot.d.ts +77 -0
  91. package/dist/tools/common/snapshot.d.ts.map +1 -0
  92. package/dist/tools/common/snapshot.js +500 -0
  93. package/dist/tools/common/snapshot.js.map +1 -0
  94. package/dist/tools/common/toolgroups.d.ts.map +1 -1
  95. package/dist/tools/common/toolgroups.js +21 -5
  96. package/dist/tools/common/toolgroups.js.map +1 -1
  97. package/dist/tools/excel/data.d.ts +0 -5
  98. package/dist/tools/excel/data.d.ts.map +1 -1
  99. package/dist/tools/excel/data.js +43 -46
  100. package/dist/tools/excel/data.js.map +1 -1
  101. package/dist/tools/excel/format.d.ts.map +1 -1
  102. package/dist/tools/excel/format.js +3 -1
  103. package/dist/tools/excel/format.js.map +1 -1
  104. package/dist/tools/excel/formula.d.ts +5 -5
  105. package/dist/tools/excel/formula.d.ts.map +1 -1
  106. package/dist/tools/excel/formula.js +65 -24
  107. package/dist/tools/excel/formula.js.map +1 -1
  108. package/dist/tools/excel/index.d.ts +3 -3
  109. package/dist/tools/excel/index.d.ts.map +1 -1
  110. package/dist/tools/excel/index.js +4 -12
  111. package/dist/tools/excel/index.js.map +1 -1
  112. package/dist/tools/excel/sheet-gaps.d.ts +2 -2
  113. package/dist/tools/excel/sheet-gaps.js +2 -2
  114. package/dist/tools/excel/sheet.d.ts +0 -10
  115. package/dist/tools/excel/sheet.d.ts.map +1 -1
  116. package/dist/tools/excel/sheet.js +37 -122
  117. package/dist/tools/excel/sheet.js.map +1 -1
  118. package/dist/tools/excel/workbook.d.ts.map +1 -1
  119. package/dist/tools/excel/workbook.js +11 -4
  120. package/dist/tools/excel/workbook.js.map +1 -1
  121. package/dist/tools/ppt/animation.d.ts +15 -58
  122. package/dist/tools/ppt/animation.d.ts.map +1 -1
  123. package/dist/tools/ppt/animation.js +39 -568
  124. package/dist/tools/ppt/animation.js.map +1 -1
  125. package/dist/tools/ppt/background.d.ts +0 -18
  126. package/dist/tools/ppt/background.d.ts.map +1 -1
  127. package/dist/tools/ppt/background.js +43 -249
  128. package/dist/tools/ppt/background.js.map +1 -1
  129. package/dist/tools/ppt/beautify-advanced.d.ts +0 -6
  130. package/dist/tools/ppt/beautify-advanced.d.ts.map +1 -1
  131. package/dist/tools/ppt/beautify-advanced.js +101 -164
  132. package/dist/tools/ppt/beautify-advanced.js.map +1 -1
  133. package/dist/tools/ppt/chart-flow.d.ts.map +1 -1
  134. package/dist/tools/ppt/chart-flow.js +5 -0
  135. package/dist/tools/ppt/chart-flow.js.map +1 -1
  136. package/dist/tools/ppt/data-viz.d.ts.map +1 -1
  137. package/dist/tools/ppt/data-viz.js +1 -1
  138. package/dist/tools/ppt/data-viz.js.map +1 -1
  139. package/dist/tools/ppt/image.d.ts.map +1 -1
  140. package/dist/tools/ppt/image.js +4 -9
  141. package/dist/tools/ppt/image.js.map +1 -1
  142. package/dist/tools/ppt/index.d.ts +5 -5
  143. package/dist/tools/ppt/index.d.ts.map +1 -1
  144. package/dist/tools/ppt/index.js +5 -35
  145. package/dist/tools/ppt/index.js.map +1 -1
  146. package/dist/tools/ppt/misc.d.ts +0 -6
  147. package/dist/tools/ppt/misc.d.ts.map +1 -1
  148. package/dist/tools/ppt/misc.js +110 -147
  149. package/dist/tools/ppt/misc.js.map +1 -1
  150. package/dist/tools/ppt/presentation.d.ts.map +1 -1
  151. package/dist/tools/ppt/presentation.js +30 -12
  152. package/dist/tools/ppt/presentation.js.map +1 -1
  153. package/dist/tools/ppt/shape-basic.d.ts.map +1 -1
  154. package/dist/tools/ppt/shape-basic.js +4 -0
  155. package/dist/tools/ppt/shape-basic.js.map +1 -1
  156. package/dist/tools/ppt/slide-ops.d.ts +0 -6
  157. package/dist/tools/ppt/slide-ops.d.ts.map +1 -1
  158. package/dist/tools/ppt/slide-ops.js +531 -437
  159. package/dist/tools/ppt/slide-ops.js.map +1 -1
  160. package/dist/tools/ppt/slide.d.ts.map +1 -1
  161. package/dist/tools/ppt/slide.js +50 -36
  162. package/dist/tools/ppt/slide.js.map +1 -1
  163. package/dist/tools/ppt/table.d.ts.map +1 -1
  164. package/dist/tools/ppt/table.js +4 -2
  165. package/dist/tools/ppt/table.js.map +1 -1
  166. package/dist/tools/ppt/textbox.d.ts.map +1 -1
  167. package/dist/tools/ppt/textbox.js +4 -1
  168. package/dist/tools/ppt/textbox.js.map +1 -1
  169. package/dist/tools/word/academic.d.ts.map +1 -1
  170. package/dist/tools/word/academic.js +14 -4
  171. package/dist/tools/word/academic.js.map +1 -1
  172. package/dist/tools/word/content.d.ts.map +1 -1
  173. package/dist/tools/word/content.js +107 -70
  174. package/dist/tools/word/content.js.map +1 -1
  175. package/dist/tools/word/document.d.ts +0 -5
  176. package/dist/tools/word/document.d.ts.map +1 -1
  177. package/dist/tools/word/document.js +121 -116
  178. package/dist/tools/word/document.js.map +1 -1
  179. package/dist/tools/word/format.d.ts.map +1 -1
  180. package/dist/tools/word/format.js +41 -35
  181. package/dist/tools/word/format.js.map +1 -1
  182. package/dist/tools/word/gaps.d.ts +2 -2
  183. package/dist/tools/word/gaps.d.ts.map +1 -1
  184. package/dist/tools/word/gaps.js +13 -7
  185. package/dist/tools/word/gaps.js.map +1 -1
  186. package/dist/tools/word/index.d.ts +1 -1
  187. package/dist/tools/word/index.d.ts.map +1 -1
  188. package/dist/tools/word/index.js +1 -3
  189. package/dist/tools/word/index.js.map +1 -1
  190. package/dist/tools/word/professional.d.ts.map +1 -1
  191. package/dist/tools/word/professional.js +123 -111
  192. package/dist/tools/word/professional.js.map +1 -1
  193. package/dist/tools/word/proofread.d.ts.map +1 -1
  194. package/dist/tools/word/proofread.js +42 -38
  195. package/dist/tools/word/proofread.js.map +1 -1
  196. package/dist/tools/word/target.d.ts +74 -0
  197. package/dist/tools/word/target.d.ts.map +1 -0
  198. package/dist/tools/word/target.js +130 -0
  199. package/dist/tools/word/target.js.map +1 -0
  200. package/dist/types/tools.d.ts +12 -1
  201. package/dist/types/tools.d.ts.map +1 -1
  202. package/dist/types/tools.js.map +1 -1
  203. package/dist/utils/logger.d.ts.map +1 -1
  204. package/dist/utils/logger.js +48 -1
  205. package/dist/utils/logger.js.map +1 -1
  206. package/dist/version.js +1 -1
  207. package/package.json +23 -10
  208. package/scripts/wps-com.ps1 +1944 -337
  209. package/scripts/wps-comd.ps1 +162 -123
  210. package/skills/wps-multitool/SKILL.md +25 -6
  211. package/skills/wps-multitool/references/dsh.md +88 -0
  212. package/skills/wps-multitool/references/recipes.md +3 -2
  213. package/dist/client/mac-poll-server.d.ts +0 -77
  214. package/dist/client/mac-poll-server.js +0 -516
@@ -7,89 +7,269 @@
7
7
 
8
8
  param(
9
9
  [string]$Action,
10
- [string]$Params = "{}"
10
+ [string]$Params = "{}",
11
+ # 第 1 期第 3 章轮 1:实例标识。user = 用户正在用的 WPS(GetActiveObject);
12
+ # sandbox-N = 本进程自己 New-Object 出来的隔离实例(句柄缓存在脚本作用域,常驻复用)。
13
+ [string]$Instance = 'user',
14
+ # 本进程负责哪个应用(word / excel / ppt / common)。word 才做文档寻址前置检查。
15
+ [string]$App = ''
11
16
  )
12
17
 
13
18
  $OutputEncoding = [System.Text.Encoding]::UTF8
14
19
  [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
15
20
 
16
- # ==================== COM Object Getters ====================
21
+ # ==================== 实例上下文 ====================
22
+ # 这几个变量是【整个进程级】的,不是单次请求的:
23
+ # WpsInstance —— 决定了 Get-WpsWord 走 GetActiveObject 还是拿沙箱句柄
24
+ # SandboxWordApp —— 沙箱实例句柄缓存(常驻进程里复用,绝不每次 New-Object)
25
+ # SandboxWordPids —— 创建沙箱时新出现的 wps PID(quitWps 只回收这几个)
26
+ # LastResolvedDoc —— 本次请求最终落到哪份文档(由 Output-Json 带回给调用方)
27
+ $script:WpsInstance = if ($Instance) { $Instance.Trim() } else { 'user' }
28
+ $script:WpsApp = if ($App) { $App.Trim().ToLower() } else { '' }
29
+ $script:SandboxWordApp = $null
30
+ $script:SandboxWordPids = @()
31
+ $script:LastResolvedDoc = $null
32
+
33
+ <#
34
+ .SYNOPSIS 当前进程是不是沙箱实例
35
+ .DESCRIPTION
36
+ 判据只有一个:WpsInstance 不是 user。不要用"有没有 New-Object 过"来判 ——
37
+ 那样第一个请求还没创建实例时会被当成 user,于是第一个动作落到用户的文档上。
38
+ #>
39
+ function Test-SandboxInstance {
40
+ return ([bool]$script:WpsInstance -and $script:WpsInstance -ne 'user')
41
+ }
17
42
 
18
- function Get-WpsExcel {
19
- try { return [System.Runtime.InteropServices.Marshal]::GetActiveObject('Ket.Application') }
20
- catch {
43
+ # ==================== WPS 进程预算(硬上限,禁止超出)====================
44
+ # 为什么有这道闸:2026-10-21 真机跑 A1–A10 时,泄漏到 24 个 wps 进程。
45
+ # 口径(所有者 2026-10-21 定):全机 wps/et/wpp 进程总数不超过 3 个。
46
+ # 注意:一个实例实测是 2 个进程(主进程 + 辅助),所以 3 个进程的预算 = 最多 1 个实例 + 1 个余量;
47
+ # 要同时开沙箱,必须先把上限显式调高(但硬顶仍是 3,不允许绕过)。
48
+ function Get-WpsProcessCount {
49
+ try { return @(Get-Process -Name wps, et, wpp -ErrorAction SilentlyContinue).Count } catch { return 0 }
50
+ }
51
+
52
+ function Get-WpsProcBudget {
53
+ $budget = 3
54
+ if ($env:WPS_PROC_BUDGET) {
21
55
  try {
22
- $app = New-Object -ComObject 'Ket.Application'
23
- if ($app) { try { $app.Visible = $true } catch {}; return $app }
24
- } catch {
25
- try {
26
- $clsid = (Get-ItemProperty -Path 'HKCU:\Software\Classes\Ket.Application\CLSID' -ErrorAction Stop).'(default)'
27
- if ($clsid) {
28
- $type = [Type]::GetTypeFromCLSID($clsid)
29
- if ($type) {
30
- $app = [Activator]::CreateInstance($type)
31
- if ($app) { try { $app.Visible = $true } catch {}; return $app }
32
- }
33
- }
34
- } catch {}
56
+ $n = [int]$env:WPS_PROC_BUDGET
57
+ if ($n -gt 0) { $budget = [Math]::Min($n, 3) } # 硬顶 3,写 8 也只按 3 算
58
+ } catch { }
59
+ }
60
+ return $budget
61
+ }
62
+
63
+ # 回收本进程自己创建过的沙箱 PID(不碰用户窗口),返回回收个数
64
+ function Remove-OwnSandboxProcs {
65
+ $n = 0
66
+ foreach ($procId in @($script:SandboxWordPids)) {
67
+ try { Stop-Process -Id $procId -Force -ErrorAction Stop; $n++ } catch { }
68
+ }
69
+ $script:SandboxWordPids = @()
70
+ if ($n -gt 0) { Start-Sleep -Milliseconds 300 }
71
+ return $n
72
+ }
73
+
74
+ # ==================== ROT 附着(PowerShell 7 兼容 · 2026-10-25) ====================
75
+ # 恶例复盘:pwsh7(.NET Core) 没有 Marshal::GetActiveObject,6 处调用点全体必抛 →
76
+ # 每个动作都走 New-Object 回落 → 每动作新建一个 WPS,几分钟堆出 30+ 进程(执行者轮 7 铁证)。
77
+ # 这里用 ole32/oleaut32 的 P/Invoke 实现同语义附着:Marshal 内部就是这条路,5.1 与 7 通用。
78
+ if (-not ('WpsRot' -as [type])) {
79
+ Add-Type -TypeDefinition @'
80
+ using System;
81
+ using System.Runtime.InteropServices;
82
+
83
+ public static class WpsRot
84
+ {
85
+ [DllImport("ole32.dll", CharSet = CharSet.Unicode)]
86
+ private static extern int CLSIDFromProgID(string lpszProgID, out Guid pclsid);
87
+
88
+ [DllImport("oleaut32.dll", PreserveSig = false)]
89
+ private static extern void GetActiveObject(ref Guid rclsid, IntPtr pvReserved, [MarshalAs(UnmanagedType.IUnknown)] out object ppunk);
90
+
91
+ // 与 Marshal.GetActiveObject 同语义:查不到 ProgID / 没有实例在跑时抛 COMException
92
+ public static object GetActiveObject(string progId)
93
+ {
94
+ Guid clsid;
95
+ int hr = CLSIDFromProgID(progId, out clsid);
96
+ if (hr != 0) { throw new COMException("CLSIDFromProgID(" + progId + ") failed: 0x" + hr.ToString("X"), hr); }
97
+ object obj;
98
+ GetActiveObject(ref clsid, IntPtr.Zero, out obj);
99
+ return obj;
100
+ }
101
+ }
102
+ '@ -ErrorAction Stop | Out-Null
103
+ }
104
+
105
+ # 统一入口:全仓"附着已运行实例"只许走这里,不许再直接调 Marshal::GetActiveObject。
106
+ # 只取不建;取不到返回 $null(不抛,调用方按 $null 判断)。
107
+ function Get-RotObject([string]$ProgId) {
108
+ try { return [WpsRot]::GetActiveObject($ProgId) } catch { return $null }
109
+ }
110
+
111
+ # 本进程(守护)自己创建过的 user 实例记账。缓存 + PID 两条腿:
112
+ # 缓存防"ROT 重注册窗口期反复新建",PID 记账让 quit/收摊时能按 PID 精确回收自己的东西。
113
+ $script:UserWordApp = $null
114
+ $script:UserExcelApp = $null
115
+ $script:UserPptApp = $null
116
+ $script:UserCreatedPids = @()
117
+
118
+ # 新建一个 user 实例并记账(PID 差集 + 看门狗 Track)。返回 $null = 没建出来。
119
+ function New-TrackedWpsInstance([string]$ProgId) {
120
+ $before = @()
121
+ try { $before = @(Get-Process -Name wps -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Id) } catch {}
122
+ $app = $null
123
+ try { $app = New-Object -ComObject $ProgId } catch { $app = $null }
124
+ if ($null -eq $app) {
125
+ # 旧路径兜底:个别环境 New-Object 失败但注册表能拿到 CLSID
126
+ try {
127
+ $clsid = (Get-ItemProperty -Path ("HKCU:\Software\Classes\" + $ProgId + "\CLSID") -ErrorAction Stop).'(default)'
128
+ if ($clsid) {
129
+ $type = [Type]::GetTypeFromCLSID($clsid)
130
+ if ($type) { $app = [Activator]::CreateInstance($type) }
131
+ }
132
+ } catch { $app = $null }
133
+ }
134
+ if ($null -eq $app) { return $null }
135
+ try { $app.Visible = $true } catch {}
136
+ $after = @()
137
+ try { $after = @(Get-Process -Name wps -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Id) } catch {}
138
+ $new = @($after | Where-Object { $before -notcontains $_ })
139
+ if ($new.Count -gt 0) {
140
+ $script:UserCreatedPids = @($script:UserCreatedPids + $new | Select-Object -Unique)
141
+ foreach ($procId in $new) {
142
+ try { if ('WpsParentWatchdog' -as [type]) { [WpsParentWatchdog]::Track([int]$procId) } } catch {}
35
143
  }
36
- return $null
37
144
  }
145
+ return $app
146
+ }
147
+
148
+ # 回收本进程创建过的 user 实例(Quit 挂钩与守护收摊共用)。只动自己的,绝不碰 ROT 附着的用户实例。
149
+ function Remove-OwnCreatedProcs {
150
+ $n = 0
151
+ foreach ($procId in @($script:UserCreatedPids)) {
152
+ try { Stop-Process -Id $procId -Force -ErrorAction Stop; $n++ } catch { }
153
+ }
154
+ $script:UserCreatedPids = @()
155
+ $script:UserWordApp = $null
156
+ $script:UserExcelApp = $null
157
+ $script:UserPptApp = $null
158
+ if ($n -gt 0) { Start-Sleep -Milliseconds 300 }
159
+ return $n
160
+ }
161
+
162
+ # ==================== COM Object Getters ====================
163
+
164
+ function Get-WpsExcel {
165
+ # 第 1 期第 2 章第 4 轮(A9):Fresh 标记"这次取到的实例是不是【新建】的"。
166
+ # 新建的实例一定是空的 —— 用它读列表会得到"0 份",而文档其实还在(ROT 重注册窗口)。
167
+ $script:WpsExcelFresh = $false
168
+ # ① 先附着已运行的实例(用户优先;pwsh7 兼容见 Get-RotObject)
169
+ $rot = Get-RotObject 'Ket.Application'
170
+ if ($null -ne $rot) { return $rot }
171
+ # ② 再看自己的缓存(ROT 重注册窗口期防反复新建)
172
+ if ($null -ne $script:UserExcelApp) {
173
+ try { $null = $script:UserExcelApp.Workbooks.Count; return $script:UserExcelApp } catch { $script:UserExcelApp = $null }
174
+ }
175
+ # ③ 都没有才新建,并记账
176
+ $app = New-TrackedWpsInstance 'Ket.Application'
177
+ if ($app) { $script:WpsExcelFresh = $true; $script:UserExcelApp = $app; return $app }
178
+ return $null
38
179
  }
39
180
 
40
181
  function Get-WpsWord {
41
- try { return [System.Runtime.InteropServices.Marshal]::GetActiveObject('Kwps.Application') }
42
- catch {
182
+ # 第 1 期第 3 章轮 1:沙箱实例走自己的句柄,绝不碰用户的 WPS。
183
+ #
184
+ # 为什么必须缓存:New-Object 每次都新开一个 WPS 进程(实测 +2 进程),
185
+ # 一个常驻进程如果每请求都 New-Object,几分钟就能堆出几十个进程。
186
+ # 为什么要探活:沙箱实例可能被用户手动关掉 / 被系统回收,
187
+ # 缓存里那个 COM 对象就成了僵尸 —— 必须能发现并重建,否则后续全报 RPC 错。
188
+ if (Test-SandboxInstance) {
189
+ if ($null -ne $script:SandboxWordApp) {
190
+ try {
191
+ # 只探一个轻量属性:能取到就认为句柄还活着
192
+ $null = $script:SandboxWordApp.Documents.Count
193
+ return $script:SandboxWordApp
194
+ } catch {
195
+ $script:SandboxWordApp = $null
196
+ $script:SandboxWordPids = @()
197
+ }
198
+ }
199
+ # 新建之前先过预算闸:先回收自己造的无窗口残留,仍不够就【拒绝】——
200
+ # 不新建、不排队、不重试。排队只会继续堆进程,正是要防的事。
201
+ $recycled = Remove-OwnSandboxProcs
202
+ $budget = Get-WpsProcBudget
203
+ $now = Get-WpsProcessCount
204
+ if (($now + 2) -gt $budget) {
205
+ throw ("进程预算不足:当前 $now 个 WPS 进程(刚回收 $recycled 个),上限 $budget,新建沙箱实例还要占 2 个。" +
206
+ "请先关掉多余的 WPS(含无窗口残留);上限本身不允许超过 3。")
207
+ }
208
+ $before = @()
209
+ try { $before = @(Get-Process -Name wps -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Id) } catch {}
210
+ $app = $null
43
211
  try {
44
212
  $app = New-Object -ComObject 'Kwps.Application'
45
- if ($app) { try { $app.Visible = $true } catch {}; return $app }
46
213
  } catch {
47
- try {
48
- $clsid = (Get-ItemProperty -Path 'HKCU:\Software\Classes\Kwps.Application\CLSID' -ErrorAction Stop).'(default)'
49
- if ($clsid) {
50
- $type = [Type]::GetTypeFromCLSID($clsid)
51
- if ($type) {
52
- $app = [Activator]::CreateInstance($type)
53
- if ($app) { try { $app.Visible = $true } catch {}; return $app }
54
- }
55
- }
56
- } catch {}
214
+ $app = $null
57
215
  }
58
- return $null
59
- }
216
+ if ($null -eq $app) { return $null }
217
+ # 沙箱默认不可见:它不该在用户桌面上弹窗口(DECISION §2 实测 Visible=false 生效)
218
+ try { $app.Visible = $false } catch {}
219
+ $after = @()
220
+ try { $after = @(Get-Process -Name wps -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Id) } catch {}
221
+ # 记下"创建前后新增的 PID" —— quitWps 只回收这批,绝不 taskkill /IM 全杀
222
+ $script:SandboxWordPids = @($after | Where-Object { $before -notcontains $_ })
223
+ foreach ($procId in $script:SandboxWordPids) {
224
+ try { if ('WpsParentWatchdog' -as [type]) { [WpsParentWatchdog]::Track([int]$procId) } } catch {}
225
+ }
226
+ $script:SandboxWordApp = $app
227
+ return $app
228
+ }
229
+ # 第 1 期第 2 章第 4 轮(A9):Fresh 标记"这次取到的实例是不是【新建】的"。
230
+ $script:WpsWordFresh = $false
231
+ # ① 先附着已运行的实例(用户优先)
232
+ $rot = Get-RotObject 'Kwps.Application'
233
+ if ($null -ne $rot) { return $rot }
234
+ # ② 自己的缓存(防 ROT 重注册窗口期反复新建)
235
+ if ($null -ne $script:UserWordApp) {
236
+ try { $null = $script:UserWordApp.Documents.Count; return $script:UserWordApp } catch { $script:UserWordApp = $null }
237
+ }
238
+ # ③ 都没有才新建,并记账
239
+ $app = New-TrackedWpsInstance 'Kwps.Application'
240
+ if ($app) { $script:WpsWordFresh = $true; $script:UserWordApp = $app; return $app }
241
+ return $null
60
242
  }
61
243
 
244
+ # 只从 ROT(Running Object Table)取正在跑的那个实例,【不新建】。
245
+ #
246
+ # 为什么需要它(第 1 期第 2 章第 4 轮 · A9):
247
+ # Get-WpsWord 在 ROT 取不到时会新建一个【新的空实例】。
248
+ # 而 WPS 退出/重启之后要重新注册 ROT,那几秒里正好取不到 ——
249
+ # 于是"暂时看不见文档"被说成了"没有文档"。
250
+ # 列表读回必须能区分这两件事,所以给它一条"只取不建"的路。
251
+ function Get-WpsWordFromRot {
252
+ return Get-RotObject 'Kwps.Application'
253
+ }
254
+ function Get-WpsExcelFromRot {
255
+ return Get-RotObject 'Ket.Application'
256
+ }
62
257
  function Get-WpsPpt {
63
- try { return [System.Runtime.InteropServices.Marshal]::GetActiveObject('Kwpp.Application') }
64
- catch {
65
- try {
66
- $app = New-Object -ComObject Kwpp.Application
67
- try { $app.Visible = $true } catch {}
68
- return $app
69
- } catch {
70
- try {
71
- $clsid = (Get-ItemProperty -Path 'HKCU:\Software\Classes\Kwpp.Application\CLSID' -ErrorAction Stop).'(default)'
72
- if ($clsid) {
73
- $type = [Type]::GetTypeFromCLSID($clsid)
74
- if ($type) {
75
- $app = [Activator]::CreateInstance($type)
76
- if ($app) {
77
- try { $app.Visible = $true } catch {}
78
- return $app
79
- }
80
- }
81
- }
82
- } catch {}
83
- }
84
- return $null
258
+ $rot = Get-RotObject 'Kwpp.Application'
259
+ if ($null -ne $rot) { return $rot }
260
+ if ($null -ne $script:UserPptApp) {
261
+ try { $null = $script:UserPptApp.Presentations.Count; return $script:UserPptApp } catch { $script:UserPptApp = $null }
85
262
  }
263
+ $app = New-TrackedWpsInstance 'Kwpp.Application'
264
+ if ($app) { $script:UserPptApp = $app; return $app }
265
+ return $null
86
266
  }
87
267
 
88
268
  # ==================== 窗口置前 / 进程退出 辅助 ====================
89
269
 
90
270
  # 仅获取【已运行】的 WPS 实例(不创建新实例),供 showWps / quitWps 这类不应产生副作用的操作使用
91
271
  function Get-ActiveWpsApp([string]$ProgId) {
92
- try { return [System.Runtime.InteropServices.Marshal]::GetActiveObject($ProgId) } catch { return $null }
272
+ return Get-RotObject $ProgId
93
273
  }
94
274
 
95
275
  # 将已运行的 WPS 主窗口置于前台(按进程主窗口句柄激活)
@@ -228,21 +408,33 @@ function Find-BookByName($app, [string]$want) {
228
408
  # 注意:本函数在同一动作里可能被调用两次(先判空、再使用),每次都会重新解析。
229
409
  # 这是有意的 —— 引入跨动作的缓存会带来"用户刚关掉文档,我们还拿着旧对象"的新问题,
230
410
  # 而重复解析只是几次 COM 属性访问,代价可忽略。
411
+ # 记下"这次到底落到哪一份",由 Output-Json 带回给调用方(__target)。
412
+ # 为什么在 Resolve-Doc 里记而不是每个 case 里记:67 个 word 工具都走它,
413
+ # 逐个加必然漏;而且漏了也不报错,只表现为"返回里没有 __target"。
414
+ function Set-LastResolvedDoc($doc, [string]$by) {
415
+ if ($null -eq $doc) { return }
416
+ $nm = ''; $pth = ''
417
+ try { $nm = [string]$doc.Name } catch {}
418
+ try { $pth = [string]$doc.Path } catch {}
419
+ $script:LastResolvedDoc = @{ name = $nm; path = $pth; by = $by }
420
+ }
421
+
231
422
  function Resolve-Doc($app, $p) {
232
423
  if ($null -eq $app) { return $null }
233
424
  if ($p -and $p.documentName) {
234
425
  $d = Find-DocByName $app ([string]$p.documentName)
235
- if ($d) { return $d }
426
+ if ($d) { Set-LastResolvedDoc $d 'documentName'; return $d }
236
427
  # 显式指定却找不到:明确返回 $null,不要静默回退到"活动文档" ——
237
428
  # 否则用户以为在改 A,结果改的是 B。
429
+ # 具体报错在 Invoke-WpsAction 的入口前置检查里(那里能一次列出所有打开的文档名)。
238
430
  return $null
239
431
  }
240
432
  try { $act = $app.ActiveDocument } catch { $act = $null }
241
- if (Test-DocHealthy $act) { return $act }
433
+ if (Test-DocHealthy $act) { Set-LastResolvedDoc $act 'active'; return $act }
242
434
  # 空壳 → 遍历找一个健康的
243
435
  try {
244
436
  foreach ($d in @($app.Documents)) {
245
- if (Test-DocHealthy $d) { return $d }
437
+ if (Test-DocHealthy $d) { Set-LastResolvedDoc $d 'firstHealthy'; return $d }
246
438
  }
247
439
  } catch {}
248
440
  return $null
@@ -266,6 +458,31 @@ function Resolve-Book($app, $p) {
266
458
  return $null
267
459
  }
268
460
 
461
+ # 第 3 轮加:把 $p.sheet 解析成工作表对象,没传就退回活动表。
462
+ # 为什么值得单开一个函数:审计(param-shape-audit.js)发现 30 多个 Excel 动作的 TS schema
463
+ # 都承诺了 sheet("工作表名,不填则当前活动表"),PS 侧却直接读 $excel.ActiveSheet ——
464
+ # 于是"指定了表也没用,照样改活动表",属于最坑的一类假成功(不报错、改错了地方)。
465
+ # 收敛到这一个函数后:没传 sheet 时行为与原来完全一致(就是 ActiveSheet);
466
+ # 传了但表不存在时返回 $null,让调用方报错,而不是静默改错表。
467
+ function Resolve-Sheet($app, $p) {
468
+ if ($null -eq $app) { return $null }
469
+ $wb = $(Resolve-Book $app $p)
470
+ if ($null -eq $wb) { return $null }
471
+ if ($p -and $p.sheet) {
472
+ $key = [string]$p.sheet
473
+ $idx = 0
474
+ if ([int]::TryParse($key, [ref]$idx)) {
475
+ try { return $wb.Sheets.Item($idx) } catch {}
476
+ }
477
+ try { return $wb.Sheets.Item($key) } catch {}
478
+ return $null
479
+ }
480
+ # 必须取【$wb 的】ActiveSheet,不能取 $app.ActiveSheet:
481
+ # 解析到的工作簿未必是活动工作簿(例如探测里刚 Workbooks.Add 出来的临时簿),
482
+ # 两者混用会把参数作用到别的工作簿上 —— 实测导致 __probeExcelCaps 全项报"不支持"。
483
+ try { return $wb.ActiveSheet } catch { return $null }
484
+ }
485
+
269
486
  # ==================== 模态对话框探测(C)====================
270
487
  # 为什么需要
271
488
  # ----------
@@ -470,6 +687,23 @@ function Output-Json($obj) {
470
687
  # 常驻模式下把请求 id 带回响应,供 Node 侧按 id 匹配请求/响应。
471
688
  # 直跑模式 $script:WpsReqId 为空,不注入,输出与改造前逐字节一致。
472
689
  if ($script:WpsReqId -and ($obj -is [hashtable])) { $obj['id'] = $script:WpsReqId }
690
+
691
+ # 第 1 期第 3 章轮 1:把"实际改的是哪一份"带回给调用方。
692
+ # 为什么挂在统一出口:67 个 word 工具的 case 各自 Output-Json,逐个加必漏;
693
+ # 而"改错了地方"恰恰最难自己发现 —— 只看 success: true 是看不出来的。
694
+ # 只在成功响应上带:失败时文档可能根本没解析到,附一份空壳只会误导。
695
+ if ($null -ne $script:LastResolvedDoc -and ($obj -is [hashtable]) -and $obj['success'] -and -not $obj.ContainsKey('__target')) {
696
+ $obj['__target'] = @{
697
+ name = [string]$script:LastResolvedDoc.name
698
+ path = [string]$script:LastResolvedDoc.path
699
+ by = [string]$script:LastResolvedDoc.by
700
+ instance = [string]$script:WpsInstance
701
+ }
702
+ }
703
+ # 每条响应只带一次:不清掉的话,下一个请求(可能压根没解析文档)会继承上一份的名字,
704
+ # 那比不带更坏 —— 它会让调用方确信自己改的是另一份。
705
+ $script:LastResolvedDoc = $null
706
+
473
707
  $obj | ConvertTo-Json -Depth 10 -Compress
474
708
  }
475
709
 
@@ -509,6 +743,28 @@ function Convert-HexColorToRgbInt([string]$hex) {
509
743
  return $r + ($g * 256) + ($b * 65536)
510
744
  }
511
745
 
746
+ # 颜色 → RGB 整数:先按 #RRGGBB 解析,再退到常见颜色名。
747
+ # 为什么不复用 Convert-HexColorToRgbInt:那个只吃十六进制,而 wps_ppt_set_font_color 的
748
+ # schema 明确承诺"支持 #FF0000 或 red 这类颜色名"—— 承诺了就得做到,否则用户传 red 会静默不生效。
749
+ function Convert-ColorToRgbInt([string]$color) {
750
+ if (-not $color) { return $null }
751
+ # Convert-HexColorToRgbInt 内部 ToInt32 遇到非十六进制会【抛异常】而不是返回 $null
752
+ # (实测 #ZZZZZZ → "未能找到任何可识别的数字",用户看不懂)。这里接住,走统一的友好报错。
753
+ $rgb = $null
754
+ try { $rgb = Convert-HexColorToRgbInt $color } catch { $rgb = $null }
755
+ if ($null -ne $rgb) { return $rgb }
756
+ $names = @{
757
+ black = '000000'; white = 'FFFFFF'; red = 'FF0000'; green = '00B050'; lime = '00FF00'
758
+ blue = '0070C0'; yellow = 'FFFF00'; orange = 'FFA500'; purple = '800080'
759
+ gray = '808080'; grey = '808080'; pink = 'FFC0CB'; brown = 'A52A2A'
760
+ cyan = '00FFFF'; magenta = 'FF00FF'; navy = '000080'; teal = '008080'
761
+ gold = 'FFD700'; silver = 'C0C0C0'
762
+ }
763
+ $key = $color.Trim().ToLower()
764
+ if ($names.ContainsKey($key)) { return Convert-HexColorToRgbInt $names[$key] }
765
+ return $null
766
+ }
767
+
512
768
  function Get-RangeFromAddress($workbook, [string]$address) {
513
769
  if ($address -match "^(?<sheet>[^!]+)!(?<range>.+)$") {
514
770
  $sheetName = $matches.sheet.Trim("'")
@@ -567,12 +823,279 @@ function Invoke-WpsAction {
567
823
  # 表现为"所有带参数的动作都收不到参数",而且不报错。实测于 ② 补参数化动作时发现。
568
824
  # 直跑模式的解析在文件末尾的入口段里做,那里才是它该待的地方。
569
825
 
826
+ # ============================================================================
827
+ # 入参归一化(第 3 轮:消灭"TS 传了、PS 不读"的静默丢弃)
828
+ # ============================================================================
829
+ # 为什么放在 switch 之前
830
+ # ------------------
831
+ # param-shape-audit.js 扫出来的 90 处候选,本质是一类病:TS 的 schema 承诺了一个参数名,
832
+ # 而 PS 的 case 读的是另一个名字(或只读扁平键)。后果分两种:
833
+ # 静默丢弃 —— "返回 success 但什么都没做"(最坏,用户以为改完了);
834
+ # 响亮失败 —— PS 缺必填键直接报错(用户至少知道自己没成功)。
835
+ # 本块把【静默丢弃】那一类在入口就抹平:改名的改名、嵌套的摊平,case 体一行都不用动。
836
+ # 值形态要转换的(比如 startRow/endRow → rows 数组)不在这里做,留在 case 里。
837
+ #
838
+ # 两条规则都是"只在对方没给时才补" —— 显式传扁平参数的调用方(wps_execute_method 裸调、
839
+ # 历史脚本)行为完全不变。
840
+ $ParamAlias = @{
841
+ 'insertPptChart' = @{ chartType = 'type' }
842
+ 'addPptHyperlink' = @{ url = 'address' }
843
+ 'alignShapes' = @{ shapeIndices = 'names' }
844
+ 'distributeShapes' = @{ shapeIndices = 'names' }
845
+ 'groupShapes' = @{ shapeIndices = 'names' }
846
+ 'smartDistribute' = @{ shapeIndices = 'shapes' }
847
+ 'addAnimation' = @{ shapeIndex = 'shapeName' }
848
+ 'addAnimationPreset' = @{ shapeIndex = 'shapeName' }
849
+ 'applyTransitionToAll' = @{ effect = 'transition' }
850
+ 'findReplace' = @{ find = 'findText'; replace = 'replaceText' }
851
+ 'deleteSheet' = @{ name = 'sheet' }
852
+ 'switchSheet' = @{ name = 'sheet' }
853
+ 'renameSheet' = @{ oldName = 'sheet' }
854
+ 'copySheet' = @{ name = 'sheet' }
855
+ 'moveSheet' = @{ name = 'sheet' }
856
+ 'deletePptImage' = @{ imageIndex = 'shapeIndex' }
857
+ 'deleteTextBox' = @{ textboxIndex = 'shapeIndex' }
858
+ 'setTextBoxText' = @{ textboxIndex = 'shapeIndex' }
859
+ 'setTextBoxStyle' = @{ textboxIndex = 'shapeIndex' }
860
+ 'setImageStyle' = @{ imageIndex = 'shapeIndex' }
861
+ 'removeAnimation' = @{ animationIndex = 'index' }
862
+ 'replacePptImage' = @{ imagePath = 'filePath' }
863
+ 'setBackgroundImage' = @{ imagePath = 'path'; filePath = 'path' }
864
+ 'insertPptImage' = @{ filePath = 'path'; imagePath = 'path' }
865
+ 'insertExcelImage' = @{ filePath = 'path'; imagePath = 'path' }
866
+ 'openPresentation' = @{ filePath = 'path' }
867
+ 'setHyperlink' = @{ url = 'address'; text = 'textToDisplay' }
868
+ 'setPageSetup' = @{ marginTop = 'topMargin'; marginBottom = 'bottomMargin'; marginLeft = 'leftMargin'; marginRight = 'rightMargin' }
869
+ 'setShapeZOrder' = @{ order = 'zOrder' }
870
+ 'setSlideNumber' = @{ show = 'visible' }
871
+ 'setPptDateTime' = @{ show = 'visible'; autoUpdate = 'useFixed' }
872
+ 'setBorder' = @{ borderStyle = 'style' }
873
+ 'setSlideTransition' = @{ transition = 'effect' }
874
+ # 这条以前把 rotation:{x,y,z} 整个对象改名成 rotationX,于是 case 里
875
+ # [float]$rx 收到一个 PSCustomObject → "无法将类型 psobject 转换为 float"。
876
+ # case 已改成自己读 rotation.x/y/z,这里不能再改名。
877
+ # 'set3DRotation' = @{ rotation = 'rotationX' }
878
+ 'autoFilter' = @{ column = 'field' }
879
+ 'createKpiCards' = @{ data = 'cards' }
880
+ 'createMiniCharts' = @{ data = 'items' }
881
+ 'createOrgChart' = @{ data = 'nodes' }
882
+ 'createProgressBar' = @{ value = 'progress' }
883
+ # sortRange 的 column 现在由 case 自己换算成列字母(TS 发的是数字,不是列地址),
884
+ # 不能再在这里改成 keyColumn —— 否则 case 会拿一个数字去 Range()。
885
+ 'subtotal' = @{ columns = 'totalColumns' }
886
+ 'transpose' = @{ source = 'sourceRange' }
887
+ 'setAnimationOrder' = @{ animationIndex = 'from'; newOrder = 'to' }
888
+ 'insertImage' = @{ imagePath = 'path' }
889
+ 'addDataValidation' = @{ type = 'validationType'; formula = 'formula1' }
890
+ }
891
+
892
+ # 嵌套对象摊平:TS 传 style:{...}/format:{...}/shadow:{...},PS 读扁平键。
893
+ # 把嵌套对象的每个属性提升成 $p 的同名键(已存在的绝不覆盖)。
894
+ $StyleFlatten = @(
895
+ 'setPptTableStyle', 'setPptTableCellStyle', 'setPptTableRowStyle', 'setPptChartStyle',
896
+ 'setCellStyle', 'setCellFormat', 'setShapeBorder', 'setShapeGradient', 'setShapeShadow',
897
+ 'setTextBoxStyle', 'setImageStyle', 'setMasterBackground', 'setBackgroundGradient',
898
+ 'setSlideBackground', 'addConditionalFormat', 'addMasterElement', 'addPageIndicator',
899
+ 'addTitleDecoration', 'protectSheet', 'protectWorkbook'
900
+ )
901
+ # 这些动作的嵌套键不叫 style,单独点名
902
+ $FlattenKeys = @{
903
+ 'setCellFormat' = @('format')
904
+ 'setShapeBorder' = @('border')
905
+ 'setShapeGradient' = @('gradient')
906
+ 'setShapeShadow' = @('shadow')
907
+ 'setBackgroundGradient' = @('gradient')
908
+ 'setMasterBackground' = @('background')
909
+ 'setSlideBackground' = @('background')
910
+ 'addConditionalFormat' = @('condition', 'format')
911
+ 'addMasterElement' = @('element')
912
+ 'addPageIndicator' = @('position')
913
+ 'addTitleDecoration' = @('style')
914
+ 'protectSheet' = @('protect')
915
+ 'protectWorkbook' = @('protect')
916
+ }
917
+
918
+
919
+ # openAfterExport:TS 的 schema 承诺"导出后顺便打开",以前 PS 压根不读这个键 ——
920
+ # 用户勾了没反应,也没有任何提示。放在回包之前统一做,失败只记 warnings 不影响导出结果。
921
+ function Open-Exported($path, $flag) {
922
+ if (-not $flag) { return }
923
+ try {
924
+ if ($path -and (Test-Path -LiteralPath $path)) { Start-Process -FilePath $path | Out-Null }
925
+ } catch { }
926
+ }
927
+
928
+ if ($null -ne $p -and $p -is [psobject]) {
929
+ $have = @($p.PSObject.Properties.Name)
930
+ # 1) 改名:TS 的文档名 → PS 实际读的名
931
+ if ($ParamAlias.ContainsKey($Action)) {
932
+ foreach ($from in @($ParamAlias[$Action].Keys)) {
933
+ $to = $ParamAlias[$Action][$from]
934
+ if (($have -contains $from) -and -not ($have -contains $to)) {
935
+ $p | Add-Member -NotePropertyName $to -NotePropertyValue $p.$from -Force
936
+ $have = @($p.PSObject.Properties.Name)
937
+ }
938
+ }
939
+ }
940
+ # 2) 摊平:嵌套对象的属性提升成 $p 的扁平键
941
+ if ($StyleFlatten -contains $Action) {
942
+ $objKeys = if ($FlattenKeys.ContainsKey($Action)) { $FlattenKeys[$Action] } else { @('style') }
943
+ foreach ($ok in $objKeys) {
944
+ $obj = $p.$ok
945
+ if ($null -eq $obj) { continue }
946
+ foreach ($prop in @($obj.PSObject.Properties)) {
947
+ if (-not ($have -contains $prop.Name)) {
948
+ $p | Add-Member -NotePropertyName $prop.Name -NotePropertyValue $prop.Value -Force
949
+ $have = @($p.PSObject.Properties.Name)
950
+ }
951
+ }
952
+ }
953
+ }
954
+ # 3) 值形态转换:这几个不是"换个名字"能解决的 —— PS 要数组/枚举,TS 给的是起止行或布尔。
955
+ # 同样放入口统一做,case 体一行不动。
956
+ # (sortRange 的 ascending→order 已改到 TS 侧做:PS 的 order 收 'desc'/'asc' 字符串,
957
+ # 在这里塞数字曾经让"降序"永远落成升序 —— 第 4 轮改回 TS 发字符串。)
958
+ if (@('hideRows', 'showRows') -contains $Action -and ($have -contains 'startRow') -and -not ($have -contains 'rows')) {
959
+ # TS 的 startRow/endRow(闭区间)→ PS 的 rows 数组。
960
+ # 修之前 PS 只认 row/rows,于是 wps_excel_hide_rows / show_rows 必然报
961
+ # "row/rows required" —— 工具等于坏的(响亮失败,不算假成功,但一样不可用)。
962
+ $from = [int]$p.startRow
963
+ $to = if (($have -contains 'endRow') -and $p.endRow) { [int]$p.endRow } else { $from }
964
+ $list = @()
965
+ for ($r = $from; $r -le $to; $r++) { $list += $r }
966
+ $p | Add-Member -NotePropertyName rows -NotePropertyValue $list -Force
967
+ $have = @($p.PSObject.Properties.Name)
968
+ }
969
+ if (@('hideColumns', 'showColumns') -contains $Action -and ($have -contains 'startColumn') -and -not ($have -contains 'columns')) {
970
+ # 列号可能是数字也可能是字母;PS 只认数字,统一在这里转
971
+ $fi = 0
972
+ $ti = 0
973
+ if (-not [int]::TryParse([string]$p.startColumn, [ref]$fi)) { $fi = Convert-ColumnLetterToNumber([string]$p.startColumn) }
974
+ if (-not [int]::TryParse([string]$p.endColumn, [ref]$ti)) { $ti = Convert-ColumnLetterToNumber([string]$p.endColumn) }
975
+ $list = @()
976
+ for ($c = $fi; $c -le $ti; $c++) { $list += $c }
977
+ $p | Add-Member -NotePropertyName columns -NotePropertyValue $list -Force
978
+ $have = @($p.PSObject.Properties.Name)
979
+ }
980
+ }
981
+
982
+ # ==================== 目标钉住的前置检查(第 1 期第 3 章轮 1)====================
983
+ # 传了 documentName 就【必须】能找到,找不到直接报错并列出所有打开的文档。
984
+ #
985
+ # 为什么放在这里而不是各 case 里:
986
+ # Resolve-Doc 找不到时返回 $null,各 case 只会报 "No active document" ——
987
+ # 那句话有两个意思("没开文档" 和 "没有你要的那份"),用户没法据此改对。
988
+ # 放在入口能一次性列出候选,而且只写一处、67 个工具全覆盖。
989
+ #
990
+ # 为什么只在 word 路($script:WpsApp='word')做:
991
+ # excel/ppt 的 parameter 是 workbookName / presentationName,本轮不碰;
992
+ # 而直跑模式没有 App 信息,保持旧行为(不新增失败路径)。
993
+ if ($script:WpsApp -eq 'word' -and $null -ne $p -and $p.documentName) {
994
+ $wantDoc = [string]$p.documentName
995
+ if (-not [string]::IsNullOrWhiteSpace($wantDoc)) {
996
+ $wordProbe = Get-WpsWord
997
+ if ($null -eq $wordProbe) {
998
+ Output-Json @{ success = $false; error = "WPS Word not running" }
999
+ return
1000
+ }
1001
+ $hit = Find-DocByName $wordProbe $wantDoc
1002
+ if ($null -eq $hit) {
1003
+ $names = @()
1004
+ try {
1005
+ foreach ($d in @($wordProbe.Documents)) {
1006
+ if (Test-DocHealthy $d) { $names += [string]$d.Name }
1007
+ }
1008
+ } catch {}
1009
+ $list = if ($names.Count -gt 0) { ($names -join '、') } else { '(当前没有打开的文档)' }
1010
+ Output-Json @{
1011
+ success = $false
1012
+ error = "[勿重试·先改参数] 找不到文档「$wantDoc」(实例:$($script:WpsInstance))。当前打开的文档共有 $($names.Count) 份:$list。要改其中一份请用完整文件名;要新建请用 openDocument/createDocument。"
1013
+ }
1014
+ return
1015
+ }
1016
+ }
1017
+ }
1018
+
570
1019
  switch ($Action) {
571
1020
 
572
1021
  # ==================== Common ====================
573
1022
  "ping" {
574
1023
  Output-Json @{ success = $true; data = @{ message = "pong"; timestamp = [DateTimeOffset]::Now.ToUnixTimeMilliseconds() } }
575
1024
  }
1025
+
1026
+ # 快照工具的前置查询:文档在哪 / 有没有未保存改动 / 只读没。
1027
+ # 这里【只读】,也不像 Get-WpsExcel 那样顺手拉起应用 —— 查个状态就把 WPS 拽起来是副作用,
1028
+ # 用户会在任务管理器里看到一堆自己没开的进程。所以只用 GetActiveWpsApp(只找已运行的实例)。
1029
+ # 真正的写文件放在 Node 侧:PS 一旦碰文件系统,路径写错就是把用户文档写坏。
1030
+ "getActiveDocumentState" {
1031
+ # 以前的实现是"Excel → Word → PPT 谁先有就报谁",这在两个应用都开着时会报错人:
1032
+ # 实测过一次——用户正在 Word 里写,Excel 里还挂着一个探测残留的工作簿,
1033
+ # 结果快照把 Excel 那个工作簿当成"当前文档",复制了错的文件。
1034
+ # 现在的口径:优先用调用方指定的 app;没指定就① 跳过取不到名字的空壳(WPS 的
1035
+ # ActiveDocument 是弱引用,Count>0 时也可能给空壳)② 优先"有未保存改动"的那个
1036
+ # (那才是需要保命的)③ 还分不出来就按 excel → word → ppt。
1037
+ $want = if ($p.app) { ([string]$p.app).ToLower() } else { '' }
1038
+ $cand = @()
1039
+
1040
+ if (-not $want -or $want -eq 'excel') {
1041
+ $excel = Get-ActiveWpsApp 'Ket.Application'
1042
+ if ($null -ne $excel) {
1043
+ try {
1044
+ $book = $excel.ActiveWorkbook
1045
+ if ($null -ne $book -and -not [string]::IsNullOrEmpty([string]$book.Name)) {
1046
+ $full = ""; try { $full = [string]$book.FullName } catch {}
1047
+ # hasPath 必须用 Path 判,不能用 FullName —— 未保存的文档 FullName 也会
1048
+ # 拼出一个"默认目录\文字编号1"(文件并不存在),拿它去 copy 只会 ENOENT。
1049
+ $dir = ""; try { $dir = [string]$book.Path } catch {}
1050
+ $saved = $true; try { $saved = [bool]$book.Saved } catch {}
1051
+ $ro = $false; try { $ro = [bool]$book.ReadOnly } catch {}
1052
+ $cand += @{ app = "excel"; name = [string]$book.Name; fullName = $full; dir = $dir; saved = $saved; readOnly = $ro; hasPath = (-not [string]::IsNullOrEmpty($dir)) }
1053
+ }
1054
+ } catch {}
1055
+ }
1056
+ }
1057
+
1058
+ if (-not $want -or $want -eq 'word') {
1059
+ $word = Get-ActiveWpsApp 'Kwps.Application'
1060
+ if ($null -ne $word) {
1061
+ try {
1062
+ $doc = $word.ActiveDocument
1063
+ if ($null -ne $doc -and -not [string]::IsNullOrEmpty([string]$doc.Name)) {
1064
+ $full = ""; try { $full = [string]$doc.FullName } catch {}
1065
+ $dir = ""; try { $dir = [string]$doc.Path } catch {}
1066
+ $saved = $true; try { $saved = [bool]$doc.Saved } catch {}
1067
+ $ro = $false; try { $ro = [bool]$doc.ReadOnly } catch {}
1068
+ $cand += @{ app = "word"; name = [string]$doc.Name; fullName = $full; dir = $dir; saved = $saved; readOnly = $ro; hasPath = (-not [string]::IsNullOrEmpty($dir)) }
1069
+ }
1070
+ } catch {}
1071
+ }
1072
+ }
1073
+
1074
+ if (-not $want -or $want -eq 'ppt') {
1075
+ $ppt = Get-ActiveWpsApp 'Kwpp.Application'
1076
+ if ($null -ne $ppt) {
1077
+ try {
1078
+ $pres = $ppt.ActivePresentation
1079
+ if ($null -ne $pres -and -not [string]::IsNullOrEmpty([string]$pres.Name)) {
1080
+ $full = ""; try { $full = [string]$pres.FullName } catch {}
1081
+ $dir = ""; try { $dir = [string]$pres.Path } catch {}
1082
+ $saved = $true; try { $saved = [bool]$pres.Saved } catch {}
1083
+ $ro = $false; try { $ro = [bool]$pres.ReadOnly } catch {}
1084
+ $cand += @{ app = "ppt"; name = [string]$pres.Name; fullName = $full; dir = $dir; saved = $saved; readOnly = $ro; hasPath = (-not [string]::IsNullOrEmpty($dir)) }
1085
+ }
1086
+ } catch {}
1087
+ }
1088
+ }
1089
+
1090
+ if ($cand.Count -eq 0) {
1091
+ Output-Json @{ success = $false; error = "No active document" }
1092
+ return
1093
+ }
1094
+ # 未保存优先(那才是需要保命的),否则保持 excel → word → ppt 的稳定顺序
1095
+ $chosen = $cand[0]
1096
+ foreach ($c in $cand) { if (-not $c.saved) { $chosen = $c; break } }
1097
+ Output-Json @{ success = $true; data = $chosen }
1098
+ }
576
1099
  # 【临时诊断】列出挡路的对话框。用来验 C 项:Get-WpsModalDialogs 能不能真找到窗口。
577
1100
  "__probeStyleAdd" {
578
1101
  # 最小对比实验:探测里 styles.add 报 supported,实现里却 E_FAIL。
@@ -654,7 +1177,11 @@ switch ($Action) {
654
1177
  try { $nm = [string]$d.Name } catch {}
655
1178
  $full = ''
656
1179
  try { $full = [string]$d.FullName } catch {}
657
- $tag = "$i(nm=$nm saved=$([bool]$full))"
1180
+ # 第 5 轮:判"存过盘没有"必须看 Path。未保存文档的 FullName 非空(等于文档名),
1181
+ # 用 [bool]$full 判会把每份未保存文档都标成 saved=true —— 这个探针的输出就是在骗人。
1182
+ $dirP = ''
1183
+ try { $dirP = [string]$d.Path } catch {}
1184
+ $tag = "$i(nm=$nm saved=$(-not [string]::IsNullOrEmpty($dirP)))"
658
1185
  # 方式1:Close($false)
659
1186
  try { $d.Close($false); $r["1_CloseFalse"] += "$tag:ok "; continue } catch { $r["1_CloseFalse"] += "$tag:FAIL($($_.Exception.Message.Substring(0,[Math]::Min(40,$_.Exception.Message.Length)))) " }
660
1187
  # 方式2:先 SaveAs 到临时文件再关
@@ -699,14 +1226,17 @@ switch ($Action) {
699
1226
  $entry.count = $docs.Count
700
1227
  foreach ($d in $docs) {
701
1228
  if ($null -eq $d) { continue }
702
- $nm = ''; $full = ''; $healthy = $false
1229
+ $nm = ''; $full = ''; $dirP = ''; $healthy = $false
703
1230
  try { $nm = [string]$d.Name } catch {}
704
1231
  try { $full = [string]$d.FullName } catch {}
1232
+ try { $dirP = [string]$d.Path } catch {}
705
1233
  if ($a.key -eq "word") { $healthy = Test-DocHealthy $d }
706
1234
  else { $healthy = Test-BookHealthy $d }
707
1235
  $entry.documents += @{
708
1236
  name = $nm
709
- saved = (-not [string]::IsNullOrWhiteSpace($full))
1237
+ # 第 5 轮修:saved 必须看 Path。原来用 FullName 判 —— 未保存文档的
1238
+ # FullName 非空(等于文档名),于是每份没存过的文档都报 saved=true。
1239
+ saved = (-not [string]::IsNullOrWhiteSpace($dirP))
710
1240
  healthy = $healthy
711
1241
  }
712
1242
  # 只关"无名"文档:没有标题也没有路径 —— 那是自动化残留的空壳。
@@ -715,6 +1245,10 @@ switch ($Action) {
715
1245
  # (RPC_E_CALL_REJECTED),而 $app.Documents.Close($false) 一次成功
716
1246
  # (countBefore=2 → countAfter=0)。这是 WPS 12.1 的实际行为。
717
1247
  # 真正执行在下面循环结束后统一做(先收集,再一次关)。
1248
+ # 第 5 轮备注(刻意不改判据):这里的 $full 仍是 FullName,而 Name 永远非空,
1249
+ # 所以本分支实际上【不会触发】—— 也就是 repair 从不自动关文档。
1250
+ # 这是偏安全的一侧:改成"没有 Path 就算空壳"会去关用户没存盘的活文档,
1251
+ # 那是比"少关几个空壳"严重得多的事故。要真修,得先定义"空壳"的可靠特征。
718
1252
  if ([string]::IsNullOrWhiteSpace($nm) -and [string]::IsNullOrWhiteSpace($full)) {
719
1253
  $unnamed += $a.key
720
1254
  }
@@ -810,6 +1344,31 @@ switch ($Action) {
810
1344
 
811
1345
  # 让 WPS 可见并置于前台:① 激活已有窗口 ② 唤起 COM 实例 ③ 兜底启动可见实例
812
1346
  "showWps" {
1347
+ # 沙箱实例:只激活【自己那一个】。
1348
+ # 原来会遍历 ROT + 全部同名进程去找窗口,多实例时不知道该激活谁,
1349
+ # 而且会把用户那份也拉到前台(看着像"我明明只要看沙箱")。
1350
+ if (Test-SandboxInstance) {
1351
+ $app = $script:SandboxWordApp
1352
+ if ($null -eq $app) {
1353
+ Output-Json @{
1354
+ success = $false
1355
+ error = "沙箱实例「$($script:WpsInstance)」还没创建。先调一个带 target.instance 的动作,它会被自动拉起。"
1356
+ }
1357
+ return
1358
+ }
1359
+ try { $app.Visible = $true } catch {}
1360
+ try { $app.Activate() } catch {}
1361
+ Output-Json @{
1362
+ success = $true
1363
+ data = @{
1364
+ instance = $script:WpsInstance
1365
+ visible = $true
1366
+ note = '只激活本沙箱实例,未遍历其他 WPS 进程'
1367
+ }
1368
+ }
1369
+ return
1370
+ }
1371
+
813
1372
  $apps = @()
814
1373
  $visible = 0
815
1374
  $activated = 0
@@ -860,30 +1419,113 @@ switch ($Action) {
860
1419
  Output-Json @{ success = $true; data = @{ apps = $apps; visible = $visible; activated = $activated; foreground = $front; launched = $launched; message = $msg } }
861
1420
  }
862
1421
 
863
- # 结束 WPS(含强制兜底)
1422
+ # 结束 WPS(优雅退出;未保存内容默认拒绝,不做全量杀进程)
864
1423
  "quitWps" {
1424
+ # 沙箱实例:只退【我们自己创建的那一个】,绝不 taskkill /IM 全杀。
1425
+ # 原来那条兜底 `taskkill /F /IM wps.exe /T` 是多实例的头号杀手 ——
1426
+ # 一退就把用户正开着的那份一起杀了,而且看起来"退出成功"。
1427
+ if (Test-SandboxInstance) {
1428
+ $app = $script:SandboxWordApp
1429
+ $killed = @()
1430
+ if ($null -ne $app) {
1431
+ try { $app.DisplayAlerts = 0 } catch {} # 吞错有据:抑制弹窗失败不影响退出,残留由 PID 收尾兜底
1432
+ # 第 2 期第 2 章轮 2 真机实测:沙箱里有未保存文档时,$app.Quit() 会卡在
1433
+ # 「是否保存」对话框上(无人值守 = 挂死,实测 300 秒超时,而且桥会因此
1434
+ # 杀掉整个 word 子进程)。沙箱里的文档本来就是可丢的,先逐个标 Saved 再关。
1435
+ try {
1436
+ for ($di = $app.Documents.Count; $di -ge 1; $di--) {
1437
+ try {
1438
+ $dd = $app.Documents.Item($di)
1439
+ $dd.Saved = $true
1440
+ $dd.Close(0) # wdDoNotSaveChanges
1441
+ } catch {} # 吞错有据:沙箱文档关闭失败由下方 Stop-Process 按 PID 兜底
1442
+ }
1443
+ } catch {} # 吞错有据:同上,PID 收尾兜底
1444
+ try { $app.Quit() } catch {} # 吞错有据:同上,PID 收尾兜底
1445
+ }
1446
+ Start-Sleep -Milliseconds 700
1447
+ # 按创建时记下的 PID 收尸:Quit 之后 WPS 常常还留着几个进程(DECISION §2 实测)
1448
+ foreach ($procId in @($script:SandboxWordPids)) {
1449
+ try {
1450
+ $proc = Get-Process -Id $procId -ErrorAction SilentlyContinue
1451
+ if ($proc) {
1452
+ # 只杀这一个 PID,且不用 /T(避免连带子进程里别人的东西)
1453
+ Stop-Process -Id $procId -Force -ErrorAction SilentlyContinue
1454
+ $killed += $procId
1455
+ }
1456
+ } catch {} # 吞错有据:收尸失败不计入 killed,结果如实反映
1457
+ }
1458
+ $script:SandboxWordApp = $null
1459
+ $script:SandboxWordPids = @()
1460
+ Output-Json @{
1461
+ success = $true
1462
+ data = @{
1463
+ quit = @('sandbox')
1464
+ instance = $script:WpsInstance
1465
+ killedPids = $killed
1466
+ userUntouched = $true
1467
+ }
1468
+ }
1469
+ return
1470
+ }
1471
+
1472
+ # 先数未保存的文档:直接 Quit 会因 DisplayAlerts=0 把未保存改动静默丢掉,
1473
+ # 而这里退出影响的是用户开着的全部 WPS —— 所以未保存时默认拒绝,confirm=true 才放行。
1474
+ $unsaved = @()
1475
+ $guardSkipped = @()
1476
+ foreach ($progId in @('Kwps.Application','Ket.Application','Kwpp.Application')) {
1477
+ $app = Get-ActiveWpsApp $progId
1478
+ if ($null -eq $app) { continue }
1479
+ $kind = switch ($progId) { 'Kwps.Application' { '文档' } 'Ket.Application' { '工作簿' } default { '演示文稿' } }
1480
+ $coll = $null
1481
+ try { $coll = $app.Documents } catch { $guardSkipped += "$kind 枚举失败:$($_.Exception.Message)" }
1482
+ if (-not $coll) { try { $coll = $app.Workbooks } catch { $guardSkipped += "$kind 枚举失败:$($_.Exception.Message)" } }
1483
+ if (-not $coll) { try { $coll = $app.Presentations } catch { $guardSkipped += "$kind 枚举失败:$($_.Exception.Message)" } }
1484
+ if ($null -eq $coll) { $guardSkipped += "$kind 集合不可读,该应用的未保存检查跳过"; continue }
1485
+ foreach ($item in $coll) {
1486
+ # 读不到 Saved 按"未保存"处理(保守方向):宁可护栏多拦一次,不可漏拦
1487
+ $saved = $false
1488
+ try { $saved = [bool]$item.Saved } catch { $guardSkipped += "$kind 文档 Saved 状态不可读,按未保存计入" }
1489
+ if (-not $saved) {
1490
+ $name = ''
1491
+ try { $name = $item.Name } catch {}
1492
+ $unsaved += "「$name」($kind)"
1493
+ }
1494
+ }
1495
+ }
1496
+ if ($unsaved.Count -gt 0 -and $p.confirm -ne $true) {
1497
+ Output-Json @{ success = $false; error = "[勿重试·先保存] 退出会丢弃这些未保存内容:$($unsaved -join '、')。确认要放弃就传 confirm=true;想保住先 wps_common_save。" }
1498
+ return
1499
+ }
1500
+
865
1501
  $quit = @()
866
1502
  foreach ($progId in @('Kwps.Application','Ket.Application','Kwpp.Application')) {
867
1503
  $app = Get-ActiveWpsApp $progId
868
1504
  if ($null -ne $app) {
869
- try { $app.DisplayAlerts = 0 } catch {}
870
- try { $app.Quit() } catch {}
871
- $quit += $progId
1505
+ try { $app.DisplayAlerts = 0 } catch { $guardSkipped += "$progId 抑制弹窗失败:$($_.Exception.Message)" }
1506
+ # 只有 Quit 真正成功才计入"优雅退出",失败如实进 guardSkipped
1507
+ try { $app.Quit(); $quit += $progId } catch { $guardSkipped += "$progId 优雅退出失败:$($_.Exception.Message)" }
872
1508
  }
873
1509
  }
874
1510
  Start-Sleep -Milliseconds 900
875
- $remainBefore = @(Get-Process -Name wps -ErrorAction SilentlyContinue).Count
876
- $forced = $false
877
- # 兜底:Quit 未清干净则强制结束残留进程(force 默认 true,传 force=false 只走优雅退出)
878
- if ($remainBefore -gt 0 -and $p.force -ne $false) {
879
- try { $null = & taskkill /F /IM wps.exe /T 2>&1 } catch {}
880
- try { $null = & taskkill /F /IM wpscloudsvr.exe /T 2>&1 } catch {}
881
- $forced = $true
1511
+ # 本进程自己创建过的实例(user 记账 + 沙箱)按 PID 直接收掉 —— 这些是我们的,
1512
+ # 不受未保存护栏约束(护栏只保护 ROT 附着的用户实例)。任务结束/异常都能杀。
1513
+ $ownKilled = (Remove-OwnCreatedProcs) + (Remove-OwnSandboxProcs)
1514
+ # 不做全量 taskkill:Quit 之后的残留多半是用户自己开的其它 WPS 实例
1515
+ # (ROT 每个 ProgID 只能激活一个,COM 够不着的那几个 /IM 一杀就误杀)。
1516
+ # 列出剩余进程交给用户决定,wpscloudsvr 是 WPS 自己的云服务,从来不该杀。
1517
+ $leftovers = @(Get-Process -Name wps -ErrorAction SilentlyContinue)
1518
+ # remaining 只数"有窗口的实例":用户关心的是"还有没有 WPS 窗口没关",
1519
+ # wpscloudsvr / 无窗口组件是 WPS 的服务进程,算进去会让"明明退干净了"报成残留。
1520
+ $leftVisible = @($leftovers | Where-Object { $_.MainWindowHandle -ne 0 })
1521
+ $leftBackground = @($leftovers | Where-Object { $_.MainWindowHandle -eq 0 })
1522
+ $left = $leftVisible.Count
1523
+ $msg = if ($left -eq 0) {
1524
+ "WPS 已退出" + $(if ($leftBackground.Count) { "(另有 $($leftBackground.Count) 个无窗口服务进程由 WPS 自管,不影响使用)" } else { '' })
1525
+ } else {
1526
+ "本会话连接的 WPS 已退出;另有 $left 个有窗口的 WPS 实例在运行(多为用户自己打开的,未强行关闭)"
882
1527
  }
883
- Start-Sleep -Milliseconds 700
884
- $left = @(Get-Process -Name wps -ErrorAction SilentlyContinue).Count
885
- $msg = if ($left -eq 0) { "WPS 已退出" } else { "仍有 $left 个 WPS 进程残留" }
886
- Output-Json @{ success = $true; data = @{ quit = $quit; forced = $forced; remaining = $left; message = $msg } }
1528
+ Output-Json @{ success = $true; data = @{ quit = $quit; forced = $false; ownKilled = $ownKilled; remaining = $left; remainingBackground = $leftBackground.Count; leftovers = @($leftovers | ForEach-Object { @{ pid = $_.Id; title = $_.MainWindowTitle } }); message = $msg } }
887
1529
  }
888
1530
 
889
1531
  "wireCheck" {
@@ -916,6 +1558,16 @@ switch ($Action) {
916
1558
  }
917
1559
 
918
1560
  "getSelectedText" {
1561
+ # 第 1 期第 3 章轮 1:选区是【全局焦点】,钉不住。
1562
+ # 带 target 或沙箱实例时显式拒绝 —— 宁可报错,也不许静默读到别人那份的选区。
1563
+ if (Test-SandboxInstance) {
1564
+ Output-Json @{ success = $false; error = "[勿重试·先改参数] 选区(Selection)依赖全局焦点,沙箱实例里钉不住。要在沙箱里取文本,请用 getDocumentText / getParagraphs 这类按文档寻址的动作。" }
1565
+ return
1566
+ }
1567
+ if ($null -ne $p -and $p.target) {
1568
+ Output-Json @{ success = $false; error = "[勿重试·先改参数] 带 target 的会话里不能用选区类动作:用户切一下焦点,读到的就是另一份文档的选区。请改用按文档寻址的动作(getDocumentText / getParagraphs)。" }
1569
+ return
1570
+ }
919
1571
  $word = Get-WpsWord
920
1572
  if ($null -ne $word) {
921
1573
  try {
@@ -956,6 +1608,15 @@ switch ($Action) {
956
1608
  }
957
1609
 
958
1610
  "setSelectedText" {
1611
+ # 同 getSelectedText:写选区比读更危险(会改到用户当前光标处的文档)
1612
+ if (Test-SandboxInstance) {
1613
+ Output-Json @{ success = $false; error = "[勿重试·先改参数] 写选区依赖全局焦点,沙箱实例里钉不住。要在沙箱里写文本,请用 insertText / setRangeText 这类按文档寻址的动作。" }
1614
+ return
1615
+ }
1616
+ if ($null -ne $p -and $p.target) {
1617
+ Output-Json @{ success = $false; error = "[勿重试·先改参数] 带 target 的会话里不能用选区类动作:焦点一换就写到别的文档里去了。请改用 insertText(可带 documentName)。" }
1618
+ return
1619
+ }
959
1620
  $text = if ($null -ne $p.text) { [string]$p.text } else { "" }
960
1621
  $word = Get-WpsWord
961
1622
  if ($null -ne $word) {
@@ -1022,31 +1683,57 @@ switch ($Action) {
1022
1683
  $path = $p.path
1023
1684
  if (-not $path) { Output-Json @{ success = $false; error = "Path required" }; return }
1024
1685
  $appType = if ($p.appType) { $p.appType } else { Get-AppTypeByExtension $path }
1686
+
1687
+ # 第 5 轮:保存之后【读回真实路径】,而不是把自己传进去的 $path 原样回显。
1688
+ # 为什么必须读回:SaveAs 可能被 WPS 改写落点(格式不符自动换扩展名、路径被规范化、
1689
+ # 同名已存在时弹选择框)。回显 $path 等于替 WPS 担保"你给的路径就是落点"。
1690
+ # 判据用 .Path(不是 .FullName —— 未保存文档的 FullName 就等于文档名,永远非空)。
1691
+ # WPS 保存后 .Path 有极短延迟,读到空就退回用户给的路径并标 verified=false,
1692
+ # 让调用方知道"这次没核实成功",而不是假装核实了。
1693
+ $resolveSavedPath = {
1694
+ param($obj, $requested)
1695
+ $actual = ''
1696
+ try { $actual = [string]$obj.Path } catch {} # 吞错有据:读不到按未验证处理,下游 verified=false 如实上报
1697
+ if ([string]::IsNullOrEmpty($actual)) {
1698
+ return @{ path = $requested; requestedPath = $requested; verified = $false
1699
+ note = "保存后没读到文档路径(可能是 WPS 有延迟),按你给的路径回报;落盘前请自行确认" }
1700
+ }
1701
+ $same = $false
1702
+ try { $same = ([IO.Path]::GetFullPath($actual) -ieq [IO.Path]::GetFullPath($requested)) } catch {} # 吞错有据:比较失败按未验证处理,不静默判成一致
1703
+ return @{ path = $actual; requestedPath = $requested; verified = $same }
1704
+ }
1705
+
1025
1706
  if ($appType -eq 'excel') {
1026
1707
  $excel = Get-WpsExcel
1027
- if ($null -eq $excel -or $null -eq $(Resolve-Book $excel $p)) { Output-Json @{ success = $false; error = "No active workbook" }; return }
1708
+ $wb = $(Resolve-Book $excel $p)
1709
+ if ($null -eq $excel -or $null -eq $wb) { Output-Json @{ success = $false; error = "No active workbook" }; return }
1028
1710
  $format = Get-ExcelFileFormat $p.format
1029
- if ($null -ne $format) { $(Resolve-Book $excel $p).SaveAs($path, $format) }
1030
- else { $(Resolve-Book $excel $p).SaveAs($path) }
1031
- Output-Json @{ success = $true; data = @{ path = $path; appType = "excel" } }
1711
+ if ($null -ne $format) { $wb.SaveAs($path, $format) }
1712
+ else { $wb.SaveAs($path) }
1713
+ $r = & $resolveSavedPath $wb $path
1714
+ Output-Json @{ success = $true; data = @{ path = $r.path; requestedPath = $r.requestedPath; verified = $r.verified; note = $r.note; appType = "excel" } }
1032
1715
  return
1033
1716
  }
1034
1717
  if ($appType -eq 'word') {
1035
1718
  $word = Get-WpsWord
1036
- if ($null -eq $word -or $null -eq $(Resolve-Doc $word $p)) { Output-Json @{ success = $false; error = "No active document" }; return }
1719
+ $docItem = $(Resolve-Doc $word $p)
1720
+ if ($null -eq $word -or $null -eq $docItem) { Output-Json @{ success = $false; error = "No active document" }; return }
1037
1721
  $format = Get-WordSaveFormat $p.format
1038
- if ($null -ne $format) { $(Resolve-Doc $word $p).SaveAs($path, $format) }
1039
- else { $(Resolve-Doc $word $p).SaveAs($path) }
1040
- Output-Json @{ success = $true; data = @{ path = $path; appType = "word" } }
1722
+ if ($null -ne $format) { $docItem.SaveAs($path, $format) }
1723
+ else { $docItem.SaveAs($path) }
1724
+ $r = & $resolveSavedPath $docItem $path
1725
+ Output-Json @{ success = $true; data = @{ path = $r.path; requestedPath = $r.requestedPath; verified = $r.verified; note = $r.note; appType = "word" } }
1041
1726
  return
1042
1727
  }
1043
1728
  if ($appType -eq 'ppt') {
1044
1729
  $ppt = Get-WpsPpt
1045
1730
  if ($null -eq $ppt -or $null -eq $ppt.ActivePresentation) { Output-Json @{ success = $false; error = "No active presentation" }; return }
1731
+ $pres = $ppt.ActivePresentation
1046
1732
  $format = Get-PptSaveFormat $p.format
1047
- if ($null -ne $format) { $ppt.ActivePresentation.SaveAs($path, $format) }
1048
- else { $ppt.ActivePresentation.SaveAs($path) }
1049
- Output-Json @{ success = $true; data = @{ path = $path; appType = "ppt" } }
1733
+ if ($null -ne $format) { $pres.SaveAs($path, $format) }
1734
+ else { $pres.SaveAs($path) }
1735
+ $r = & $resolveSavedPath $pres $path
1736
+ Output-Json @{ success = $true; data = @{ path = $r.path; requestedPath = $r.requestedPath; verified = $r.verified; note = $r.note; appType = "ppt" } }
1050
1737
  return
1051
1738
  }
1052
1739
  Output-Json @{ success = $false; error = "Unknown app type" }
@@ -1122,8 +1809,12 @@ switch ($Action) {
1122
1809
  "createPresentation" {
1123
1810
  $ppt = Get-WpsPpt
1124
1811
  if ($null -eq $ppt) { Output-Json @{ success = $false; error = "WPS PPT not running" }; return }
1125
- $ppt.Presentations.Add() | Out-Null
1126
- Output-Json @{ success = $true }
1812
+ $pres = $ppt.Presentations.Add()
1813
+ # 必须回 data:Node 侧的 handler 判的是 success && data,
1814
+ # 只回 success 会被当成失败("新建演示文稿失败: undefined" —— 实测踩过)
1815
+ $nm = ""
1816
+ try { $nm = [string]$pres.Name } catch {}
1817
+ Output-Json @{ success = $true; data = @{ name = $nm; count = $ppt.Presentations.Count } }
1127
1818
  }
1128
1819
 
1129
1820
  "convertToPDF" {
@@ -1133,7 +1824,8 @@ switch ($Action) {
1133
1824
  $sourcePath = $wb.FullName
1134
1825
  $outputPath = if ($p.outputPath) { $p.outputPath } else { [System.IO.Path]::ChangeExtension($sourcePath, 'pdf') }
1135
1826
  $wb.ExportAsFixedFormat(0, $outputPath)
1136
- Output-Json @{ success = $true; data = @{ sourcePath = $sourcePath; outputPath = $outputPath; appType = "excel" } }
1827
+ Open-Exported $outputPath $p.openAfterExport
1828
+ Output-Json @{ success = $true; data = @{ sourcePath = $sourcePath; outputPath = $outputPath; appType = "excel"; opened = [bool]$p.openAfterExport } }
1137
1829
  return
1138
1830
  }
1139
1831
  $word = Get-WpsWord
@@ -1142,7 +1834,8 @@ switch ($Action) {
1142
1834
  $sourcePath = $doc.FullName
1143
1835
  $outputPath = if ($p.outputPath) { $p.outputPath } else { [System.IO.Path]::ChangeExtension($sourcePath, 'pdf') }
1144
1836
  $doc.ExportAsFixedFormat($outputPath, 17)
1145
- Output-Json @{ success = $true; data = @{ sourcePath = $sourcePath; outputPath = $outputPath; appType = "word" } }
1837
+ Open-Exported $outputPath $p.openAfterExport
1838
+ Output-Json @{ success = $true; data = @{ sourcePath = $sourcePath; outputPath = $outputPath; appType = "word"; opened = [bool]$p.openAfterExport } }
1146
1839
  return
1147
1840
  }
1148
1841
  $ppt = Get-WpsPpt
@@ -1151,7 +1844,8 @@ switch ($Action) {
1151
1844
  $sourcePath = $pres.FullName
1152
1845
  $outputPath = if ($p.outputPath) { $p.outputPath } else { [System.IO.Path]::ChangeExtension($sourcePath, 'pdf') }
1153
1846
  $pres.SaveAs($outputPath, 32)
1154
- Output-Json @{ success = $true; data = @{ sourcePath = $sourcePath; outputPath = $outputPath; appType = "ppt" } }
1847
+ Open-Exported $outputPath $p.openAfterExport
1848
+ Output-Json @{ success = $true; data = @{ sourcePath = $sourcePath; outputPath = $outputPath; appType = "ppt"; opened = [bool]$p.openAfterExport } }
1155
1849
  return
1156
1850
  }
1157
1851
  Output-Json @{ success = $false; error = "No active document" }
@@ -1219,7 +1913,23 @@ switch ($Action) {
1219
1913
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
1220
1914
  $wb = $(Resolve-Book $excel $p)
1221
1915
  $sheet = if ($p.sheet -is [int]) { $wb.Sheets.Item($p.sheet) } else { $wb.Sheets.Item($p.sheet) }
1222
- $sheet.Cells.Item($p.row, $p.col).Value2 = $p.value
1916
+ # 第 1 期第 2 章第 4 轮(B1):与 setRangeData 同一个雷 —— 原样 `.Value2 = $p.value`
1917
+ # 在 daemon 里会抛 "无法将类型为 System.Int32 的对象强制转换为类型 System.String"。
1918
+ # 同一个分派:数字写数字、文本按文本格式写(保住 "007" 这类形状)、布尔写布尔、null 清空。
1919
+ $cell = $sheet.Cells.Item($p.row, $p.col)
1920
+ $v = $p.value
1921
+ if ($null -eq $v) {
1922
+ $cell.ClearContents()
1923
+ } elseif ($v -is [bool]) {
1924
+ $cell.NumberFormat = 'General'
1925
+ $cell.Value2 = [bool]$v
1926
+ } elseif ($v -is [int] -or $v -is [long] -or $v -is [double] -or $v -is [decimal]) {
1927
+ $cell.NumberFormat = 'General'
1928
+ $cell.Value2 = [double]$v
1929
+ } else {
1930
+ $cell.NumberFormat = '@'
1931
+ $cell.Value2 = [string]$v
1932
+ }
1223
1933
  Output-Json @{ success = $true }
1224
1934
  }
1225
1935
 
@@ -1241,11 +1951,40 @@ switch ($Action) {
1241
1951
  "setRangeData" {
1242
1952
  $excel = Get-WpsExcel
1243
1953
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
1244
- $wb = $(Resolve-Book $excel $p)
1245
- $sheet = if ($p.sheet -is [int]) { $wb.Sheets.Item($p.sheet) } else { $wb.Sheets.Item($p.sheet) }
1954
+ # 第 1 期第 2 章第 2 轮:两句分支完全相同 + 没给 sheet 时 Sheets.Item($null) 会抛。
1955
+ # wps_excel_evaluate_formula 的"写回单元格"要复用这个动作(它没有 sheet 参数),所以先修这层。
1956
+ $sheet = $(Resolve-Sheet $excel $p)
1957
+ if ($null -eq $sheet) { Output-Json @{ success = $false; error = "No active sheet" }; return }
1246
1958
  $range = $sheet.Range($p.range)
1247
1959
  for ($r = 0; $r -lt $p.data.Count; $r++) {
1248
- for ($c = 0; $c -lt $p.data[$r].Count; $c++) { $range.Cells.Item($r + 1, $c + 1).Value2 = $p.data[$r][$c] }
1960
+ for ($c = 0; $c -lt $p.data[$r].Count; $c++) {
1961
+ $cell = $range.Cells.Item($r + 1, $c + 1)
1962
+ $v = $p.data[$r][$c]
1963
+ # 第 1 期第 2 章第 4 轮(B1):写数字必失败,报
1964
+ # "无法将类型为 System.Int32 的对象强制转换为类型 System.String"
1965
+ # 根因不是"值是数字",是【值的来源】:daemon 里 $p 来自 ConvertFrom-Json,
1966
+ # 取出来的元素是 PSObject 包着的,COM 绑定器接不住这种包装,
1967
+ # 于是退回去按 String 转换 → 数字转不过去就抛。
1968
+ # 实测(daemon 内,52 组对照):原样赋值 Int32 过、Double 抛、String 抛;
1969
+ # 而【显式强转】过的值四种全过 —— 强转产出的是"裸" .NET 值,绑定器认。
1970
+ # 但直接 [string] 化会毁掉形状:"007" 变 7、"2024-01-15" 变日期序列号 45306。
1971
+ # 所以按类型分派:
1972
+ # 数字 → 先把单元格格式设回常规再写数字(WPS 存成数值,=SUM() 能算)
1973
+ # 文本 → 先设成文本格式('@')再写,"007"/"1e5"/日期串原样保住
1974
+ # 布尔 → 写成真正的布尔单元格
1975
+ # null → 清空
1976
+ if ($null -eq $v) { $cell.ClearContents(); continue }
1977
+ if ($v -is [bool]) {
1978
+ $cell.NumberFormat = 'General'
1979
+ $cell.Value2 = [bool]$v
1980
+ } elseif ($v -is [int] -or $v -is [long] -or $v -is [double] -or $v -is [decimal]) {
1981
+ $cell.NumberFormat = 'General'
1982
+ $cell.Value2 = [double]$v
1983
+ } else {
1984
+ $cell.NumberFormat = '@'
1985
+ $cell.Value2 = [string]$v
1986
+ }
1987
+ }
1249
1988
  }
1250
1989
  Output-Json @{ success = $true }
1251
1990
  }
@@ -1255,7 +1994,7 @@ switch ($Action) {
1255
1994
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
1256
1995
  $wb = $(Resolve-Book $excel $p)
1257
1996
  if ($null -eq $wb) { Output-Json @{ success = $false; error = "No active workbook" }; return }
1258
- $sheet = $excel.ActiveSheet
1997
+ $sheet = $(Resolve-Sheet $excel $p)
1259
1998
  $cell = $sheet.Range($p.cell)
1260
1999
  $value = $cell.Value2
1261
2000
  $formula = $cell.Formula
@@ -1382,7 +2121,7 @@ switch ($Action) {
1382
2121
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
1383
2122
  $wb = $(Resolve-Book $excel $p)
1384
2123
  if ($null -eq $wb) { Output-Json @{ success = $false; error = "No active workbook" }; return }
1385
- $sheet = $excel.ActiveSheet
2124
+ $sheet = $(Resolve-Sheet $excel $p)
1386
2125
  $table = $null
1387
2126
  if ($p.pivotTableName) {
1388
2127
  try { $table = $sheet.PivotTables($p.pivotTableName) } catch {}
@@ -1461,17 +2200,86 @@ switch ($Action) {
1461
2200
  "setFormula" {
1462
2201
  $excel = Get-WpsExcel
1463
2202
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
1464
- $wb = $(Resolve-Book $excel $p)
1465
- $sheet = if ($p.sheet -is [int]) { $wb.Sheets.Item($p.sheet) } else { $wb.Sheets.Item($p.sheet) }
1466
- $range = if ($p.range) { $sheet.Range($p.range) } else { $sheet.Cells.Item($p.row, $p.col) }
1467
- $range.Formula = $p.formula
1468
- Output-Json @{ success = $true }
2203
+ # 第 1 期第 2 章第 2 轮:原来两句分支完全相同(`if ($p.sheet -is [int])` 两边都写
2204
+ # `$wb.Sheets.Item($p.sheet)`),而且没给 sheet 时是 `Sheets.Item($null)` —— 会抛。
2205
+ # wps_excel_auto_sum 要映射到这个动作(它没有 sheet 参数),所以必须先修好这层解析。
2206
+ $sheet = $(Resolve-Sheet $excel $p)
2207
+ if ($null -eq $sheet) { Output-Json @{ success = $false; error = "No active sheet" }; return }
2208
+ $formula = [string]$p.formula
2209
+ if (-not $formula) {
2210
+ Output-Json @{ success = $false; error = "[勿重试·先改参数] 要给 formula(如 =SUM(A1:A10))" }
2211
+ return
2212
+ }
2213
+ $range = if ($p.range) { $sheet.Range([string]$p.range) } elseif ($p.row -and $p.col) { $sheet.Cells.Item($p.row, $p.col) } else { $null }
2214
+ if ($null -eq $range) {
2215
+ Output-Json @{ success = $false; error = "[勿重试·先改参数] 要给 range(如 A11)或 row+col" }
2216
+ return
2217
+ }
2218
+ $range.Formula = $formula
2219
+ # 读回:公式写进去之后单元格的【值】是多少。写公式不等于算出了数
2220
+ # (引用空区域会得 0,引用坏区域会得 #REF!),把值一起回给调用方才算诚实。
2221
+ $value = $null
2222
+ try { $value = $range.Value2 } catch {}
2223
+ Output-Json @{ success = $true; data = @{ range = [string]$p.range; formula = $formula; value = $value } }
2224
+ }
2225
+
2226
+ # 第 1 期第 2 章第 2 轮新增:wps_excel_evaluate_formula 一直调 evaluateFormula,
2227
+ # 而 ps1 里没有这个 case → 每次都是 Unknown action(这工具从上线起就没成功过)。
2228
+ # 能力就是 Excel 的 Application.Evaluate:只算不写;给了 cell 才把结果落格。
2229
+ # 与 setFormula 的分工:setFormula 是【把公式写进单元格(落盘)】,本动作是【算一个值出来(不落盘)】。
2230
+ "evaluateFormula" {
2231
+ $excel = Get-WpsExcel
2232
+ if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2233
+ $formula = [string]$p.formula
2234
+ if (-not $formula) {
2235
+ Output-Json @{ success = $false; error = "[勿重试·先改参数] 要给 formula(如 =SUM(A1:A10) 或 1+2)" }
2236
+ return
2237
+ }
2238
+ if (-not $formula.StartsWith('=')) { $formula = '=' + $formula }
2239
+ $result = $null
2240
+ try { $result = $excel.Evaluate($formula) } catch {
2241
+ Output-Json @{ success = $false; error = "[勿重试·先改参数] 公式无法计算:$($formula)。$($_.Exception.Message)" }
2242
+ return
2243
+ }
2244
+ if ($null -eq $result) {
2245
+ Output-Json @{ success = $false; error = "[勿重试·先改参数] 公式 $formula 没有返回值(语法错或引用了不存在的区域)" }
2246
+ return
2247
+ }
2248
+ # 【只算不写】—— 这里刻意不落盘。
2249
+ # 为什么:cancellable.ts:67 把 evaluateFormula 归在 READ_ONLY_EXTRA 里(客户端会据此
2250
+ # 跳过写操作确认)。一个"被声明为只读"的动作如果偷偷写单元格,就是安全语义矛盾。
2251
+ # 要落盘由 TS 侧再发一次 setRangeData(写入动作,注解本身是写入型),职责分开。
2252
+ Output-Json @{ success = $true; data = @{ formula = $formula; result = $result } }
2253
+ }
2254
+
2255
+ # 第 1 期第 2 章第 2 轮新增:wps_excel_set_zoom 一直调 setZoom,ps1 里没有 → Unknown action。
2256
+ # 这是【窗口缩放】(ActiveWindow.Zoom,10-400),不是【打印缩放】(PageSetup.Zoom)——
2257
+ # ps1 里 2706 行那个 $ps.Zoom 是 PageSetup 的,属于打印设置,两回事。
2258
+ "setZoom" {
2259
+ $excel = Get-WpsExcel
2260
+ if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2261
+ $pct = 0
2262
+ if (-not [int]::TryParse([string]$p.percent, [ref]$pct)) {
2263
+ Output-Json @{ success = $false; error = "[勿重试·先改参数] percent 必须是整数(收到「$($p.percent)」)" }
2264
+ return
2265
+ }
2266
+ if ($pct -lt 10 -or $pct -gt 400) {
2267
+ Output-Json @{ success = $false; error = "[勿重试·先改参数] 缩放比例必须在 10-400 之间(收到 $pct)" }
2268
+ return
2269
+ }
2270
+ $win = $excel.ActiveWindow
2271
+ if ($null -eq $win) { Output-Json @{ success = $false; error = "没有活动窗口(工作簿可能未激活)" }; return }
2272
+ $win.Zoom = $pct
2273
+ # 读回真实值:WPS 可能夹取到自己的范围,回包要说"现在到底是多少"
2274
+ $actual = $null
2275
+ try { $actual = $win.Zoom } catch {}
2276
+ Output-Json @{ success = $true; data = @{ zoom = $actual; requested = $pct } }
1469
2277
  }
1470
2278
 
1471
2279
  "setCellFormat" {
1472
2280
  $excel = Get-WpsExcel
1473
2281
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
1474
- $sheet = $excel.ActiveSheet
2282
+ $sheet = $(Resolve-Sheet $excel $p)
1475
2283
  $range = $sheet.Range($p.range)
1476
2284
  if ($p.numberFormat) { $range.NumberFormat = $p.numberFormat }
1477
2285
  Output-Json @{ success = $true; data = @{ range = $p.range; format = $p.numberFormat } }
@@ -1480,7 +2288,7 @@ switch ($Action) {
1480
2288
  "setCellStyle" {
1481
2289
  $excel = Get-WpsExcel
1482
2290
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
1483
- $sheet = $excel.ActiveSheet
2291
+ $sheet = $(Resolve-Sheet $excel $p)
1484
2292
  $range = $sheet.Range($p.range)
1485
2293
  if ($p.fontSize) { $range.Font.Size = $p.fontSize }
1486
2294
  if ($null -ne $p.bold) { $range.Font.Bold = [bool]$p.bold }
@@ -1517,7 +2325,7 @@ switch ($Action) {
1517
2325
  "setBorder" {
1518
2326
  $excel = Get-WpsExcel
1519
2327
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
1520
- $sheet = $excel.ActiveSheet
2328
+ $sheet = $(Resolve-Sheet $excel $p)
1521
2329
  $range = $sheet.Range($p.range)
1522
2330
  $styleMap = @{ thin = 1; medium = 2; thick = 4; double = 6; none = 0 }
1523
2331
  $style = $styleMap[$p.style]
@@ -1548,7 +2356,7 @@ switch ($Action) {
1548
2356
  "copyFormat" {
1549
2357
  $excel = Get-WpsExcel
1550
2358
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
1551
- $sheet = $excel.ActiveSheet
2359
+ $sheet = $(Resolve-Sheet $excel $p)
1552
2360
  $sourceRange = $sheet.Range($p.source)
1553
2361
  $targetRange = $sheet.Range($p.target)
1554
2362
  $sourceRange.Copy()
@@ -1560,7 +2368,7 @@ switch ($Action) {
1560
2368
  "clearFormats" {
1561
2369
  $excel = Get-WpsExcel
1562
2370
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
1563
- $sheet = $excel.ActiveSheet
2371
+ $sheet = $(Resolve-Sheet $excel $p)
1564
2372
  $range = $sheet.Range($p.range)
1565
2373
  $range.ClearFormats()
1566
2374
  Output-Json @{ success = $true; data = @{ range = $p.range } }
@@ -1569,7 +2377,7 @@ switch ($Action) {
1569
2377
  "addConditionalFormat" {
1570
2378
  $excel = Get-WpsExcel
1571
2379
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
1572
- $sheet = $excel.ActiveSheet
2380
+ $sheet = $(Resolve-Sheet $excel $p)
1573
2381
  $range = $sheet.Range($p.range)
1574
2382
  $formatType = if ($p.type) { $p.type } else { "cellValue" }
1575
2383
  if ($formatType -eq "cellValue") {
@@ -1599,7 +2407,7 @@ switch ($Action) {
1599
2407
  "removeConditionalFormat" {
1600
2408
  $excel = Get-WpsExcel
1601
2409
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
1602
- $sheet = $excel.ActiveSheet
2410
+ $sheet = $(Resolve-Sheet $excel $p)
1603
2411
  $range = $sheet.Range($p.range)
1604
2412
  if ($p.index) {
1605
2413
  $range.FormatConditions.Item([int]$p.index).Delete()
@@ -1612,7 +2420,7 @@ switch ($Action) {
1612
2420
  "getConditionalFormats" {
1613
2421
  $excel = Get-WpsExcel
1614
2422
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
1615
- $sheet = $excel.ActiveSheet
2423
+ $sheet = $(Resolve-Sheet $excel $p)
1616
2424
  $range = $sheet.Range($p.range)
1617
2425
  $formats = @()
1618
2426
  $count = $range.FormatConditions.Count
@@ -1626,7 +2434,7 @@ switch ($Action) {
1626
2434
  "addDataValidation" {
1627
2435
  $excel = Get-WpsExcel
1628
2436
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
1629
- $sheet = $excel.ActiveSheet
2437
+ $sheet = $(Resolve-Sheet $excel $p)
1630
2438
  $range = $sheet.Range($p.range)
1631
2439
  $typeMap = @{ list = 3; whole = 1; decimal = 2; date = 4; time = 5; textLength = 6; custom = 7 }
1632
2440
  $validationType = $typeMap[$p.validationType]
@@ -1660,7 +2468,7 @@ switch ($Action) {
1660
2468
  "removeDataValidation" {
1661
2469
  $excel = Get-WpsExcel
1662
2470
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
1663
- $sheet = $excel.ActiveSheet
2471
+ $sheet = $(Resolve-Sheet $excel $p)
1664
2472
  $range = $sheet.Range($p.range)
1665
2473
  $range.Validation.Delete()
1666
2474
  Output-Json @{ success = $true; data = @{ range = $p.range } }
@@ -1669,7 +2477,7 @@ switch ($Action) {
1669
2477
  "getDataValidations" {
1670
2478
  $excel = Get-WpsExcel
1671
2479
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
1672
- $sheet = $excel.ActiveSheet
2480
+ $sheet = $(Resolve-Sheet $excel $p)
1673
2481
  $range = $sheet.Range($p.range)
1674
2482
  $validation = $range.Validation
1675
2483
  Output-Json @{ success = $true; data = @{ range = $p.range; type = $validation.Type; formula1 = $validation.Formula1; formula2 = $validation.Formula2; inputTitle = $validation.InputTitle; inputMessage = $validation.InputMessage } }
@@ -1678,7 +2486,7 @@ switch ($Action) {
1678
2486
  "getFormula" {
1679
2487
  $excel = Get-WpsExcel
1680
2488
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
1681
- $sheet = $excel.ActiveSheet
2489
+ $sheet = $(Resolve-Sheet $excel $p)
1682
2490
  $cell = $sheet.Range($p.cell)
1683
2491
  $formula = if ($cell.Formula) { $cell.Formula } else { "" }
1684
2492
  $formulaLocal = ""
@@ -1689,7 +2497,7 @@ switch ($Action) {
1689
2497
  "setArrayFormula" {
1690
2498
  $excel = Get-WpsExcel
1691
2499
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
1692
- $sheet = $excel.ActiveSheet
2500
+ $sheet = $(Resolve-Sheet $excel $p)
1693
2501
  $range = $sheet.Range($p.range)
1694
2502
  $range.FormulaArray = $p.formula
1695
2503
  Output-Json @{ success = $true; data = @{ range = $p.range; formula = $p.formula } }
@@ -1698,7 +2506,7 @@ switch ($Action) {
1698
2506
  "getCellInfo" {
1699
2507
  $excel = Get-WpsExcel
1700
2508
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
1701
- $sheet = $excel.ActiveSheet
2509
+ $sheet = $(Resolve-Sheet $excel $p)
1702
2510
  $cell = $sheet.Range($p.cell)
1703
2511
  $value = $cell.Value2
1704
2512
  $formula = if ($cell.Formula) { $cell.Formula } else { "" }
@@ -1729,7 +2537,7 @@ switch ($Action) {
1729
2537
  "consolidate" {
1730
2538
  $excel = Get-WpsExcel
1731
2539
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
1732
- $sheet = $excel.ActiveSheet
2540
+ $sheet = $(Resolve-Sheet $excel $p)
1733
2541
  $destRange = $sheet.Range($p.destination)
1734
2542
  $funcMap = @{ sum = 9; count = 2; average = 1; max = 4; min = 5 }
1735
2543
  $func = $funcMap[$p.function]
@@ -1757,7 +2565,7 @@ switch ($Action) {
1757
2565
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
1758
2566
  $wb = $(Resolve-Book $excel $p)
1759
2567
  if ($null -eq $wb) { Output-Json @{ success = $false; error = "No active workbook" }; return }
1760
- $sheet = $excel.ActiveSheet
2568
+ $sheet = $(Resolve-Sheet $excel $p)
1761
2569
  $usedRange = $sheet.UsedRange
1762
2570
  $headers = @()
1763
2571
  if ($usedRange.Rows.Count -gt 0) {
@@ -1778,7 +2586,7 @@ switch ($Action) {
1778
2586
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
1779
2587
  $wb = $(Resolve-Book $excel $p)
1780
2588
  if ($null -eq $wb) { Output-Json @{ success = $false; error = "No active workbook" }; return }
1781
- $sheet = $excel.ActiveSheet
2589
+ $sheet = $(Resolve-Sheet $excel $p)
1782
2590
  $usedRange = $sheet.UsedRange
1783
2591
  $headers = @()
1784
2592
  if ($usedRange.Rows.Count -gt 0) {
@@ -1797,18 +2605,34 @@ switch ($Action) {
1797
2605
  "sortRange" {
1798
2606
  $excel = Get-WpsExcel
1799
2607
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
1800
- $sheet = $excel.ActiveSheet
2608
+ $sheet = $(Resolve-Sheet $excel $p)
1801
2609
  $range = $sheet.Range($p.range)
1802
- $keyCol = $sheet.Range($p.keyColumn)
1803
- $order = if ($p.order -eq "desc") { 2 } else { 1 }
2610
+ # 第 4 轮修:TS 传的是 column(排序范围里的第几列,数字),PS 以前读 keyColumn 并把它
2611
+ # 直接塞进 Range() —— 传数字进去必然抛(Range 只收地址/名字)。现在两种都接:
2612
+ # keyColumn(地址,如 "B:B")直接用;column(数字)按排序范围的左边界换算成列字母。
2613
+ $keyCol = $null
2614
+ if ($p.keyColumn) {
2615
+ $keyCol = $sheet.Range([string]$p.keyColumn)
2616
+ } elseif ($p.column) {
2617
+ $baseCol = $range.Column
2618
+ $colLetter = Convert-ColumnNumberToLetter($baseCol + [int]$p.column - 1)
2619
+ $keyCol = $sheet.Range("${colLetter}1")
2620
+ } else {
2621
+ Output-Json @{ success = $false; error = "要给 column(排序依据的列号)或 keyColumn(列地址,如 B:B)" }
2622
+ return
2623
+ }
2624
+ # order 支持 'desc'/'asc' 字符串(TS 现在发这个)与 1/2 数字(历史裸调用)
2625
+ $order = 1
2626
+ if ([string]$p.order -eq 'desc') { $order = 2 }
2627
+ elseif ([string]$p.order -match '^\d+$') { $order = [int]$p.order }
1804
2628
  $range.Sort($keyCol, $order)
1805
- Output-Json @{ success = $true }
2629
+ Output-Json @{ success = $true; data = @{ range = $p.range; order = $order } }
1806
2630
  }
1807
2631
 
1808
2632
  "autoFilter" {
1809
2633
  $excel = Get-WpsExcel
1810
2634
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
1811
- $sheet = $excel.ActiveSheet
2635
+ $sheet = $(Resolve-Sheet $excel $p)
1812
2636
  $range = $sheet.Range($p.range)
1813
2637
  if ($p.criteria) {
1814
2638
  $range.AutoFilter($p.field, $p.criteria)
@@ -1821,7 +2645,7 @@ switch ($Action) {
1821
2645
  "createChart" {
1822
2646
  $excel = Get-WpsExcel
1823
2647
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
1824
- $sheet = $excel.ActiveSheet
2648
+ $sheet = $(Resolve-Sheet $excel $p)
1825
2649
  $range = $sheet.Range($p.dataRange)
1826
2650
  $chartType = $p.chartType
1827
2651
  if ($null -eq $chartType) {
@@ -1969,7 +2793,7 @@ switch ($Action) {
1969
2793
  "removeDuplicates" {
1970
2794
  $excel = Get-WpsExcel
1971
2795
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
1972
- $sheet = $excel.ActiveSheet
2796
+ $sheet = $(Resolve-Sheet $excel $p)
1973
2797
  $range = $sheet.Range($p.range)
1974
2798
  $originalCount = $range.Rows.Count
1975
2799
  $cols = @()
@@ -2053,7 +2877,7 @@ switch ($Action) {
2053
2877
  Output-Json @{ success = $true; data = @{ sheets = $sheets; count = $sheets.Count; activeSheet = $excel.ActiveSheet.Name } }
2054
2878
  }
2055
2879
 
2056
- # ===== 第 4 期补齐(对齐 dsh-plugin-wps-office-next 的高频缺口)=====
2880
+ # ===== 第 4 期补齐(常见高频缺口:表内查找 / 图表删除 / 透视表 / 页面设置)=====
2057
2881
  # 逐条说明"为什么缺它会真的卡住",不是凑数。
2058
2882
  # 真机支持情况见 __probeCaps 的对应项;未验的一律走 warnings,不假装成功。
2059
2883
 
@@ -2511,12 +3335,23 @@ switch ($Action) {
2511
3335
  $wb = $(Resolve-Book $excel $p)
2512
3336
  if ($null -eq $wb) { Output-Json @{ success = $false; error = "No active workbook" }; return }
2513
3337
  $sheet = if ($p.sheet) { $wb.Sheets.Item($p.sheet) } else { $excel.ActiveSheet }
2514
- if ($p.before) {
3338
+ # 第 4 轮修:TS 传的是 position(0 基目标位置),PS 只认 before/after ——
3339
+ # 两个都没给时【什么都不做还返回 success】,用户以为移动了。
3340
+ # 现在三条路都走通:position 优先,其次 before/after。
3341
+ if ($null -ne $p.position) {
3342
+ $target = [int]$p.position + 1
3343
+ if ($target -lt 1) { $target = 1 }
3344
+ if ($target -gt $wb.Sheets.Count) { $target = $wb.Sheets.Count }
3345
+ $sheet.Move($wb.Sheets.Item($target))
3346
+ } elseif ($p.before) {
2515
3347
  $sheet.Move($wb.Sheets.Item($p.before))
2516
3348
  } elseif ($p.after) {
2517
3349
  $sheet.Move($null, $wb.Sheets.Item($p.after))
3350
+ } else {
3351
+ Output-Json @{ success = $false; error = "要给 position(0 基目标位置),或 before/after(工作表名)。两个都没给就没法移动。" }
3352
+ return
2518
3353
  }
2519
- Output-Json @{ success = $true; data = @{ movedSheet = $sheet.Name } }
3354
+ Output-Json @{ success = $true; data = @{ movedSheet = $sheet.Name; position = $sheet.Index - 1 } }
2520
3355
  }
2521
3356
 
2522
3357
  "mergeCells" {
@@ -2524,7 +3359,7 @@ switch ($Action) {
2524
3359
  if ($null -eq $word) { Output-Json @{ success = $false; error = "WPS Word not running" }; return }
2525
3360
  $excel = Get-WpsExcel
2526
3361
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2527
- $sheet = $excel.ActiveSheet
3362
+ $sheet = $(Resolve-Sheet $excel $p)
2528
3363
  $range = $sheet.Range($p.range)
2529
3364
  $across = if ($null -ne $p.across) { [bool]$p.across } else { $false }
2530
3365
  $range.Merge($across)
@@ -2534,7 +3369,7 @@ switch ($Action) {
2534
3369
  "unmergeCells" {
2535
3370
  $excel = Get-WpsExcel
2536
3371
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2537
- $sheet = $excel.ActiveSheet
3372
+ $sheet = $(Resolve-Sheet $excel $p)
2538
3373
  $range = $sheet.Range($p.range)
2539
3374
  $range.UnMerge()
2540
3375
  Output-Json @{ success = $true; data = @{ range = $p.range } }
@@ -2543,7 +3378,7 @@ switch ($Action) {
2543
3378
  "setColumnWidth" {
2544
3379
  $excel = Get-WpsExcel
2545
3380
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2546
- $sheet = $excel.ActiveSheet
3381
+ $sheet = $(Resolve-Sheet $excel $p)
2547
3382
  $col = $p.column
2548
3383
  if ($col -is [int]) { $col = Convert-ColumnNumberToLetter([int]$col) }
2549
3384
  $sheet.Range("${col}:${col}").ColumnWidth = $p.width
@@ -2553,7 +3388,7 @@ switch ($Action) {
2553
3388
  "setRowHeight" {
2554
3389
  $excel = Get-WpsExcel
2555
3390
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2556
- $sheet = $excel.ActiveSheet
3391
+ $sheet = $(Resolve-Sheet $excel $p)
2557
3392
  $sheet.Range("$($p.row):$($p.row)").RowHeight = $p.height
2558
3393
  Output-Json @{ success = $true; data = @{ row = $p.row; height = $p.height } }
2559
3394
  }
@@ -2561,7 +3396,7 @@ switch ($Action) {
2561
3396
  "autoFitColumn" {
2562
3397
  $excel = Get-WpsExcel
2563
3398
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2564
- $sheet = $excel.ActiveSheet
3399
+ $sheet = $(Resolve-Sheet $excel $p)
2565
3400
  if ($p.range) {
2566
3401
  $sheet.Range($p.range).Columns.AutoFit()
2567
3402
  } elseif ($p.column) {
@@ -2577,7 +3412,7 @@ switch ($Action) {
2577
3412
  "autoFitRow" {
2578
3413
  $excel = Get-WpsExcel
2579
3414
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2580
- $sheet = $excel.ActiveSheet
3415
+ $sheet = $(Resolve-Sheet $excel $p)
2581
3416
  if ($p.range) {
2582
3417
  $sheet.Range($p.range).Rows.AutoFit()
2583
3418
  } elseif ($p.row) {
@@ -2591,7 +3426,7 @@ switch ($Action) {
2591
3426
  "autoFitAll" {
2592
3427
  $excel = Get-WpsExcel
2593
3428
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2594
- $sheet = $excel.ActiveSheet
3429
+ $sheet = $(Resolve-Sheet $excel $p)
2595
3430
  $range = if ($p.range) { $sheet.Range($p.range) } else { $sheet.UsedRange }
2596
3431
  $range.Columns.AutoFit()
2597
3432
  $range.Rows.AutoFit()
@@ -2601,7 +3436,7 @@ switch ($Action) {
2601
3436
  "setNumberFormat" {
2602
3437
  $excel = Get-WpsExcel
2603
3438
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2604
- $sheet = $excel.ActiveSheet
3439
+ $sheet = $(Resolve-Sheet $excel $p)
2605
3440
  $range = $sheet.Range($p.range)
2606
3441
  if ($p.format) { $range.NumberFormat = $p.format }
2607
3442
  Output-Json @{ success = $true; data = @{ range = $p.range; format = $p.format } }
@@ -2610,7 +3445,7 @@ switch ($Action) {
2610
3445
  "wrapText" {
2611
3446
  $excel = Get-WpsExcel
2612
3447
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2613
- $sheet = $excel.ActiveSheet
3448
+ $sheet = $(Resolve-Sheet $excel $p)
2614
3449
  $range = $sheet.Range($p.range)
2615
3450
  $wrap = if ($null -ne $p.wrap) { [bool]$p.wrap } else { $true }
2616
3451
  $range.WrapText = $wrap
@@ -2620,7 +3455,7 @@ switch ($Action) {
2620
3455
  "setPrintArea" {
2621
3456
  $excel = Get-WpsExcel
2622
3457
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2623
- $sheet = $excel.ActiveSheet
3458
+ $sheet = $(Resolve-Sheet $excel $p)
2624
3459
  if ($p.range) { $sheet.PageSetup.PrintArea = $p.range } else { $sheet.PageSetup.PrintArea = "" }
2625
3460
  Output-Json @{ success = $true; data = @{ printArea = if ($p.range) { $p.range } else { "cleared" } } }
2626
3461
  }
@@ -2637,7 +3472,7 @@ switch ($Action) {
2637
3472
  "clearRange" {
2638
3473
  $excel = Get-WpsExcel
2639
3474
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2640
- $sheet = $excel.ActiveSheet
3475
+ $sheet = $(Resolve-Sheet $excel $p)
2641
3476
  $range = $sheet.Range($p.range)
2642
3477
  $clearType = if ($p.type) { $p.type } else { "all" }
2643
3478
  if ($clearType -eq "contents") { $range.ClearContents() }
@@ -2650,7 +3485,7 @@ switch ($Action) {
2650
3485
  "insertRows" {
2651
3486
  $excel = Get-WpsExcel
2652
3487
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2653
- $sheet = $excel.ActiveSheet
3488
+ $sheet = $(Resolve-Sheet $excel $p)
2654
3489
  $startRow = if ($p.row) { [int]$p.row } elseif ($p.startRow) { [int]$p.startRow } else { $null }
2655
3490
  if ($null -eq $startRow) { Output-Json @{ success = $false; error = "row/startRow required" }; return }
2656
3491
  $count = if ($p.count) { [int]$p.count } else { 1 }
@@ -2662,7 +3497,7 @@ switch ($Action) {
2662
3497
  "insertColumns" {
2663
3498
  $excel = Get-WpsExcel
2664
3499
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2665
- $sheet = $excel.ActiveSheet
3500
+ $sheet = $(Resolve-Sheet $excel $p)
2666
3501
  $col = if ($p.column) { $p.column } elseif ($p.startColumn) { $p.startColumn } else { $null }
2667
3502
  if ($null -eq $col) { Output-Json @{ success = $false; error = "column/startColumn required" }; return }
2668
3503
  if ($col -is [int]) { $col = Convert-ColumnNumberToLetter([int]$col) }
@@ -2676,7 +3511,7 @@ switch ($Action) {
2676
3511
  "deleteRows" {
2677
3512
  $excel = Get-WpsExcel
2678
3513
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2679
- $sheet = $excel.ActiveSheet
3514
+ $sheet = $(Resolve-Sheet $excel $p)
2680
3515
  $startRow = if ($p.row) { [int]$p.row } elseif ($p.startRow) { [int]$p.startRow } else { $null }
2681
3516
  if ($null -eq $startRow) { Output-Json @{ success = $false; error = "row/startRow required" }; return }
2682
3517
  $count = if ($p.count) { [int]$p.count } else { 1 }
@@ -2688,7 +3523,7 @@ switch ($Action) {
2688
3523
  "deleteColumns" {
2689
3524
  $excel = Get-WpsExcel
2690
3525
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2691
- $sheet = $excel.ActiveSheet
3526
+ $sheet = $(Resolve-Sheet $excel $p)
2692
3527
  $col = if ($p.column) { $p.column } elseif ($p.startColumn) { $p.startColumn } else { $null }
2693
3528
  if ($null -eq $col) { Output-Json @{ success = $false; error = "column/startColumn required" }; return }
2694
3529
  if ($col -is [int]) { $col = Convert-ColumnNumberToLetter([int]$col) }
@@ -2702,7 +3537,7 @@ switch ($Action) {
2702
3537
  "hideRows" {
2703
3538
  $excel = Get-WpsExcel
2704
3539
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2705
- $sheet = $excel.ActiveSheet
3540
+ $sheet = $(Resolve-Sheet $excel $p)
2706
3541
  $rows = if ($p.rows) { $p.rows } elseif ($p.row) { @($p.row) } else { @() }
2707
3542
  if ($rows.Count -eq 0) { Output-Json @{ success = $false; error = "row/rows required" }; return }
2708
3543
  foreach ($r in $rows) { $sheet.Range("${r}:${r}").Hidden = $true }
@@ -2712,7 +3547,7 @@ switch ($Action) {
2712
3547
  "hideColumns" {
2713
3548
  $excel = Get-WpsExcel
2714
3549
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2715
- $sheet = $excel.ActiveSheet
3550
+ $sheet = $(Resolve-Sheet $excel $p)
2716
3551
  $cols = if ($p.columns) { $p.columns } elseif ($p.column) { @($p.column) } else { @() }
2717
3552
  if ($cols.Count -eq 0) { Output-Json @{ success = $false; error = "column/columns required" }; return }
2718
3553
  $hidden = @()
@@ -2728,7 +3563,7 @@ switch ($Action) {
2728
3563
  "showRows" {
2729
3564
  $excel = Get-WpsExcel
2730
3565
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2731
- $sheet = $excel.ActiveSheet
3566
+ $sheet = $(Resolve-Sheet $excel $p)
2732
3567
  $rows = if ($p.rows) { $p.rows } elseif ($p.row) { @($p.row) } else { @() }
2733
3568
  if ($rows.Count -eq 0) { Output-Json @{ success = $false; error = "row/rows required" }; return }
2734
3569
  foreach ($r in $rows) { $sheet.Range("${r}:${r}").Hidden = $false }
@@ -2738,7 +3573,7 @@ switch ($Action) {
2738
3573
  "showColumns" {
2739
3574
  $excel = Get-WpsExcel
2740
3575
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2741
- $sheet = $excel.ActiveSheet
3576
+ $sheet = $(Resolve-Sheet $excel $p)
2742
3577
  $cols = if ($p.columns) { $p.columns } elseif ($p.column) { @($p.column) } else { @() }
2743
3578
  if ($cols.Count -eq 0) { Output-Json @{ success = $false; error = "column/columns required" }; return }
2744
3579
  $shown = @()
@@ -2754,7 +3589,7 @@ switch ($Action) {
2754
3589
  "groupRows" {
2755
3590
  $excel = Get-WpsExcel
2756
3591
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2757
- $sheet = $excel.ActiveSheet
3592
+ $sheet = $(Resolve-Sheet $excel $p)
2758
3593
  if (-not $p.startRow -or -not $p.endRow) { Output-Json @{ success = $false; error = "startRow/endRow required" }; return }
2759
3594
  $sheet.Range("$($p.startRow):$($p.endRow)").Group()
2760
3595
  Output-Json @{ success = $true; data = @{ grouped = "$($p.startRow):$($p.endRow)" } }
@@ -2763,7 +3598,7 @@ switch ($Action) {
2763
3598
  "groupColumns" {
2764
3599
  $excel = Get-WpsExcel
2765
3600
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2766
- $sheet = $excel.ActiveSheet
3601
+ $sheet = $(Resolve-Sheet $excel $p)
2767
3602
  if (-not $p.startColumn -or -not $p.endColumn) { Output-Json @{ success = $false; error = "startColumn/endColumn required" }; return }
2768
3603
  $startCol = $p.startColumn
2769
3604
  $endCol = $p.endColumn
@@ -2776,16 +3611,29 @@ switch ($Action) {
2776
3611
  "freezePanes" {
2777
3612
  $excel = Get-WpsExcel
2778
3613
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2779
- $sheet = $excel.ActiveSheet
2780
- if ($p.cell) {
2781
- $sheet.Range($p.cell).Select()
2782
- } elseif ($p.row -and $p.column) {
2783
- $col = $p.column
2784
- if ($col -is [int]) { $col = Convert-ColumnNumberToLetter([int]$col) }
2785
- $sheet.Range("$col$($p.row)").Select()
3614
+ $sheet = $(Resolve-Sheet $excel $p)
3615
+ # 第 4 轮修三处:
3616
+ # ① TS 传 freeze=false 表示"取消冻结",以前照样冻上;
3617
+ # ② 只给 row 或只给 column 时以前啥都不选($p.row -and $p.column 才动),冻的还是上次的位置;
3618
+ # ③ 三个都没给时 $sheet.Range($null) 直接抛 COM 错。
3619
+ $want = if ($null -ne $p.freeze) { [bool]$p.freeze } else { $true }
3620
+ if (-not $want) {
3621
+ $excel.ActiveWindow.FreezePanes = $false
3622
+ Output-Json @{ success = $true; data = @{ frozen = $false; message = "窗格冻结已取消" } }
3623
+ return
2786
3624
  }
3625
+ # 冻结 N 行选 A(N+1)、冻结 M 列选 (M+1)1、两个都要选 (M+1)(N+1) —— 与 Excel UI 的语义一致
3626
+ if ($p.cell) {
3627
+ $sheet.Range([string]$p.cell).Select()
3628
+ } elseif ($p.row -or $p.column) {
3629
+ $rowIdx = if ($p.row) { [int]$p.row + 1 } else { 1 }
3630
+ $colIdx = if ($p.column) { [int]$p.column + 1 } else { 1 }
3631
+ $colLetter = Convert-ColumnNumberToLetter($colIdx)
3632
+ $sheet.Range("$colLetter$rowIdx").Select()
3633
+ }
3634
+ # 三个都没给:不移动选区,就地冻结当前活动单元格的上方/左侧(Excel 的默认行为)
2787
3635
  $excel.ActiveWindow.FreezePanes = $true
2788
- Output-Json @{ success = $true; data = @{ message = "窗格已冻结" } }
3636
+ Output-Json @{ success = $true; data = @{ frozen = $true; message = "窗格已冻结" } }
2789
3637
  }
2790
3638
 
2791
3639
  "unfreezePanes" {
@@ -2798,7 +3646,7 @@ switch ($Action) {
2798
3646
  "replaceInSheet" {
2799
3647
  $excel = Get-WpsExcel
2800
3648
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2801
- $sheet = $excel.ActiveSheet
3649
+ $sheet = $(Resolve-Sheet $excel $p)
2802
3650
  $searchRange = if ($p.range) { $sheet.Range($p.range) } else { $sheet.UsedRange }
2803
3651
  $lookAt = if ($p.matchCase) { 1 } else { 2 }
2804
3652
  $replaced = $searchRange.Replace($p.searchText, $p.replaceText, $lookAt)
@@ -2808,7 +3656,7 @@ switch ($Action) {
2808
3656
  "copyRange" {
2809
3657
  $excel = Get-WpsExcel
2810
3658
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2811
- $sheet = $excel.ActiveSheet
3659
+ $sheet = $(Resolve-Sheet $excel $p)
2812
3660
  $range = $sheet.Range($p.range)
2813
3661
  $range.Copy()
2814
3662
  Output-Json @{ success = $true; data = @{ range = $p.range; message = "已复制到剪贴板" } }
@@ -2817,7 +3665,7 @@ switch ($Action) {
2817
3665
  "pasteRange" {
2818
3666
  $excel = Get-WpsExcel
2819
3667
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2820
- $sheet = $excel.ActiveSheet
3668
+ $sheet = $(Resolve-Sheet $excel $p)
2821
3669
  $destRange = $sheet.Range($p.destination)
2822
3670
  if ($p.pasteType -eq "values") {
2823
3671
  $destRange.PasteSpecial(-4163)
@@ -2834,7 +3682,7 @@ switch ($Action) {
2834
3682
  "fillSeries" {
2835
3683
  $excel = Get-WpsExcel
2836
3684
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2837
- $sheet = $excel.ActiveSheet
3685
+ $sheet = $(Resolve-Sheet $excel $p)
2838
3686
  $range = $sheet.Range($p.range)
2839
3687
  $startCell = $range.Cells.Item(1, 1)
2840
3688
  $startCell.Value2 = if ($null -ne $p.startValue) { $p.startValue } else { 1 }
@@ -2849,7 +3697,7 @@ switch ($Action) {
2849
3697
  "transpose" {
2850
3698
  $excel = Get-WpsExcel
2851
3699
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2852
- $sheet = $excel.ActiveSheet
3700
+ $sheet = $(Resolve-Sheet $excel $p)
2853
3701
  $sourceRange = $sheet.Range($p.sourceRange)
2854
3702
  $destCell = if ($p.destinationCell) { $p.destinationCell } elseif ($p.targetCell) { $p.targetCell } else { $null }
2855
3703
  if ($null -eq $destCell) { Output-Json @{ success = $false; error = "destinationCell/targetCell required" }; return }
@@ -2863,7 +3711,7 @@ switch ($Action) {
2863
3711
  "textToColumns" {
2864
3712
  $excel = Get-WpsExcel
2865
3713
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2866
- $sheet = $excel.ActiveSheet
3714
+ $sheet = $(Resolve-Sheet $excel $p)
2867
3715
  $range = $sheet.Range($p.range)
2868
3716
  $delimiter = if ($p.delimiter) { $p.delimiter } else { "," }
2869
3717
  $tab = $false; $semicolon = $false; $comma = $false; $space = $false; $other = $false; $otherChar = $null
@@ -2879,7 +3727,7 @@ switch ($Action) {
2879
3727
  "subtotal" {
2880
3728
  $excel = Get-WpsExcel
2881
3729
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2882
- $sheet = $excel.ActiveSheet
3730
+ $sheet = $(Resolve-Sheet $excel $p)
2883
3731
  $range = $sheet.Range($p.range)
2884
3732
  $funcMap = @{ sum = 9; count = 2; average = 1; max = 4; min = 5 }
2885
3733
  $func = $funcMap[$p.function]
@@ -2897,7 +3745,7 @@ switch ($Action) {
2897
3745
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2898
3746
  $wb = $(Resolve-Book $excel $p)
2899
3747
  if ($null -eq $wb) { Output-Json @{ success = $false; error = "No active workbook" }; return }
2900
- $sheet = $excel.ActiveSheet
3748
+ $sheet = $(Resolve-Sheet $excel $p)
2901
3749
  $range = $sheet.Range($p.range)
2902
3750
  $addr = $range.Address()
2903
3751
  $wb.Names.Add($p.name, "=" + $sheet.Name + "!" + $addr)
@@ -2929,18 +3777,27 @@ switch ($Action) {
2929
3777
  "addCellComment" {
2930
3778
  $excel = Get-WpsExcel
2931
3779
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2932
- $sheet = $excel.ActiveSheet
2933
- $cell = $sheet.Range($p.cell)
2934
- if ($cell.Comment) { $cell.Comment.Delete() }
2935
- $cell.AddComment($p.text)
2936
- if ($p.visible) { $cell.Comment.Visible = $true }
2937
- Output-Json @{ success = $true; data = @{ cell = $p.cell; text = $p.text } }
3780
+ $sheet = $(Resolve-Sheet $excel $p)
3781
+ if ($null -eq $sheet) { Output-Json @{ success = $false; error = "No sheet" }; return }
3782
+ $cellAddr = [string]$p.cell
3783
+ if (-not $cellAddr) { Output-Json @{ success = $false; error = "cell required" }; return }
3784
+ # 第 4 轮修:TS 的 schema 里这个参数叫 comment(历史 PS 只认 text)——
3785
+ # 曾经 $p.text 为 $null → AddComment($null) 造出一条空批注,还返回 success。
3786
+ # 两个键都认,comment 优先。
3787
+ $text = if ($p.comment) { $p.comment } else { $p.text }
3788
+ if (-not $text) { Output-Json @{ success = $false; error = "comment required(批注内容不能为空)" }; return }
3789
+ $target = $sheet.Range($cellAddr)
3790
+ # 同一格已有批注时 AddComment 会抛(WPS 与 Excel 都不允许一格两条)→ 先删后加,等价于覆盖
3791
+ try { if ($null -ne $target.Comment) { $target.Comment.Delete() } } catch {}
3792
+ $target.AddComment([string]$text) | Out-Null
3793
+ if ($p.visible) { try { $target.Comment.Visible = $true } catch {} }
3794
+ Output-Json @{ success = $true; data = @{ cell = $cellAddr; sheet = $sheet.Name; comment = [string]$text } }
2938
3795
  }
2939
3796
 
2940
3797
  "deleteCellComment" {
2941
3798
  $excel = Get-WpsExcel
2942
3799
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2943
- $sheet = $excel.ActiveSheet
3800
+ $sheet = $(Resolve-Sheet $excel $p)
2944
3801
  $cell = $sheet.Range($p.cell)
2945
3802
  if ($cell.Comment) { $cell.Comment.Delete() }
2946
3803
  Output-Json @{ success = $true; data = @{ cell = $p.cell } }
@@ -2949,7 +3806,7 @@ switch ($Action) {
2949
3806
  "getCellComments" {
2950
3807
  $excel = Get-WpsExcel
2951
3808
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2952
- $sheet = $excel.ActiveSheet
3809
+ $sheet = $(Resolve-Sheet $excel $p)
2953
3810
  $comments = @()
2954
3811
  for ($i = 1; $i -le $sheet.Comments.Count; $i++) {
2955
3812
  $c = $sheet.Comments.Item($i)
@@ -2991,7 +3848,7 @@ switch ($Action) {
2991
3848
  "insertExcelImage" {
2992
3849
  $excel = Get-WpsExcel
2993
3850
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
2994
- $sheet = $excel.ActiveSheet
3851
+ $sheet = $(Resolve-Sheet $excel $p)
2995
3852
  $left = if ($null -ne $p.left) { $p.left } else { 100 }
2996
3853
  $top = if ($null -ne $p.top) { $p.top } else { 100 }
2997
3854
  $width = if ($null -ne $p.width) { $p.width } else { -1 }
@@ -3003,7 +3860,7 @@ switch ($Action) {
3003
3860
  "setHyperlink" {
3004
3861
  $excel = Get-WpsExcel
3005
3862
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
3006
- $sheet = $excel.ActiveSheet
3863
+ $sheet = $(Resolve-Sheet $excel $p)
3007
3864
  $range = $sheet.Range($p.cell)
3008
3865
  $address = if ($p.address) { $p.address } else { "" }
3009
3866
  $subAddress = if ($p.subAddress) { $p.subAddress } else { "" }
@@ -3016,7 +3873,7 @@ switch ($Action) {
3016
3873
  "lockCells" {
3017
3874
  $excel = Get-WpsExcel
3018
3875
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
3019
- $sheet = $excel.ActiveSheet
3876
+ $sheet = $(Resolve-Sheet $excel $p)
3020
3877
  $range = $sheet.Range($p.range)
3021
3878
  $locked = if ($null -ne $p.locked) { [bool]$p.locked } else { $true }
3022
3879
  $range.Locked = $locked
@@ -3033,14 +3890,54 @@ switch ($Action) {
3033
3890
  "getOpenWorkbooks" {
3034
3891
  $excel = Get-WpsExcel
3035
3892
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
3893
+ # 第 1 期第 2 章第 4 轮(A9):空列表【不能直接信】。
3894
+ # quit 之后 WPS 要重新注册到 ROT(Running Object Table),那几秒里
3895
+ # GetActiveObject 要么取不到(于是 Get-WpsWord 新建一个空的实例),
3896
+ # 要么取到一个刚重启、文档还没恢复的实例 —— 两种都表现为"列表 0 份",
3897
+ # 可文档其实还在(真机 A9 实测:连续 4 次 × 1.5s 读到 0 份,同一时刻按名读内容 6/6 可读)。
3898
+ # 后果是模型据此判断"文档没了",会误判。
3899
+ #
3900
+ # 所以:读到空列表时,重新【只从 ROT 取】再取一次,最多 3 次 × 400ms,取到非空就停。
3901
+ # 只从 ROT 取、不新建 —— 新建的实例必然是空的,重试没有意义。
3902
+ #
3903
+ # 沙箱实例不做这个重试:它本来就是 New-Object 出来的,"空"是常态;
3904
+ # 而且重试时从 ROT 取到的是【用户】实例,拿用户的列表回答沙箱的查询是错的。
3905
+ #
3906
+ # 顺带:每个工作簿的属性单独 try/catch —— 以前一个取属性抛错,整份列表就没了。
3036
3907
  $workbooks = @()
3037
- for ($i = 1; $i -le $excel.Workbooks.Count; $i++) {
3038
- $wb = $excel.Workbooks.Item($i)
3039
- $workbooks += @{ name = $wb.Name; path = $wb.FullName; sheets = $wb.Sheets.Count; active = ($wb.Name -eq $(Resolve-Book $excel $p).Name) }
3908
+ $suspicious = $false
3909
+ for ($attempt = 1; $attempt -le 3; $attempt++) {
3910
+ $workbooks = @()
3911
+ $total = 0
3912
+ try { $total = $excel.Workbooks.Count } catch {}
3913
+ for ($i = 1; $i -le $total; $i++) {
3914
+ $wb = $null
3915
+ try { $wb = $excel.Workbooks.Item($i) } catch { continue }
3916
+ if ($null -eq $wb) { continue }
3917
+ $nm = ""; $fp = ""; $extra = 0; $act = $false
3918
+ try { $nm = [string]$wb.Name } catch {}
3919
+ try { $fp = [string]$wb.FullName } catch {}
3920
+ try { $extra = $wb.Sheets.Count } catch {}
3921
+ try { $act = ($nm -eq $(Resolve-Book $excel $p).Name) } catch {}
3922
+ $workbooks += @{ name = $nm; path = $fp; sheets = $extra; active = $act }
3923
+ }
3924
+ if ($workbooks.Count -gt 0) { break }
3925
+ $suspicious = (-not (Test-SandboxInstance))
3926
+ if (-not $suspicious -or $attempt -ge 3) { break }
3927
+ $rot = Get-WpsExcelFromRot
3928
+ if ($null -ne $rot) { $excel = $rot }
3929
+ Start-Sleep -Milliseconds 400
3930
+ }
3931
+ $data = @{ workbooks = $workbooks; count = $workbooks.Count }
3932
+ if ($suspicious -and $workbooks.Count -eq 0) {
3933
+ # 还是 0 份 —— 说清楚,别让模型当成"文档没了"。
3934
+ $data.warnings = @(@{
3935
+ step = "getOpenWorkbooks"
3936
+ message = "读到 0 份工作簿。如果刚执行过 quit/close,这可能是 WPS 重新注册到 ROT 的那几秒窗口(实测可持续数秒),工作簿可能还在 —— 别据此判断工作簿没了,隔一会儿再读一次,或按名字直接读内容核实。"
3937
+ })
3040
3938
  }
3041
- Output-Json @{ success = $true; data = @{ workbooks = $workbooks; count = $workbooks.Count } }
3939
+ Output-Json @{ success = $true; data = $data }
3042
3940
  }
3043
-
3044
3941
  "switchWorkbook" {
3045
3942
  $excel = Get-WpsExcel
3046
3943
  if ($null -eq $excel) { Output-Json @{ success = $false; error = "WPS Excel not running" }; return }
@@ -3056,6 +3953,18 @@ switch ($Action) {
3056
3953
  if ($null -eq $wb) { Output-Json @{ success = $false; error = "No workbook" }; return }
3057
3954
  $name = $wb.Name
3058
3955
  $saveChanges = if ($null -ne $p.saveChanges) { [bool]$p.saveChanges } else { $true }
3956
+ # 未保存工作簿的护栏(第 3 轮补,照 Word 侧 closeDocument 的同一套设计答案):
3957
+ # 从未存过盘的工作簿 Close($true) 会弹「另存为」模态框,COM 是 STA ——
3958
+ # 弹框会把桥通道卡死(实测卡 120 秒,后续全部调用超时)。
3959
+ # 所以这里不猜、不硬关:明确报错让调用方先 save_as,或显式 saveChanges=false。
3960
+ if ($saveChanges) {
3961
+ $hasPath = $false
3962
+ try { $hasPath = -not [string]::IsNullOrEmpty([string]$wb.Path) } catch {} # 吞错有据:读不到 Path 按"从未保存"处理(保守方向,护栏会拦)
3963
+ if (-not $hasPath) {
3964
+ Output-Json @{ success = $false; error = "[勿重试·先另存为] 工作簿「$name」从未保存过,直接关闭会弹出「另存为」对话框卡住通道(120 秒)。请先另存为(wps_excel_save_as),或显式传 save=false 放弃保存" }
3965
+ return
3966
+ }
3967
+ }
3059
3968
  $wb.Close($saveChanges)
3060
3969
  Output-Json @{ success = $true; data = @{ closed = $name } }
3061
3970
  }
@@ -3106,14 +4015,54 @@ switch ($Action) {
3106
4015
  "getOpenDocuments" {
3107
4016
  $word = Get-WpsWord
3108
4017
  if ($null -eq $word) { Output-Json @{ success = $false; error = "WPS Word not running" }; return }
4018
+ # 第 1 期第 2 章第 4 轮(A9):空列表【不能直接信】。
4019
+ # quit 之后 WPS 要重新注册到 ROT(Running Object Table),那几秒里
4020
+ # GetActiveObject 要么取不到(于是 Get-WpsWord 新建一个空的实例),
4021
+ # 要么取到一个刚重启、文档还没恢复的实例 —— 两种都表现为"列表 0 份",
4022
+ # 可文档其实还在(真机 A9 实测:连续 4 次 × 1.5s 读到 0 份,同一时刻按名读内容 6/6 可读)。
4023
+ # 后果是模型据此判断"文档没了",会误判。
4024
+ #
4025
+ # 所以:读到空列表时,重新【只从 ROT 取】再取一次,最多 3 次 × 400ms,取到非空就停。
4026
+ # 只从 ROT 取、不新建 —— 新建的实例必然是空的,重试没有意义。
4027
+ #
4028
+ # 沙箱实例不做这个重试:它本来就是 New-Object 出来的,"空"是常态;
4029
+ # 而且重试时从 ROT 取到的是【用户】实例,拿用户的列表回答沙箱的查询是错的。
4030
+ #
4031
+ # 顺带:每个文档的属性单独 try/catch —— 以前一个取属性抛错,整份列表就没了。
3109
4032
  $documents = @()
3110
- for ($i = 1; $i -le $word.Documents.Count; $i++) {
3111
- $docItem = $word.Documents.Item($i)
3112
- $documents += @{ name = $docItem.Name; path = $docItem.FullName; paragraphs = $docItem.Paragraphs.Count; active = ($(Resolve-Doc $word $p).Name -eq $docItem.Name) }
4033
+ $suspicious = $false
4034
+ for ($attempt = 1; $attempt -le 3; $attempt++) {
4035
+ $documents = @()
4036
+ $total = 0
4037
+ try { $total = $word.Documents.Count } catch {}
4038
+ for ($i = 1; $i -le $total; $i++) {
4039
+ $docItem = $null
4040
+ try { $docItem = $word.Documents.Item($i) } catch { continue }
4041
+ if ($null -eq $docItem) { continue }
4042
+ $nm = ""; $fp = ""; $extra = 0; $act = $false
4043
+ try { $nm = [string]$docItem.Name } catch {}
4044
+ try { $fp = [string]$docItem.FullName } catch {}
4045
+ try { $extra = $docItem.Paragraphs.Count } catch {}
4046
+ try { $act = ((Resolve-Doc $word $p).Name -eq $nm) } catch {}
4047
+ $documents += @{ name = $nm; path = $fp; paragraphs = $extra; active = $act }
4048
+ }
4049
+ if ($documents.Count -gt 0) { break }
4050
+ $suspicious = (-not (Test-SandboxInstance))
4051
+ if (-not $suspicious -or $attempt -ge 3) { break }
4052
+ $rot = Get-WpsWordFromRot
4053
+ if ($null -ne $rot) { $word = $rot }
4054
+ Start-Sleep -Milliseconds 400
4055
+ }
4056
+ $data = @{ documents = $documents; count = $documents.Count }
4057
+ if ($suspicious -and $documents.Count -eq 0) {
4058
+ # 还是 0 份 —— 说清楚,别让模型当成"文档没了"。
4059
+ $data.warnings = @(@{
4060
+ step = "getOpenDocuments"
4061
+ message = "读到 0 份文档。如果刚执行过 quit/close,这可能是 WPS 重新注册到 ROT 的那几秒窗口(实测可持续数秒),文档可能还在 —— 别据此判断文档没了,隔一会儿再读一次,或按名字直接读内容核实。"
4062
+ })
3113
4063
  }
3114
- Output-Json @{ success = $true; data = @{ documents = $documents; count = $documents.Count } }
4064
+ Output-Json @{ success = $true; data = $data }
3115
4065
  }
3116
-
3117
4066
  "switchDocument" {
3118
4067
  $word = Get-WpsWord
3119
4068
  if ($null -eq $word) { Output-Json @{ success = $false; error = "WPS Word not running" }; return }
@@ -3142,9 +4091,15 @@ switch ($Action) {
3142
4091
  # 所以这里不猜、不硬关:明确报错让调用方先 save_as,或显式 saveChanges=false。
3143
4092
  if ($saveChanges) {
3144
4093
  $hasPath = $false
3145
- try { $hasPath = -not [string]::IsNullOrEmpty([string]$docItem.FullName) } catch {}
4094
+ try { $hasPath = -not [string]::IsNullOrEmpty([string]$docItem.Path) } catch {} # 吞错有据:读不到 Path 按"从未保存"处理(保守方向,护栏会拦)
3146
4095
  if (-not $hasPath) {
3147
- Output-Json @{ success = $false; error = "文档「$name」从未保存过,直接关闭会弹出「另存为」对话框卡住通道。请先另存为(wps_word_save_as),或显式传 saveChanges=false 放弃保存" }
4096
+ # 第 1 期第 2 章第 4 轮(B3):提示里原来写的是 saveChanges=false —— 那是【PS 动作】的
4097
+ # 参数名,不是【工具】的。wps_word_close_document 的公开 schema 参数叫 save;
4098
+ # 照提示传 saveChanges 的话工具收不到 → save 仍是 undefined → TS 兜成 saveChanges=true
4099
+ # → 护栏照样触发 → 用户卡死在同一个错误里出不来。
4100
+ # 实测(word-close-param-probe.js):照提示传 saveChanges=false 关不掉,
4101
+ # 传 save=false 一次就关掉了。所以提示必须写【工具能收的那个名字】。
4102
+ Output-Json @{ success = $false; error = "文档「$name」从未保存过,直接关闭会弹出「另存为」对话框卡住通道。请先另存为(wps_word_save_as),或显式传 save=false 放弃保存" }
3148
4103
  return
3149
4104
  }
3150
4105
  }
@@ -3215,7 +4170,7 @@ switch ($Action) {
3215
4170
  $doc = $(Resolve-Doc $word $p)
3216
4171
  if ($null -eq $doc) { Output-Json @{ success = $false; error = "No active document" }; return }
3217
4172
  $n = 0
3218
- try { $n = [int]$doc.Comments.Count } catch {}
4173
+ try { $n = [int]$doc.Comments.Count } catch {} # 吞错有据:读不到按 0 处理,走"没有批注"路径(不会误删)
3219
4174
  if ($n -le 0) { Output-Json @{ success = $false; error = "文档里没有批注" }; return }
3220
4175
  $target = $null
3221
4176
  if ($null -ne $p.index) {
@@ -3227,7 +4182,7 @@ switch ($Action) {
3227
4182
  $c = $null
3228
4183
  try { $c = $doc.Comments.Item($i) } catch { continue }
3229
4184
  $t = ""
3230
- try { $t = [string]$c.Range.Text } catch {}
4185
+ try { $t = [string]$c.Range.Text } catch {} # 吞错有据:读不到文本按空串处理,该项匹配跳过
3231
4186
  if ($t -like "*$($p.text)*") { $target = $c; break }
3232
4187
  }
3233
4188
  if ($null -eq $target) { Output-Json @{ success = $false; error = "没有找到包含「$($p.text)」的批注" }; return }
@@ -3235,10 +4190,10 @@ switch ($Action) {
3235
4190
  Output-Json @{ success = $false; error = "需要 index(序号)或 text(批注内容片段)之一" }; return
3236
4191
  }
3237
4192
  $before = ""
3238
- try { $before = [string]$target.Range.Text } catch {}
4193
+ try { $before = [string]$target.Range.Text } catch {} # 吞错有据:展示用的删除前文本,读不到不影响删除本身
3239
4194
  $target.Delete()
3240
4195
  $n1 = 0
3241
- try { $n1 = [int]$doc.Comments.Count } catch {}
4196
+ try { $n1 = [int]$doc.Comments.Count } catch {} # 吞错有据:剩余计数读不到按 0 展示
3242
4197
  Output-Json @{ success = $true; data = @{ deleted = $before; remaining = $n1 } }
3243
4198
  }
3244
4199
 
@@ -3366,7 +4321,7 @@ switch ($Action) {
3366
4321
  Output-Json @{ success = $false; error = "表格转文本失败: $(Get-CallError $_)" }; return
3367
4322
  }
3368
4323
  $left = 0
3369
- try { $left = [int]$doc.Tables.Count } catch {}
4324
+ try { $left = [int]$doc.Tables.Count } catch {} # 吞错有据:剩余表格计数读不到按 0 展示
3370
4325
  Output-Json @{ success = $true; data = @{ tableIndex = $idx; separator = $sep; remainingTables = $left } }
3371
4326
  }
3372
4327
 
@@ -3376,14 +4331,21 @@ switch ($Action) {
3376
4331
  # 这个在【临时文档】上探新接口,探完原样关闭(不保存),不碰用户任何文档。
3377
4332
  $word = Get-WpsWord
3378
4333
  if ($null -eq $word) { Output-Json @{ success = $false; error = "WPS Word not running" }; return }
3379
- $doc = $null
3380
- try {
3381
- $doc = $word.Documents.Add()
3382
- # 等文档就绪(同 createDocument 的教训:零等待会拿到空壳)
3383
- for ($i = 0; $i -lt 20; $i++) {
3384
- Start-Sleep -Milliseconds 150
3385
- try { $cur = $word.Documents.Item($word.Documents.Count); if (Test-DocHealthy $cur) { $doc = $cur; break } } catch {}
3386
- }
4334
+ $doc = $null
4335
+ try {
4336
+ $doc = $word.Documents.Add()
4337
+ # 等文档就绪(同 createDocument 的教训:零等待会拿到空壳)
4338
+ for ($i = 0; $i -lt 20; $i++) {
4339
+ Start-Sleep -Milliseconds 150
4340
+ try { $cur = $word.Documents.Item($word.Documents.Count); if (Test-DocHealthy $cur) { $doc = $cur; break } } catch {}
4341
+ }
4342
+ # 空壳判空(2026-10-25 补):文档没就绪就往下走,第一个能力项就会抛
4343
+ # "不能对值为 Null 的表达式调用方法",把"环境没就绪"伪装成"能力不支持"。
4344
+ # 这里显式失败,让门禁把它当 FAIL 而不是当成探测结果。
4345
+ if ($null -eq $doc) {
4346
+ Output-Json @{ success = $false; error = "探测失败:临时文档未就绪(Documents.Add 返回空壳,等待 3 秒仍不可用)" }
4347
+ return
4348
+ }
3387
4349
  # 铺探测素材:一段文字 + 一张 2x2 表 + 一个书签
3388
4350
  try { $null = $doc.Content.InsertAfter("__probe__ 内容") } catch {}
3389
4351
  try { $null = $doc.Tables.Add($doc.Range($doc.Content.End - 1, $doc.Content.End - 1), 2, 2) } catch {}
@@ -3428,9 +4390,11 @@ switch ($Action) {
3428
4390
  } catch {
3429
4391
  Output-Json @{ success = $false; error = "探测失败: $(Get-CallError $_)" }
3430
4392
  } finally {
3431
- # 探测不留垃圾:临时文档不保存直接关。新建文档 FullName 为空,
3432
- # 不能走 closeDocument 的 saveChanges 守卫(它会为从未保存的文档报错),
3433
- # 这里显式 Close($false) 正是"放弃保存"的语义。
4393
+ # 探测不留垃圾:临时文档不保存直接关。
4394
+ # 第 5 轮更正:原注释说"新建文档 FullName 为空"是错的 —— 实测未保存文档的
4395
+ # FullName 非空(等于文档名),空的是 Path。判"存过盘没有"一律看 Path。
4396
+ # 这里不能用 closeDocument 的 saveChanges 守卫(它会为从未保存的文档报错),
4397
+ # 显式 Close($false) 正是"放弃保存"的语义。
3434
4398
  if ($null -ne $doc) { try { $doc.Close($false) } catch {} }
3435
4399
  }
3436
4400
  }
@@ -3441,21 +4405,46 @@ switch ($Action) {
3441
4405
  $doc = $(Resolve-Doc $word $p)
3442
4406
  if ($null -eq $doc) { Output-Json @{ success = $false; error = "No active document" }; return }
3443
4407
  $position = if ($p.position) { $p.position } else { "cursor" }
4408
+ # 第 2 期第 2 章轮 2:钉住文档(documentName 有值)时**绝不能**走 Selection。
4409
+ # Selection 是【全局焦点】:target.doc=A、而 B 恰好是活动文档时,文字会写进 B,
4410
+ # 而且返回 success —— 这正是 A1/A2 要抓的"静默改错"。
4411
+ # 钉住时 cursor 没有意义(光标属于活动文档),退化成"追加到目标文档末尾"。
4412
+ $pinned = [bool]($p -and $p.documentName)
4413
+ $range = $null
3444
4414
  switch ($position) {
3445
- "start" { $range = $doc.Range(0, 0); $range.InsertBefore($p.text) }
3446
- "end" { $range = $doc.Range($doc.Content.End - 1, $doc.Content.End - 1); $range.InsertAfter($p.text) }
3447
- default { $word.Selection.TypeText($p.text) }
4415
+ "start" { $range = $doc.Range(0, 0); $range.InsertBefore([string]$p.text) }
4416
+ "end" { $range = $doc.Range($doc.Content.End - 1, $doc.Content.End - 1); $range.InsertAfter([string]$p.text) }
4417
+ default {
4418
+ if ($pinned) {
4419
+ $range = $doc.Range($doc.Content.End - 1, $doc.Content.End - 1)
4420
+ $range.InsertAfter([string]$p.text)
4421
+ } else {
4422
+ $word.Selection.TypeText([string]$p.text)
4423
+ }
4424
+ }
3448
4425
  }
3449
4426
  if ($p.style) {
3450
- try { $word.Selection.Range.Style = $p.style } catch {}
4427
+ try {
4428
+ if ($pinned -and $null -ne $range) { $range.Style = $p.style }
4429
+ else { $word.Selection.Range.Style = $p.style }
4430
+ } catch {}
3451
4431
  }
3452
- Output-Json @{ success = $true; data = @{ position = $position; textLength = $p.text.Length } }
4432
+ $landed = ''
4433
+ try { $landed = [string]$doc.Name } catch {}
4434
+ # doc = 实际落到了哪一份(钉住时它必须等于 documentName,不等就是串档)
4435
+ Output-Json @{ success = $true; data = @{ position = $position; textLength = $p.text.Length; doc = $landed } }
3453
4436
  }
3454
4437
 
3455
4438
  "setFont" {
3456
4439
  $word = Get-WpsWord
3457
4440
  if ($null -eq $word) { Output-Json @{ success = $false; error = "WPS Word not running" }; return }
3458
4441
  $doc = $(Resolve-Doc $word $p)
4442
+ # 第 2 期第 2 章轮 2:钉住文档 + 非 all 范围 = 用的是【活动文档的选区】,会改错地方。
4443
+ # 与 getSelectedText/setSelectedText 同一条理由:选区钉不住,宁可报错。
4444
+ if ($p.documentName -and $p.range -ne "all") {
4445
+ Output-Json @{ success = $false; error = '[勿重试·先改参数] 钉住文档(documentName)时不能用选区范围改字体:选区属于活动文档,会改到别人身上。请改传 range=all(作用于整份目标文档)。' }
4446
+ return
4447
+ }
3459
4448
  $range = if ($p.range -eq "all") { $doc.Content } else { $word.Selection.Range }
3460
4449
  if ($p.fontName) { $range.Font.Name = $p.fontName }
3461
4450
  if ($p.fontSize) { $range.Font.Size = $p.fontSize }
@@ -3563,18 +4552,31 @@ switch ($Action) {
3563
4552
  if ($null -eq $word) { Output-Json @{ success = $false; error = "WPS Word not running" }; return }
3564
4553
  $doc = $(Resolve-Doc $word $p)
3565
4554
  $breakType = if ($p.type) { $p.type } else { "page" }
3566
- $breakTypeMap = @{ page = 7; column = 8; section = 2; sectionContinuous = 3 }
4555
+ # 第 1 期第 2 章第 2 轮:补 evenPage/oddPage(wdSectionBreakEvenPage=4 / OddPage=5)。
4556
+ # 之前 wps_word_insert_section_break 走的是另一个不存在的动作,而要接住它的四种类型
4557
+ # 就得让这个映射表认识这四个值 —— 否则 evenPage/oddPage 会静默退化成【分页符】,
4558
+ # 用户以为分了节,其实只是换页(后面按节设页边距会全部落到同一节上)。
4559
+ $breakTypeMap = @{ page = 7; column = 8; section = 2; sectionContinuous = 3; evenPage = 4; oddPage = 5 }
3567
4560
  $bt = $breakTypeMap[$breakType]
3568
- if ($null -eq $bt) { $bt = 7 }
4561
+ if ($null -eq $bt) {
4562
+ Output-Json @{ success = $false; error = "[勿重试·先改参数] 不认识的分隔符类型「$breakType」。可用:page / column / section / sectionContinuous / evenPage / oddPage" }
4563
+ return
4564
+ }
3569
4565
  $word.Selection.InsertBreak($bt)
3570
- Output-Json @{ success = $true; data = @{ type = $breakType } }
4566
+ Output-Json @{ success = $true; data = @{ type = $breakType; code = $bt } }
3571
4567
  }
3572
4568
 
3573
4569
  "insertHeader" {
3574
4570
  $word = Get-WpsWord
3575
4571
  if ($null -eq $word) { Output-Json @{ success = $false; error = "WPS Word not running" }; return }
3576
4572
  $doc = $(Resolve-Doc $word $p)
3577
- $section = $doc.Sections.Item(1)
4573
+ # 第 4 轮修:原来硬编码 Sections.Item(1),指定第 3 节完全无效(还返回 success)。
4574
+ $secIdx = if ($p.section) { [int]$p.section } else { 1 }
4575
+ if ($secIdx -lt 1 -or $secIdx -gt $doc.Sections.Count) {
4576
+ Output-Json @{ success = $false; error = "第 $secIdx 节不存在(本文档共 $($doc.Sections.Count) 节)" }
4577
+ return
4578
+ }
4579
+ $section = $doc.Sections.Item($secIdx)
3578
4580
  $header = $section.Headers.Item(1)
3579
4581
  $header.Range.Text = if ($p.text) { $p.text } else { "" }
3580
4582
  if ($p.alignment) {
@@ -3588,7 +4590,13 @@ switch ($Action) {
3588
4590
  $word = Get-WpsWord
3589
4591
  if ($null -eq $word) { Output-Json @{ success = $false; error = "WPS Word not running" }; return }
3590
4592
  $doc = $(Resolve-Doc $word $p)
3591
- $section = $doc.Sections.Item(1)
4593
+ # 同 insertHeader:section 参数以前被丢弃,永远改第 1 节
4594
+ $secIdx = if ($p.section) { [int]$p.section } else { 1 }
4595
+ if ($secIdx -lt 1 -or $secIdx -gt $doc.Sections.Count) {
4596
+ Output-Json @{ success = $false; error = "第 $secIdx 节不存在(本文档共 $($doc.Sections.Count) 节)" }
4597
+ return
4598
+ }
4599
+ $section = $doc.Sections.Item($secIdx)
3592
4600
  $footer = $section.Footers.Item(1)
3593
4601
  $footer.Range.Text = if ($p.text) { $p.text } else { "" }
3594
4602
  if ($p.alignment) {
@@ -3924,11 +4932,44 @@ switch ($Action) {
3924
4932
  "closePresentation" {
3925
4933
  $ppt = Get-WpsPpt
3926
4934
  if ($null -eq $ppt) { Output-Json @{ success = $false; error = "WPS PPT not running" }; return }
3927
- $pres = if ($p.name) { $ppt.Presentations.Item($p.name) } else { $ppt.ActivePresentation }
4935
+ # 按名字定位必须自己遍历:WPS 的 Presentations.Item() 只吃序号,传名字会抛
4936
+ # DISP_E_NOTACOLLECTION("Does not support a collection")—— 实测踩过,
4937
+ # 表现为"关不掉演示文稿",而且报错完全看不出是参数类型问题。
4938
+ $pres = $null
4939
+ if ($p.name) {
4940
+ for ($i = 1; $i -le $ppt.Presentations.Count; $i++) {
4941
+ $cand = $ppt.Presentations.Item($i)
4942
+ if ([string]$cand.Name -eq [string]$p.name) { $pres = $cand; break }
4943
+ }
4944
+ if ($null -eq $pres) {
4945
+ Output-Json @{ success = $false; error = "找不到名为「$($p.name)」的演示文稿" }
4946
+ return
4947
+ }
4948
+ } else {
4949
+ $pres = $ppt.ActivePresentation
4950
+ }
3928
4951
  if ($null -eq $pres) { Output-Json @{ success = $false; error = "No presentation" }; return }
3929
4952
  $name = $pres.Name
4953
+ # 第 3 轮修:原来 $pres.Close() 不带参数,TS 传的 save 被整个丢掉 ——
4954
+ # 既"没保存就关了",未保存文稿还会弹「另存为」卡死通道。与 closeDocument /
4955
+ # closeWorkbook 同一套设计答案:读 saveChanges,未保存 + 要求保存就明确报错。
4956
+ $saveChanges = if ($null -ne $p.saveChanges) { [bool]$p.saveChanges } else { $true }
4957
+ if ($saveChanges) {
4958
+ $hasPath = $false
4959
+ try { $hasPath = -not [string]::IsNullOrEmpty([string]$pres.Path) } catch {} # 吞错有据:读不到 Path 按"从未保存"处理(保守方向,护栏会拦)
4960
+ if (-not $hasPath) {
4961
+ Output-Json @{ success = $false; error = "[勿重试·先另存为] 演示文稿「$name」从未保存过,直接关闭会弹出「另存为」对话框卡住通道(120 秒)。请先另存为(wps_ppt_save_as),或显式传 save=false 放弃保存" }
4962
+ return
4963
+ }
4964
+ }
4965
+ # Presentation.Close() 在 WPS/PPT 的对象模型里【不接受参数】——
4966
+ # 传 $saveChanges 进去会抛 DISP_E_NOTACOLLECTION,看着像集合用法错,其实是方法签名不符。
4967
+ # 想丢弃改动又要抑制「另存为」弹框,标准做法是先把 Saved 置 true 再 Close()。
4968
+ if (-not $saveChanges) { try { $pres.Saved = $true } catch {} }
3930
4969
  $pres.Close()
3931
- Output-Json @{ success = $true; data = @{ closed = $name } }
4970
+ # 第 6 轮:回包补 name。TS 读的是 data.name(打印"名称: xxx"),原来只回 closed
4971
+ # → 每次关闭后用户看到"名称: undefined"(自检里就是这么发现的)。
4972
+ Output-Json @{ success = $true; data = @{ closed = $name; name = $name; saved = [bool]$saveChanges } }
3932
4973
  }
3933
4974
 
3934
4975
  "getOpenPresentations" {
@@ -4048,7 +5089,13 @@ switch ($Action) {
4048
5089
  if ($txt.Length -gt 90) { $txt = $txt.Substring(0, 90) + "…" }
4049
5090
  $hasTxt = $false
4050
5091
  if ($shape.HasTextFrame) { $hasTxt = $true }
4051
- $shapes += @{ name = $shape.Name; type = "$($shape.Type)"; hasText = $hasTxt; text = $txt }
5092
+ # placeholderType:Shape.Type 对所有占位符都是 14(msoPlaceholder),没法区分标题/副标题/正文。
5093
+ # 而 setSlideSubtitle / setSlideContent 正是按 PlaceholderFormat.Type 找占位符的 ——
5094
+ # 不报出来的话,那两个工具报"placeholder not found"时根本无从判断是哪种版式能写。
5095
+ # ppPlaceholder 枚举:1=Title 2=Body 3=CenterTitle 4=Subtitle 7=Object
5096
+ $phType = ""
5097
+ try { if ($shape.Type -eq 14) { $phType = "$($shape.PlaceholderFormat.Type)" } } catch {}
5098
+ $shapes += @{ name = $shape.Name; type = "$($shape.Type)"; placeholderType = $phType; hasText = $hasTxt; text = $txt }
4052
5099
  }
4053
5100
  Output-Json @{ success = $true; data = @{ index = $index; slideIndex = $index; shapeCount = $slide.Shapes.Count; shapesCount = $slide.Shapes.Count; shapes = $shapes; layout = "$($slide.Layout)" } }
4054
5101
  }
@@ -4077,6 +5124,50 @@ switch ($Action) {
4077
5124
  Output-Json @{ success = $true; data = @{ slideIndex = $index; layout = $layout } }
4078
5125
  }
4079
5126
 
5127
+ # 第 6 轮补:setSlideSize / setSlideTheme 两个动作 TS 一直在调,PS 里都没有 case
5128
+ # → 冒烟里稳定报 Unknown action。补上,并且把"做不到的"说清楚,不糊一个 success。
5129
+ "setSlideSize" {
5130
+ $ppt = Get-WpsPpt
5131
+ if ($null -eq $ppt) { Output-Json @{ success = $false; error = "WPS PPT not running" }; return }
5132
+ $pres = Get-TargetPres $ppt $p
5133
+ if ($null -eq $pres) { Output-Json @{ success = $false; error = "No active presentation" }; return }
5134
+ $w = [double]$p.width
5135
+ $h = [double]$p.height
5136
+ if ($w -le 0 -or $h -le 0) {
5137
+ Output-Json @{ success = $false; error = "[勿重试·先改参数] 宽高必须是正数(收到 width=$($p.width) height=$($p.height))" }
5138
+ return
5139
+ }
5140
+ # 单位换算:TS 的 schema 承诺的是【像素】,而 WPS 的 PageSetup 要的是【磅】。
5141
+ # 1 px = 0.75 pt(96 DPI)。不换算的话 960×720 会被当成 960×720 磅 = 13.3×10 英寸,
5142
+ # 页面上所有元素都跑到角落里去 —— 用户看到的是"设完尺寸版面全乱了"。
5143
+ $wPt = $w * 0.75
5144
+ $hPt = $h * 0.75
5145
+ $pres.PageSetup.SlideWidth = $wPt
5146
+ $pres.PageSetup.SlideHeight = $hPt
5147
+ Output-Json @{ success = $true; data = @{ width = $w; height = $h; widthPt = $wPt; heightPt = $hPt; slideCount = $pres.Slides.Count } }
5148
+ }
5149
+
5150
+ "setSlideTheme" {
5151
+ $ppt = Get-WpsPpt
5152
+ if ($null -eq $ppt) { Output-Json @{ success = $false; error = "WPS PPT not running" }; return }
5153
+ $pres = Get-TargetPres $ppt $p
5154
+ if ($null -eq $pres) { Output-Json @{ success = $false; error = "No active presentation" }; return }
5155
+ $theme = [string]$p.theme
5156
+ if (-not $theme) {
5157
+ Output-Json @{ success = $false; error = "[勿重试·先改参数] 要给 theme(模板文件的完整路径)" }
5158
+ return
5159
+ }
5160
+ # WPS 的 COM 只有 ApplyTemplate(文件路径),没有"按主题名切换"的接口。
5161
+ # 传进来的是名字(如「商务主题」)时明确报错 —— 这一条最容易被糊成 success,
5162
+ # 因为 ApplyTemplate 对不存在的文件在某些版本上会静默什么都不做。
5163
+ if (-not (Test-Path -LiteralPath $theme)) {
5164
+ Output-Json @{ success = $false; error = "[勿重试·先改参数] 主题需要【模板文件路径】,而「$theme」不是本机存在的文件。WPS 没有按主题名切换的接口,请改用 .thmx / .potx / .ppt 模板文件的完整路径" }
5165
+ return
5166
+ }
5167
+ $pres.ApplyTemplate($theme)
5168
+ Output-Json @{ success = $true; data = @{ theme = $theme; slideCount = $pres.Slides.Count } }
5169
+ }
5170
+
4080
5171
  "getSlideNotes" {
4081
5172
  $ppt = Get-WpsPpt
4082
5173
  if ($null -eq $ppt) { Output-Json @{ success = $false; error = "WPS PPT not running" }; return }
@@ -4263,13 +5354,15 @@ switch ($Action) {
4263
5354
  $shape = $slide.Shapes.Item($i)
4264
5355
  $placeholderType = $null
4265
5356
  try { $placeholderType = $shape.PlaceholderFormat.Type } catch {}
4266
- if ($placeholderType -eq 2) {
5357
+ if ($placeholderType -eq 4) {
4267
5358
  $shape.TextFrame.TextRange.Text = if ($p.subtitle) { $p.subtitle } else { "" }
4268
5359
  Output-Json @{ success = $true; data = @{ slideIndex = $slideIndex; subtitle = $p.subtitle } }
4269
5360
  return
4270
5361
  }
4271
5362
  }
4272
- Output-Json @{ success = $false; error = "Subtitle placeholder not found" }
5363
+ # 这两个工具的占位符编号是按 PlaceholderFormat.Type 匹配的,编号是【实测】出来的,
5364
+ # 不是查表抄的(WPS 的版式与 PowerPoint 不完全一样)。见 getSlideInfo 的 placeholderType 字段。
5365
+ Output-Json @{ success = $false; error = "[勿重试·先换版式] 本页没有副标题占位符(需要 PlaceholderFormat.Type=4)。WPS 上只有 layout='title' 的页有;空白页/标题+正文页没有。用 wps_ppt_add_slide(layout:'title') 新建一页,或改用 wps_ppt_set_slide_content 写正文占位符" }
4273
5366
  }
4274
5367
 
4275
5368
  "setSlideContent" {
@@ -4282,13 +5375,17 @@ switch ($Action) {
4282
5375
  $shape = $slide.Shapes.Item($i)
4283
5376
  $placeholderType = $null
4284
5377
  try { $placeholderType = $shape.PlaceholderFormat.Type } catch {}
4285
- if ($placeholderType -eq 7) {
5378
+ # 2 = ppPlaceholderBody,7 = ppPlaceholderObject。
5379
+ # 实测 WPS 的 title_content 版式给的是 2(不是 PowerPoint 常见的 7),
5380
+ # 而这里原来只认 7 —— 于是"标题+正文"版式的页永远报 Content placeholder not found。
5381
+ # two_column / comparison 版式还有多个正文占位符,取第一个。
5382
+ if ($placeholderType -eq 2 -or $placeholderType -eq 7) {
4286
5383
  $shape.TextFrame.TextRange.Text = if ($p.content) { $p.content } else { "" }
4287
- Output-Json @{ success = $true; data = @{ slideIndex = $slideIndex } }
5384
+ Output-Json @{ success = $true; data = @{ slideIndex = $slideIndex; content = $p.content } }
4288
5385
  return
4289
5386
  }
4290
5387
  }
4291
- Output-Json @{ success = $false; error = "Content placeholder not found" }
5388
+ Output-Json @{ success = $false; error = "[勿重试·先换版式] 本页没有正文占位符(需要 PlaceholderFormat.Type=2 或 7)。WPS 上 layout='title_content' / 'two_column' / 'comparison' 的页有;空白页没有。用 wps_ppt_add_slide(layout:'title_content') 新建一页,或改用 wps_ppt_add_textbox 自己放一个文本框" }
4292
5389
  }
4293
5390
 
4294
5391
  "addShape" {
@@ -4357,6 +5454,55 @@ switch ($Action) {
4357
5454
  Output-Json @{ success = $true; data = @{ name = $shape.Name } }
4358
5455
  }
4359
5456
 
5457
+ # 第 6 轮补:TS 侧 wps_ppt_set_font_color 一直在调 setFontColor,但 PS 里没有这个 case,
5458
+ # 于是永远报 Unknown action(冒烟里就是这条)。注意"空文本"必须报错而不是返回 success ——
5459
+ # 给一个没有文字的形状设字体颜色,改了也看不见,属于本轮要消灭的假成功。
5460
+ "setFontColor" {
5461
+ $ppt = Get-WpsPpt
5462
+ if ($null -eq $ppt) { Output-Json @{ success = $false; error = "WPS PPT not running" }; return }
5463
+ $pres = Get-TargetPres $ppt $p
5464
+ if ($null -eq $pres) { Output-Json @{ success = $false; error = "No active presentation" }; return }
5465
+ $slideIndex = if ($p.slideIndex) { $p.slideIndex } else { 1 }
5466
+ $slide = $pres.Slides.Item($slideIndex)
5467
+ $shape = $slide.Shapes.Item($(if ($p.name) { $p.name } else { $p.shapeIndex }))
5468
+ $rgb = Convert-ColorToRgbInt([string]$p.color)
5469
+ if ($null -eq $rgb) {
5470
+ Output-Json @{ success = $false; error = "[勿重试·先改参数] 颜色「$($p.color)」无法识别。请用 #RRGGBB(如 #FF0000)或常见颜色名(red/green/blue/black/white/yellow/orange/purple/gray/pink/cyan/magenta)" }
5471
+ return
5472
+ }
5473
+ if (-not $shape.HasTextFrame) {
5474
+ Output-Json @{ success = $false; error = "第 $slideIndex 页第 $($p.shapeIndex) 个形状没有文本框,无法设置文字颜色(要改填充色用 wps_ppt_set_shape_fill)" }
5475
+ return
5476
+ }
5477
+ if (-not $shape.TextFrame.HasText) {
5478
+ Output-Json @{ success = $false; error = "第 $slideIndex 页第 $($p.shapeIndex) 个形状是空文本,设置字色不会有任何可见变化。请先 wps_ppt_set_shape_text 写入文字" }
5479
+ return
5480
+ }
5481
+ $shape.TextFrame.TextRange.Font.Color.RGB = $rgb
5482
+ Output-Json @{ success = $true; data = @{ name = $shape.Name; color = [string]$p.color } }
5483
+ }
5484
+
5485
+ # 第 3 轮补:TS 侧 wps_ppt_set_shape_fill 早就在调这个动作,但 PS 里没有这个 case,
5486
+ # 于是每次都报 Unknown action(表现为"工具坏了"而不是"参数丢了")。
5487
+ # 写法照 setShapeStyle 的 fillColor 分支,只是参数名叫 color(schema 承诺的就是 color)。
5488
+ "setShapeFill" {
5489
+ $ppt = Get-WpsPpt
5490
+ if ($null -eq $ppt) { Output-Json @{ success = $false; error = "WPS PPT not running" }; return }
5491
+ $pres = Get-TargetPres $ppt $p
5492
+ $slideIndex = if ($p.slideIndex) { $p.slideIndex } else { 1 }
5493
+ $slide = $pres.Slides.Item($slideIndex)
5494
+ $shape = $slide.Shapes.Item($(if ($p.name) { $p.name } else { $p.shapeIndex }))
5495
+ if ($p.color) {
5496
+ $fillColor = Convert-HexColorToRgbInt([string]$p.color)
5497
+ if ($null -ne $fillColor) {
5498
+ $shape.Fill.Visible = $true
5499
+ $shape.Fill.Solid()
5500
+ $shape.Fill.ForeColor.RGB = $fillColor
5501
+ }
5502
+ }
5503
+ Output-Json @{ success = $true; data = @{ name = $shape.Name; color = $p.color } }
5504
+ }
5505
+
4360
5506
  "setShapeText" {
4361
5507
  $ppt = Get-WpsPpt
4362
5508
  if ($null -eq $ppt) { Output-Json @{ success = $false; error = "WPS PPT not running" }; return }
@@ -4423,10 +5569,10 @@ switch ($Action) {
4423
5569
  $old = $slide.Shapes.Item($sel)
4424
5570
  $l = $old.Left; $t = $old.Top; $w = $old.Width; $h = $old.Height
4425
5571
  $rot = 0
4426
- try { $rot = $old.Rotation } catch {}
5572
+ try { $rot = $old.Rotation } catch {} # 吞错有据:旋转角读不到按 0 处理
4427
5573
  $old.Delete()
4428
5574
  $pic = $slide.Shapes.AddPicture($newPath, $false, $true, $l, $t, $w, $h)
4429
- try { $pic.Rotation = $rot } catch {}
5575
+ try { $pic.Rotation = $rot } catch {} # 吞错有据:旋转角写不回按原样放置
4430
5576
  Output-Json @{ success = $true; data = @{ name = $pic.Name; left = $l; top = $t; width = $w; height = $h; path = $newPath } }
4431
5577
  }
4432
5578
 
@@ -4442,7 +5588,20 @@ switch ($Action) {
4442
5588
  if ($null -ne $p.width) { $shape.Width = $p.width }
4443
5589
  if ($null -ne $p.height) { $shape.Height = $p.height }
4444
5590
  if ($null -ne $p.rotation) { $shape.Rotation = $p.rotation }
4445
- Output-Json @{ success = $true; data = @{ name = $shape.Name } }
5591
+ # 样式:schema 承诺了 style{borderColor,borderWidth,...},而这个 case 以前只摆位置,
5592
+ # 传了样式等于没传(返回 success,图上啥都没变)。这里真正落到 Line 上。
5593
+ if ($p.borderColor -or $p.borderWidth) {
5594
+ try {
5595
+ $shape.Line.Visible = $true
5596
+ if ($p.borderColor) {
5597
+ $bc = Convert-HexColorToRgbInt([string]$p.borderColor)
5598
+ if ($null -ne $bc) { $shape.Line.ForeColor.RGB = $bc }
5599
+ }
5600
+ if ($null -ne $p.borderWidth) { $shape.Line.Weight = [double]$p.borderWidth }
5601
+ } catch {}
5602
+ }
5603
+ if ($p.shadow -and $p.shadow -is [string]) { } # 历史形状,忽略
5604
+ Output-Json @{ success = $true; data = @{ name = $shape.Name; styled = [bool]($p.borderColor -or $p.borderWidth) } }
4446
5605
  }
4447
5606
 
4448
5607
  "exportSlideAsImage" {
@@ -4490,7 +5649,19 @@ switch ($Action) {
4490
5649
  $width = if ($p.width) { $p.width } else { 400 }
4491
5650
  $height = if ($p.height) { $p.height } else { 200 }
4492
5651
  $table = $slide.Shapes.AddTable($rows, $cols, $left, $top, $width, $height)
4493
- Output-Json @{ success = $true; data = @{ name = $table.Name; rows = $rows; cols = $cols } }
5652
+ # 第 3 轮补 tableIndex:原来只回 name,TS 侧读 tableIndex 于是永远打印
5653
+ # "表格索引: undefined"。而 set_table_cell / set_table_row_style / get_table_cell
5654
+ # 全都按"第 N 个表格"定位 —— 不给序号,调用方建完表没法接着操作。
5655
+ # 算法与 setPptTableCellStyle 的定位算法一致:数本页 HasTable 的形状,新表排第几就是几。
5656
+ $tableIndex = 0
5657
+ for ($i = 1; $i -le $slide.Shapes.Count; $i++) {
5658
+ $s = $slide.Shapes.Item($i)
5659
+ if ($s.HasTable) {
5660
+ $tableIndex++
5661
+ if ($s.Name -eq $table.Name) { break }
5662
+ }
5663
+ }
5664
+ Output-Json @{ success = $true; data = @{ name = $table.Name; tableIndex = $tableIndex; rows = $rows; cols = $cols } }
4494
5665
  }
4495
5666
 
4496
5667
  "setPptTableCell" {
@@ -4557,12 +5728,64 @@ switch ($Action) {
4557
5728
  $pres = Get-TargetPres $ppt $p
4558
5729
  $slideIndex = if ($p.slideIndex) { $p.slideIndex } else { 1 }
4559
5730
  $slide = $pres.Slides.Item($slideIndex)
4560
- $shape = $slide.Shapes.Item($(if ($p.tableName) { $p.tableName } else { $p.tableIndex }))
5731
+ # tableIndex 是"第几个表格",不是"第几个形状" —— 以前直接当形状序号用,
5732
+ # 拿到的往往是矩形文本框,于是设样式全落空、返回却是 success。
5733
+ $shape = $null
5734
+ if ($p.tableName) {
5735
+ try { $shape = $slide.Shapes.Item([string]$p.tableName) } catch {}
5736
+ }
5737
+ if ($null -eq $shape) {
5738
+ $want = if ($null -ne $p.tableIndex) { [int]$p.tableIndex } else { 1 }
5739
+ $seen = 0
5740
+ for ($i = 1; $i -le $slide.Shapes.Count; $i++) {
5741
+ $cand = $slide.Shapes.Item($i)
5742
+ $isTable = $false
5743
+ try { $isTable = [bool]$cand.HasTable } catch {}
5744
+ if ($isTable) {
5745
+ $seen++
5746
+ if ($seen -eq $want) { $shape = $cand; break }
5747
+ }
5748
+ }
5749
+ }
5750
+ if ($null -eq $shape) {
5751
+ Output-Json @{ success = $false; error = "[勿重试·先改参数] 本页找不到第 $($p.tableIndex) 个表格" }
5752
+ return
5753
+ }
4561
5754
  if ($null -ne $p.left) { $shape.Left = $p.left }
4562
5755
  if ($null -ne $p.top) { $shape.Top = $p.top }
4563
5756
  if ($null -ne $p.width) { $shape.Width = $p.width }
4564
5757
  if ($null -ne $p.height) { $shape.Height = $p.height }
4565
- Output-Json @{ success = $true; data = @{ name = $shape.Name } }
5758
+ # 样式:这个 case 以前只摆位置/尺寸,传了 headerColor/fontSize 也什么都不做。
5759
+ $styled = 0
5760
+ try {
5761
+ if ($shape.HasTable) {
5762
+ $tbl = $shape.Table
5763
+ if ($p.headerColor) {
5764
+ $hc = Convert-HexColorToRgbInt([string]$p.headerColor)
5765
+ if ($null -ne $hc) {
5766
+ for ($c = 1; $c -le $tbl.Columns.Count; $c++) {
5767
+ $tbl.Cell(1, $c).Shape.Fill.ForeColor.RGB = $hc
5768
+ }
5769
+ $styled++
5770
+ }
5771
+ }
5772
+ if ($null -ne $p.fontSize -or $p.fontColor -or $null -ne $p.bold) {
5773
+ for ($r = 1; $r -le $tbl.Rows.Count; $r++) {
5774
+ for ($c = 1; $c -le $tbl.Columns.Count; $c++) {
5775
+ $tr = $tbl.Cell($r, $c).Shape.TextFrame.TextRange
5776
+ if ($null -ne $p.fontSize) { $tr.Font.Size = [double]$p.fontSize }
5777
+ if ($p.fontColor) {
5778
+ $fc = Convert-HexColorToRgbInt([string]$p.fontColor)
5779
+ if ($null -ne $fc) { $tr.Font.Color.RGB = $fc }
5780
+ }
5781
+ if ($null -ne $p.bold) { $tr.Font.Bold = [bool]$p.bold }
5782
+ }
5783
+ }
5784
+ $styled++
5785
+ }
5786
+ }
5787
+ } catch {}
5788
+ Output-Json @{ success = $true; data = @{ name = $shape.Name; styled = ($styled -gt 0) } }
4566
5789
  }
4567
5790
 
4568
5791
  "setPptTableCellStyle" {
@@ -4624,18 +5847,38 @@ switch ($Action) {
4624
5847
  if ($null -eq $shape -or -not $shape.HasTable) { Output-Json @{ success = $false; error = "Table not found" }; return }
4625
5848
  $rowIndex = if ($p.row) { $p.row } else { 1 }
4626
5849
  $row = $shape.Table.Rows.Item($rowIndex)
5850
+ # 参数形状归一化(第 3 轮修"假成功"):
5851
+ # TS 侧 schema 承诺 style:{backgroundColor,fontColor,fontSize,bold,italic,fontName,alignment,height},
5852
+ # 而历史裸调用(wps_execute_method 直穿)用的是扁平 $p.backgroundColor。
5853
+ # 两个形状都接:扁平优先(显式传来的),嵌套补位。只认一个,另一半调用方就是
5854
+ # "返回 success 但一个格子都没变"—— 那正是本轮要消灭的假成功。
5855
+ $st = @{}
5856
+ if ($p.style) {
5857
+ foreach ($k in $p.style.PSObject.Properties.Name) { $st[$k] = $p.style.$k }
5858
+ }
5859
+ foreach ($k in @('backgroundColor', 'fontColor', 'fontSize', 'bold', 'italic', 'fontName', 'alignment', 'height')) {
5860
+ if ($p.PSObject.Properties.Name -contains $k -and -not $st.ContainsKey($k)) { $st[$k] = $p.$k }
5861
+ }
5862
+ if ($null -ne $st.height) { $row.Height = $st.height }
4627
5863
  for ($c = 1; $c -le $row.Cells.Count; $c++) {
4628
5864
  $cellShape = $row.Cells.Item($c).Shape
4629
- if ($p.backgroundColor) {
4630
- $bg = Convert-HexColorToRgbInt([string]$p.backgroundColor)
5865
+ if ($st.backgroundColor) {
5866
+ $bg = Convert-HexColorToRgbInt([string]$st.backgroundColor)
4631
5867
  if ($null -ne $bg) { $cellShape.Fill.Visible = $true; $cellShape.Fill.Solid(); $cellShape.Fill.ForeColor.RGB = $bg }
4632
5868
  }
4633
- if ($p.fontColor) {
4634
- $fc = Convert-HexColorToRgbInt([string]$p.fontColor)
5869
+ if ($st.fontColor) {
5870
+ $fc = Convert-HexColorToRgbInt([string]$st.fontColor)
4635
5871
  if ($null -ne $fc) { $cellShape.TextFrame.TextRange.Font.Color.RGB = $fc }
4636
5872
  }
4637
- if ($p.fontSize) { $cellShape.TextFrame.TextRange.Font.Size = $p.fontSize }
4638
- if ($null -ne $p.bold) { $cellShape.TextFrame.TextRange.Font.Bold = $p.bold }
5873
+ if ($st.fontSize) { $cellShape.TextFrame.TextRange.Font.Size = $st.fontSize }
5874
+ if ($null -ne $st.bold) { $cellShape.TextFrame.TextRange.Font.Bold = $st.bold }
5875
+ if ($null -ne $st.italic) { $cellShape.TextFrame.TextRange.Font.Italic = $st.italic }
5876
+ if ($st.fontName) { $cellShape.TextFrame.TextRange.Font.Name = $st.fontName }
5877
+ if ($st.alignment) {
5878
+ $alignMap = @{ left = 1; center = 2; right = 3 }
5879
+ $al = $alignMap[[string]$st.alignment]
5880
+ if ($null -ne $al) { $cellShape.TextFrame.TextRange.ParagraphFormat.Alignment = $al }
5881
+ }
4639
5882
  }
4640
5883
  Output-Json @{ success = $true; data = @{ row = $rowIndex } }
4641
5884
  }
@@ -4667,6 +5910,12 @@ switch ($Action) {
4667
5910
  $slide = $pres.Slides.Item($slideIndex)
4668
5911
  $bg = $slide.Background.Fill
4669
5912
  $bg.Visible = $true
5913
+ # 同 setShapeGradient:schema 给 gradient:{colors:[...]},摊平后是 $p.colors
5914
+ if ($null -eq $p.color1 -and $p.colors) {
5915
+ $arr = @($p.colors)
5916
+ if ($arr.Count -ge 1) { $p | Add-Member -NotePropertyName color1 -NotePropertyValue $arr[0] -Force }
5917
+ if ($arr.Count -ge 2) { $p | Add-Member -NotePropertyName color2 -NotePropertyValue $arr[1] -Force }
5918
+ }
4670
5919
  $bg.TwoColorGradient(1, 1)
4671
5920
  if ($p.color1) {
4672
5921
  $c1 = Convert-HexColorToRgbInt([string]$p.color1)
@@ -4686,6 +5935,13 @@ switch ($Action) {
4686
5935
  $slideIndex = if ($p.slideIndex) { $p.slideIndex } else { 1 }
4687
5936
  $slide = $pres.Slides.Item($slideIndex)
4688
5937
  $shape = $slide.Shapes.Item($(if ($p.name) { $p.name } else { $p.shapeIndex }))
5938
+ # 文档承诺的是 gradient:{type,colors:["#a","#b"]},入口摊平后变成 $p.colors;
5939
+ # 而这里只认 $p.color1/$p.color2 —— 于是"传了渐变却什么都没变"。两种都接。
5940
+ if ($null -eq $p.color1 -and $p.colors) {
5941
+ $arr = @($p.colors)
5942
+ if ($arr.Count -ge 1) { $p | Add-Member -NotePropertyName color1 -NotePropertyValue $arr[0] -Force }
5943
+ if ($arr.Count -ge 2) { $p | Add-Member -NotePropertyName color2 -NotePropertyValue $arr[1] -Force }
5944
+ }
4689
5945
  $shape.Fill.TwoColorGradient(1, 1)
4690
5946
  if ($p.color1) {
4691
5947
  $c1 = Convert-HexColorToRgbInt([string]$p.color1)
@@ -4720,7 +5976,14 @@ switch ($Action) {
4720
5976
  $slideIndex = if ($p.slideIndex) { $p.slideIndex } else { 1 }
4721
5977
  $slide = $pres.Slides.Item($slideIndex)
4722
5978
  $shape = $slide.Shapes.Item($(if ($p.name) { $p.name } else { $p.shapeIndex }))
4723
- if ($null -ne $p.transparency) { $shape.Fill.Transparency = $p.transparency }
5979
+ if ($null -ne $p.transparency) {
5980
+ # 工具/文档说的是"百分比 0~100",COM 要的是 0~1 —— 直接塞 50 会报"值不在预期的范围内"。
5981
+ $tv = [double]$p.transparency
5982
+ if ($tv -gt 1) { $tv = $tv / 100 }
5983
+ if ($tv -lt 0) { $tv = 0 }
5984
+ if ($tv -gt 1) { $tv = 1 }
5985
+ $shape.Fill.Transparency = $tv
5986
+ }
4724
5987
  Output-Json @{ success = $true; data = @{ name = $shape.Name } }
4725
5988
  }
4726
5989
 
@@ -4758,6 +6021,14 @@ switch ($Action) {
4758
6021
  $alignMap = @{ left = 1; center = 2; right = 3; top = 4; middle = 5; bottom = 6 }
4759
6022
  $align = $alignMap[$p.alignment]
4760
6023
  if ($null -eq $align) { $align = 1 }
6024
+ # 没给形状清单就【不要】替用户选。
6025
+ # Shapes.Range($null) 在 WPS 上不是报错,是"整页所有形状"——
6026
+ # 于是一个只想对齐两个形状的调用,会把表格、图片、母版继承的占位符一起搬走,
6027
+ # 而且工具回 success。宁可响亮失败([勿重试·先改参数]),也不要静默改整页。
6028
+ if (-not $p.names -or @($p.names).Count -eq 0) {
6029
+ Output-Json @{ success = $false; error = "[勿重试·先改参数] alignShapes 需要 shapeIndices(要参与对齐的形状序号数组)。不给就整页对齐会误伤表格/图片,请传 shapeIndices(1 起)" }
6030
+ return
6031
+ }
4761
6032
  $range = $slide.Shapes.Range($p.names)
4762
6033
  $range.Align($align, 1)
4763
6034
  Output-Json @{ success = $true; data = @{ alignment = $p.alignment } }
@@ -4823,8 +6094,33 @@ switch ($Action) {
4823
6094
  $top = if ($p.top) { $p.top } else { 100 }
4824
6095
  $width = if ($p.width) { $p.width } else { 400 }
4825
6096
  $height = if ($p.height) { $p.height } else { 300 }
4826
- $shape = $slide.Shapes.AddChart($p.type, $left, $top, $width, $height)
4827
- Output-Json @{ success = $true; data = @{ name = $shape.Name } }
6097
+ # AddChart 的第一个参数是 xlChartType 枚举(数字),不是类型名字符串。
6098
+ # 之前这里直接把 $p.type 丢进去:TS 传 chartType 时它是 $null(靠 COM 兜默认值蒙混过去),
6099
+ # 入口归一化把 chartType 映射成 type 之后,"bar" 这个字符串就撞上来了 ——
6100
+ # 报"无法将类型 string 的 bar 值转换为类型"。根因是这张枚举表从来没写过。
6101
+ # 现在显式翻译:名字 → 数字;已经是数字的照用;认不出来的退回柱状图(Excel 侧同一套表,见 addChart)。
6102
+ $chartTypeEnum = @{
6103
+ column = 51; column_clustered = 51; column_stacked = 52
6104
+ bar = 57; bar_clustered = 57; bar_stacked = 58
6105
+ line = 4; line_markers = 65; line_stacked = 63
6106
+ pie = 5; doughnut = -4120
6107
+ area = 1; area_stacked = 76
6108
+ scatter = -4169; bubble = 15; radar = -4151
6109
+ }
6110
+ $rawType = if ($null -ne $p.type) { $p.type } elseif ($null -ne $p.chartType) { $p.chartType } else { $null }
6111
+ $chartType = if ($rawType -is [int] -or $rawType -is [long] -or $rawType -is [double]) {
6112
+ [int]$rawType
6113
+ } elseif ($null -ne $rawType -and $chartTypeEnum.ContainsKey([string]$rawType)) {
6114
+ $chartTypeEnum[[string]$rawType]
6115
+ } else {
6116
+ 51
6117
+ }
6118
+ $before = $slide.Shapes.Count
6119
+ $shape = $slide.Shapes.AddChart($chartType, $left, $top, $width, $height)
6120
+ # 回 chartIndex(= 插入后的形状总数,因为 AddChart 总是追加在最后)。
6121
+ # TS 的 insertPptChartHandler 打印的是 data.chartIndex,原来不返回 → 用户永远看到
6122
+ # "图表索引: undefined",而后续 set_ppt_chart_data / set_ppt_chart_style 恰恰靠它定位图表。
6123
+ Output-Json @{ success = $true; data = @{ name = $shape.Name; chartType = $chartType; chartIndex = $slide.Shapes.Count; previousShapeCount = $before } }
4828
6124
  }
4829
6125
 
4830
6126
  "addAnimation" {
@@ -4833,9 +6129,53 @@ switch ($Action) {
4833
6129
  $pres = Get-TargetPres $ppt $p
4834
6130
  $slideIndex = if ($p.slideIndex) { $p.slideIndex } else { 1 }
4835
6131
  $slide = $pres.Slides.Item($slideIndex)
4836
- $shape = $slide.Shapes.Item($p.shapeName)
4837
- $slide.TimeLine.MainSequence.AddEffect($shape, $p.effect, 1)
4838
- Output-Json @{ success = $true }
6132
+ # 两个致命点,都是实测踩出来的(不是推测):
6133
+ # 1) 老实现只读 shapeName,而工具传的是 shapeIndex → Shapes.Item($null) 拿到坏对象,
6134
+ # AddEffect 之后【整页】的 Shapes/Background 全部报"不能对 Null 值表达式调用方法",
6135
+ # 而且文稿列表还正常 —— 表现像"69 个工具一起坏了",实际是这一条把页状态弄坏了。
6136
+ # 2) effect 直接透传字符串("fadeIn"),而 AddEffect 要的是 MsoAnimEffect 枚举数字。
6137
+ # 这里补一张小表,认不出的明确报错,不再把坏值喂给 COM。
6138
+ $shape = $null
6139
+ if ($p.shapeName) { try { $shape = $slide.Shapes.Item([string]$p.shapeName) } catch {} }
6140
+ if ($null -eq $shape -and $p.shapeIndex) { try { $shape = $slide.Shapes.Item([int]$p.shapeIndex) } catch {} }
6141
+ if ($null -eq $shape) {
6142
+ Output-Json @{ success = $false; error = "[勿重试·先改参数] 找不到要加动画的形状:shapeIndex(1 起)/shapeName 都没给或不存在" }
6143
+ return
6144
+ }
6145
+ # animationType 是已下线工具 wps_ppt_set_animation 的旧键名,仍认(否则老调用一律失败)
6146
+ $rawEffect = if ($p.effect) { $p.effect } elseif ($p.animationType) { $p.animationType } else { $null }
6147
+ if (-not $rawEffect) {
6148
+ Output-Json @{ success = $false; error = "[勿重试·先改参数] 缺少 effect(可用:appear/fadeIn/flyIn/wipeIn/zoomIn/pulse/spin/grow/teeter,或直接给 MsoAnimEffect 数字)" }
6149
+ return
6150
+ }
6151
+ # 第 8 轮动画族合并后,这张表要同时接住三类:入场(entrance)、强调(emphasis)、退场(exit)。
6152
+ # 强调那几个值沿用 addEmphasisAnimation 一直在用的;退场在 WPS 上没有稳定的枚举名,
6153
+ # 所以【不猜】—— 认不出的名字会明确报错并提示改传 MsoAnimEffect 数字(AddEffect 是吃数字的)。
6154
+ $effectMap = @{
6155
+ # 入场
6156
+ appear = 1; fadeIn = 10; flyIn = 2; wipeIn = 22; zoomIn = 53; bounceIn = 26; spinIn = 15
6157
+ dissolveIn = 9; boxIn = 4; circleIn = 6; diamondIn = 8; wheelIn = 21; plusIn = 13
6158
+ wedgeIn = 20; randomBarsIn = 14; stripsIn = 18; blindsIn = 3; checkerboardIn = 5
6159
+ crawlIn = 7; stretchIn = 17; swivelIn = 19; floatUp = 30; riseUp = 34; thinLine = 36
6160
+ unfold = 37; whip = 38; expand = 50; shrink = 46
6161
+ # 强调(与 addEmphasisAnimation 用的是同一套)
6162
+ pulse = 63; spin = 15; grow = 59; teeter = 28; colorPulse = 62
6163
+ }
6164
+ $effectId = if ($rawEffect -is [int] -or $rawEffect -is [long] -or $rawEffect -is [double]) { [int]$rawEffect } elseif ($effectMap.ContainsKey([string]$rawEffect)) { $effectMap[[string]$rawEffect] } else { $null }
6165
+ if ($null -eq $effectId) {
6166
+ Output-Json @{ success = $false; error = "[勿重试·先改参数] 不认识的 effect「$($p.effect)」;常用:appear/fadeIn/flyIn/wipeIn/zoomIn(入场)、pulse/spin/grow/teeter(强调)。退场效果请直接给 MsoAnimEffect 数字(AddEffect 吃的是数字)" }
6167
+ return
6168
+ }
6169
+ try {
6170
+ # 第三个参数是 Level(文本级别),不是"触发时机"。对没有文本的形状必须传
6171
+ # msoAnimateLevelNone(0):传 1 会让 WPS 建出【两条】一模一样的效果
6172
+ # (实测 count=2,getAnimations 里两条同名同效果),删一条还剩一条,看起来像删不掉。
6173
+ $slide.TimeLine.MainSequence.AddEffect($shape, $effectId, 0) | Out-Null
6174
+ } catch {
6175
+ Output-Json @{ success = $false; error = "添加动画失败:$(Get-CallError $_)" }
6176
+ return
6177
+ }
6178
+ Output-Json @{ success = $true; data = @{ slideIndex = $slideIndex; effectId = $effectId; count = $slide.TimeLine.MainSequence.Count } }
4839
6179
  }
4840
6180
 
4841
6181
  "setSlideTransition" {
@@ -4844,8 +6184,26 @@ switch ($Action) {
4844
6184
  $pres = Get-TargetPres $ppt $p
4845
6185
  $slideIndex = if ($p.slideIndex) { $p.slideIndex } else { 1 }
4846
6186
  $slide = $pres.Slides.Item($slideIndex)
4847
- $slide.SlideShowTransition.EntryEffect = $p.effect
4848
- Output-Json @{ success = $true; data = @{ slideIndex = $slideIndex; effect = $p.effect } }
6187
+ # 合并后的 wps_ppt_set_transition 传的是 effect;旧的直接调用方还在传 transition,两个都认。
6188
+ if ($null -eq $p.effect -and $p.transition) { $p | Add-Member -NotePropertyName effect -NotePropertyValue $p.transition -Force }
6189
+ $effectName = if ($p.effect) { ([string]$p.effect).ToLower() } else { "fade" }
6190
+ # EntryEffect 是 PpEntryEffect 枚举:直接赋字符串 WPS 会抛"指定的转换无效",
6191
+ # 而以前这里就是把 $p.effect 原样赋过去 —— 取消切换(none)更是必然炸。
6192
+ $effectMap = @{ none = 0; fade = 1; push = 2; wipe = 3; split = 4; reveal = 5; cover = 6; dissolve = 7; curtains = 8; random = 6; blinds = 3 }
6193
+ $entry = -1
6194
+ if ($effectMap.ContainsKey($effectName)) { $entry = $effectMap[$effectName] }
6195
+ elseif ($effectName -match '^\d+$') { $entry = [int]$effectName }
6196
+ if ($entry -lt 0) {
6197
+ Output-Json @{ success = $false; error = "不认识的切换效果:$effectName(可用:none/fade/push/wipe/split/reveal/cover/dissolve/curtains)" }
6198
+ return
6199
+ }
6200
+ $tr = $slide.SlideShowTransition
6201
+ $tr.EntryEffect = $entry
6202
+ $dur = 0.0
6203
+ if ($p.duration) { try { $dur = [double]$p.duration } catch { $dur = 0.0 } }
6204
+ if ($dur -gt 0) { try { $tr.Duration = $dur } catch {} }
6205
+ # WPS COM 没有"切换时播放声音"的接口(那是 PowerPoint 的 AddMediaObject2),传了如实回报而不是假装生效
6206
+ Output-Json @{ success = $true; data = @{ slideIndex = $slideIndex; effect = $effectName; entryEffect = $entry; duration = $dur; soundApplied = $false } }
4849
6207
  }
4850
6208
 
4851
6209
  "setSlideBackground" {
@@ -4862,6 +6220,27 @@ switch ($Action) {
4862
6220
  $slide.FollowMasterBackground = $false
4863
6221
  $slide.Background.Fill.UserPicture($p.imagePath)
4864
6222
  }
6223
+ # 渐变:合并后的 wps_ppt_set_background(target=slide,type=gradient) 走的就是这条,
6224
+ # 而这里以前只认 color/imagePath → 传渐变没反应。colors 数组与 color1/color2 都接。
6225
+ if ($null -eq $p.color1 -and $p.colors) {
6226
+ $arr = @($p.colors)
6227
+ if ($arr.Count -ge 1) { $p | Add-Member -NotePropertyName color1 -NotePropertyValue $arr[0] -Force }
6228
+ if ($arr.Count -ge 2) { $p | Add-Member -NotePropertyName color2 -NotePropertyValue $arr[1] -Force }
6229
+ }
6230
+ if ($p.color1) {
6231
+ try {
6232
+ $slide.FollowMasterBackground = $false
6233
+ $bgf = $slide.Background.Fill
6234
+ $bgf.Visible = $true
6235
+ $bgf.TwoColorGradient(1, 1)
6236
+ $c1 = Convert-HexColorToRgbInt([string]$p.color1)
6237
+ if ($null -ne $c1) { $bgf.ForeColor.RGB = $c1 }
6238
+ if ($p.color2) {
6239
+ $c2 = Convert-HexColorToRgbInt([string]$p.color2)
6240
+ if ($null -ne $c2) { $bgf.BackColor.RGB = $c2 }
6241
+ }
6242
+ } catch {}
6243
+ }
4865
6244
  Output-Json @{ success = $true; data = @{ slideIndex = $slideIndex } }
4866
6245
  }
4867
6246
 
@@ -4969,7 +6348,8 @@ switch ($Action) {
4969
6348
  }
4970
6349
  } catch {}
4971
6350
  }
4972
- Output-Json @{ success = $true; data = @{ style = $schemeKey; count = $count } }
6351
+ # 第 6 轮:把"改了几个文本"和"处理了哪页"分开回,TS 才不会把 count 当页数打印。
6352
+ Output-Json @{ success = $true; data = @{ style = $schemeKey; count = $count; slideCount = 1; slideIndex = $slideIndex } }
4973
6353
  }
4974
6354
 
4975
6355
  "createKpiCards" {
@@ -4979,7 +6359,11 @@ switch ($Action) {
4979
6359
  $slideIndex = if ($p.slideIndex) { $p.slideIndex } else { 1 }
4980
6360
  $slide = $pres.Slides.Item($slideIndex)
4981
6361
 
4982
- $cards = if ($p.cards) { $p.cards } else { @() }
6362
+ # `@(...)` 不是多余的:写成 `$cards = if ($p.cards) { $p.cards }` 时,
6363
+ # PowerShell 会把【单元素】数组在管道里摊平,$cards 变成裸 PSCustomObject,
6364
+ # 它的 .Count 是空的 → 下面的 for 一次都不跑 → 工具返回 success 却一个形状都没建。
6365
+ # (createMiniCharts / smartDistribute 是同一个写法,同一个坑。)
6366
+ $cards = @(if ($p.cards) { $p.cards })
4983
6367
  $startX = if ($p.startX) { $p.startX } else { 50 }
4984
6368
  $startY = if ($p.startY) { $p.startY } else { 350 }
4985
6369
  $cardWidth = if ($p.cardWidth) { $p.cardWidth } else { 150 }
@@ -5135,7 +6519,8 @@ switch ($Action) {
5135
6519
  } catch {}
5136
6520
  }
5137
6521
  }
5138
- Output-Json @{ success = $true; data = @{ style = $schemeKey; count = $count } }
6522
+ # 第 6 轮:TS 读 data.slideCount("处理页数: N 页"),原来只回 count → 永远 undefined
6523
+ Output-Json @{ success = $true; data = @{ style = $schemeKey; count = $count; slideCount = $pres.Slides.Count } }
5139
6524
  }
5140
6525
 
5141
6526
  "createProgressBar" {
@@ -5228,7 +6613,7 @@ switch ($Action) {
5228
6613
  $slideIndex = if ($p.slideIndex) { $p.slideIndex } else { 1 }
5229
6614
  $slide = $pres.Slides.Item($slideIndex)
5230
6615
 
5231
- $items = if ($p.items) { $p.items } else { @() }
6616
+ $items = @(if ($p.items) { $p.items })
5232
6617
  $startX = if ($p.startX) { $p.startX } else { 50 }
5233
6618
  $startY = if ($p.startY) { $p.startY } else { 400 }
5234
6619
  $itemWidth = if ($p.itemWidth) { $p.itemWidth } else { 100 }
@@ -5243,7 +6628,9 @@ switch ($Action) {
5243
6628
  $colorValue = Convert-HexColorToRgbInt([string]$color)
5244
6629
 
5245
6630
  $valueBox = $slide.Shapes.AddTextbox(1, $x, $startY, $itemWidth, 30)
5246
- $valueBox.TextFrame.TextRange.Text = if ($item.value) { $item.value } else { "0" }
6631
+ # [string] 不是多余的:data[].value 从 JSON 过来是 Int32,
6632
+ # 直接赋给 TextRange.Text 会抛"指定的转换无效"(同 setPptChartData 里 Value2 的坑)。
6633
+ $valueBox.TextFrame.TextRange.Text = [string]$(if ($item.value) { $item.value } else { "0" })
5247
6634
  $valueBox.TextFrame.TextRange.Font.Size = 20
5248
6635
  $valueBox.TextFrame.TextRange.Font.Bold = $true
5249
6636
  if ($null -ne $colorValue) { $valueBox.TextFrame.TextRange.Font.Color.RGB = $colorValue }
@@ -5319,55 +6706,76 @@ switch ($Action) {
5319
6706
  $slide = $pres.Slides.Item($slideIndex)
5320
6707
 
5321
6708
  $layout = if ($p.layout) { $p.layout } else { "grid" }
5322
- $margin = if ($p.margin) { $p.margin } else { 50 }
5323
- $gap = if ($p.gap) { $p.gap } else { 20 }
5324
- $slideWidth = 720
5325
- $slideHeight = 540
5326
-
6709
+ $margin = if ($p.margin) { [double]$p.margin } else { 50.0 }
6710
+ $gap = if ($p.gap) { [double]$p.gap } else { 20.0 }
6711
+ $slideWidth = 720.0
6712
+ $slideHeight = 540.0
6713
+
6714
+ # 逐个形状取值:属性读取会抛。实测在整轮冒烟里,前面的用例给形状加过 3D 旋转/材质之后,
6715
+ # 再读 Width/Height 就抛"指定的转换无效" —— 一个形状读失败不该让整页排版全废。
6716
+ # 这里把可排的形状收成 { shape, w, h },取不到尺寸的直接跳过。
5327
6717
  $shapes = @()
6718
+ $skipped = 0
5328
6719
  for ($i = 1; $i -le $slide.Shapes.Count; $i++) {
5329
- $s = $slide.Shapes.Item($i)
5330
- if ($s.Type -eq 1 -or $s.Type -eq 6 -or $s.Type -eq 17) { $shapes += $s }
6720
+ $s = $null
6721
+ try { $s = $slide.Shapes.Item($i) } catch { $skipped++; continue }
6722
+ $t = -1
6723
+ try { $t = [int]$s.Type } catch { $t = -1 }
6724
+ if ($t -ne 1 -and $t -ne 6 -and $t -ne 17) { continue }
6725
+ $w = 0.0; $h = 0.0
6726
+ try { $w = [double]$s.Width } catch { $skipped++; continue }
6727
+ try { $h = [double]$s.Height } catch { $skipped++; continue }
6728
+ $shapes += , @($s, $w, $h)
5331
6729
  }
5332
6730
 
5333
6731
  if ($shapes.Count -eq 0) {
5334
- Output-Json @{ success = $true; data = @{ message = "没有可排列的形状"; count = 0 } }
5335
- break
6732
+ Output-Json @{ success = $true; data = @{ message = "没有可排列的形状"; count = 0; skipped = $skipped } }
6733
+ return
5336
6734
  }
5337
6735
 
5338
6736
  if ($layout -eq "horizontal") {
5339
- $totalWidth = 0
5340
- foreach ($shape in $shapes) { $totalWidth += $shape.Width }
6737
+ $totalWidth = 0.0
6738
+ foreach ($row in $shapes) { $totalWidth += [double]$row[1] }
5341
6739
  $availWidth = $slideWidth - 2 * $margin
5342
6740
  $spacing = ($availWidth - $totalWidth) / ($shapes.Count + 1)
5343
- $currentX = $margin + $spacing
5344
- foreach ($shape in $shapes) {
5345
- $shape.Left = $currentX
5346
- $shape.Top = ($slideHeight - $shape.Height) / 2
5347
- $currentX += $shape.Width + $spacing
6741
+ $currentX = [double]$margin + $spacing
6742
+ foreach ($row in $shapes) {
6743
+ $shape = $row[0]; $w = [double]$row[1]; $h = [double]$row[2]
6744
+ try { $shape.Left = [double]$currentX } catch { $skipped++ }
6745
+ try { $shape.Top = [double](($slideHeight - $h) / 2) } catch { $skipped++ }
6746
+ $currentX = $currentX + $w + $spacing
5348
6747
  }
5349
6748
  } elseif ($layout -eq "vertical") {
5350
- $currentY = $margin
5351
- foreach ($shape in $shapes) {
5352
- $shape.Left = ($slideWidth - $shape.Width) / 2
5353
- $shape.Top = $currentY
5354
- $currentY += $shape.Height + $gap
6749
+ # 全部走 double 本地变量再赋值:直接拿表达式结果写 COM 的 Single 属性
6750
+ # 会抛"指定的转换无效"(实测只有 vertical 分支炸)。
6751
+ $currentY = [double]$margin
6752
+ foreach ($row in $shapes) {
6753
+ $shape = $row[0]; $w = [double]$row[1]; $h = [double]$row[2]
6754
+ try { $shape.Left = [double](($slideWidth - $w) / 2) } catch { $skipped++ }
6755
+ try { $shape.Top = [double]$currentY } catch { $skipped++ }
6756
+ $currentY = $currentY + $h + [double]$gap
5355
6757
  }
5356
6758
  } else {
5357
- $cols = if ($p.cols) { $p.cols } else { [Math]::Ceiling([Math]::Sqrt($shapes.Count)) }
5358
- $rows = [Math]::Ceiling($shapes.Count / $cols)
6759
+ # 显式 int:Math.Ceiling/Floor 返回 double,拿去做取模/赋值时 COM 的 Single 属性会抛"指定的转换无效"
6760
+ $cols = if ($p.cols) { [int]$p.cols } else { [int][Math]::Ceiling([Math]::Sqrt($shapes.Count)) }
6761
+ if ($cols -lt 1) { $cols = 1 }
6762
+ $rows = [int][Math]::Ceiling($shapes.Count / $cols)
6763
+ if ($rows -lt 1) { $rows = 1 }
5359
6764
  $cellWidth = ($slideWidth - 2 * $margin) / $cols
5360
6765
  $cellHeight = ($slideHeight - 2 * $margin) / $rows
5361
6766
  for ($idx = 0; $idx -lt $shapes.Count; $idx++) {
5362
6767
  $col = $idx % $cols
5363
- $row = [Math]::Floor($idx / $cols)
5364
- $shape = $shapes[$idx]
5365
- $shape.Left = $margin + $col * $cellWidth + ($cellWidth - $shape.Width) / 2
5366
- $shape.Top = $margin + $row * $cellHeight + ($cellHeight - $shape.Height) / 2
6768
+ $rowIdx = [int][Math]::Floor($idx / $cols)
6769
+ $row = $shapes[$idx]
6770
+ $shape = $row[0]; $w = [double]$row[1]; $h = [double]$row[2]
6771
+ $newLeft = [double]$margin + [double]$col * [double]$cellWidth + ([double]$cellWidth - $w) / 2
6772
+ $newTop = [double]$margin + [double]$rowIdx * [double]$cellHeight + ([double]$cellHeight - $h) / 2
6773
+ try { $shape.Left = [double]$newLeft } catch { $skipped++ }
6774
+ try { $shape.Top = [double]$newTop } catch { $skipped++ }
5367
6775
  }
5368
6776
  }
5369
6777
 
5370
- Output-Json @{ success = $true; data = @{ layout = $layout; count = $shapes.Count } }
6778
+ Output-Json @{ success = $true; data = @{ layout = $layout; count = $shapes.Count; skipped = $skipped } }
5371
6779
  }
5372
6780
 
5373
6781
  "smartDistribute" {
@@ -5378,7 +6786,7 @@ switch ($Action) {
5378
6786
  $slide = $pres.Slides.Item($slideIndex)
5379
6787
 
5380
6788
  $direction = if ($p.direction) { $p.direction } else { "horizontal" }
5381
- $shapeNames = if ($p.shapes) { $p.shapes } else { @() }
6789
+ $shapeNames = @(if ($p.shapes) { $p.shapes })
5382
6790
  $shapes = @()
5383
6791
 
5384
6792
  if ($shapeNames.Count -gt 0) {
@@ -5386,40 +6794,69 @@ switch ($Action) {
5386
6794
  try { $shapes += $slide.Shapes.Item($name) } catch {}
5387
6795
  }
5388
6796
  } else {
6797
+ # 同 autoLayout:Shape.Type 与尺寸都可能抛(页面里有 3D/表格/图片时),
6798
+ # 收集阶段就逐个 try/catch,别让一个形状把整次分布拖垮。
5389
6799
  for ($i = 1; $i -le $slide.Shapes.Count; $i++) {
5390
- $s = $slide.Shapes.Item($i)
5391
- if ($s.Type -eq 1 -or $s.Type -eq 6 -or $s.Type -eq 17) { $shapes += $s }
6800
+ $s = $null
6801
+ try { $s = $slide.Shapes.Item($i) } catch { continue }
6802
+ $t = -1
6803
+ try { $t = [int]$s.Type } catch { $t = -1 }
6804
+ if ($t -eq 1 -or $t -eq 6 -or $t -eq 17) {
6805
+ $okSize = $true
6806
+ try { $null = [double]$s.Width } catch { $okSize = $false }
6807
+ if ($okSize) { try { $null = [double]$s.Height } catch { $okSize = $false } }
6808
+ if ($okSize) { $shapes += $s }
6809
+ }
5392
6810
  }
5393
6811
  }
5394
6812
 
5395
6813
  if ($shapes.Count -lt 2) {
5396
6814
  Output-Json @{ success = $true; data = @{ message = "需要至少2个形状"; count = $shapes.Count } }
5397
- break
6815
+ return
5398
6816
  }
5399
6817
 
5400
- $shapes = if ($direction -eq "horizontal") { $shapes | Sort-Object Left } else { $shapes | Sort-Object Top }
6818
+ # 不用 Sort-Object:COM 形状对象参与比较会抛"指定的转换无效"(只取到 1 个时返回的还不是数组)。
6819
+ # 自己按 [double] 键插入排序,键先落本地变量。
6820
+ $keys = @()
6821
+ foreach ($shp in $shapes) {
6822
+ $v = 0.0
6823
+ try { $v = if ($direction -eq "horizontal") { [double]$shp.Left } else { [double]$shp.Top } } catch { $v = 0.0 }
6824
+ $keys += , @($v, $shp)
6825
+ }
6826
+ for ($a = 1; $a -lt $keys.Count; $a++) {
6827
+ $cur = $keys[$a]; $b = $a - 1
6828
+ while ($b -ge 0 -and $keys[$b][0] -gt $cur[0]) { $keys[$b + 1] = $keys[$b]; $b-- }
6829
+ $keys[$b + 1] = $cur
6830
+ }
6831
+ $shapes = @()
6832
+ foreach ($kv in $keys) { $shapes += $kv[1] }
5401
6833
 
6834
+ # 与 autoLayout 同一个坑:COM 属性参与算术会抛"指定的转换无效",统一先落 [double]
5402
6835
  if ($direction -eq "horizontal") {
5403
- $minX = $shapes[0].Left
5404
- $maxX = $shapes[$shapes.Count - 1].Left + $shapes[$shapes.Count - 1].Width
5405
- $totalWidth = 0
5406
- foreach ($shape in $shapes) { $totalWidth += $shape.Width }
5407
- $spacing = ($maxX - $minX - $totalWidth) / ($shapes.Count - 1)
6836
+ $minX = 0.0; try { $minX = [double]$shapes[0].Left } catch {}
6837
+ $maxX = $minX
6838
+ try { $last = $shapes[$shapes.Count - 1]; $maxX = [double]$last.Left + [double]$last.Width } catch {}
6839
+ $totalWidth = 0.0
6840
+ foreach ($shape in $shapes) { try { $totalWidth += [double]$shape.Width } catch {} }
6841
+ $spacing = ($maxX - $minX - $totalWidth) / [Math]::Max(1, $shapes.Count - 1)
5408
6842
  $currentX = $minX
5409
6843
  foreach ($shape in $shapes) {
5410
- $shape.Left = $currentX
5411
- $currentX += $shape.Width + $spacing
6844
+ $w = 0.0; try { $w = [double]$shape.Width } catch {}
6845
+ try { $shape.Left = [double]$currentX } catch {}
6846
+ $currentX = $currentX + $w + $spacing
5412
6847
  }
5413
6848
  } else {
5414
- $minY = $shapes[0].Top
5415
- $maxY = $shapes[$shapes.Count - 1].Top + $shapes[$shapes.Count - 1].Height
5416
- $totalHeight = 0
5417
- foreach ($shape in $shapes) { $totalHeight += $shape.Height }
5418
- $spacing = ($maxY - $minY - $totalHeight) / ($shapes.Count - 1)
6849
+ $minY = 0.0; try { $minY = [double]$shapes[0].Top } catch {}
6850
+ $maxY = $minY
6851
+ try { $last = $shapes[$shapes.Count - 1]; $maxY = [double]$last.Top + [double]$last.Height } catch {}
6852
+ $totalHeight = 0.0
6853
+ foreach ($shape in $shapes) { try { $totalHeight += [double]$shape.Height } catch {} }
6854
+ $spacing = ($maxY - $minY - $totalHeight) / [Math]::Max(1, $shapes.Count - 1)
5419
6855
  $currentY = $minY
5420
6856
  foreach ($shape in $shapes) {
5421
- $shape.Top = $currentY
5422
- $currentY += $shape.Height + $spacing
6857
+ $h = 0.0; try { $h = [double]$shape.Height } catch {}
6858
+ try { $shape.Top = [double]$currentY } catch {}
6859
+ $currentY = $currentY + $h + $spacing
5423
6860
  }
5424
6861
  }
5425
6862
 
@@ -5755,9 +7192,15 @@ switch ($Action) {
5755
7192
  $slide = $pres.Slides.Item($slideIndex)
5756
7193
  $shape = $slide.Shapes.Item($(if ($p.shapeName) { $p.shapeName } else { $p.shapeIndex }))
5757
7194
 
5758
- $shape.ThreeD.RotationX = if ($p.rotationX -ne $null) { $p.rotationX } else { 0 }
5759
- $shape.ThreeD.RotationY = if ($p.rotationY -ne $null) { $p.rotationY } else { 0 }
5760
- $shape.ThreeD.RotationZ = if ($p.rotationZ -ne $null) { $p.rotationZ } else { 0 }
7195
+ # 工具传的是 rotation:{x,y,z} 对象,而这里读的是扁平 rotationX/Y/Z ——
7196
+ # 三种形状都认,否则整包 psobject 会被塞进 float 属性(实测报"无法将 psobject 转换为类型 float")。
7197
+ $rot = $p.rotation
7198
+ $rx = if ($null -ne $p.rotationX) { $p.rotationX } elseif ($null -ne $rot -and $null -ne $rot.x) { $rot.x } else { 0 }
7199
+ $ry = if ($null -ne $p.rotationY) { $p.rotationY } elseif ($null -ne $rot -and $null -ne $rot.y) { $rot.y } else { 0 }
7200
+ $rz = if ($null -ne $p.rotationZ) { $p.rotationZ } elseif ($null -ne $rot -and $null -ne $rot.z) { $rot.z } else { 0 }
7201
+ $shape.ThreeD.RotationX = [float]$rx
7202
+ $shape.ThreeD.RotationY = [float]$ry
7203
+ $shape.ThreeD.RotationZ = [float]$rz
5761
7204
 
5762
7205
  if ($p.preset) {
5763
7206
  $presets = @{ isometric = @{ x = 45; y = 45; z = 0 }; perspective = @{ x = 30; y = 30; z = 0 }; oblique = @{ x = 20; y = 60; z = 0 }; tiltLeft = @{ x = 0; y = -30; z = 0 }; tiltRight = @{ x = 0; y = 30; z = 0 } }
@@ -5855,10 +7298,45 @@ switch ($Action) {
5855
7298
  $chart.ChartData.Activate()
5856
7299
  $dataSheet = $chart.ChartData.Workbook.Worksheets.Item(1)
5857
7300
  if ($p.data) {
5858
- for ($r = 0; $r -lt $p.data.Count; $r++) {
5859
- $rowData = $p.data[$r]
7301
+ # 参数形状归一化(第 3 轮修"假成功"):
7302
+ # TS 侧 schema 承诺 {categories:[...], series:[{name, values:[...]}]}(文档是给用户看的承诺),
7303
+ # 历史裸调用(wps_execute_method 直穿)传的是二维数组。两个形状都接。
7304
+ # 第 4 个坑:数字从 JSON 过来是 Int32,直接塞 Value2 会报 Int32→String 类型错 ——
7305
+ # 数值统一转 [double],字符串才按字符串写。
7306
+ $rows = @()
7307
+ if ($p.data -is [System.Array]) {
7308
+ # 二维数组(历史形状):原样逐格写
7309
+ foreach ($r in $p.data) { $rows += ,@($r) }
7310
+ } elseif ($p.data.PSObject.Properties.Name -contains 'categories' -or $p.data.PSObject.Properties.Name -contains 'series') {
7311
+ # 文档承诺的形状:摊成"表头行 + 每类别一行"
7312
+ $cats = @()
7313
+ if ($p.data.categories) { $cats = @($p.data.categories) }
7314
+ $seriesList = @()
7315
+ if ($p.data.series) { $seriesList = @($p.data.series) }
7316
+ $header = @('类别')
7317
+ foreach ($s in $seriesList) { $header += [string]$s.name }
7318
+ $rows += ,@($header)
7319
+ for ($i = 0; $i -lt $cats.Count; $i++) {
7320
+ $line = @([string]$cats[$i])
7321
+ foreach ($s in $seriesList) {
7322
+ $vals = @($s.values)
7323
+ $v = if ($i -lt $vals.Count) { $vals[$i] } else { $null }
7324
+ $line += $v
7325
+ }
7326
+ $rows += ,$line
7327
+ }
7328
+ }
7329
+ for ($r = 0; $r -lt $rows.Count; $r++) {
7330
+ $rowData = $rows[$r]
5860
7331
  for ($c = 0; $c -lt $rowData.Count; $c++) {
5861
- $dataSheet.Cells.Item($r + 1, $c + 1).Value2 = $rowData[$c]
7332
+ $cell = $dataSheet.Cells.Item($r + 1, $c + 1)
7333
+ $v = $rowData[$c]
7334
+ if ($null -eq $v) { continue }
7335
+ if ($v -is [int] -or $v -is [long] -or $v -is [double] -or $v -is [decimal]) {
7336
+ $cell.Value2 = [double]$v
7337
+ } else {
7338
+ $cell.Value2 = [string]$v
7339
+ }
5862
7340
  }
5863
7341
  }
5864
7342
  }
@@ -5873,14 +7351,61 @@ switch ($Action) {
5873
7351
  $slide = $pres.Slides.Item($slideIndex)
5874
7352
  $shape = $slide.Shapes.Item($(if ($p.chartName) { $p.chartName } else { $p.chartIndex }))
5875
7353
  $chart = $shape.Chart
5876
- if ($p.title) {
5877
- $chart.HasTitle = $true
5878
- $chart.ChartTitle.Text = $p.title
7354
+ # 参数形状归一化(第 3 轮修"假成功"):
7355
+ # TS 侧 schema 承诺 style:{title,showLegend,legendPosition,showDataLabels,fontSize},
7356
+ # 历史裸调用用扁平 $p.title / $p.hasLegend。两个都接,扁平优先。
7357
+ # 注意 schema 写的是 showLegend,PS 老代码读的是 hasLegend —— 两个键都认。
7358
+ $st = @{}
7359
+ if ($p.style) {
7360
+ foreach ($k in $p.style.PSObject.Properties.Name) { $st[$k] = $p.style.$k }
5879
7361
  }
5880
- if ($null -ne $p.hasLegend) {
5881
- $chart.HasLegend = $p.hasLegend
7362
+ foreach ($k in @('title', 'hasLegend', 'showLegend', 'legendPosition', 'showDataLabels', 'fontSize', 'colorScheme')) {
7363
+ if ($p.PSObject.Properties.Name -contains $k -and -not $st.ContainsKey($k)) { $st[$k] = $p.$k }
5882
7364
  }
5883
- Output-Json @{ success = $true; data = @{ chartName = $shape.Name } }
7365
+ $applied = @()
7366
+ if ($st.title) {
7367
+ try {
7368
+ $chart.HasTitle = $true
7369
+ $chart.ChartTitle.Text = [string]$st.title
7370
+ $applied += 'title'
7371
+ } catch { }
7372
+ }
7373
+ $legendFlag = $null
7374
+ if ($null -ne $st.showLegend) { $legendFlag = $st.showLegend }
7375
+ elseif ($null -ne $st.hasLegend) { $legendFlag = $st.hasLegend }
7376
+ if ($null -ne $legendFlag) {
7377
+ try {
7378
+ $chart.HasLegend = [bool]$legendFlag
7379
+ $applied += 'legend'
7380
+ } catch { }
7381
+ }
7382
+ if ($st.legendPosition) {
7383
+ # 图例位置枚举与 Excel 侧 updateChart(wps-com.ps1 的 updateChart case)保持一致
7384
+ $legMap = @{ bottom = -4107; top = -4160; left = -4131; right = -4152 }
7385
+ $lp = $legMap[[string]$st.legendPosition]
7386
+ if ($null -ne $lp) {
7387
+ try {
7388
+ $chart.Legend.Position = $lp
7389
+ $applied += 'legendPosition'
7390
+ } catch { }
7391
+ }
7392
+ }
7393
+ if ($null -ne $st.showDataLabels) {
7394
+ # 只开不关:关标签要逐系列 Delete,失败率高;调用方要关就别传这个键
7395
+ if ([bool]$st.showDataLabels) {
7396
+ try {
7397
+ $chart.ApplyDataLabels()
7398
+ $applied += 'dataLabels'
7399
+ } catch { }
7400
+ }
7401
+ }
7402
+ if ($st.fontSize) {
7403
+ try {
7404
+ $chart.ChartArea.Font.Size = $st.fontSize
7405
+ $applied += 'fontSize'
7406
+ } catch { }
7407
+ }
7408
+ Output-Json @{ success = $true; data = @{ chartName = $shape.Name; applied = $applied } }
5884
7409
  }
5885
7410
 
5886
7411
  "removeAnimation" {
@@ -5890,8 +7415,19 @@ switch ($Action) {
5890
7415
  $slideIndex = if ($p.slideIndex) { $p.slideIndex } else { 1 }
5891
7416
  $slide = $pres.Slides.Item($slideIndex)
5892
7417
  $seq = $slide.TimeLine.MainSequence
5893
- if ($p.index) {
5894
- $seq.Item($p.index).Delete()
7418
+ # 工具传的是 animationIndex,这里以前只读 index → 落进 else 分支把【所有动画都删了】,
7419
+ # 计数变化看起来"成功",但删多删少都不受控。两个键都认,并做越界检查。
7420
+ $idx = if ($null -ne $p.animationIndex) { [int]$p.animationIndex } elseif ($null -ne $p.index) { [int]$p.index } else { 0 }
7421
+ if ($seq.Count -eq 0) {
7422
+ Output-Json @{ success = $true; data = @{ removed = 0; note = "本页本来就没有动画" } }
7423
+ return
7424
+ }
7425
+ if ($idx -ge 1) {
7426
+ if ($idx -gt $seq.Count) {
7427
+ Output-Json @{ success = $false; error = "[勿重试·先改参数] 动画序号 $idx 越界:本页共 $($seq.Count) 个(1 起)" }
7428
+ return
7429
+ }
7430
+ $seq.Item($idx).Delete()
5895
7431
  } else {
5896
7432
  while ($seq.Count -gt 0) { $seq.Item(1).Delete() }
5897
7433
  }
@@ -5920,9 +7456,21 @@ switch ($Action) {
5920
7456
  $slideIndex = if ($p.slideIndex) { $p.slideIndex } else { 1 }
5921
7457
  $slide = $pres.Slides.Item($slideIndex)
5922
7458
  $seq = $slide.TimeLine.MainSequence
5923
- $effect = $seq.Item($p.from)
5924
- $effect.MoveTo($p.to)
5925
- Output-Json @{ success = $true; data = @{ from = $p.from; to = $p.to } }
7459
+ # 工具传的是 animationIndex/newOrder,这里以前只读 from/to → Item($null) 必报"值不在预期的范围内"
7460
+ $fromIdx = if ($null -ne $p.animationIndex) { [int]$p.animationIndex } elseif ($null -ne $p.from) { [int]$p.from } else { 0 }
7461
+ $toIdx = if ($null -ne $p.newOrder) { [int]$p.newOrder } elseif ($null -ne $p.to) { [int]$p.to } else { 0 }
7462
+ $cnt = $seq.Count
7463
+ if ($cnt -eq 0) {
7464
+ Output-Json @{ success = $false; error = "[勿重试·先改参数] 本页还没有动画,谈不上排序;先 add_animation" }
7465
+ return
7466
+ }
7467
+ if ($fromIdx -lt 1 -or $fromIdx -gt $cnt -or $toIdx -lt 1 -or $toIdx -gt $cnt) {
7468
+ Output-Json @{ success = $false; error = "[勿重试·先改参数] 动画序号越界:本页共 $cnt 个(1 起),收到 from=$fromIdx to=$toIdx" }
7469
+ return
7470
+ }
7471
+ $effect = $seq.Item($fromIdx)
7472
+ $effect.MoveTo($toIdx)
7473
+ Output-Json @{ success = $true; data = @{ from = $fromIdx; to = $toIdx } }
5926
7474
  }
5927
7475
 
5928
7476
  "removeSlideTransition" {
@@ -5939,14 +7487,30 @@ switch ($Action) {
5939
7487
  $ppt = Get-WpsPpt
5940
7488
  if ($null -eq $ppt) { Output-Json @{ success = $false; error = "WPS PPT not running" }; return }
5941
7489
  $pres = Get-TargetPres $ppt $p
5942
- $transitionMap = @{ none = 0; fade = 1; push = 2; wipe = 3; split = 4; reveal = 5; random = 6 }
5943
- $transition = if ($transitionMap[$p.transition]) { $transitionMap[$p.transition] } else { if ($p.transition) { $p.transition } else { 1 } }
7490
+ # 参数名是 effect(合并后的 set_transition target='all' 就是它);
7491
+ # 以前这里只读 $p.transition,工具传的一直是 effect → 映射表查不到 → 静默全设成 fade。
7492
+ if ($null -eq $p.effect -and $p.transition) { $p | Add-Member -NotePropertyName effect -NotePropertyValue $p.transition -Force }
7493
+ $effectName = if ($p.effect) { ([string]$p.effect).ToLower() } else { "fade" }
7494
+ $transitionMap = @{ none = 0; fade = 1; push = 2; wipe = 3; split = 4; reveal = 5; cover = 6; dissolve = 7; curtains = 8; random = 6; blinds = 3 }
7495
+ $transition = -1
7496
+ if ($transitionMap.ContainsKey($effectName)) { $transition = $transitionMap[$effectName] }
7497
+ elseif ($effectName -match '^\d+$') { $transition = [int]$effectName }
7498
+ if ($transition -lt 0) {
7499
+ Output-Json @{ success = $false; error = "不认识的切换效果:$effectName(可用:none/fade/push/wipe/split/reveal/cover/dissolve/curtains)" }
7500
+ return
7501
+ }
7502
+ $dur = 0.0
7503
+ if ($p.duration) { try { $dur = [double]$p.duration } catch { $dur = 0.0 } }
7504
+ $applied = 0
5944
7505
  for ($i = 1; $i -le $pres.Slides.Count; $i++) {
5945
7506
  $slide = $pres.Slides.Item($i)
5946
- $slide.SlideShowTransition.EntryEffect = $transition
5947
- if ($p.duration) { $slide.SlideShowTransition.Duration = $p.duration }
7507
+ $tr = $slide.SlideShowTransition
7508
+ $tr.EntryEffect = $transition
7509
+ if ($dur -gt 0) { try { $tr.Duration = $dur } catch {} }
7510
+ $applied++
5948
7511
  }
5949
- Output-Json @{ success = $true; data = @{ transition = $p.transition; appliedTo = $pres.Slides.Count } }
7512
+ # 回读字段名与 setSlideTransition 对齐(slideCount);appliedTo 留着兼容老调用方
7513
+ Output-Json @{ success = $true; data = @{ effect = $effectName; entryEffect = $transition; duration = $dur; slideCount = $applied; appliedTo = $applied } }
5950
7514
  }
5951
7515
 
5952
7516
  "setBackgroundColor" {
@@ -6161,33 +7725,76 @@ switch ($Action) {
6161
7725
  Output-Json @{ success = $true; data = @{ slideIndex = $slideIndexOut; operations = $ops } }
6162
7726
  }
6163
7727
 
7728
+ # 第 6 轮重写。原来的三处病:
7729
+ # ① 回包只有 {style,count},而 TS 读 data.operations 并 .forEach → 直接崩
7730
+ # "Cannot read properties of undefined (reading 'forEach')"(冒烟里 79 条失败的第一条);
7731
+ # ② TS 传的是嵌套 style:{colorScheme,font},PS 却把 $p.style 当字符串查配色表
7732
+ # → 永远落到 business,配色方案参数形同摆设;
7733
+ # ③ slideIndex 传 'all'(美化整份)时 $pres.Slides.Item('all') 必炸。
7734
+ # 现在:配色/字体两种形状都认、支持 all、把【真做了哪几件事】按 operations 数组回给 TS。
7735
+ # 说明:描述里承诺的"对齐元素/优化间距"没有实现,所以不往 operations 里塞 —— 假报一条
7736
+ # 比少报一条更坏(用户会以为版面被整理过)。
6164
7737
  "beautifySlide" {
6165
7738
  $ppt = Get-WpsPpt
6166
7739
  if ($null -eq $ppt) { Output-Json @{ success = $false; error = "WPS PPT not running" }; return }
6167
7740
  $pres = Get-TargetPres $ppt $p
6168
- $slideIndex = if ($p.slideIndex) { $p.slideIndex } else { $ppt.ActiveWindow.Selection.SlideRange.SlideIndex }
6169
- $slide = $pres.Slides.Item($slideIndex)
7741
+ if ($null -eq $pres) { Output-Json @{ success = $false; error = "No active presentation" }; return }
7742
+
7743
+ # 参数归一:嵌套 style{} 与扁平两套都收(TS 发的是嵌套)
7744
+ $schemeKey = if ($p.colorScheme) { [string]$p.colorScheme } elseif ($p.style -and ($p.style.PSObject.Properties.Name -contains 'colorScheme')) { [string]$p.style.colorScheme } elseif ($p.style -is [string]) { [string]$p.style } else { 'business' }
7745
+ $fontName = if ($p.font) { [string]$p.font } elseif ($p.style -and ($p.style.PSObject.Properties.Name -contains 'font')) { [string]$p.style.font } else { '微软雅黑' }
7746
+
6170
7747
  $schemes = @{
6171
7748
  business = @{ title = 0x2F5496; body = 0x333333 }
6172
7749
  tech = @{ title = 0x00B0F0; body = 0x404040 }
6173
7750
  creative = @{ title = 0xFF6B6B; body = 0x4A4A4A }
6174
7751
  minimal = @{ title = 0x000000; body = 0x666666 }
6175
7752
  }
6176
- $scheme = $schemes[$p.style]
6177
- if ($null -eq $scheme) { $scheme = $schemes["business"] }
6178
- $count = 0
6179
- for ($j = 1; $j -le $slide.Shapes.Count; $j++) {
6180
- $shape = $slide.Shapes.Item($j)
6181
- try {
6182
- if ($shape.HasTextFrame -and $shape.TextFrame.HasText) {
6183
- $textRange = $shape.TextFrame.TextRange
6184
- if ($textRange.Font.Size -ge 24) { $textRange.Font.Color.RGB = $scheme.title }
6185
- else { $textRange.Font.Color.RGB = $scheme.body }
6186
- $count++
6187
- }
6188
- } catch {}
7753
+ $scheme = $schemes[$schemeKey]
7754
+ if ($null -eq $scheme) { $scheme = $schemes["business"]; $schemeKey = 'business' }
7755
+
7756
+ # 范围:'all' 或没给(以当前页为准)
7757
+ $allSlides = ([string]$p.slideIndex -eq 'all')
7758
+ $startIdx = 1
7759
+ $endIdx = $pres.Slides.Count
7760
+ if (-not $allSlides) {
7761
+ if ($p.slideIndex) { $startIdx = [int]$p.slideIndex; $endIdx = $startIdx }
7762
+ else {
7763
+ try { $cur = $ppt.ActiveWindow.Selection.SlideRange.SlideIndex; if ($cur) { $startIdx = $cur; $endIdx = $cur } } catch {}
7764
+ }
7765
+ }
7766
+
7767
+ $fontCount = 0
7768
+ $colorCount = 0
7769
+ for ($i = $startIdx; $i -le $endIdx; $i++) {
7770
+ $slide = $pres.Slides.Item($i)
7771
+ for ($j = 1; $j -le $slide.Shapes.Count; $j++) {
7772
+ $shape = $slide.Shapes.Item($j)
7773
+ try {
7774
+ if ($shape.HasTextFrame -and $shape.TextFrame.HasText) {
7775
+ $textRange = $shape.TextFrame.TextRange
7776
+ $textRange.Font.Name = $fontName
7777
+ $fontCount++
7778
+ if ($textRange.Font.Size -ge 24) { $textRange.Font.Color.RGB = $scheme.title }
7779
+ else { $textRange.Font.Color.RGB = $scheme.body }
7780
+ $colorCount++
7781
+ }
7782
+ } catch {}
7783
+ }
6189
7784
  }
6190
- Output-Json @{ success = $true; data = @{ style = $p.style; count = $count } }
7785
+
7786
+ $operations = @(
7787
+ @{ operation = 'unify_font'; count = $fontCount },
7788
+ @{ operation = 'apply_color_scheme'; count = $colorCount }
7789
+ )
7790
+ Output-Json @{ success = $true; data = @{
7791
+ slideIndex = $(if ($allSlides) { 'all' } else { $startIdx })
7792
+ slideCount = $endIdx - $startIdx + 1
7793
+ style = $schemeKey
7794
+ font = $fontName
7795
+ count = $colorCount
7796
+ operations = $operations
7797
+ } }
6191
7798
  }
6192
7799
 
6193
7800
  # ==================== Word 长文档 / 学术排版(补 office-mcp 那条缺失链路)====================
@@ -6727,7 +8334,7 @@ switch ($Action) {
6727
8334
  if ($null -eq $doc) { Output-Json @{ success = $false; error = "No active document" }; return }
6728
8335
  $mode = [string]$p.mode
6729
8336
  $before = 0
6730
- try { $before = [int]$doc.Revisions.Count } catch {}
8337
+ try { $before = [int]$doc.Revisions.Count } catch {} # 吞错有据:读不到按 0 处理,走"没有修订"路径(不会误删)
6731
8338
  if ($before -eq 0) {
6732
8339
  Output-Json @{ success = $true; data = @{ mode = $mode; count = 0; handled = 0; note = "文档里没有修订" } }
6733
8340
  return