dsh-external-toolbox 0.0.0-stage → 0.2.0
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.
- package/LICENSE +21 -0
- package/README.md +189 -2
- package/cordis.patch.yml +9 -0
- package/helper/capture.ps1 +3291 -0
- package/icon.png +0 -0
- package/lib/client.js +264 -0
- package/lib/index.js +860 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +67 -4
- package/tools/say.mjs +52 -0
|
@@ -0,0 +1,3291 @@
|
|
|
1
|
+
# capture.ps1 - global hotkey selection capture + floating translate card (dsh-external-toolbox).
|
|
2
|
+
#
|
|
3
|
+
# Modes:
|
|
4
|
+
# -SelfTest create an off-screen window with a selected TextBox, read it back
|
|
5
|
+
# through UI Automation, print the result, exit.
|
|
6
|
+
# -CardTest render the floating card with sample text, screenshot it to
|
|
7
|
+
# -ShotPath, exit. Used to verify the layout without a hotkey.
|
|
8
|
+
# -Once capture the current focus once, print the result, exit.
|
|
9
|
+
# (default) register the global hotkey, wait in a message loop, and for every
|
|
10
|
+
# press: capture the selection in the focused app, then show the
|
|
11
|
+
# floating card in place so translating never needs the DSH window.
|
|
12
|
+
#
|
|
13
|
+
# Output contract (one JSON object per line, UTF-8):
|
|
14
|
+
# {"type":"ready","hotkey":"Ctrl+Alt+Q"}
|
|
15
|
+
# {"type":"selection","id":"...","text":"...","via":"uia|clipboard","chars":123}
|
|
16
|
+
# {"type":"intent","intent":"ask","id":"..."}
|
|
17
|
+
# {"type":"error","message":"..."}
|
|
18
|
+
#
|
|
19
|
+
# The script body must stay pure ASCII: Windows PowerShell 5.1 decodes a BOM-less
|
|
20
|
+
# .ps1 as the ANSI code page, so any non-ASCII byte breaks parsing. UI strings are
|
|
21
|
+
# built from code points with U.
|
|
22
|
+
|
|
23
|
+
[CmdletBinding()]
|
|
24
|
+
param(
|
|
25
|
+
[string]$Hotkey = "Ctrl+Alt+Q",
|
|
26
|
+
[string]$WindowTitle = "DeepSeek Harness",
|
|
27
|
+
[string]$TranslateUrl = "",
|
|
28
|
+
# CardTest only: which task to run ("translate" or "explain").
|
|
29
|
+
[string]$Task = "translate",
|
|
30
|
+
[string]$Target = "auto",
|
|
31
|
+
[int]$ParentPid = 0,
|
|
32
|
+
[switch]$Once,
|
|
33
|
+
[switch]$SelfTest,
|
|
34
|
+
[switch]$CardTest,
|
|
35
|
+
[switch]$LangTest,
|
|
36
|
+
[switch]$ProbeWindows,
|
|
37
|
+
[switch]$MinimizeTest,
|
|
38
|
+
[switch]$HideTest,
|
|
39
|
+
[switch]$BarTest,
|
|
40
|
+
[switch]$ReviewTest,
|
|
41
|
+
[switch]$ReviewAnswer,
|
|
42
|
+
[string]$ReviewGrade = "",
|
|
43
|
+
[switch]$ReviewSpeak,
|
|
44
|
+
[switch]$ActivateTest,
|
|
45
|
+
[string]$ShotPath = "",
|
|
46
|
+
[switch]$NoAuto,
|
|
47
|
+
[int]$AutoInterval = 350,
|
|
48
|
+
[switch]$CaptureSelf,
|
|
49
|
+
[switch]$AutoTest,
|
|
50
|
+
[switch]$DragTest,
|
|
51
|
+
[switch]$NoActivate,
|
|
52
|
+
[switch]$NoRestoreClipboard,
|
|
53
|
+
# CardTest only: keep the machine quiet.
|
|
54
|
+
[switch]$SurfaceTest,
|
|
55
|
+
[switch]$NoSpeak
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
$ErrorActionPreference = "Stop"
|
|
59
|
+
try { [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 } catch {}
|
|
60
|
+
|
|
61
|
+
# Target language shown on the card: "auto" lets the host pick the direction of
|
|
62
|
+
# a Chinese/English (or Japanese, Korean) pair, any other code forces that one.
|
|
63
|
+
$script:LANG_CODES = @("auto", "zh", "en", "ja", "ko", "es", "fr", "de", "ru", "pt", "it")
|
|
64
|
+
# Selections longer than this are almost always a stray Ctrl+A.
|
|
65
|
+
# The card scrolls, so long selections are welcome; this is only a guard against
|
|
66
|
+
# an accidental Ctrl+A over a huge file.
|
|
67
|
+
$script:MAX_CAPTURE_CHARS = 100000
|
|
68
|
+
$script:LANG_LABELS = @{
|
|
69
|
+
auto = "AUTO"; zh = "ZH"; en = "EN"; ja = "JA"; ko = "KO"
|
|
70
|
+
es = "ES"; fr = "FR"; de = "DE"; ru = "RU"; pt = "PT"; it = "IT"
|
|
71
|
+
}
|
|
72
|
+
$script:lang = "auto"
|
|
73
|
+
if ($script:LANG_CODES -contains $Target) { $script:lang = $Target }
|
|
74
|
+
|
|
75
|
+
# Same trace file the host half writes, so a failed start leaves evidence even
|
|
76
|
+
# though the DSH desktop app's stderr is not reachable from outside.
|
|
77
|
+
$script:LogPath = Join-Path $env:TEMP "dsh-external-toolbox-host.log"
|
|
78
|
+
function Write-Trace([string]$Text) {
|
|
79
|
+
try {
|
|
80
|
+
$stamp = (Get-Date).ToString("o")
|
|
81
|
+
Add-Content -LiteralPath $script:LogPath -Value ($stamp + " helper " + $Text) -Encoding ASCII
|
|
82
|
+
} catch { }
|
|
83
|
+
}
|
|
84
|
+
# Only one helper may live at a time: a second copy would install a second
|
|
85
|
+
# mouse hook and pop the card twice.
|
|
86
|
+
try {
|
|
87
|
+
$script:singleInstance = New-Object System.Threading.Mutex($false, "Global\dsh-external-toolbox-helper")
|
|
88
|
+
if (-not $SelfTest -and -not $CardTest -and -not $BarTest -and -not $DragTest -and -not $ActivateTest -and -not $AutoTest -and (-not $script:singleInstance.WaitOne(0))) {
|
|
89
|
+
Write-Json @{ type = "error"; message = "another helper is already running" }
|
|
90
|
+
exit 0
|
|
91
|
+
}
|
|
92
|
+
} catch { }
|
|
93
|
+
|
|
94
|
+
Write-Trace ("start pid=" + $PID + " ps=" + $PSVersionTable.PSVersion.ToString())
|
|
95
|
+
trap {
|
|
96
|
+
try { Write-Trace ("fatal line=" + $_.InvocationInfo.ScriptLineNumber + " " + $_.Exception.GetType().Name + " " + $_.Exception.Message) } catch { }
|
|
97
|
+
try { Write-Json @{ type = "error"; message = [string]$_.Exception.Message } } catch { }
|
|
98
|
+
exit 1
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
Add-Type -AssemblyName System.Windows.Forms
|
|
102
|
+
Add-Type -AssemblyName System.Drawing
|
|
103
|
+
Add-Type -AssemblyName UIAutomationClient
|
|
104
|
+
Add-Type -AssemblyName UIAutomationTypes
|
|
105
|
+
|
|
106
|
+
if (-not ("QuickAsk.CardForm" -as [type])) {
|
|
107
|
+
$refs = @(
|
|
108
|
+
[System.Windows.Forms.Form].Assembly.Location,
|
|
109
|
+
[System.Drawing.Point].Assembly.Location
|
|
110
|
+
)
|
|
111
|
+
Add-Type -TypeDefinition @'
|
|
112
|
+
using System;
|
|
113
|
+
using System.Runtime.InteropServices;
|
|
114
|
+
using System.Windows.Forms;
|
|
115
|
+
|
|
116
|
+
namespace QuickAsk {
|
|
117
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
118
|
+
public struct RECT {
|
|
119
|
+
public int Left;
|
|
120
|
+
public int Top;
|
|
121
|
+
public int Right;
|
|
122
|
+
public int Bottom;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
126
|
+
public struct POINT { public int X; public int Y; }
|
|
127
|
+
|
|
128
|
+
public static class Native {
|
|
129
|
+
[DllImport("user32.dll", SetLastError = true)]
|
|
130
|
+
public static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
|
|
131
|
+
[DllImport("user32.dll", SetLastError = true)]
|
|
132
|
+
public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
|
|
133
|
+
[DllImport("user32.dll")]
|
|
134
|
+
public static extern bool SetForegroundWindow(IntPtr hWnd);
|
|
135
|
+
[DllImport("user32.dll")]
|
|
136
|
+
public static extern IntPtr GetForegroundWindow();
|
|
137
|
+
[DllImport("user32.dll")]
|
|
138
|
+
public static extern int GetWindowThreadProcessId(IntPtr hWnd, out int processId);
|
|
139
|
+
[DllImport("user32.dll")]
|
|
140
|
+
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
|
|
141
|
+
[DllImport("user32.dll")]
|
|
142
|
+
public static extern bool IsIconic(IntPtr hWnd);
|
|
143
|
+
[DllImport("user32.dll")]
|
|
144
|
+
public static extern short GetKeyState(int vk);
|
|
145
|
+
[DllImport("user32.dll", SetLastError = true)]
|
|
146
|
+
public static extern bool AttachThreadInput(int idAttach, int idAttachTo, bool attach);
|
|
147
|
+
[DllImport("kernel32.dll")]
|
|
148
|
+
public static extern int GetCurrentThreadId();
|
|
149
|
+
[DllImport("user32.dll")]
|
|
150
|
+
public static extern bool BringWindowToTop(IntPtr hWnd);
|
|
151
|
+
[DllImport("user32.dll")]
|
|
152
|
+
public static extern IntPtr SetFocus(IntPtr hWnd);
|
|
153
|
+
[DllImport("user32.dll")]
|
|
154
|
+
public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, IntPtr extraInfo);
|
|
155
|
+
[DllImport("user32.dll")]
|
|
156
|
+
public static extern bool IsWindowVisible(IntPtr hWnd);
|
|
157
|
+
[DllImport("user32.dll")] public static extern uint MapVirtualKey(uint code, uint mapType);
|
|
158
|
+
public static void KeyTap(byte vk) {
|
|
159
|
+
keybd_event(vk, (byte)MapVirtualKey(vk, 0), 0, IntPtr.Zero);
|
|
160
|
+
keybd_event(vk, (byte)MapVirtualKey(vk, 0), 2, IntPtr.Zero);
|
|
161
|
+
}
|
|
162
|
+
public static void KeyCombo(byte mod, byte vk) {
|
|
163
|
+
keybd_event(mod, (byte)MapVirtualKey(mod, 0), 0, IntPtr.Zero);
|
|
164
|
+
keybd_event(vk, (byte)MapVirtualKey(vk, 0), 0, IntPtr.Zero);
|
|
165
|
+
keybd_event(vk, (byte)MapVirtualKey(vk, 0), 2, IntPtr.Zero);
|
|
166
|
+
keybd_event(mod, (byte)MapVirtualKey(mod, 0), 2, IntPtr.Zero);
|
|
167
|
+
}
|
|
168
|
+
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
|
|
169
|
+
public static extern int GetWindowTextLengthW(IntPtr hWnd);
|
|
170
|
+
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
|
|
171
|
+
public static extern int GetWindowTextW(IntPtr hWnd, System.Text.StringBuilder text, int maxCount);
|
|
172
|
+
[DllImport("user32.dll")]
|
|
173
|
+
public static extern bool GetWindowRect(IntPtr hWnd, out RECT rect);
|
|
174
|
+
[DllImport("user32.dll")]
|
|
175
|
+
public static extern int GetWindowLongW(IntPtr hWnd, int nIndex);
|
|
176
|
+
[DllImport("user32.dll")]
|
|
177
|
+
public static extern bool PrintWindow(IntPtr hWnd, IntPtr hdc, uint flags);
|
|
178
|
+
[DllImport("user32.dll")]
|
|
179
|
+
public static extern bool EnumWindows(EnumWindowsProc callback, IntPtr param);
|
|
180
|
+
|
|
181
|
+
public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr param);
|
|
182
|
+
|
|
183
|
+
// The DSH window belongs to a renderer process, so looking at the
|
|
184
|
+
// process name or MainWindowHandle of the host process finds nothing.
|
|
185
|
+
// Match the window title instead and take the largest hit; a minimized
|
|
186
|
+
// (hidden) window still counts, the caller restores it afterwards.
|
|
187
|
+
public static IntPtr FindWindowByTitle(string needle) {
|
|
188
|
+
IntPtr best = IntPtr.Zero;
|
|
189
|
+
int bestArea = 0;
|
|
190
|
+
EnumWindows(delegate(IntPtr h, IntPtr param) {
|
|
191
|
+
if (IsWindowVisible(h)) {
|
|
192
|
+
int len = GetWindowTextLengthW(h);
|
|
193
|
+
if (len > 0) {
|
|
194
|
+
System.Text.StringBuilder sb = new System.Text.StringBuilder(len + 2);
|
|
195
|
+
GetWindowTextW(h, sb, sb.Capacity);
|
|
196
|
+
if (sb.ToString().IndexOf(needle, StringComparison.OrdinalIgnoreCase) >= 0) {
|
|
197
|
+
RECT r;
|
|
198
|
+
if (GetWindowRect(h, out r)) {
|
|
199
|
+
int area = (r.Right - r.Left) * (r.Bottom - r.Top);
|
|
200
|
+
if (area > bestArea) { bestArea = area; best = h; }
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
return true;
|
|
206
|
+
}, IntPtr.Zero);
|
|
207
|
+
return best;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// Diagnostics: every top level window whose title or executable name
|
|
211
|
+
// contains the needle, visible or not.
|
|
212
|
+
public static string[] DescribeWindows(string needle) {
|
|
213
|
+
System.Collections.Generic.List<string> list = new System.Collections.Generic.List<string>();
|
|
214
|
+
EnumWindows(delegate(IntPtr h, IntPtr param) {
|
|
215
|
+
int len = GetWindowTextLengthW(h);
|
|
216
|
+
if (len <= 0) return true;
|
|
217
|
+
System.Text.StringBuilder sb = new System.Text.StringBuilder(len + 2);
|
|
218
|
+
GetWindowTextW(h, sb, sb.Capacity);
|
|
219
|
+
string title = sb.ToString();
|
|
220
|
+
int pid = 0;
|
|
221
|
+
GetWindowThreadProcessId(h, out pid);
|
|
222
|
+
string pname = "";
|
|
223
|
+
try { pname = System.Diagnostics.Process.GetProcessById(pid).ProcessName; } catch { }
|
|
224
|
+
bool hit = title.IndexOf(needle, StringComparison.OrdinalIgnoreCase) >= 0 ||
|
|
225
|
+
pname.IndexOf(needle, StringComparison.OrdinalIgnoreCase) >= 0;
|
|
226
|
+
if (hit) list.Add(string.Format("hwnd={0} vis={1} pid={2} proc={3} title={4}", h, IsWindowVisible(h), pid, pname, title));
|
|
227
|
+
return true;
|
|
228
|
+
}, IntPtr.Zero);
|
|
229
|
+
return list.ToArray();
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// Fallback that does not depend on the title at all: any top level window
|
|
233
|
+
// owned by an executable with this name (visible or not).
|
|
234
|
+
public static IntPtr FindWindowByProcessName(string exeName) {
|
|
235
|
+
IntPtr best = IntPtr.Zero;
|
|
236
|
+
int bestArea = 0;
|
|
237
|
+
EnumWindows(delegate(IntPtr h, IntPtr param) {
|
|
238
|
+
// A window hidden to the tray may already have lost its title,
|
|
239
|
+
// so the process name has to be enough on its own.
|
|
240
|
+
int pid = 0;
|
|
241
|
+
int tid = GetWindowThreadProcessId(h, out pid);
|
|
242
|
+
if (pid == 0) return true;
|
|
243
|
+
string name = null;
|
|
244
|
+
try { name = System.Diagnostics.Process.GetProcessById(pid).ProcessName; } catch { return true; }
|
|
245
|
+
if (name == null) return true;
|
|
246
|
+
if (name.IndexOf(exeName, StringComparison.OrdinalIgnoreCase) < 0) return true;
|
|
247
|
+
RECT r;
|
|
248
|
+
if (!GetWindowRect(h, out r)) return true;
|
|
249
|
+
int area = (r.Right - r.Left) * (r.Bottom - r.Top);
|
|
250
|
+
// Message-only and helper windows are 0x0; only real app windows count.
|
|
251
|
+
if (area < 200 * 120) return true;
|
|
252
|
+
bool visible = IsWindowVisible(h);
|
|
253
|
+
// The BrowserWindow is always Chrome_WidgetWin_1. Chrome_WidgetWin_0
|
|
254
|
+
// and friends are internal Electron surfaces: showing one of those
|
|
255
|
+
// instead of the UI is exactly the "nothing appeared" failure.
|
|
256
|
+
System.Text.StringBuilder cls = new System.Text.StringBuilder(64);
|
|
257
|
+
GetClassName(h, cls, 64);
|
|
258
|
+
bool real = cls.ToString() == "Chrome_WidgetWin_1";
|
|
259
|
+
int score = (visible ? 1000 : 0) + (real ? 500 : 0) + System.Math.Min(area / 100000, 400);
|
|
260
|
+
if (score > bestArea) { bestArea = score; best = h; }
|
|
261
|
+
return true;
|
|
262
|
+
}, IntPtr.Zero);
|
|
263
|
+
return best;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
[DllImport("user32.dll")]
|
|
267
|
+
public static extern bool GetCursorPos(out POINT point);
|
|
268
|
+
[DllImport("user32.dll")] public static extern bool SetCursorPos(int x, int y);
|
|
269
|
+
[DllImport("user32.dll")] public static extern void mouse_event(uint flags, uint dx, uint dy, uint data, IntPtr extra);
|
|
270
|
+
public static void ClickAt(int x, int y) {
|
|
271
|
+
SetCursorPos(x, y);
|
|
272
|
+
System.Threading.Thread.Sleep(40);
|
|
273
|
+
mouse_event(0x0002, 0, 0, 0, IntPtr.Zero);
|
|
274
|
+
System.Threading.Thread.Sleep(40);
|
|
275
|
+
mouse_event(0x0004, 0, 0, 0, IntPtr.Zero);
|
|
276
|
+
}
|
|
277
|
+
[DllImport("user32.dll")]
|
|
278
|
+
public static extern bool ReleaseCapture();
|
|
279
|
+
[DllImport("user32.dll")]
|
|
280
|
+
public static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
|
|
281
|
+
[DllImport("user32.dll")]
|
|
282
|
+
public static extern bool PostMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
|
|
283
|
+
[DllImport("user32.dll")]
|
|
284
|
+
public static extern bool SetProcessDPIAware();
|
|
285
|
+
[DllImport("user32.dll")]
|
|
286
|
+
public static extern bool SetProcessDpiAwarenessContext(IntPtr context);
|
|
287
|
+
[DllImport("user32.dll")]
|
|
288
|
+
public static extern IntPtr WindowFromPoint(POINT point);
|
|
289
|
+
[DllImport("user32.dll")]
|
|
290
|
+
public static extern IntPtr GetAncestor(IntPtr hWnd, uint flags);
|
|
291
|
+
[DllImport("user32.dll")]
|
|
292
|
+
public static extern IntPtr MonitorFromPoint(POINT point, uint flags);
|
|
293
|
+
[DllImport("shcore.dll")]
|
|
294
|
+
public static extern int GetDpiForMonitor(IntPtr monitor, int type, out uint dpiX, out uint dpiY);
|
|
295
|
+
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
|
|
296
|
+
public static extern IntPtr GetModuleHandle(string name);
|
|
297
|
+
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
|
|
298
|
+
public static extern int GetClassName(IntPtr hWnd, System.Text.StringBuilder name, int maxCount);
|
|
299
|
+
[DllImport("user32.dll", SetLastError = true)]
|
|
300
|
+
public static extern IntPtr SetWindowsHookEx(int idHook, HookProc callback, IntPtr module, uint threadId);
|
|
301
|
+
[DllImport("user32.dll", SetLastError = true)]
|
|
302
|
+
public static extern bool UnhookWindowsHookEx(IntPtr hook);
|
|
303
|
+
[DllImport("user32.dll")]
|
|
304
|
+
public static extern IntPtr CallNextHookEx(IntPtr hook, int code, IntPtr wParam, IntPtr lParam);
|
|
305
|
+
// Windows treats this one as if the user asked for the switch, which the
|
|
306
|
+
// plain SetForegroundWindow call is often not allowed to do.
|
|
307
|
+
[DllImport("user32.dll")]
|
|
308
|
+
public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);
|
|
309
|
+
[DllImport("user32.dll")]
|
|
310
|
+
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
|
|
311
|
+
[DllImport("user32.dll")]
|
|
312
|
+
public static extern bool InvalidateRect(IntPtr hWnd, IntPtr lpRect, bool bErase);
|
|
313
|
+
[DllImport("user32.dll")]
|
|
314
|
+
public static extern bool UpdateWindow(IntPtr hWnd);
|
|
315
|
+
// Lets this process take the foreground without an input-queue attach,
|
|
316
|
+
// which is what used to wedge the target window.
|
|
317
|
+
[DllImport("user32.dll", SetLastError = true)]
|
|
318
|
+
public static extern bool SystemParametersInfo(uint uiAction, uint uiParam, IntPtr pvParam, uint fWinIni);
|
|
319
|
+
public delegate IntPtr HookProc(int code, IntPtr wParam, IntPtr lParam);
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
323
|
+
public struct MSLLHOOKSTRUCT {
|
|
324
|
+
public POINT pt;
|
|
325
|
+
public uint mouseData;
|
|
326
|
+
public uint flags;
|
|
327
|
+
public uint time;
|
|
328
|
+
public IntPtr dwExtraInfo;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// 0x08000000 = WS_EX_NOACTIVATE: the card shows without stealing focus from
|
|
332
|
+
// the app the user just selected text in.
|
|
333
|
+
public sealed class CardForm : Form {
|
|
334
|
+
public bool ActivateOnShow = true;
|
|
335
|
+
protected override bool ShowWithoutActivation { get { return !ActivateOnShow; } }
|
|
336
|
+
protected override CreateParams CreateParams {
|
|
337
|
+
get {
|
|
338
|
+
CreateParams cp = base.CreateParams;
|
|
339
|
+
cp.ExStyle |= 0x08000000;
|
|
340
|
+
return cp;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
// Dragging from a PowerShell event handler would re-enter the script
|
|
345
|
+
// engine inside the modal move loop (the "unhandled exception" dialog),
|
|
346
|
+
// so the whole gesture lives in C#.
|
|
347
|
+
public void MakeDraggable(Control target) {
|
|
348
|
+
target.MouseDown += delegate(object sender, MouseEventArgs e) {
|
|
349
|
+
if (e.Button != MouseButtons.Left) return;
|
|
350
|
+
Native.ReleaseCapture();
|
|
351
|
+
Native.SendMessage(Handle, 0xA1, (IntPtr)2, IntPtr.Zero);
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
public sealed class HotkeyWindow : NativeWindow {
|
|
357
|
+
public const int WM_HOTKEY = 0x0312;
|
|
358
|
+
public const int WM_HOOK = 0x8001;
|
|
359
|
+
private readonly int id;
|
|
360
|
+
public event Action<int> Pressed;
|
|
361
|
+
public event Action<int> HookPing;
|
|
362
|
+
public MouseWatcher Mouse;
|
|
363
|
+
public KeyboardWatcher Keyboard;
|
|
364
|
+
|
|
365
|
+
public HotkeyWindow(int id) {
|
|
366
|
+
this.id = id;
|
|
367
|
+
CreateHandle(new CreateParams {
|
|
368
|
+
Caption = "external-toolbox-hotkey",
|
|
369
|
+
X = -4000,
|
|
370
|
+
Y = -4000,
|
|
371
|
+
Width = 1,
|
|
372
|
+
Height = 1,
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
public bool Register(uint mods, uint vk) {
|
|
377
|
+
return Native.RegisterHotKey(Handle, id, mods, vk);
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
public void Unregister() {
|
|
381
|
+
try { Native.UnregisterHotKey(Handle, id); } catch { }
|
|
382
|
+
try { DestroyHandle(); } catch { }
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
protected override void WndProc(ref Message m) {
|
|
386
|
+
if (m.Msg == WM_HOTKEY) {
|
|
387
|
+
var handler = Pressed;
|
|
388
|
+
if (handler != null) {
|
|
389
|
+
try { handler(m.WParam.ToInt32()); } catch { }
|
|
390
|
+
}
|
|
391
|
+
} else if (m.Msg == WM_HOOK) {
|
|
392
|
+
int code = m.WParam.ToInt32();
|
|
393
|
+
if (Mouse != null) Mouse.ClearPending(code);
|
|
394
|
+
if (Keyboard != null) Keyboard.ClearPending(code);
|
|
395
|
+
var ping = HookPing;
|
|
396
|
+
if (ping != null) { try { ping(code); } catch { } }
|
|
397
|
+
}
|
|
398
|
+
base.WndProc(ref m);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// A low level hook that takes too long makes Windows drop input for the
|
|
403
|
+
// whole desktop, and script execution is far too slow for that path. The
|
|
404
|
+
// hooks only post a message to the hotkey window; the UI thread runs the
|
|
405
|
+
// script side afterwards.
|
|
406
|
+
public sealed class MouseWatcher : IDisposable {
|
|
407
|
+
public const int PingClick = 1;
|
|
408
|
+
public const int PingGesture = 2;
|
|
409
|
+
|
|
410
|
+
private const int WH_MOUSE_LL = 14;
|
|
411
|
+
private const int WM_LBUTTONDOWN = 0x0201;
|
|
412
|
+
private const int WM_LBUTTONUP = 0x0202;
|
|
413
|
+
private const int WM_MOUSEWHEEL = 0x020A;
|
|
414
|
+
private const int EM_LINESCROLL = 0x00B6;
|
|
415
|
+
|
|
416
|
+
private Native.HookProc proc;
|
|
417
|
+
private IntPtr hook = IntPtr.Zero;
|
|
418
|
+
private POINT down;
|
|
419
|
+
private bool downSeen;
|
|
420
|
+
private bool doubleClick;
|
|
421
|
+
// A low level hook never sees WM_LBUTTONDBLCLK (that is generated by the
|
|
422
|
+
// target window), so the second click has to be recognised by timing.
|
|
423
|
+
private int lastDownTime;
|
|
424
|
+
private POINT lastDownPt;
|
|
425
|
+
private bool hasLastDown;
|
|
426
|
+
private int pendingClick;
|
|
427
|
+
private int pendingGesture;
|
|
428
|
+
|
|
429
|
+
public IntPtr Notify = IntPtr.Zero;
|
|
430
|
+
// Wheel events are swallowed and forwarded to a text box when the cursor
|
|
431
|
+
// is over our own card; otherwise the window under it would scroll.
|
|
432
|
+
public IntPtr WheelWindow = IntPtr.Zero;
|
|
433
|
+
public IntPtr WheelTarget = IntPtr.Zero;
|
|
434
|
+
// The card has two panes; scrolling has to follow the one under the
|
|
435
|
+
// pointer instead of always landing on the translation.
|
|
436
|
+
public IntPtr WheelSrc = IntPtr.Zero;
|
|
437
|
+
public IntPtr WheelDst = IntPtr.Zero;
|
|
438
|
+
|
|
439
|
+
public bool Start() {
|
|
440
|
+
if (hook != IntPtr.Zero) return true;
|
|
441
|
+
proc = OnHook;
|
|
442
|
+
hook = Native.SetWindowsHookEx(WH_MOUSE_LL, proc, Native.GetModuleHandle(null), 0);
|
|
443
|
+
return hook != IntPtr.Zero;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
public void Stop() {
|
|
447
|
+
if (hook != IntPtr.Zero) {
|
|
448
|
+
Native.UnhookWindowsHookEx(hook);
|
|
449
|
+
hook = IntPtr.Zero;
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
public void Dispose() { Stop(); }
|
|
454
|
+
|
|
455
|
+
public void ClearPending(int code) {
|
|
456
|
+
if (code == PingClick) System.Threading.Interlocked.Exchange(ref pendingClick, 0);
|
|
457
|
+
if (code == PingGesture) System.Threading.Interlocked.Exchange(ref pendingGesture, 0);
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
private void Post(int code, ref int pending) {
|
|
461
|
+
if (Notify == IntPtr.Zero) return;
|
|
462
|
+
if (System.Threading.Interlocked.Exchange(ref pending, 1) != 0) return;
|
|
463
|
+
Native.PostMessage(Notify, HotkeyWindow.WM_HOOK, (IntPtr)code, IntPtr.Zero);
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
private IntPtr OnHook(int code, IntPtr wParam, IntPtr lParam) {
|
|
467
|
+
if (code >= 0) {
|
|
468
|
+
int msg = (int)(long)wParam;
|
|
469
|
+
MSLLHOOKSTRUCT info = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT));
|
|
470
|
+
if (msg == WM_MOUSEWHEEL && WheelWindow != IntPtr.Zero && WheelTarget != IntPtr.Zero) {
|
|
471
|
+
RECT box;
|
|
472
|
+
if (Native.GetWindowRect(WheelWindow, out box)
|
|
473
|
+
&& info.pt.X >= box.Left && info.pt.X <= box.Right
|
|
474
|
+
&& info.pt.Y >= box.Top && info.pt.Y <= box.Bottom) {
|
|
475
|
+
IntPtr pane = IntPtr.Zero;
|
|
476
|
+
RECT area;
|
|
477
|
+
if (WheelDst != IntPtr.Zero && Native.IsWindowVisible(WheelDst)
|
|
478
|
+
&& Native.GetWindowRect(WheelDst, out area)
|
|
479
|
+
&& info.pt.Y >= area.Top && info.pt.Y <= area.Bottom) {
|
|
480
|
+
pane = WheelDst;
|
|
481
|
+
} else if (WheelSrc != IntPtr.Zero && Native.GetWindowRect(WheelSrc, out area)
|
|
482
|
+
&& info.pt.Y >= area.Top && info.pt.Y <= area.Bottom) {
|
|
483
|
+
pane = WheelSrc;
|
|
484
|
+
}
|
|
485
|
+
// inside the card but outside both panes (header, lane,
|
|
486
|
+
// footer): scrolling nothing is better than scrolling the
|
|
487
|
+
// wrong box.
|
|
488
|
+
int delta = (short)((info.mouseData >> 16) & 0xffff);
|
|
489
|
+
int lines = -(delta / 120) * 3;
|
|
490
|
+
if (lines != 0 && pane != IntPtr.Zero) Native.PostMessage(pane, EM_LINESCROLL, IntPtr.Zero, (IntPtr)lines);
|
|
491
|
+
if (Notify != IntPtr.Zero) Native.PostMessage(Notify, HotkeyWindow.WM_HOOK, (IntPtr)6, IntPtr.Zero);
|
|
492
|
+
return (IntPtr)1;
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
if (msg == WM_LBUTTONDOWN) {
|
|
496
|
+
bool second = hasLastDown
|
|
497
|
+
&& (int)info.time - lastDownTime <= 500
|
|
498
|
+
&& Math.Abs(info.pt.X - lastDownPt.X) <= 4
|
|
499
|
+
&& Math.Abs(info.pt.Y - lastDownPt.Y) <= 4;
|
|
500
|
+
down = info.pt;
|
|
501
|
+
downSeen = true;
|
|
502
|
+
doubleClick = second;
|
|
503
|
+
hasLastDown = !second;
|
|
504
|
+
lastDownTime = (int)info.time;
|
|
505
|
+
lastDownPt = info.pt;
|
|
506
|
+
Post(PingClick, ref pendingClick);
|
|
507
|
+
} else if (msg == WM_LBUTTONUP) {
|
|
508
|
+
bool dragged = downSeen && (Math.Abs(info.pt.X - down.X) > 5 || Math.Abs(info.pt.Y - down.Y) > 5);
|
|
509
|
+
bool fire = dragged || doubleClick;
|
|
510
|
+
downSeen = false;
|
|
511
|
+
doubleClick = false;
|
|
512
|
+
if (fire) Post(PingGesture, ref pendingGesture);
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
return Native.CallNextHookEx(hook, code, wParam, lParam);
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
// Ctrl+A and Shift+arrows create a selection without touching the mouse,
|
|
520
|
+
// so the mouse hook cannot see them; watch those key ups instead.
|
|
521
|
+
public sealed class KeyboardWatcher : IDisposable {
|
|
522
|
+
public const int PingGesture = 3;
|
|
523
|
+
public const int PingEscape = 4;
|
|
524
|
+
|
|
525
|
+
private const int WH_KEYBOARD_LL = 13;
|
|
526
|
+
private const int WM_KEYDOWN = 0x0100;
|
|
527
|
+
private const int WM_SYSKEYDOWN = 0x0104;
|
|
528
|
+
private const int WM_KEYUP = 0x0101;
|
|
529
|
+
private const int WM_SYSKEYUP = 0x0105;
|
|
530
|
+
private const int VK_SHIFT = 0x10;
|
|
531
|
+
private const int VK_CONTROL = 0x11;
|
|
532
|
+
private const int VK_ESCAPE = 0x1B;
|
|
533
|
+
|
|
534
|
+
private Native.HookProc proc;
|
|
535
|
+
private IntPtr hook = IntPtr.Zero;
|
|
536
|
+
private int pendingGesture;
|
|
537
|
+
|
|
538
|
+
public IntPtr Notify = IntPtr.Zero;
|
|
539
|
+
// Our own windows. Escape is only swallowed while one of them is on
|
|
540
|
+
// screen; checking that here keeps the hook free of script calls.
|
|
541
|
+
public IntPtr[] Guarded = new IntPtr[0];
|
|
542
|
+
|
|
543
|
+
public bool Start() {
|
|
544
|
+
if (hook != IntPtr.Zero) return true;
|
|
545
|
+
proc = OnHook;
|
|
546
|
+
hook = Native.SetWindowsHookEx(WH_KEYBOARD_LL, proc, Native.GetModuleHandle(null), 0);
|
|
547
|
+
return hook != IntPtr.Zero;
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
public void Stop() {
|
|
551
|
+
if (hook != IntPtr.Zero) {
|
|
552
|
+
Native.UnhookWindowsHookEx(hook);
|
|
553
|
+
hook = IntPtr.Zero;
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
public void Dispose() { Stop(); }
|
|
558
|
+
|
|
559
|
+
public void ClearPending(int code) {
|
|
560
|
+
if (code == PingGesture) System.Threading.Interlocked.Exchange(ref pendingGesture, 0);
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
private bool GuardVisible() {
|
|
564
|
+
if (Guarded == null) return false;
|
|
565
|
+
foreach (IntPtr h in Guarded) {
|
|
566
|
+
if (h != IntPtr.Zero && Native.IsWindowVisible(h)) return true;
|
|
567
|
+
}
|
|
568
|
+
return false;
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
private void Post(int code) {
|
|
572
|
+
if (Notify == IntPtr.Zero) return;
|
|
573
|
+
Native.PostMessage(Notify, HotkeyWindow.WM_HOOK, (IntPtr)code, IntPtr.Zero);
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
private void PostGesture() {
|
|
577
|
+
if (Notify == IntPtr.Zero) return;
|
|
578
|
+
if (System.Threading.Interlocked.Exchange(ref pendingGesture, 1) != 0) return;
|
|
579
|
+
Native.PostMessage(Notify, HotkeyWindow.WM_HOOK, (IntPtr)PingGesture, IntPtr.Zero);
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
private IntPtr OnHook(int code, IntPtr wParam, IntPtr lParam) {
|
|
583
|
+
if (code >= 0) {
|
|
584
|
+
int msg = (int)(long)wParam;
|
|
585
|
+
int vk = Marshal.ReadInt32(lParam);
|
|
586
|
+
if ((msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN) && vk == VK_ESCAPE) {
|
|
587
|
+
if (GuardVisible()) {
|
|
588
|
+
Post(PingEscape);
|
|
589
|
+
return (IntPtr)1;
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
if (msg == WM_KEYUP || msg == WM_SYSKEYUP) {
|
|
593
|
+
bool ctrl = (Native.GetKeyState(VK_CONTROL) & 0x8000) != 0;
|
|
594
|
+
bool shift = (Native.GetKeyState(VK_SHIFT) & 0x8000) != 0;
|
|
595
|
+
bool all = ctrl && vk == 0x41;
|
|
596
|
+
bool extend = shift && (vk >= 0x21 && vk <= 0x28);
|
|
597
|
+
if (all || extend) PostGesture();
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
return Native.CallNextHookEx(hook, code, wParam, lParam);
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
'@ -ReferencedAssemblies $refs
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
function Write-Json([hashtable]$Payload) {
|
|
608
|
+
$json = $Payload | ConvertTo-Json -Compress -Depth 4
|
|
609
|
+
[Console]::Out.WriteLine($json)
|
|
610
|
+
[Console]::Out.Flush()
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
# This process IS per-monitor DPI aware (see the dpi block below): Windows does
|
|
614
|
+
# not bitmap-stretch the card, and Sz()/Fs() scale the 96 dpi design to pixels.
|
|
615
|
+
|
|
616
|
+
# Builds a string from code points so this file stays ASCII.
|
|
617
|
+
function U {
|
|
618
|
+
param([int[]]$Codes)
|
|
619
|
+
return (($Codes | ForEach-Object { [char]$_ }) -join "")
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
$T_SCRAPE = U 0x5212, 0x8BCD # "scrape" (card title)
|
|
623
|
+
$T_TRANSLATE = U 0x7FFB, 0x8BD1 # translate
|
|
624
|
+
$T_ASK = U 0x5F15, 0x7528 # quote
|
|
625
|
+
$T_COPY = U 0x590D, 0x5236 # copy
|
|
626
|
+
$T_CLOSE = U 0x5173, 0x95ED # close
|
|
627
|
+
$T_TRANSLATING = (U 0x7FFB, 0x8BD1, 0x4E2D) + "..." # translating...
|
|
628
|
+
$T_EXPLAIN = U 0x89E3, 0x91CA # explain
|
|
629
|
+
$T_EXPLAINING = (U 0x89E3, 0x91CA, 0x4E2D) + "..." # explaining...
|
|
630
|
+
$T_SAVE = U 0x6536, 0x85CF # save (to vocabulary)
|
|
631
|
+
$T_SAVED = U 0x5DF2, 0x6536, 0x85CF # saved
|
|
632
|
+
$T_SAVE_FAILED = U 0x6536, 0x85CF, 0x5931, 0x8D25 # save failed
|
|
633
|
+
$T_SPEAKING = U 0x6717, 0x8BFB, 0x4E2D # speaking
|
|
634
|
+
$T_COPIED = U 0x5DF2, 0x590D, 0x5236 # copied
|
|
635
|
+
$T_COPY_DST = U 0x590D, 0x5236, 0x8BD1, 0x6587 # copy translation
|
|
636
|
+
$T_COPY_SRC = U 0x590D, 0x5236, 0x539F, 0x6587 # copy original
|
|
637
|
+
$T_NO_TEXT = U 0x6CA1, 0x53D6, 0x5230, 0x9009, 0x4E2D, 0x6587, 0x672C # nothing selected
|
|
638
|
+
$T_NO_SERVICE = (U 0x7FFB, 0x8BD1, 0x670D, 0x52A1, 0x672A, 0x8FDE, 0x63A5) + " (DSH)" # translate service offline
|
|
639
|
+
$T_FAILED = U 0x7FFB, 0x8BD1, 0x5931, 0x8D25 # translation failed
|
|
640
|
+
$T_ASKED = (U 0x5DF2, 0x590D, 0x5236, 0x5E76, 0x5524, 0x8D77) + " DSH" # copied + DSH activated
|
|
641
|
+
$T_HINT = (U 0x9009, 0x4E2D, 0x6587, 0x672C, 0x540E, 0x6309) + " Ctrl+Alt+Q" # select text, press Ctrl+Alt+Q
|
|
642
|
+
|
|
643
|
+
# Display names for the drop-down; kept as code points so this file stays ASCII.
|
|
644
|
+
$script:LANG_NAMES = @{
|
|
645
|
+
auto = "Detect"; zh = (U 0x4E2D, 0x6587); en = "English"; ja = (U 0x65E5, 0x672C, 0x8A9E)
|
|
646
|
+
ko = (U 0xD55C, 0xAD6D, 0xC5B4); es = ("Espa" + [char]0x00F1 + "ol"); fr = ("Fran" + [char]0x00E7 + "ais")
|
|
647
|
+
de = "Deutsch"; ru = (U 0x0420, 0x0443, 0x0441, 0x0441, 0x043A, 0x0438, 0x0439)
|
|
648
|
+
pt = ("Portugu" + [char]0x00EA + "s"); it = "Italiano"
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
# ---------------------------------------------------------------- window focus
|
|
652
|
+
|
|
653
|
+
function Get-HostWindow {
|
|
654
|
+
# The DSH window often belongs to a renderer process, so MainWindowHandle on
|
|
655
|
+
# the host process is zero; match the window title first.
|
|
656
|
+
foreach ($needle in @("DeepSeek Harness", $WindowTitle, "DeepSeek")) {
|
|
657
|
+
if ([string]::IsNullOrWhiteSpace($needle)) { continue }
|
|
658
|
+
try {
|
|
659
|
+
$h = [QuickAsk.Native]::FindWindowByTitle($needle)
|
|
660
|
+
if ($h -ne [IntPtr]::Zero) { return $h }
|
|
661
|
+
} catch { }
|
|
662
|
+
}
|
|
663
|
+
# Titles change with the conversation, and a window sent to the tray is not
|
|
664
|
+
# "visible" any more, so fall back to the executable name.
|
|
665
|
+
try {
|
|
666
|
+
$h = [QuickAsk.Native]::FindWindowByProcessName("DeepSeek Harness")
|
|
667
|
+
if ($h -ne [IntPtr]::Zero) { return $h }
|
|
668
|
+
} catch { }
|
|
669
|
+
try {
|
|
670
|
+
$h = [QuickAsk.Native]::FindWindowByProcessName("DeepseekHaeness")
|
|
671
|
+
if ($h -ne [IntPtr]::Zero) { return $h }
|
|
672
|
+
} catch { }
|
|
673
|
+
$patterns = @($WindowTitle, "DeepSeek Harness", "DeepSeek")
|
|
674
|
+
foreach ($pattern in $patterns) {
|
|
675
|
+
$procs = Get-Process -ErrorAction SilentlyContinue |
|
|
676
|
+
Where-Object { $_.MainWindowHandle -ne 0 -and $_.ProcessName -like "*$pattern*" }
|
|
677
|
+
foreach ($p in $procs) { return $p.MainWindowHandle }
|
|
678
|
+
}
|
|
679
|
+
return [IntPtr]::Zero
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
# Runs in a background runspace: activating another process's window can block
|
|
683
|
+
# for as long as that process takes to pump messages, and doing it on the UI
|
|
684
|
+
# thread is what made DSH look frozen.
|
|
685
|
+
$script:ActivateScript = @'
|
|
686
|
+
param($Handle, $LogPath)
|
|
687
|
+
function AL($m) {
|
|
688
|
+
try { Add-Content -LiteralPath $LogPath -Value (("{0} activate[bg]: {1}" -f (Get-Date -Format "HH:mm:ss.fff"), $m)) -Encoding UTF8 } catch { }
|
|
689
|
+
}
|
|
690
|
+
function CheckTop {
|
|
691
|
+
# Keep this dumb and ordered. Earlier versions asked "who owns the centre
|
|
692
|
+
# pixel" and retried, but Electron shows its window a few hundred ms after we
|
|
693
|
+
# quote, so every answer was stale and the retries only logged noise. A fixed
|
|
694
|
+
# sequence is predictable: raise to the topmost band (which puts us above the
|
|
695
|
+
# editor), hold long enough for the app to finish its own restore, then drop
|
|
696
|
+
# the topmost flag. HWND_NOTOPMOST keeps the current z position, so the
|
|
697
|
+
# window stays above the editor without floating over everything forever.
|
|
698
|
+
$top = New-Object System.IntPtr(-1)
|
|
699
|
+
$notTop = New-Object System.IntPtr(-2)
|
|
700
|
+
try {
|
|
701
|
+
Start-Sleep -Milliseconds 350
|
|
702
|
+
[void][QuickAsk.Native]::SetWindowPos($h, $top, 0, 0, 0, 0, 0x0001 -bor 0x0002 -bor 0x0010)
|
|
703
|
+
[void][QuickAsk.Native]::SetForegroundWindow($h)
|
|
704
|
+
AL 'top raised'
|
|
705
|
+
Start-Sleep -Milliseconds 600
|
|
706
|
+
[void][QuickAsk.Native]::SetWindowPos($h, $notTop, 0, 0, 0, 0, 0x0001 -bor 0x0002 -bor 0x0010)
|
|
707
|
+
AL 'top released'
|
|
708
|
+
$rc = New-Object QuickAsk.RECT
|
|
709
|
+
if ([QuickAsk.Native]::GetWindowRect($h, [ref]$rc)) {
|
|
710
|
+
$pt = New-Object QuickAsk.POINT
|
|
711
|
+
$pt.X = [int](($rc.L + $rc.R) / 2)
|
|
712
|
+
$pt.Y = [int](($rc.T + $rc.B) / 2)
|
|
713
|
+
$owner = [QuickAsk.Native]::GetAncestor([QuickAsk.Native]::WindowFromPoint($pt), 2)
|
|
714
|
+
AL ("top=" + [string]$owner.ToInt64() + " self=" + [string]$h.ToInt64())
|
|
715
|
+
}
|
|
716
|
+
} catch { AL ("top failed: " + $_.Exception.Message) }
|
|
717
|
+
}
|
|
718
|
+
$h = [IntPtr]([int64]$Handle)
|
|
719
|
+
# Remember the pre-activation window state: SW_RESTORE un-maximises a
|
|
720
|
+
# maximised window, so if it was zoomed before we must put it back.
|
|
721
|
+
$wasZoomed = $false
|
|
722
|
+
try { $wasZoomed = [QuickAsk.Native]::IsZoomed($h) } catch { }
|
|
723
|
+
$relaunched = $false
|
|
724
|
+
$mem = [System.Runtime.InteropServices.Marshal]::AllocHGlobal(4)
|
|
725
|
+
$altDown = $false
|
|
726
|
+
try {
|
|
727
|
+
# Showing a window the app hid itself is only half the job: Chromium stops
|
|
728
|
+
# compositing for a window it believes is hidden, so the HWND can be visible,
|
|
729
|
+
# foreground and still show a stale (or blank) frame. A one pixel resize makes
|
|
730
|
+
# the compositor lay out and emit a fresh frame, and the invalidate/redraw pair
|
|
731
|
+
# quotes for the paint explicitly.
|
|
732
|
+
if (-not [QuickAsk.Native]::IsWindowVisible($h)) {
|
|
733
|
+
# The only way to get live frames back is to let the application show its
|
|
734
|
+
# own window: Electron keeps its own idea of visibility, and Chromium stops
|
|
735
|
+
# compositing for a window it still considers hidden, which is exactly the
|
|
736
|
+
# "window appears but the picture is frozen" symptom. Relaunching the exe
|
|
737
|
+
# hits the single-instance path in the app, which calls focusPrimaryWindow()
|
|
738
|
+
# -> window.show(), so the renderer starts producing frames again.
|
|
739
|
+
# External ShowWindow (even SW_RESTORE) makes pixels appear but leaves the
|
|
740
|
+
# compositor parked, so it is only the fallback.
|
|
741
|
+
$wpid = 0
|
|
742
|
+
try { [void][QuickAsk.Native]::GetWindowThreadProcessId($h, [ref]$wpid) } catch { }
|
|
743
|
+
$exe = $null
|
|
744
|
+
if ($wpid -gt 0) { try { $exe = (Get-Process -Id $wpid -ErrorAction Stop).Path } catch { AL ("exe lookup failed for pid " + [string]$wpid + ": " + $_.Exception.Message) } }
|
|
745
|
+
if (-not $exe) {
|
|
746
|
+
try {
|
|
747
|
+
$parentId = (Get-CimInstance Win32_Process -Filter ("ProcessId=" + [string]$PID)).ParentProcessId
|
|
748
|
+
$exe = (Get-Process -Id $parentId -ErrorAction Stop).Path
|
|
749
|
+
AL ("exe from parent pid " + [string]$parentId)
|
|
750
|
+
} catch { }
|
|
751
|
+
}
|
|
752
|
+
if (-not $exe) {
|
|
753
|
+
$known = "D:\DeepseekHaeness\DeepSeek Harness.exe"
|
|
754
|
+
if (Test-Path -LiteralPath $known) { $exe = $known; AL 'exe from known path' }
|
|
755
|
+
}
|
|
756
|
+
if ($exe) {
|
|
757
|
+
try {
|
|
758
|
+
# The helper runs under the DSH host, which is itself an Electron process
|
|
759
|
+
# started with ELECTRON_RUN_AS_NODE=1. If that variable leaks into the
|
|
760
|
+
# relaunched exe it starts as a plain Node script and no window is
|
|
761
|
+
# created, so strip it before starting.
|
|
762
|
+
$psi = New-Object System.Diagnostics.ProcessStartInfo
|
|
763
|
+
$psi.FileName = $exe
|
|
764
|
+
$psi.UseShellExecute = $false
|
|
765
|
+
try { $psi.EnvironmentVariables.Remove("ELECTRON_RUN_AS_NODE") } catch { }
|
|
766
|
+
try { $psi.EnvironmentVariables.Remove("ELECTRON_NO_ATTACH_CONSOLE") } catch { }
|
|
767
|
+
[void][System.Diagnostics.Process]::Start($psi)
|
|
768
|
+
AL ("relaunched " + $exe)
|
|
769
|
+
} catch { AL ("relaunch failed: " + $_.Exception.Message) }
|
|
770
|
+
for ($k = 0; $k -lt 24; $k++) {
|
|
771
|
+
Start-Sleep -Milliseconds 250
|
|
772
|
+
if ([QuickAsk.Native]::IsWindowVisible($h)) { break }
|
|
773
|
+
}
|
|
774
|
+
AL ("visible after relaunch=" + [string]([QuickAsk.Native]::IsWindowVisible($h)))
|
|
775
|
+
if ([QuickAsk.Native]::IsWindowVisible($h)) { $relaunched = $true }
|
|
776
|
+
}
|
|
777
|
+
if (-not [QuickAsk.Native]::IsWindowVisible($h)) {
|
|
778
|
+
if ($wasZoomed) { [void][QuickAsk.Native]::ShowWindow($h, 3) } else { [void][QuickAsk.Native]::ShowWindow($h, 9) }
|
|
779
|
+
}
|
|
780
|
+
Start-Sleep -Milliseconds 120
|
|
781
|
+
if (-not [QuickAsk.Native]::IsWindowVisible($h)) {
|
|
782
|
+
[void][QuickAsk.Native]::SetWindowPos($h, [IntPtr]::Zero, 0, 0, 0, 0, 0x0040 -bor 0x0002 -bor 0x0001 -bor 0x0010)
|
|
783
|
+
Start-Sleep -Milliseconds 150
|
|
784
|
+
}
|
|
785
|
+
AL ("forced visible=" + [string]([QuickAsk.Native]::IsWindowVisible($h)))
|
|
786
|
+
if ($wasZoomed -and -not [QuickAsk.Native]::IsZoomed($h)) {
|
|
787
|
+
[void][QuickAsk.Native]::ShowWindow($h, 3)
|
|
788
|
+
AL "re-maximized"
|
|
789
|
+
}
|
|
790
|
+
Start-Sleep -Milliseconds 150
|
|
791
|
+
$rc = New-Object QuickAsk.RECT
|
|
792
|
+
if ((-not $relaunched) -and [QuickAsk.Native]::GetWindowRect($h, [ref]$rc)) {
|
|
793
|
+
$w = $rc.R - $rc.L
|
|
794
|
+
$hh = $rc.B - $rc.T
|
|
795
|
+
[void][QuickAsk.Native]::SetWindowPos($h, [IntPtr]::Zero, 0, 0, ($w + 1), $hh, 0x0002 -bor 0x0004 -bor 0x0010)
|
|
796
|
+
Start-Sleep -Milliseconds 60
|
|
797
|
+
[void][QuickAsk.Native]::SetWindowPos($h, [IntPtr]::Zero, 0, 0, $w, $hh, 0x0002 -bor 0x0004 -bor 0x0010)
|
|
798
|
+
[void][QuickAsk.Native]::InvalidateRect($h, [IntPtr]::Zero, $true)
|
|
799
|
+
[void][QuickAsk.Native]::UpdateWindow($h)
|
|
800
|
+
AL 'paint nudged'
|
|
801
|
+
}
|
|
802
|
+
# Shown and repainted is still not the same as "on top": raise the window
|
|
803
|
+
# above every other window (including always-on-top ones) for a moment, so
|
|
804
|
+
# it cannot stay buried behind the editor it was invoked from.
|
|
805
|
+
try {
|
|
806
|
+
$top = New-Object System.IntPtr(-1)
|
|
807
|
+
$notTop = New-Object System.IntPtr(-2)
|
|
808
|
+
[void][QuickAsk.Native]::SetWindowPos($h, $top, 0, 0, 0, 0, 0x0001 -bor 0x0002 -bor 0x0010 -bor 0x0020)
|
|
809
|
+
Start-Sleep -Milliseconds 200
|
|
810
|
+
[void][QuickAsk.Native]::SetWindowPos($h, $notTop, 0, 0, 0, 0, 0x0001 -bor 0x0002 -bor 0x0010)
|
|
811
|
+
AL 'raised'
|
|
812
|
+
} catch { AL ("raise failed: " + $_.Exception.Message) }
|
|
813
|
+
} else {
|
|
814
|
+
AL 'already visible'
|
|
815
|
+
}
|
|
816
|
+
if ([QuickAsk.Native]::IsIconic($h)) { [void][QuickAsk.Native]::ShowWindow($h, 9); AL 'restored from minimize' }
|
|
817
|
+
if (([QuickAsk.Native]::GetForegroundWindow() -eq $h) -and [QuickAsk.Native]::IsWindowVisible($h)) { AL 'ok already'; CheckTop; return }
|
|
818
|
+
$prev = 200000
|
|
819
|
+
try {
|
|
820
|
+
[void][QuickAsk.Native]::SystemParametersInfo(0x2000, 0, $mem, 0)
|
|
821
|
+
$prev = [System.Runtime.InteropServices.Marshal]::ReadInt32($mem)
|
|
822
|
+
} catch { }
|
|
823
|
+
try {
|
|
824
|
+
[System.Runtime.InteropServices.Marshal]::WriteInt32($mem, 0)
|
|
825
|
+
[void][QuickAsk.Native]::SystemParametersInfo(0x2001, 0, $mem, 0)
|
|
826
|
+
} catch { }
|
|
827
|
+
try {
|
|
828
|
+
[void][QuickAsk.Native]::SetForegroundWindow($h)
|
|
829
|
+
Start-Sleep -Milliseconds 120
|
|
830
|
+
if ([QuickAsk.Native]::GetForegroundWindow() -eq $h) { AL 'ok direct'; CheckTop; return }
|
|
831
|
+
[QuickAsk.Native]::SwitchToThisWindow($h, $true)
|
|
832
|
+
Start-Sleep -Milliseconds 150
|
|
833
|
+
if ([QuickAsk.Native]::GetForegroundWindow() -eq $h) { AL 'ok switch'; CheckTop; return }
|
|
834
|
+
[QuickAsk.Native]::keybd_event(0x12, 0, 0, [IntPtr]::Zero)
|
|
835
|
+
$altDown = $true
|
|
836
|
+
Start-Sleep -Milliseconds 25
|
|
837
|
+
[void][QuickAsk.Native]::SetForegroundWindow($h)
|
|
838
|
+
Start-Sleep -Milliseconds 25
|
|
839
|
+
[QuickAsk.Native]::keybd_event(0x12, 0, 2, [IntPtr]::Zero)
|
|
840
|
+
$altDown = $false
|
|
841
|
+
Start-Sleep -Milliseconds 150
|
|
842
|
+
AL ("final=" + [string]([QuickAsk.Native]::GetForegroundWindow() -eq $h))
|
|
843
|
+
CheckTop
|
|
844
|
+
} finally {
|
|
845
|
+
if ($altDown) { try { [QuickAsk.Native]::keybd_event(0x12, 0, 2, [IntPtr]::Zero) } catch { } }
|
|
846
|
+
try {
|
|
847
|
+
[System.Runtime.InteropServices.Marshal]::WriteInt32($mem, $prev)
|
|
848
|
+
[void][QuickAsk.Native]::SystemParametersInfo(0x2001, 0, $mem, 0)
|
|
849
|
+
} catch { }
|
|
850
|
+
}
|
|
851
|
+
} catch {
|
|
852
|
+
AL ("error: " + $_.Exception.Message)
|
|
853
|
+
} finally {
|
|
854
|
+
AL 'finally entered'
|
|
855
|
+
}
|
|
856
|
+
'@
|
|
857
|
+
# The app's own activation path. On Windows open-url never fires, so a dsh://
|
|
858
|
+
# URL is ignored; launching the executable again is what works, because the
|
|
859
|
+
# running instance receives second-instance and runs focusPrimaryWindow()
|
|
860
|
+
# (restore + show + focus). That is the tray-click path, and the only one that
|
|
861
|
+
# keeps Electron's visibility state and the real HWND in step.
|
|
862
|
+
function Get-HostExe {
|
|
863
|
+
if (-not [string]::IsNullOrWhiteSpace($script:hostExe)) { return $script:hostExe }
|
|
864
|
+
$path = ""
|
|
865
|
+
try {
|
|
866
|
+
if ($script:parentPid -gt 0) { $path = (Get-Process -Id $script:parentPid -ErrorAction Stop).Path }
|
|
867
|
+
} catch { }
|
|
868
|
+
if ([string]::IsNullOrWhiteSpace($path)) {
|
|
869
|
+
try {
|
|
870
|
+
$p = @(Get-Process "DeepSeek Harness" -ErrorAction SilentlyContinue)[0]
|
|
871
|
+
if ($null -ne $p) { $path = $p.Path }
|
|
872
|
+
} catch { }
|
|
873
|
+
}
|
|
874
|
+
if (-not [string]::IsNullOrWhiteSpace($path)) { $script:hostExe = $path }
|
|
875
|
+
return $path
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
function Start-HostProtocol {
|
|
879
|
+
$exe = Get-HostExe
|
|
880
|
+
if ([string]::IsNullOrWhiteSpace($exe)) {
|
|
881
|
+
Write-Trace "activate: host exe not found"
|
|
882
|
+
return $false
|
|
883
|
+
}
|
|
884
|
+
try {
|
|
885
|
+
Start-Process -FilePath $exe -ErrorAction Stop
|
|
886
|
+
Write-Trace ("activate: second instance " + $exe)
|
|
887
|
+
return $true
|
|
888
|
+
} catch {
|
|
889
|
+
Write-Trace ("activate: second instance failed " + $_.Exception.Message)
|
|
890
|
+
return $false
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
function Show-HostWindow {
|
|
895
|
+
if ($NoActivate) { return }
|
|
896
|
+
# One activation in flight at a time: repeated hotkeys must not stack up.
|
|
897
|
+
$now = Get-Date
|
|
898
|
+
if ($null -ne $script:activateAt -and ($now - $script:activateAt).TotalSeconds -lt 3) {
|
|
899
|
+
Write-Trace "activate: busy"
|
|
900
|
+
return
|
|
901
|
+
}
|
|
902
|
+
$hwnd = Get-HostWindow
|
|
903
|
+
# No "already foreground" shortcut: GetForegroundWindow() also reports a hidden
|
|
904
|
+
# (or covered) window, so the test can pass while nothing is on screen.
|
|
905
|
+
$script:activateAt = $now
|
|
906
|
+
$activateUrl = ""
|
|
907
|
+
if (-not [string]::IsNullOrWhiteSpace($TranslateUrl)) {
|
|
908
|
+
$marker = $TranslateUrl.IndexOf("/toolbox/translate")
|
|
909
|
+
if ($marker -ge 0) { $activateUrl = $TranslateUrl.Substring(0, $marker) + "/toolbox/activate" }
|
|
910
|
+
}
|
|
911
|
+
if ($hwnd -eq [IntPtr]::Zero) {
|
|
912
|
+
Start-Sleep -Milliseconds 150
|
|
913
|
+
$hwnd = Get-HostWindow
|
|
914
|
+
}
|
|
915
|
+
if ($hwnd -eq [IntPtr]::Zero) {
|
|
916
|
+
$cand = @()
|
|
917
|
+
try { $cand = [QuickAsk.Native]::DescribeWindows("DeepSeek") } catch { }
|
|
918
|
+
Write-Trace ("activate: host window not found; candidates=" + ($cand -join " || "))
|
|
919
|
+
return
|
|
920
|
+
}
|
|
921
|
+
# The background runspace owns the whole show/nudge/raise sequence: doing a
|
|
922
|
+
# ShowWindow here first would make it take the "already visible" branch and
|
|
923
|
+
# skip the repaint nudge, which is exactly what leaves a stale frame.
|
|
924
|
+
$visible = $false
|
|
925
|
+
try { $visible = [QuickAsk.Native]::IsWindowVisible($hwnd) } catch { }
|
|
926
|
+
if (-not $visible) { Write-Trace "activate: window hidden, background script will show it" }
|
|
927
|
+
try {
|
|
928
|
+
# Keep the runner alive: an unreferenced PowerShell object can be collected
|
|
929
|
+
# while its background script is still running, which aborts it mid-flight
|
|
930
|
+
# and skips its finally block (losing the evidence screenshot).
|
|
931
|
+
$ps = [powershell]::Create()
|
|
932
|
+
[void]$ps.AddScript($script:ActivateScript).AddArgument([string]$hwnd.ToInt64()).AddArgument($script:LogPath)
|
|
933
|
+
[void]$ps.BeginInvoke()
|
|
934
|
+
$script:activateRunner = $ps
|
|
935
|
+
Write-Trace "activate: spawned bg"
|
|
936
|
+
} catch {
|
|
937
|
+
Write-Trace ("activate: spawn failed " + $_.Exception.Message)
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
# ---------------------------------------------------------------- UIA capture
|
|
941
|
+
|
|
942
|
+
function Get-UiaSelectionText {
|
|
943
|
+
param([System.Windows.Automation.AutomationElement]$Element)
|
|
944
|
+
|
|
945
|
+
if ($null -eq $Element) { return $null }
|
|
946
|
+
for ($depth = 0; $depth -lt 6 -and $null -ne $Element; $depth++) {
|
|
947
|
+
$hasText = $false
|
|
948
|
+
try {
|
|
949
|
+
foreach ($p in $Element.GetSupportedPatterns()) {
|
|
950
|
+
if ($p.Id -eq [System.Windows.Automation.TextPattern]::Pattern.Id) { $hasText = $true; break }
|
|
951
|
+
}
|
|
952
|
+
} catch { }
|
|
953
|
+
if ($hasText) {
|
|
954
|
+
try {
|
|
955
|
+
$tp = [System.Windows.Automation.TextPattern]$Element.GetCurrentPattern([System.Windows.Automation.TextPattern]::Pattern)
|
|
956
|
+
$ranges = $tp.GetSelection()
|
|
957
|
+
if ($null -ne $ranges -and $ranges.Count -gt 0) {
|
|
958
|
+
$text = $ranges[0].GetText(-1)
|
|
959
|
+
if (-not [string]::IsNullOrWhiteSpace($text)) { return $text }
|
|
960
|
+
}
|
|
961
|
+
} catch { }
|
|
962
|
+
}
|
|
963
|
+
try {
|
|
964
|
+
$Element = [System.Windows.Automation.TreeWalker]::ControlViewWalker.GetParent($Element)
|
|
965
|
+
} catch { $Element = $null }
|
|
966
|
+
}
|
|
967
|
+
return $null
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
# Electron/Chromium apps (VS Code, TRAE) put the TextPattern on the document
|
|
971
|
+
# node, which is often a *descendant* of the focused element, not an ancestor.
|
|
972
|
+
# Walking up therefore misses the selection; look down as a second pass.
|
|
973
|
+
function Get-UiaSelectionTextDeep {
|
|
974
|
+
param([System.Windows.Automation.AutomationElement]$Element, [int]$Limit = 24)
|
|
975
|
+
if ($null -eq $Element) { return $null }
|
|
976
|
+
$cond = $null
|
|
977
|
+
try {
|
|
978
|
+
$cond = New-Object System.Windows.Automation.PropertyCondition([System.Windows.Automation.AutomationElement]::IsTextPatternAvailableProperty, $true)
|
|
979
|
+
} catch { return $null }
|
|
980
|
+
$found = $null
|
|
981
|
+
try { $found = $Element.FindAll([System.Windows.Automation.TreeScope]::Descendants, $cond) } catch { return $null }
|
|
982
|
+
if ($null -eq $found) { return $null }
|
|
983
|
+
$n = [Math]::Min($found.Count, $Limit)
|
|
984
|
+
for ($i = 0; $i -lt $n; $i++) {
|
|
985
|
+
try {
|
|
986
|
+
$tp = [System.Windows.Automation.TextPattern]$found[$i].GetCurrentPattern([System.Windows.Automation.TextPattern]::Pattern)
|
|
987
|
+
$ranges = $tp.GetSelection()
|
|
988
|
+
if ($null -ne $ranges -and $ranges.Count -gt 0) {
|
|
989
|
+
$text = $ranges[0].GetText(-1)
|
|
990
|
+
if (-not [string]::IsNullOrWhiteSpace($text)) { return $text }
|
|
991
|
+
}
|
|
992
|
+
} catch { }
|
|
993
|
+
}
|
|
994
|
+
return $null
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
# ---------------------------------------------------------------- clipboard path
|
|
998
|
+
|
|
999
|
+
function Get-ClipboardSelectionText {
|
|
1000
|
+
param([string]$Keys = "^c")
|
|
1001
|
+
$previous = $null
|
|
1002
|
+
$hadText = $false
|
|
1003
|
+
try { $previous = Get-Clipboard -Raw -ErrorAction SilentlyContinue; $hadText = $true } catch { $previous = $null }
|
|
1004
|
+
|
|
1005
|
+
# Clear first: a second selection of the same text must still look like a copy.
|
|
1006
|
+
if (-not $NoRestoreClipboard) {
|
|
1007
|
+
try { Set-Clipboard -Value "" } catch { }
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
# A single Ctrl+C is often swallowed (focus still moving, app busy), so try a
|
|
1011
|
+
# few times before giving up; the clipboard stays cleared between attempts.
|
|
1012
|
+
$text = $null
|
|
1013
|
+
for ($attempt = 0; $attempt -lt 3 -and [string]::IsNullOrEmpty($text); $attempt++) {
|
|
1014
|
+
if ($attempt -gt 0) { Start-Sleep -Milliseconds 120 }
|
|
1015
|
+
[System.Windows.Forms.SendKeys]::SendWait($Keys)
|
|
1016
|
+
for ($i = 0; $i -lt 10; $i++) {
|
|
1017
|
+
Start-Sleep -Milliseconds 50
|
|
1018
|
+
try {
|
|
1019
|
+
$candidate = Get-Clipboard -Raw -ErrorAction SilentlyContinue
|
|
1020
|
+
if (-not [string]::IsNullOrEmpty($candidate)) { $text = $candidate; break }
|
|
1021
|
+
} catch { }
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
if (-not $NoRestoreClipboard -and $hadText) {
|
|
1026
|
+
try {
|
|
1027
|
+
if ($null -ne $previous) { Set-Clipboard -Value $previous } else { Set-Clipboard -Value "" }
|
|
1028
|
+
} catch { }
|
|
1029
|
+
}
|
|
1030
|
+
return $text
|
|
1031
|
+
}
|
|
1032
|
+
|
|
1033
|
+
# ---------------------------------------------------------------- capture
|
|
1034
|
+
|
|
1035
|
+
function Invoke-Capture {
|
|
1036
|
+
$text = $null
|
|
1037
|
+
$via = $null
|
|
1038
|
+
$uiaNote = ""
|
|
1039
|
+
$clipNote = ""
|
|
1040
|
+
|
|
1041
|
+
try {
|
|
1042
|
+
$focused = [System.Windows.Automation.AutomationElement]::FocusedElement
|
|
1043
|
+
$uiaNote = "el=" + $focused.Current.Name + "|" + $focused.Current.ClassName + "|" + $focused.Current.ControlType.ProgrammaticName
|
|
1044
|
+
$text = Get-UiaSelectionText -Element $focused
|
|
1045
|
+
if (-not [string]::IsNullOrWhiteSpace($text)) { $via = "uia" }
|
|
1046
|
+
} catch {
|
|
1047
|
+
$uiaNote = "error=" + $_.Exception.GetType().Name + ":" + $_.Exception.Message
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
if ([string]::IsNullOrWhiteSpace($text)) {
|
|
1051
|
+
try {
|
|
1052
|
+
$text = Get-ClipboardSelectionText
|
|
1053
|
+
if (-not [string]::IsNullOrWhiteSpace($text)) { $via = "clipboard" }
|
|
1054
|
+
else { $clipNote = "clip=empty" }
|
|
1055
|
+
} catch {
|
|
1056
|
+
$clipNote = "clip-error=" + $_.Exception.Message
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
if ($env:QUICKASK_DEBUG) {
|
|
1061
|
+
Write-Json @{ type = "dbg"; uia = $uiaNote; clip = $clipNote; got = [int]($text -ne $null -and $text -ne "") }
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
if ([string]::IsNullOrWhiteSpace($text)) { return $null }
|
|
1065
|
+
|
|
1066
|
+
$text = $text -replace "`r`n", "`n"
|
|
1067
|
+
return @{ type = "selection"; id = [guid]::NewGuid().ToString("N"); text = $text; via = $via; chars = $text.Length }
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1070
|
+
# ------------------------------------------------------------ dpi scaling
|
|
1071
|
+
# The card is laid out in 96 dpi design pixels; Sz()/Fs() turn those into
|
|
1072
|
+
# physical pixels for the current monitor. Without the awareness call Windows
|
|
1073
|
+
# bitmap-stretches this process's windows on high-dpi screens, which is both
|
|
1074
|
+
# blurry and makes GetWindowRect report virtualized coordinates.
|
|
1075
|
+
$script:dpi = 96
|
|
1076
|
+
$script:scale = 1.0
|
|
1077
|
+
try {
|
|
1078
|
+
[void][QuickAsk.Native]::SetProcessDpiAwarenessContext([IntPtr](-4))
|
|
1079
|
+
} catch {
|
|
1080
|
+
try { [void][QuickAsk.Native]::SetProcessDPIAware() } catch { }
|
|
1081
|
+
}
|
|
1082
|
+
try {
|
|
1083
|
+
# The card is laid out once, so key the scale off the primary display:
|
|
1084
|
+
# following the cursor would rebuild the whole card when it crosses screens.
|
|
1085
|
+
$cur = New-Object QuickAsk.POINT
|
|
1086
|
+
$cur.X = 0
|
|
1087
|
+
$cur.Y = 0
|
|
1088
|
+
$mon = [QuickAsk.Native]::MonitorFromPoint($cur, 2)
|
|
1089
|
+
$dx = [uint32]0
|
|
1090
|
+
$dy = [uint32]0
|
|
1091
|
+
if ($mon -ne [IntPtr]::Zero -and [QuickAsk.Native]::GetDpiForMonitor($mon, 0, [ref]$dx, [ref]$dy) -eq 0 -and $dx -gt 0) {
|
|
1092
|
+
$script:dpi = [int]$dx
|
|
1093
|
+
}
|
|
1094
|
+
} catch { }
|
|
1095
|
+
if ($script:dpi -le 96) {
|
|
1096
|
+
try {
|
|
1097
|
+
$g = [System.Drawing.Graphics]::FromHwnd([IntPtr]::Zero)
|
|
1098
|
+
if ($g.DpiX -gt 96) { $script:dpi = [int]$g.DpiX }
|
|
1099
|
+
$g.Dispose()
|
|
1100
|
+
} catch { }
|
|
1101
|
+
}
|
|
1102
|
+
$script:scale = $script:dpi / 96.0
|
|
1103
|
+
# Never let the card outgrow the screen in the smallest dimension available.
|
|
1104
|
+
try {
|
|
1105
|
+
$wa = [System.Windows.Forms.Screen]::PrimaryScreen.WorkingArea
|
|
1106
|
+
$capW = ($wa.Width * 0.86) / 620.0
|
|
1107
|
+
$capH = ($wa.Height * 0.86) / 420.0
|
|
1108
|
+
$cap = [Math]::Min($capW, $capH)
|
|
1109
|
+
if ($cap -gt 0.5 -and $script:scale -gt $cap) { $script:scale = $cap }
|
|
1110
|
+
} catch { }
|
|
1111
|
+
Write-Trace ("dpi=" + $script:dpi + " scale=" + [Math]::Round($script:scale, 3))
|
|
1112
|
+
|
|
1113
|
+
function Sz([double]$v) { return [int][Math]::Round($v * $script:scale) }
|
|
1114
|
+
# Font sizes below are design pixels at 96 dpi, the same unit as Sz(), so text and
|
|
1115
|
+
# layout stay in step. Points are 0.75 px at 96 dpi, and the control converts
|
|
1116
|
+
# points with the monitor dpi on its own, so multiply by scale exactly once.
|
|
1117
|
+
function Fs([double]$px) { return (New-Object System.Drawing.Font("Microsoft YaHei UI", [float]($px * 0.75))) }
|
|
1118
|
+
function FsB([double]$px) { return (New-Object System.Drawing.Font("Microsoft YaHei UI", [float]($px * 0.75), [System.Drawing.FontStyle]::Bold)) }
|
|
1119
|
+
|
|
1120
|
+
# ---------------------------------------------------------------- card styles
|
|
1121
|
+
|
|
1122
|
+
$CARD_BG = [System.Drawing.Color]::FromArgb(27, 28, 31)
|
|
1123
|
+
$BAR_BG = [System.Drawing.Color]::FromArgb(36, 37, 41)
|
|
1124
|
+
$INK = [System.Drawing.Color]::FromArgb(232, 233, 235)
|
|
1125
|
+
$INK_DIM = [System.Drawing.Color]::FromArgb(154, 160, 166)
|
|
1126
|
+
$ACCENT = [System.Drawing.Color]::FromArgb(138, 180, 248)
|
|
1127
|
+
$OK_INK = [System.Drawing.Color]::FromArgb(163, 216, 165)
|
|
1128
|
+
$ERR_INK = [System.Drawing.Color]::FromArgb(240, 160, 160)
|
|
1129
|
+
$BTN_BG = [System.Drawing.Color]::FromArgb(48, 50, 56)
|
|
1130
|
+
$BTN_HOVER = [System.Drawing.Color]::FromArgb(62, 65, 72)
|
|
1131
|
+
$LINE = [System.Drawing.Color]::FromArgb(78, 82, 92)
|
|
1132
|
+
$DROPDOWN_BG = [System.Drawing.Color]::FromArgb(44, 46, 52)
|
|
1133
|
+
$THUMB = [System.Drawing.Color]::FromArgb(96, 101, 112)
|
|
1134
|
+
$ACCENT_BG = [System.Drawing.Color]::FromArgb(52, 88, 150)
|
|
1135
|
+
|
|
1136
|
+
function New-CardButton {
|
|
1137
|
+
param([string]$Text, [int]$Width = 76)
|
|
1138
|
+
$b = New-Object System.Windows.Forms.Button
|
|
1139
|
+
$b.Text = $Text
|
|
1140
|
+
$b.AutoSize = $true
|
|
1141
|
+
$b.AutoSizeMode = [System.Windows.Forms.AutoSizeMode]::GrowAndShrink
|
|
1142
|
+
$b.MinimumSize = New-Object System.Drawing.Size((Sz $Width), (Sz 22))
|
|
1143
|
+
$b.Padding = New-Object System.Windows.Forms.Padding((Sz 9), 0, (Sz 9), 0)
|
|
1144
|
+
$b.FlatStyle = [System.Windows.Forms.FlatStyle]::Flat
|
|
1145
|
+
$b.BackColor = $BTN_BG
|
|
1146
|
+
$b.ForeColor = $INK
|
|
1147
|
+
$b.FlatAppearance.BorderColor = [System.Drawing.Color]::FromArgb(64, 67, 74)
|
|
1148
|
+
$b.FlatAppearance.MouseOverBackColor = $BTN_HOVER
|
|
1149
|
+
$b.Margin = New-Object System.Windows.Forms.Padding((Sz 5), 0, 0, 0)
|
|
1150
|
+
$b.TabStop = $false
|
|
1151
|
+
return $b
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
function Set-CardRegion {
|
|
1155
|
+
param([System.Windows.Forms.Form]$Form)
|
|
1156
|
+
$w = $Form.Width
|
|
1157
|
+
$h = $Form.Height
|
|
1158
|
+
$r = (Sz 13)
|
|
1159
|
+
$path = New-Object System.Drawing.Drawing2D.GraphicsPath
|
|
1160
|
+
$path.AddArc(0, 0, $r, $r, 180, 90)
|
|
1161
|
+
$path.AddArc($w - $r, 0, $r, $r, 270, 90)
|
|
1162
|
+
$path.AddArc($w - $r, $h - $r, $r, $r, 0, 90)
|
|
1163
|
+
$path.AddArc(0, $h - $r, $r, $r, 90, 90)
|
|
1164
|
+
$path.CloseFigure()
|
|
1165
|
+
$Form.Region = New-Object System.Drawing.Region($path)
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
|
|
1169
|
+
# ---------------------------------------------------------------- card UI
|
|
1170
|
+
|
|
1171
|
+
$script:card = $null
|
|
1172
|
+
$script:srcText = ""
|
|
1173
|
+
$script:dstText = ""
|
|
1174
|
+
$script:lastId = ""
|
|
1175
|
+
$script:busy = $false
|
|
1176
|
+
$script:activeTask = "translate"
|
|
1177
|
+
$script:activeBtn = $null
|
|
1178
|
+
$script:activeLabel = ""
|
|
1179
|
+
$script:autoCandidate = ""
|
|
1180
|
+
$script:autoCount = 0
|
|
1181
|
+
$script:autoShown = ""
|
|
1182
|
+
$script:autoShownAt = [DateTime]::MinValue
|
|
1183
|
+
$script:pollN = 0
|
|
1184
|
+
$script:dismissed = ""
|
|
1185
|
+
$script:ownGestureUntil = [DateTime]::MinValue
|
|
1186
|
+
$script:clipBlockedUntil = [DateTime]::MinValue
|
|
1187
|
+
$script:poll = $null
|
|
1188
|
+
$script:runner = $null
|
|
1189
|
+
$script:async = $null
|
|
1190
|
+
$script:statusTimer = $null
|
|
1191
|
+
$script:langMenu = $null
|
|
1192
|
+
|
|
1193
|
+
# ---------------------------------------------------------------- language menu
|
|
1194
|
+
|
|
1195
|
+
function Hide-LangMenu {
|
|
1196
|
+
if ($null -ne $script:langMenu -and $script:langMenu.Visible) { $script:langMenu.Hide() }
|
|
1197
|
+
}
|
|
1198
|
+
|
|
1199
|
+
function Set-Lang([string]$Code) {
|
|
1200
|
+
if ($script:LANG_CODES -notcontains $Code) { return }
|
|
1201
|
+
$script:lang = $Code
|
|
1202
|
+
if ($null -ne $script:btnLang) { $script:btnLang.Text = ($script:LANG_LABELS[$Code] + " " + (U 0x25BE)) }
|
|
1203
|
+
Hide-LangMenu
|
|
1204
|
+
Set-CardStatus ("-> " + $Code) $INK_DIM
|
|
1205
|
+
# A visible translation follows the new choice instead of going stale.
|
|
1206
|
+
if (-not $script:busy -and $script:lastId -ne "" -and $script:dstText -ne "") { Start-Task $script:activeTask }
|
|
1207
|
+
}
|
|
1208
|
+
|
|
1209
|
+
function New-LangMenu {
|
|
1210
|
+
$pad = (Sz 5)
|
|
1211
|
+
$rowH = (Sz 21)
|
|
1212
|
+
$w = (Sz 150)
|
|
1213
|
+
$f = New-Object QuickAsk.CardForm
|
|
1214
|
+
$f.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::None
|
|
1215
|
+
$f.ShowInTaskbar = $false
|
|
1216
|
+
$f.TopMost = $true
|
|
1217
|
+
$f.StartPosition = [System.Windows.Forms.FormStartPosition]::Manual
|
|
1218
|
+
$f.BackColor = $DROPDOWN_BG
|
|
1219
|
+
$f.ClientSize = New-Object System.Drawing.Size($w, ($pad * 2 + $rowH * $script:LANG_CODES.Count))
|
|
1220
|
+
$i = 0
|
|
1221
|
+
foreach ($code in $script:LANG_CODES) {
|
|
1222
|
+
$b = New-CardButton ($script:LANG_LABELS[$code] + " " + $script:LANG_NAMES[$code]) 60
|
|
1223
|
+
$b.AutoSize = $false
|
|
1224
|
+
$b.MinimumSize = New-Object System.Drawing.Size(0, 0)
|
|
1225
|
+
$b.Size = New-Object System.Drawing.Size(($w - $pad * 2), $rowH)
|
|
1226
|
+
$b.Location = New-Object System.Drawing.Point($pad, ($pad + $rowH * $i))
|
|
1227
|
+
$b.FlatAppearance.BorderSize = 0
|
|
1228
|
+
$b.BackColor = $DROPDOWN_BG
|
|
1229
|
+
$b.ForeColor = $(if ($code -eq $script:lang) { $ACCENT } else { $INK })
|
|
1230
|
+
$b.Font = Fs 12.5
|
|
1231
|
+
$b.TextAlign = [System.Drawing.ContentAlignment]::MiddleLeft
|
|
1232
|
+
$b.Padding = New-Object System.Windows.Forms.Padding((Sz 6), 0, 0, 0)
|
|
1233
|
+
$b.Tag = $code
|
|
1234
|
+
$b.Add_Click({ param($sender, $e) Set-Lang ([string]$sender.Tag) })
|
|
1235
|
+
$f.Controls.Add($b)
|
|
1236
|
+
$i++
|
|
1237
|
+
}
|
|
1238
|
+
Set-CardRegion $f
|
|
1239
|
+
return $f
|
|
1240
|
+
}
|
|
1241
|
+
|
|
1242
|
+
function Show-LangMenu {
|
|
1243
|
+
if ($null -eq $script:btnLang) { return }
|
|
1244
|
+
if ($null -eq $script:langMenu) { $script:langMenu = New-LangMenu }
|
|
1245
|
+
$origin = $script:btnLang.PointToScreen((New-Object System.Drawing.Point(0, ($script:btnLang.Height + (Sz 2)))))
|
|
1246
|
+
$scr = [System.Windows.Forms.Screen]::FromPoint($origin).WorkingArea
|
|
1247
|
+
$x = [Math]::Min([Math]::Max($origin.X, $scr.Left), ($scr.Right - $script:langMenu.Width))
|
|
1248
|
+
$y = [Math]::Min($origin.Y, ($scr.Bottom - $script:langMenu.Height))
|
|
1249
|
+
$script:langMenu.Location = New-Object System.Drawing.Point($x, $y)
|
|
1250
|
+
$script:langMenu.Show()
|
|
1251
|
+
$script:langMenu.BringToFront()
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
function Toggle-LangMenu {
|
|
1255
|
+
if ($null -ne $script:langMenu -and $script:langMenu.Visible) { Hide-LangMenu; return }
|
|
1256
|
+
Show-LangMenu
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
|
|
1260
|
+
function New-Card {
|
|
1261
|
+
$form = New-Object QuickAsk.CardForm
|
|
1262
|
+
$form.Text = "dsh-external-toolbox"
|
|
1263
|
+
$form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::None
|
|
1264
|
+
$form.ShowInTaskbar = $false
|
|
1265
|
+
$form.TopMost = $true
|
|
1266
|
+
$form.StartPosition = [System.Windows.Forms.FormStartPosition]::Manual
|
|
1267
|
+
$form.ClientSize = New-Object System.Drawing.Size((Sz 400), (Sz 214))
|
|
1268
|
+
$form.BackColor = $CARD_BG
|
|
1269
|
+
$form.ForeColor = $INK
|
|
1270
|
+
$form.Font = Fs 12
|
|
1271
|
+
$form.KeyPreview = $true
|
|
1272
|
+
$form.Padding = New-Object System.Windows.Forms.Padding(1)
|
|
1273
|
+
|
|
1274
|
+
$head = New-Object System.Windows.Forms.Panel
|
|
1275
|
+
$head.Dock = [System.Windows.Forms.DockStyle]::Top
|
|
1276
|
+
$head.Height = (Sz 34)
|
|
1277
|
+
$head.BackColor = $BAR_BG
|
|
1278
|
+
|
|
1279
|
+
$title = New-Object System.Windows.Forms.Label
|
|
1280
|
+
$title.Text = $T_SCRAPE + (U 0x00B7) + (U 0x5916, 0x90E8, 0x5DE5, 0x5177, 0x7BB1)
|
|
1281
|
+
$title.ForeColor = $ACCENT
|
|
1282
|
+
$title.Font = FsB 15
|
|
1283
|
+
$title.AutoSize = $true
|
|
1284
|
+
$title.Location = New-Object System.Drawing.Point((Sz 14), (Sz 9))
|
|
1285
|
+
|
|
1286
|
+
# Explicit placement beats docking here: the header must read
|
|
1287
|
+
# [title ............ language picker] [x]
|
|
1288
|
+
$btnX = New-CardButton (U 0x2715) 22
|
|
1289
|
+
$btnX.AutoSize = $false
|
|
1290
|
+
$btnX.MinimumSize = New-Object System.Drawing.Size((Sz 22), (Sz 16))
|
|
1291
|
+
$btnX.Size = New-Object System.Drawing.Size((Sz 22), (Sz 18))
|
|
1292
|
+
$btnX.Location = New-Object System.Drawing.Point((Sz 372), (Sz 8))
|
|
1293
|
+
$btnX.FlatAppearance.BorderSize = 1
|
|
1294
|
+
$btnX.FlatAppearance.BorderColor = $LINE
|
|
1295
|
+
$btnX.BackColor = $BTN_BG
|
|
1296
|
+
$btnX.ForeColor = $INK
|
|
1297
|
+
$btnX.Font = Fs 12
|
|
1298
|
+
$btnX.FlatAppearance.MouseOverBackColor = $BTN_HOVER
|
|
1299
|
+
|
|
1300
|
+
# Language picker: a styled button plus our own drop-down panel, because the
|
|
1301
|
+
# native ComboBox can only be half-themed (white arrow strip, clipped text).
|
|
1302
|
+
$btnLang = New-CardButton ($script:LANG_LABELS[$script:lang] + " " + (U 0x25BE)) 60
|
|
1303
|
+
$btnLang.AutoSize = $false
|
|
1304
|
+
$btnLang.MinimumSize = New-Object System.Drawing.Size((Sz 78), (Sz 16))
|
|
1305
|
+
$btnLang.Size = New-Object System.Drawing.Size((Sz 78), (Sz 18))
|
|
1306
|
+
$btnLang.Location = New-Object System.Drawing.Point((Sz 286), (Sz 8))
|
|
1307
|
+
$btnLang.FlatAppearance.BorderSize = 1
|
|
1308
|
+
$btnLang.FlatAppearance.BorderColor = $LINE
|
|
1309
|
+
$btnLang.BackColor = $BTN_BG
|
|
1310
|
+
$btnLang.ForeColor = $INK
|
|
1311
|
+
$btnLang.Font = Fs 12
|
|
1312
|
+
$btnLang.TextAlign = [System.Drawing.ContentAlignment]::MiddleCenter
|
|
1313
|
+
$btnLang.Add_Click({ Toggle-LangMenu })
|
|
1314
|
+
|
|
1315
|
+
$btnVocab = New-CardButton (U 0x751F, 0x8BCD) 56
|
|
1316
|
+
$btnVocab.AutoSize = $false
|
|
1317
|
+
$btnVocab.MinimumSize = New-Object System.Drawing.Size((Sz 56), (Sz 16))
|
|
1318
|
+
$btnVocab.Size = New-Object System.Drawing.Size((Sz 56), (Sz 18))
|
|
1319
|
+
$btnVocab.Location = New-Object System.Drawing.Point((Sz 222), (Sz 8))
|
|
1320
|
+
$btnVocab.FlatAppearance.BorderSize = 1
|
|
1321
|
+
$btnVocab.FlatAppearance.BorderColor = $LINE
|
|
1322
|
+
$btnVocab.BackColor = $BTN_BG
|
|
1323
|
+
$btnVocab.ForeColor = $INK_DIM
|
|
1324
|
+
$btnVocab.Font = Fs 12
|
|
1325
|
+
$btnVocab.TextAlign = [System.Drawing.ContentAlignment]::MiddleCenter
|
|
1326
|
+
$btnVocab.Add_Click({ Show-Review })
|
|
1327
|
+
|
|
1328
|
+
$head.Controls.Add($btnX)
|
|
1329
|
+
$head.Controls.Add($btnLang)
|
|
1330
|
+
$head.Controls.Add($btnVocab)
|
|
1331
|
+
$head.Controls.Add($title)
|
|
1332
|
+
$tip = New-Object System.Windows.Forms.ToolTip
|
|
1333
|
+
$tip.SetToolTip($btnLang, "Translate into")
|
|
1334
|
+
$tip.SetToolTip($btnX, "Close")
|
|
1335
|
+
|
|
1336
|
+
$grid = New-Object System.Windows.Forms.TableLayoutPanel
|
|
1337
|
+
$grid.Dock = [System.Windows.Forms.DockStyle]::Fill
|
|
1338
|
+
$grid.ColumnCount = 1
|
|
1339
|
+
$grid.RowCount = 3
|
|
1340
|
+
$grid.Padding = New-Object System.Windows.Forms.Padding((Sz 14), (Sz 12), (Sz 14), (Sz 5))
|
|
1341
|
+
$grid.ColumnStyles.Add((New-Object System.Windows.Forms.ColumnStyle([System.Windows.Forms.SizeType]::Percent, 100))) | Out-Null
|
|
1342
|
+
# Row 1 is the divider: one hair line with a little air above and below.
|
|
1343
|
+
$grid.RowStyles.Add((New-Object System.Windows.Forms.RowStyle([System.Windows.Forms.SizeType]::Percent, 100))) | Out-Null
|
|
1344
|
+
$grid.RowStyles.Add((New-Object System.Windows.Forms.RowStyle([System.Windows.Forms.SizeType]::Absolute, (Sz 10)))) | Out-Null
|
|
1345
|
+
$grid.RowStyles.Add((New-Object System.Windows.Forms.RowStyle([System.Windows.Forms.SizeType]::Percent, 0))) | Out-Null
|
|
1346
|
+
|
|
1347
|
+
$divider = New-Object System.Windows.Forms.Panel
|
|
1348
|
+
$divider.Dock = [System.Windows.Forms.DockStyle]::Fill
|
|
1349
|
+
$divider.BackColor = $LINE
|
|
1350
|
+
$divider.Margin = New-Object System.Windows.Forms.Padding(0, (Sz 4), 0, (Sz 5))
|
|
1351
|
+
$divider.Visible = $false
|
|
1352
|
+
|
|
1353
|
+
$txtSrc = New-Object System.Windows.Forms.TextBox
|
|
1354
|
+
$txtSrc.Multiline = $true
|
|
1355
|
+
$txtSrc.ReadOnly = $true
|
|
1356
|
+
$txtSrc.BorderStyle = [System.Windows.Forms.BorderStyle]::None
|
|
1357
|
+
$txtSrc.BackColor = $CARD_BG
|
|
1358
|
+
$txtSrc.ForeColor = $INK
|
|
1359
|
+
$txtSrc.Dock = [System.Windows.Forms.DockStyle]::Fill
|
|
1360
|
+
$txtSrc.ScrollBars = [System.Windows.Forms.ScrollBars]::None
|
|
1361
|
+
$txtSrc.Font = Fs 13.5
|
|
1362
|
+
$txtSrc.TabStop = $false
|
|
1363
|
+
|
|
1364
|
+
$txtDst = New-Object System.Windows.Forms.TextBox
|
|
1365
|
+
$txtDst.Multiline = $true
|
|
1366
|
+
$txtDst.ReadOnly = $true
|
|
1367
|
+
$txtDst.BorderStyle = [System.Windows.Forms.BorderStyle]::None
|
|
1368
|
+
$txtDst.BackColor = $CARD_BG
|
|
1369
|
+
$txtDst.ForeColor = $OK_INK
|
|
1370
|
+
$txtDst.Dock = [System.Windows.Forms.DockStyle]::Fill
|
|
1371
|
+
$txtDst.ScrollBars = [System.Windows.Forms.ScrollBars]::None
|
|
1372
|
+
$txtDst.Font = Fs 13.5
|
|
1373
|
+
$txtDst.Visible = $false
|
|
1374
|
+
$txtDst.TabStop = $false
|
|
1375
|
+
|
|
1376
|
+
# Each pane gets its own speaker button: reading is opt-in per side, so the
|
|
1377
|
+
# card never starts talking on its own.
|
|
1378
|
+
$btnSaySrc = New-CardButton (U 0x25B6) 30
|
|
1379
|
+
$btnSaySrc.MinimumSize = New-Object System.Drawing.Size((Sz 30), (Sz 26))
|
|
1380
|
+
$btnSaySrc.Margin = New-Object System.Windows.Forms.Padding((Sz 6), 0, 0, 0)
|
|
1381
|
+
$btnSaySrc.Visible = $true
|
|
1382
|
+
|
|
1383
|
+
$btnSayDst = New-CardButton (U 0x25B6) 30
|
|
1384
|
+
$btnSayDst.MinimumSize = New-Object System.Drawing.Size((Sz 30), (Sz 26))
|
|
1385
|
+
$btnSayDst.Margin = New-Object System.Windows.Forms.Padding((Sz 6), 0, 0, 0)
|
|
1386
|
+
|
|
1387
|
+
$srcRow = New-Object System.Windows.Forms.TableLayoutPanel
|
|
1388
|
+
$srcRow.Dock = [System.Windows.Forms.DockStyle]::Fill
|
|
1389
|
+
$srcRow.ColumnCount = 3
|
|
1390
|
+
$srcRow.RowCount = 1
|
|
1391
|
+
$srcRow.Margin = New-Object System.Windows.Forms.Padding(0)
|
|
1392
|
+
$srcRow.BackColor = $CARD_BG
|
|
1393
|
+
$srcRow.ColumnStyles.Add((New-Object System.Windows.Forms.ColumnStyle([System.Windows.Forms.SizeType]::Percent, 100))) | Out-Null
|
|
1394
|
+
$srcRow.ColumnStyles.Add((New-Object System.Windows.Forms.ColumnStyle([System.Windows.Forms.SizeType]::Absolute, (Sz 10)))) | Out-Null
|
|
1395
|
+
$srcRow.ColumnStyles.Add((New-Object System.Windows.Forms.ColumnStyle([System.Windows.Forms.SizeType]::Absolute, (Sz 40)))) | Out-Null
|
|
1396
|
+
$srcRow.RowStyles.Add((New-Object System.Windows.Forms.RowStyle([System.Windows.Forms.SizeType]::Percent, 100))) | Out-Null
|
|
1397
|
+
$script:sbSrc = New-Scrollbar $txtSrc
|
|
1398
|
+
$script:sbDst = New-Scrollbar $txtDst
|
|
1399
|
+
$srcRow.Controls.Add($txtSrc, 0, 0)
|
|
1400
|
+
$srcRow.Controls.Add($script:sbSrc, 1, 0)
|
|
1401
|
+
$srcRow.Controls.Add($btnSaySrc, 2, 0)
|
|
1402
|
+
|
|
1403
|
+
$dstRow = New-Object System.Windows.Forms.TableLayoutPanel
|
|
1404
|
+
$dstRow.Dock = [System.Windows.Forms.DockStyle]::Fill
|
|
1405
|
+
$dstRow.ColumnCount = 3
|
|
1406
|
+
$dstRow.RowCount = 1
|
|
1407
|
+
$dstRow.Margin = New-Object System.Windows.Forms.Padding(0)
|
|
1408
|
+
$dstRow.BackColor = $CARD_BG
|
|
1409
|
+
$dstRow.ColumnStyles.Add((New-Object System.Windows.Forms.ColumnStyle([System.Windows.Forms.SizeType]::Percent, 100))) | Out-Null
|
|
1410
|
+
$dstRow.ColumnStyles.Add((New-Object System.Windows.Forms.ColumnStyle([System.Windows.Forms.SizeType]::Absolute, (Sz 10)))) | Out-Null
|
|
1411
|
+
$dstRow.ColumnStyles.Add((New-Object System.Windows.Forms.ColumnStyle([System.Windows.Forms.SizeType]::Absolute, (Sz 40)))) | Out-Null
|
|
1412
|
+
$dstRow.RowStyles.Add((New-Object System.Windows.Forms.RowStyle([System.Windows.Forms.SizeType]::Percent, 100))) | Out-Null
|
|
1413
|
+
$dstRow.Controls.Add($txtDst, 0, 0)
|
|
1414
|
+
$dstRow.Controls.Add($script:sbDst, 1, 0)
|
|
1415
|
+
$dstRow.Controls.Add($btnSayDst, 2, 0)
|
|
1416
|
+
|
|
1417
|
+
$grid.Controls.Add($srcRow, 0, 0)
|
|
1418
|
+
$grid.Controls.Add($divider, 0, 1)
|
|
1419
|
+
$grid.Controls.Add($dstRow, 0, 2)
|
|
1420
|
+
|
|
1421
|
+
$foot = New-Object System.Windows.Forms.Panel
|
|
1422
|
+
$foot.Dock = [System.Windows.Forms.DockStyle]::Bottom
|
|
1423
|
+
$foot.Height = (Sz 46)
|
|
1424
|
+
$foot.BackColor = $BAR_BG
|
|
1425
|
+
|
|
1426
|
+
$status = New-Object System.Windows.Forms.Label
|
|
1427
|
+
$status.Text = ""
|
|
1428
|
+
$status.ForeColor = $INK_DIM
|
|
1429
|
+
$status.AutoSize = $false
|
|
1430
|
+
$status.Dock = [System.Windows.Forms.DockStyle]::Left
|
|
1431
|
+
$status.Width = (Sz 200)
|
|
1432
|
+
$status.TextAlign = [System.Drawing.ContentAlignment]::MiddleLeft
|
|
1433
|
+
$status.Padding = New-Object System.Windows.Forms.Padding((Sz 11), 0, 0, 0)
|
|
1434
|
+
|
|
1435
|
+
$buttons = New-Object System.Windows.Forms.FlowLayoutPanel
|
|
1436
|
+
$buttons.Dock = [System.Windows.Forms.DockStyle]::Right
|
|
1437
|
+
$buttons.FlowDirection = [System.Windows.Forms.FlowDirection]::LeftToRight
|
|
1438
|
+
$buttons.WrapContents = $false
|
|
1439
|
+
$buttons.AutoSize = $true
|
|
1440
|
+
$buttons.Padding = New-Object System.Windows.Forms.Padding(0, (Sz 10), (Sz 12), (Sz 10))
|
|
1441
|
+
$buttons.BackColor = $BAR_BG
|
|
1442
|
+
|
|
1443
|
+
$btnTranslate = New-CardButton $T_TRANSLATE 64
|
|
1444
|
+
$btnExplain = New-CardButton $T_EXPLAIN 64
|
|
1445
|
+
$btnAsk = New-CardButton $T_ASK 56
|
|
1446
|
+
$btnSave = New-CardButton $T_SAVE 56
|
|
1447
|
+
$btnCopy = New-CardButton $T_COPY 56
|
|
1448
|
+
$buttons.Controls.Add($btnTranslate)
|
|
1449
|
+
$buttons.Controls.Add($btnExplain)
|
|
1450
|
+
$buttons.Controls.Add($btnAsk)
|
|
1451
|
+
$buttons.Controls.Add($btnSave)
|
|
1452
|
+
$buttons.Controls.Add($btnCopy)
|
|
1453
|
+
|
|
1454
|
+
$foot.Controls.Add($buttons)
|
|
1455
|
+
$foot.Controls.Add($status)
|
|
1456
|
+
|
|
1457
|
+
$form.Controls.Add($grid)
|
|
1458
|
+
$form.Controls.Add($foot)
|
|
1459
|
+
$form.Controls.Add($head)
|
|
1460
|
+
|
|
1461
|
+
$script:head = $head
|
|
1462
|
+
Set-CardRegion $form
|
|
1463
|
+
$form.MakeDraggable($head)
|
|
1464
|
+
$form.MakeDraggable($title)
|
|
1465
|
+
|
|
1466
|
+
$btnX.Add_Click({ Hide-Card })
|
|
1467
|
+
$form.Add_KeyDown({
|
|
1468
|
+
param($sender, $e)
|
|
1469
|
+
if ($e.KeyCode -eq [System.Windows.Forms.Keys]::Escape) { Hide-Card }
|
|
1470
|
+
})
|
|
1471
|
+
|
|
1472
|
+
$btnCopy.Add_Click({
|
|
1473
|
+
# What the user highlighted inside the card wins over the whole pane.
|
|
1474
|
+
$text = ""
|
|
1475
|
+
if ($null -ne $script:txtDst -and $script:txtDst.SelectionLength -gt 0) { $text = $script:txtDst.SelectedText }
|
|
1476
|
+
elseif ($null -ne $script:txtSrc -and $script:txtSrc.SelectionLength -gt 0) { $text = $script:txtSrc.SelectedText }
|
|
1477
|
+
elseif (-not [string]::IsNullOrEmpty($script:dstText)) { $text = $script:dstText }
|
|
1478
|
+
else { $text = $script:srcText }
|
|
1479
|
+
try { Set-Clipboard -Value $text } catch { }
|
|
1480
|
+
Set-CardStatus $T_COPIED $INK_DIM
|
|
1481
|
+
$script:btnCopy.Text = $T_COPIED
|
|
1482
|
+
if ($null -ne $script:statusTimer) { $script:statusTimer.Stop() }
|
|
1483
|
+
$script:statusTimer = New-Object System.Windows.Forms.Timer
|
|
1484
|
+
$script:statusTimer.Interval = 1400
|
|
1485
|
+
$script:statusTimer.Add_Tick({
|
|
1486
|
+
$script:statusTimer.Stop()
|
|
1487
|
+
$script:btnCopy.Text = $T_COPY
|
|
1488
|
+
Set-CardStatus "" $INK_DIM
|
|
1489
|
+
})
|
|
1490
|
+
$script:statusTimer.Start()
|
|
1491
|
+
})
|
|
1492
|
+
|
|
1493
|
+
$btnAsk.Add_Click({
|
|
1494
|
+
Write-Json @{ type = "intent"; intent = "ask"; id = $script:lastId }
|
|
1495
|
+
try { Set-Clipboard -Value $script:srcText } catch { }
|
|
1496
|
+
Show-HostWindow
|
|
1497
|
+
Hide-Card
|
|
1498
|
+
})
|
|
1499
|
+
|
|
1500
|
+
$btnTranslate.Add_Click({ Start-Task "translate" })
|
|
1501
|
+
$btnExplain.Add_Click({ Start-Task "explain" })
|
|
1502
|
+
|
|
1503
|
+
# Vocabulary: the host owns the file, the card only reports the pair.
|
|
1504
|
+
$btnSaySrc.Add_Click({
|
|
1505
|
+
$text = [string]$script:srcText
|
|
1506
|
+
if ([string]::IsNullOrWhiteSpace($text)) { return }
|
|
1507
|
+
$script:btnSaySrc.Text = U 0x25A0
|
|
1508
|
+
Speak-Text $text $script:srcLang
|
|
1509
|
+
$script:btnSaySrc.Text = U 0x25B6
|
|
1510
|
+
})
|
|
1511
|
+
|
|
1512
|
+
$btnSayDst.Add_Click({
|
|
1513
|
+
$text = [string]$script:dstText
|
|
1514
|
+
if ([string]::IsNullOrWhiteSpace($text)) { return }
|
|
1515
|
+
$script:btnSayDst.Text = U 0x25A0
|
|
1516
|
+
Speak-Text $text $script:dstLang
|
|
1517
|
+
$script:btnSayDst.Text = U 0x25B6
|
|
1518
|
+
})
|
|
1519
|
+
|
|
1520
|
+
$btnSave.Add_Click({
|
|
1521
|
+
# Select a word in the source pane and this saves that word instead of the
|
|
1522
|
+
# whole sentence - the usual case: one or two words per sentence are new.
|
|
1523
|
+
$picked = ""
|
|
1524
|
+
if ($null -ne $script:txtSrc -and $script:txtSrc.SelectionLength -gt 0) {
|
|
1525
|
+
$picked = [string]$script:txtSrc.SelectedText
|
|
1526
|
+
}
|
|
1527
|
+
$picked = $picked.Trim()
|
|
1528
|
+
if ($picked -ne "") {
|
|
1529
|
+
Write-Json @{
|
|
1530
|
+
type = "vocab"
|
|
1531
|
+
word = $picked
|
|
1532
|
+
translation = ""
|
|
1533
|
+
context = [string]$script:srcText
|
|
1534
|
+
lang = $script:srcLang
|
|
1535
|
+
task = $script:activeTask
|
|
1536
|
+
}
|
|
1537
|
+
Set-CardStatus ((U 0x5DF2, 0x6536, 0x85CF) + " " + $picked) $OK_INK
|
|
1538
|
+
return
|
|
1539
|
+
}
|
|
1540
|
+
if ([string]::IsNullOrWhiteSpace($script:srcText)) { return }
|
|
1541
|
+
Write-Json @{
|
|
1542
|
+
type = "vocab"
|
|
1543
|
+
word = $script:srcText
|
|
1544
|
+
translation = $script:dstText
|
|
1545
|
+
context = $script:srcText
|
|
1546
|
+
lang = $script:lang
|
|
1547
|
+
task = $script:activeTask
|
|
1548
|
+
}
|
|
1549
|
+
Set-CardStatus $T_SAVED $OK_INK
|
|
1550
|
+
$script:btnSave.Text = $T_SAVED
|
|
1551
|
+
})
|
|
1552
|
+
|
|
1553
|
+
$script:brushDrop = New-Object System.Drawing.SolidBrush($DROPDOWN_BG)
|
|
1554
|
+
$script:brushInk = New-Object System.Drawing.SolidBrush($INK)
|
|
1555
|
+
|
|
1556
|
+
$script:card = $form
|
|
1557
|
+
$script:head = $head
|
|
1558
|
+
$script:grid = $grid
|
|
1559
|
+
$script:txtSrc = $txtSrc
|
|
1560
|
+
$script:divider = $divider
|
|
1561
|
+
$script:txtDst = $txtDst
|
|
1562
|
+
$script:status = $status
|
|
1563
|
+
$script:btnLang = $btnLang
|
|
1564
|
+
$script:btnVocab = $btnVocab
|
|
1565
|
+
$script:btnTranslate = $btnTranslate
|
|
1566
|
+
$script:btnExplain = $btnExplain
|
|
1567
|
+
$script:btnAsk = $btnAsk
|
|
1568
|
+
$script:btnCopy = $btnCopy
|
|
1569
|
+
$script:btnSave = $btnSave
|
|
1570
|
+
$script:btnSaySrc = $btnSaySrc
|
|
1571
|
+
$script:btnSayDst = $btnSayDst
|
|
1572
|
+
$btnCopy.Visible = $false
|
|
1573
|
+
|
|
1574
|
+
$script:poll = New-Object System.Windows.Forms.Timer
|
|
1575
|
+
$script:poll.Interval = 150
|
|
1576
|
+
$script:poll.Add_Tick({ Poll-Translate })
|
|
1577
|
+
}
|
|
1578
|
+
|
|
1579
|
+
# ---------------------------------------------------------------- quick bar
|
|
1580
|
+
#
|
|
1581
|
+
# Selecting text pops a small pill instead of the full card, like the toolbar
|
|
1582
|
+
# Doubao shows: pick translate and the card opens with the translation, pick
|
|
1583
|
+
# quote and the text goes to the DSH composer, pick x and nothing else happens.
|
|
1584
|
+
$script:bar = $null
|
|
1585
|
+
$script:barCapture = $null
|
|
1586
|
+
|
|
1587
|
+
function Set-PillRegion {
|
|
1588
|
+
param([System.Windows.Forms.Form]$Form)
|
|
1589
|
+
$w = $Form.Width
|
|
1590
|
+
$h = $Form.Height
|
|
1591
|
+
$r = [int]($h / 2)
|
|
1592
|
+
$path = New-Object System.Drawing.Drawing2D.GraphicsPath
|
|
1593
|
+
$path.AddArc(0, 0, $r, $r, 180, 90)
|
|
1594
|
+
$path.AddArc($w - $r, 0, $r, $r, 270, 90)
|
|
1595
|
+
$path.AddArc($w - $r, $h - $r, $r, $r, 0, 90)
|
|
1596
|
+
$path.AddArc(0, $h - $r, $r, $r, 90, 90)
|
|
1597
|
+
$path.CloseFigure()
|
|
1598
|
+
$Form.Region = New-Object System.Drawing.Region($path)
|
|
1599
|
+
}
|
|
1600
|
+
|
|
1601
|
+
function New-Bar {
|
|
1602
|
+
$f = New-Object QuickAsk.CardForm
|
|
1603
|
+
$f.Text = "dsh-external-toolbox-bar"
|
|
1604
|
+
$f.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::None
|
|
1605
|
+
$f.ShowInTaskbar = $false
|
|
1606
|
+
$f.TopMost = $true
|
|
1607
|
+
$f.StartPosition = [System.Windows.Forms.FormStartPosition]::Manual
|
|
1608
|
+
$f.BackColor = $BAR_BG
|
|
1609
|
+
$f.ForeColor = $INK
|
|
1610
|
+
$f.Font = Fs 12
|
|
1611
|
+
$f.Padding = New-Object System.Windows.Forms.Padding(1)
|
|
1612
|
+
|
|
1613
|
+
$flow = New-Object System.Windows.Forms.FlowLayoutPanel
|
|
1614
|
+
$flow.Dock = [System.Windows.Forms.DockStyle]::Fill
|
|
1615
|
+
$flow.FlowDirection = [System.Windows.Forms.FlowDirection]::LeftToRight
|
|
1616
|
+
$flow.WrapContents = $false
|
|
1617
|
+
$flow.BackColor = $BAR_BG
|
|
1618
|
+
$flow.Padding = New-Object System.Windows.Forms.Padding((Sz 5), (Sz 4), (Sz 5), (Sz 4))
|
|
1619
|
+
|
|
1620
|
+
# No close button: clicking anywhere outside the pill, or dropping the
|
|
1621
|
+
# selection, hides it already, and the pill is meant to be two actions only.
|
|
1622
|
+
$bTranslate = New-CardButton $T_TRANSLATE 56
|
|
1623
|
+
$bExplain = New-CardButton $T_EXPLAIN 56
|
|
1624
|
+
$bAsk = New-CardButton $T_ASK 50
|
|
1625
|
+
$bVocab = New-CardButton (U 0x751F, 0x8BCD) 50
|
|
1626
|
+
$bVocab.Add_Click({ Hide-Bar; Show-Review })
|
|
1627
|
+
$bCopy = New-CardButton (U 0x590D, 0x5236) 50
|
|
1628
|
+
$bCopy.Add_Click({
|
|
1629
|
+
Write-Trace "bar copy clicked"
|
|
1630
|
+
$captured = $script:barCapture
|
|
1631
|
+
Hide-Bar
|
|
1632
|
+
if ($null -eq $captured) { return }
|
|
1633
|
+
try { Set-Clipboard -Value ([string]$captured.text) } catch { }
|
|
1634
|
+
})
|
|
1635
|
+
foreach ($b in @($bTranslate, $bExplain, $bAsk, $bVocab, $bCopy)) {
|
|
1636
|
+
$b.MinimumSize = New-Object System.Drawing.Size($b.MinimumSize.Width, (Sz 22))
|
|
1637
|
+
$b.FlatAppearance.BorderSize = 0
|
|
1638
|
+
$b.BackColor = $BAR_BG
|
|
1639
|
+
$b.Margin = New-Object System.Windows.Forms.Padding((Sz 4), 0, 0, 0)
|
|
1640
|
+
$flow.Controls.Add($b)
|
|
1641
|
+
}
|
|
1642
|
+
$bTranslate.ForeColor = $ACCENT
|
|
1643
|
+
|
|
1644
|
+
$bTranslate.Add_Click({
|
|
1645
|
+
Write-Trace "bar translate clicked"
|
|
1646
|
+
$captured = $script:barCapture
|
|
1647
|
+
Hide-Bar
|
|
1648
|
+
if ($null -eq $captured) { return }
|
|
1649
|
+
Show-Card $captured
|
|
1650
|
+
Start-Task "translate"
|
|
1651
|
+
})
|
|
1652
|
+
$bExplain.Add_Click({
|
|
1653
|
+
Write-Trace "bar explain clicked"
|
|
1654
|
+
$captured = $script:barCapture
|
|
1655
|
+
Hide-Bar
|
|
1656
|
+
if ($null -eq $captured) { return }
|
|
1657
|
+
Show-Card $captured
|
|
1658
|
+
Start-Task "explain"
|
|
1659
|
+
})
|
|
1660
|
+
$bAsk.Add_Click({
|
|
1661
|
+
Write-Trace "bar ask clicked"
|
|
1662
|
+
$captured = $script:barCapture
|
|
1663
|
+
Hide-Bar
|
|
1664
|
+
if ($null -eq $captured) { return }
|
|
1665
|
+
Write-Json @{ type = "intent"; intent = "ask"; id = [string]$captured.id }
|
|
1666
|
+
try { Set-Clipboard -Value ([string]$captured.text) } catch { }
|
|
1667
|
+
Show-HostWindow
|
|
1668
|
+
})
|
|
1669
|
+
|
|
1670
|
+
|
|
1671
|
+
$f.Controls.Add($flow)
|
|
1672
|
+
$f.AutoSize = $false
|
|
1673
|
+
$f.ClientSize = New-Object System.Drawing.Size((Sz 204), (Sz 38))
|
|
1674
|
+
# Buttons grow to fit their text at the current dpi, so let the flow panel
|
|
1675
|
+
# report the size it actually wants instead of guessing one.
|
|
1676
|
+
$flow.PerformLayout()
|
|
1677
|
+
$pref = $flow.PreferredSize
|
|
1678
|
+
$f.ClientSize = New-Object System.Drawing.Size(($pref.Width + (Sz 2)), ($pref.Height + (Sz 2)))
|
|
1679
|
+
Set-PillRegion $f
|
|
1680
|
+
$f.MakeDraggable($flow)
|
|
1681
|
+
|
|
1682
|
+
$script:barTranslate = $bTranslate
|
|
1683
|
+
$script:barExplain = $bExplain
|
|
1684
|
+
$script:barAsk = $bAsk
|
|
1685
|
+
return $f
|
|
1686
|
+
}
|
|
1687
|
+
|
|
1688
|
+
function Show-Bar {
|
|
1689
|
+
param([hashtable]$Captured)
|
|
1690
|
+
if ($null -eq $script:bar) { $script:bar = New-Bar }
|
|
1691
|
+
$script:barCapture = $Captured
|
|
1692
|
+
|
|
1693
|
+
$p = New-Object QuickAsk.POINT
|
|
1694
|
+
[void][QuickAsk.Native]::GetCursorPos([ref]$p)
|
|
1695
|
+
$cursor = New-Object System.Drawing.Point($p.X, $p.Y)
|
|
1696
|
+
$wa = [System.Windows.Forms.Screen]::FromPoint($cursor).WorkingArea
|
|
1697
|
+
$x = $p.X + 12
|
|
1698
|
+
$y = $p.Y + 18
|
|
1699
|
+
if ($x + $script:bar.Width -gt $wa.Right) { $x = $wa.Right - $script:bar.Width - 6 }
|
|
1700
|
+
if ($y + $script:bar.Height -gt $wa.Bottom) { $y = $p.Y - $script:bar.Height - 12 }
|
|
1701
|
+
if ($x -lt $wa.Left) { $x = $wa.Left + 6 }
|
|
1702
|
+
if ($y -lt $wa.Top) { $y = $wa.Top + 6 }
|
|
1703
|
+
$script:bar.Location = New-Object System.Drawing.Point($x, $y)
|
|
1704
|
+
$script:bar.Show()
|
|
1705
|
+
Write-Trace ("bar shown at " + [string]$x + "," + [string]$y + " " + [string]$script:bar.Width + "x" + [string]$script:bar.Height)
|
|
1706
|
+
$script:bar.BringToFront()
|
|
1707
|
+
if ($env:QUICKASK_DEBUG) { Write-Json @{ type = "bar"; bounds = $script:bar.Bounds.ToString() } }
|
|
1708
|
+
}
|
|
1709
|
+
|
|
1710
|
+
function Hide-Bar {
|
|
1711
|
+
if ($null -ne $script:bar -and $script:bar.Visible) { $script:bar.Hide() }
|
|
1712
|
+
}
|
|
1713
|
+
|
|
1714
|
+
function Set-CardStatus {
|
|
1715
|
+
param([string]$Text, [System.Drawing.Color]$Color)
|
|
1716
|
+
if ($null -eq $script:status) { return }
|
|
1717
|
+
$script:status.Text = $Text
|
|
1718
|
+
$script:status.ForeColor = $Color
|
|
1719
|
+
}
|
|
1720
|
+
|
|
1721
|
+
# Compact height (source only) and tall height (source + divider + translation),
|
|
1722
|
+
# both in 96 dpi design pixels.
|
|
1723
|
+
$script:CARD_H_COMPACT = 214
|
|
1724
|
+
$script:CARD_H_TALL = 330
|
|
1725
|
+
|
|
1726
|
+
# keyed by textbox handle: paint/mouse handlers need to find their own state
|
|
1727
|
+
$script:scrollbars = @{}
|
|
1728
|
+
function Set-CardHeight {
|
|
1729
|
+
param([int]$Design)
|
|
1730
|
+
if ($null -eq $script:card) { return }
|
|
1731
|
+
$h = Sz $Design
|
|
1732
|
+
if ($script:card.Height -eq $h) { return }
|
|
1733
|
+
$script:card.Height = $h
|
|
1734
|
+
Set-CardRegion $script:card
|
|
1735
|
+
# growing downwards near the bottom edge would push the buttons off screen
|
|
1736
|
+
$wa = [System.Windows.Forms.Screen]::FromPoint($script:card.Location).WorkingArea
|
|
1737
|
+
$y = $script:card.Top
|
|
1738
|
+
if ($y + $h -gt ($wa.Bottom - 8)) { $y = $wa.Bottom - $h - 8 }
|
|
1739
|
+
if ($y -lt ($wa.Top + 8)) { $y = $wa.Top + 8 }
|
|
1740
|
+
$script:card.Top = $y
|
|
1741
|
+
# A taller pane fits more lines, so the overflow decision has to be redone.
|
|
1742
|
+
Update-Scrollbar $script:txtSrc
|
|
1743
|
+
Update-Scrollbar $script:txtDst
|
|
1744
|
+
}
|
|
1745
|
+
|
|
1746
|
+
# The card is WS_EX_NOACTIVATE, so WinForms never sees a wheel: the mouse hook
|
|
1747
|
+
# forwards it into whichever pane is on screen instead (see MouseWatcher).
|
|
1748
|
+
function Update-WheelTarget {
|
|
1749
|
+
if ($null -eq $script:mouseWatcher -or $null -eq $script:card) { return }
|
|
1750
|
+
$script:mouseWatcher.WheelWindow = $script:card.Handle
|
|
1751
|
+
$script:mouseWatcher.WheelSrc = $script:txtSrc.Handle
|
|
1752
|
+
$script:mouseWatcher.WheelDst = $script:txtDst.Handle
|
|
1753
|
+
if ($script:txtDst.Visible) { $script:mouseWatcher.WheelTarget = $script:txtDst.Handle }
|
|
1754
|
+
else { $script:mouseWatcher.WheelTarget = $script:txtSrc.Handle }
|
|
1755
|
+
}
|
|
1756
|
+
|
|
1757
|
+
# A slim scrolling lane drawn by ourselves: the stock TextBox scrollbar is 17px
|
|
1758
|
+
# of white chrome that fights the card, and it cannot be themed. The lane only
|
|
1759
|
+
# appears when the pane actually overflows, and its thumb length is the visible
|
|
1760
|
+
# fraction, so "how much is left" stays readable at a glance.
|
|
1761
|
+
function Get-ScrollGeometry($Box, $Track) {
|
|
1762
|
+
$perLine = [Math]::Max(1, [int]$Box.Font.Height)
|
|
1763
|
+
$visible = [Math]::Max(1, [int](($Box.ClientSize.Height - (Sz 6)) / $perLine))
|
|
1764
|
+
$total = $Box.GetLineFromCharIndex([Math]::Max(0, $Box.TextLength - 1)) + 1
|
|
1765
|
+
$first = [int][QuickAsk.Native]::SendMessage($Box.Handle, 0x00CE, [IntPtr]::Zero, [IntPtr]::Zero)
|
|
1766
|
+
$over = $total -gt $visible
|
|
1767
|
+
$lane = [Math]::Max(1, $Track.ClientSize.Height)
|
|
1768
|
+
$thumb = if ($over) {
|
|
1769
|
+
[Math]::Max((Sz 16), [int]($lane * $visible / [Math]::Max(1, $total)))
|
|
1770
|
+
} else {
|
|
1771
|
+
$lane
|
|
1772
|
+
}
|
|
1773
|
+
$span = [Math]::Max(1, $total - $visible)
|
|
1774
|
+
$top = if ($over -and $span -gt 0) {
|
|
1775
|
+
[int](($lane - $thumb) * ([Math]::Min([Math]::Max(0, $first), $span)) / $span)
|
|
1776
|
+
} else {
|
|
1777
|
+
0
|
|
1778
|
+
}
|
|
1779
|
+
return @{ over = $over; total = $total; visible = $visible; first = $first; height = $thumb; top = $top }
|
|
1780
|
+
}
|
|
1781
|
+
|
|
1782
|
+
function Update-Scrollbar($Box) {
|
|
1783
|
+
if ($null -eq $Box) { return }
|
|
1784
|
+
$state = $script:scrollbars[$Box.Handle.ToInt64()]
|
|
1785
|
+
if ($null -eq $state) { return }
|
|
1786
|
+
try {
|
|
1787
|
+
$track = $state.track
|
|
1788
|
+
$geo = Get-ScrollGeometry $Box $track
|
|
1789
|
+
$state.geometry = $geo
|
|
1790
|
+
$track.Tag = $state
|
|
1791
|
+
if ($track.Visible -ne $geo.over) { $track.Visible = $geo.over }
|
|
1792
|
+
if ($geo.over) { $track.Invalidate() }
|
|
1793
|
+
} catch {
|
|
1794
|
+
Write-Trace ("scrollbar failed: " + $_.Exception.Message)
|
|
1795
|
+
}
|
|
1796
|
+
}
|
|
1797
|
+
|
|
1798
|
+
function Update-AllScrollbars {
|
|
1799
|
+
Update-Scrollbar $script:txtSrc
|
|
1800
|
+
Update-Scrollbar $script:txtDst
|
|
1801
|
+
}
|
|
1802
|
+
|
|
1803
|
+
function Move-ScrollbarTo($Track, [int]$Y) {
|
|
1804
|
+
$state = $Track.Tag
|
|
1805
|
+
if ($null -eq $state -or $null -eq $state.geometry) { return }
|
|
1806
|
+
$geo = $state.geometry
|
|
1807
|
+
$lane = [Math]::Max(1, $Track.ClientSize.Height)
|
|
1808
|
+
$room = [Math]::Max(1, $lane - $geo.height)
|
|
1809
|
+
$span = [Math]::Max(1, $geo.total - $geo.visible)
|
|
1810
|
+
$want = [int]([Math]::Round(($Y - $state.grabOffset) * $span / $room))
|
|
1811
|
+
$want = [Math]::Min([Math]::Max(0, $want), $span)
|
|
1812
|
+
$delta = $want - $geo.first
|
|
1813
|
+
if ($delta -ne 0) {
|
|
1814
|
+
[void][QuickAsk.Native]::SendMessage($state.box.Handle, 0x00B6, [IntPtr]::Zero, [IntPtr]$delta)
|
|
1815
|
+
$state.box.Refresh()
|
|
1816
|
+
Update-Scrollbar $state.box
|
|
1817
|
+
}
|
|
1818
|
+
}
|
|
1819
|
+
|
|
1820
|
+
function New-Scrollbar($Box) {
|
|
1821
|
+
$track = New-Object System.Windows.Forms.Panel
|
|
1822
|
+
$track.Dock = [System.Windows.Forms.DockStyle]::Fill
|
|
1823
|
+
$track.Margin = New-Object System.Windows.Forms.Padding((Sz 2), (Sz 4), (Sz 2), 0)
|
|
1824
|
+
$track.BackColor = $CARD_BG
|
|
1825
|
+
$track.Cursor = [System.Windows.Forms.Cursors]::Hand
|
|
1826
|
+
$track.Visible = $false
|
|
1827
|
+
$state = @{ track = $track; box = $Box; geometry = $null; dragging = $false; grabOffset = 0 }
|
|
1828
|
+
$track.Tag = $state
|
|
1829
|
+
$track.Add_Paint({
|
|
1830
|
+
param($sender, $e)
|
|
1831
|
+
$state = $sender.Tag
|
|
1832
|
+
if ($null -eq $state -or $null -eq $state.geometry) { return }
|
|
1833
|
+
$geo = $state.geometry
|
|
1834
|
+
if (-not $geo.over) { return }
|
|
1835
|
+
$brush = New-Object System.Drawing.SolidBrush($THUMB)
|
|
1836
|
+
$e.Graphics.FillRectangle($brush, 1, $geo.top, ($sender.Width - 2), $geo.height)
|
|
1837
|
+
$brush.Dispose()
|
|
1838
|
+
})
|
|
1839
|
+
$track.Add_MouseDown({
|
|
1840
|
+
param($sender, $e)
|
|
1841
|
+
$state = $sender.Tag
|
|
1842
|
+
if ($null -eq $state -or $null -eq $state.geometry) { return }
|
|
1843
|
+
if (-not $state.geometry.over) { return }
|
|
1844
|
+
if ($e.Y -ge $state.geometry.top -and $e.Y -le ($state.geometry.top + $state.geometry.height)) {
|
|
1845
|
+
$state.dragging = $true
|
|
1846
|
+
$state.grabOffset = $e.Y - $state.geometry.top
|
|
1847
|
+
} else {
|
|
1848
|
+
# clicking the lane pages one screen towards the click
|
|
1849
|
+
$step = [Math]::Max(1, $state.geometry.visible - 2)
|
|
1850
|
+
if ($e.Y -lt $state.geometry.top) { $step = -$step }
|
|
1851
|
+
[void][QuickAsk.Native]::SendMessage($state.box.Handle, 0x00B6, [IntPtr]::Zero, [IntPtr]$step)
|
|
1852
|
+
$state.box.Refresh()
|
|
1853
|
+
Update-Scrollbar $state.box
|
|
1854
|
+
}
|
|
1855
|
+
})
|
|
1856
|
+
$track.Add_MouseMove({
|
|
1857
|
+
param($sender, $e)
|
|
1858
|
+
$state = $sender.Tag
|
|
1859
|
+
if ($null -ne $state -and $state.dragging) { Move-ScrollbarTo $sender $e.Y }
|
|
1860
|
+
})
|
|
1861
|
+
$track.Add_MouseUp({
|
|
1862
|
+
param($sender, $e)
|
|
1863
|
+
if ($null -ne $sender.Tag) { $sender.Tag.dragging = $false }
|
|
1864
|
+
})
|
|
1865
|
+
$script:scrollbars[$Box.Handle.ToInt64()] = $state
|
|
1866
|
+
return $track
|
|
1867
|
+
}
|
|
1868
|
+
function Show-CardTranslation {
|
|
1869
|
+
param([string]$Text, [System.Drawing.Color]$Color)
|
|
1870
|
+
$script:txtDst.ForeColor = $Color
|
|
1871
|
+
$script:txtDst.Text = $Text
|
|
1872
|
+
$script:txtDst.Visible = $true
|
|
1873
|
+
$script:txtDst.SelectionStart = 0
|
|
1874
|
+
$script:divider.Visible = $true
|
|
1875
|
+
$script:grid.RowStyles[1].Height = (Sz 10)
|
|
1876
|
+
$script:grid.RowStyles[0].Height = 46
|
|
1877
|
+
$script:grid.RowStyles[2].Height = 54
|
|
1878
|
+
$script:dstText = $Text
|
|
1879
|
+
Set-CardHeight $script:CARD_H_TALL
|
|
1880
|
+
Update-Scrollbar $script:txtSrc
|
|
1881
|
+
Update-Scrollbar $script:txtDst
|
|
1882
|
+
Update-WheelTarget
|
|
1883
|
+
if (
|
|
1884
|
+
$Text -ne $T_TRANSLATING -and
|
|
1885
|
+
$Text -ne $T_EXPLAINING -and
|
|
1886
|
+
-not $Text.StartsWith($T_NO_SERVICE) -and
|
|
1887
|
+
-not $Text.StartsWith($T_FAILED)
|
|
1888
|
+
) {
|
|
1889
|
+
$script:btnCopy.Text = $T_COPY
|
|
1890
|
+
$script:btnCopy.Visible = $true
|
|
1891
|
+
}
|
|
1892
|
+
}
|
|
1893
|
+
|
|
1894
|
+
function Hide-CardTranslation {
|
|
1895
|
+
$script:txtDst.Visible = $false
|
|
1896
|
+
$script:txtDst.Text = ""
|
|
1897
|
+
$script:divider.Visible = $false
|
|
1898
|
+
$script:grid.RowStyles[1].Height = 0
|
|
1899
|
+
$script:grid.RowStyles[0].Height = 100
|
|
1900
|
+
$script:grid.RowStyles[2].Height = 0
|
|
1901
|
+
$script:dstText = ""
|
|
1902
|
+
$script:btnCopy.Text = $T_COPY
|
|
1903
|
+
$script:btnCopy.Visible = $false
|
|
1904
|
+
Set-CardHeight $script:CARD_H_COMPACT
|
|
1905
|
+
Update-Scrollbar $script:txtSrc
|
|
1906
|
+
Update-Scrollbar $script:txtDst
|
|
1907
|
+
Update-WheelTarget
|
|
1908
|
+
}
|
|
1909
|
+
|
|
1910
|
+
function Show-Card {
|
|
1911
|
+
param([hashtable]$Captured)
|
|
1912
|
+
if ($null -eq $script:card) { New-Card }
|
|
1913
|
+
|
|
1914
|
+
if ($null -eq $Captured) {
|
|
1915
|
+
$script:lastId = ""
|
|
1916
|
+
$script:srcText = ""
|
|
1917
|
+
$script:txtSrc.Text = $T_NO_TEXT + " - " + $T_HINT
|
|
1918
|
+
Hide-CardTranslation
|
|
1919
|
+
$script:btnTranslate.Enabled = $false
|
|
1920
|
+
$script:btnAsk.Enabled = $false
|
|
1921
|
+
$script:btnCopy.Enabled = $false
|
|
1922
|
+
} else {
|
|
1923
|
+
$script:lastId = [string]$Captured.id
|
|
1924
|
+
$script:srcText = [string]$Captured.text
|
|
1925
|
+
# Only two voices exist on this machine (zh/en); anything else reads as en.
|
|
1926
|
+
$script:srcLang = if ($script:srcText -match "[\u4e00-\u9fff]") { "zh" } else { "en" }
|
|
1927
|
+
$script:txtSrc.Text = $script:srcText
|
|
1928
|
+
Hide-CardTranslation
|
|
1929
|
+
$script:btnTranslate.Enabled = $true
|
|
1930
|
+
$script:btnExplain.Enabled = $true
|
|
1931
|
+
$script:btnAsk.Enabled = $true
|
|
1932
|
+
$script:btnSave.Enabled = $true
|
|
1933
|
+
$script:btnCopy.Enabled = $true
|
|
1934
|
+
$script:txtSrc.SelectionStart = 0
|
|
1935
|
+
$script:txtSrc.SelectionLength = 0
|
|
1936
|
+
}
|
|
1937
|
+
|
|
1938
|
+
$script:busy = $false
|
|
1939
|
+
$script:btnTranslate.Text = $T_TRANSLATE
|
|
1940
|
+
$script:btnExplain.Text = $T_EXPLAIN
|
|
1941
|
+
$script:btnSave.Text = $T_SAVE
|
|
1942
|
+
Set-CardStatus "" $INK_DIM
|
|
1943
|
+
|
|
1944
|
+
# place near the cursor, clamped to the screen it is on
|
|
1945
|
+
$p = New-Object QuickAsk.POINT
|
|
1946
|
+
[void][QuickAsk.Native]::GetCursorPos([ref]$p)
|
|
1947
|
+
$cursor = New-Object System.Drawing.Point($p.X, $p.Y)
|
|
1948
|
+
$wa = [System.Windows.Forms.Screen]::FromPoint($cursor).WorkingArea
|
|
1949
|
+
$x = $p.X + 16
|
|
1950
|
+
$y = $p.Y + 16
|
|
1951
|
+
if ($x + $script:card.Width -gt $wa.Right) { $x = $wa.Right - $script:card.Width - 8 }
|
|
1952
|
+
if ($y + $script:card.Height -gt $wa.Bottom) { $y = $wa.Bottom - $script:card.Height - 8 }
|
|
1953
|
+
if ($x -lt $wa.Left) { $x = $wa.Left + 8 }
|
|
1954
|
+
if ($y -lt $wa.Top) { $y = $wa.Top + 8 }
|
|
1955
|
+
$script:card.Location = New-Object System.Drawing.Point($x, $y)
|
|
1956
|
+
|
|
1957
|
+
$script:card.Show()
|
|
1958
|
+
Update-Scrollbar $script:txtSrc
|
|
1959
|
+
Update-Scrollbar $script:txtDst
|
|
1960
|
+
Update-WheelTarget
|
|
1961
|
+
$script:card.BringToFront()
|
|
1962
|
+
if ($env:QUICKASK_DEBUG) {
|
|
1963
|
+
Write-Json @{ type = "card"; bounds = $script:card.Bounds.ToString(); client = $script:card.ClientSize.ToString() }
|
|
1964
|
+
}
|
|
1965
|
+
}
|
|
1966
|
+
|
|
1967
|
+
function Hide-Card {
|
|
1968
|
+
Hide-LangMenu
|
|
1969
|
+
if ($null -ne $script:card) { $script:card.Hide() }
|
|
1970
|
+
# A hidden card still has a rect: stop swallowing the wheel over it.
|
|
1971
|
+
if ($null -ne $script:mouseWatcher) {
|
|
1972
|
+
$script:mouseWatcher.WheelWindow = [IntPtr]::Zero
|
|
1973
|
+
$script:mouseWatcher.WheelTarget = [IntPtr]::Zero
|
|
1974
|
+
$script:mouseWatcher.WheelSrc = [IntPtr]::Zero
|
|
1975
|
+
$script:mouseWatcher.WheelDst = [IntPtr]::Zero
|
|
1976
|
+
}
|
|
1977
|
+
Hide-Bar
|
|
1978
|
+
# Once dismissed, selecting the same text again should pop the card again,
|
|
1979
|
+
# but a selection that is merely still highlighted must not reopen it.
|
|
1980
|
+
$script:dismissed = $script:autoShown
|
|
1981
|
+
$script:autoShown = ""
|
|
1982
|
+
}
|
|
1983
|
+
|
|
1984
|
+
# ---------------------------------------------------------------- auto watch
|
|
1985
|
+
#
|
|
1986
|
+
# Two triggers, both ending in Show-AutoCapture:
|
|
1987
|
+
# * mouse gestures (drag select, double click word select). A low level mouse
|
|
1988
|
+
# hook fires right after the selection exists; the capture then tries UIA and
|
|
1989
|
+
# falls back to copying the selection, restoring the clipboard right after.
|
|
1990
|
+
# * a slow poll of the focused element's TextPattern, for selections made with
|
|
1991
|
+
# the keyboard in applications that expose text over UIA.
|
|
1992
|
+
|
|
1993
|
+
function Get-ForegroundOwnerPid {
|
|
1994
|
+
try {
|
|
1995
|
+
$h = [QuickAsk.Native]::GetForegroundWindow()
|
|
1996
|
+
if ($h -eq [IntPtr]::Zero) { return 0 }
|
|
1997
|
+
$owner = 0
|
|
1998
|
+
[void][QuickAsk.Native]::GetWindowThreadProcessId($h, [ref]$owner)
|
|
1999
|
+
return $owner
|
|
2000
|
+
} catch {
|
|
2001
|
+
return 0
|
|
2002
|
+
}
|
|
2003
|
+
}
|
|
2004
|
+
|
|
2005
|
+
function Get-ForegroundClassName {
|
|
2006
|
+
try {
|
|
2007
|
+
$h = [QuickAsk.Native]::GetForegroundWindow()
|
|
2008
|
+
if ($h -eq [IntPtr]::Zero) { return "" }
|
|
2009
|
+
$sb = New-Object System.Text.StringBuilder 256
|
|
2010
|
+
[void][QuickAsk.Native]::GetClassName($h, $sb, 256)
|
|
2011
|
+
return $sb.ToString()
|
|
2012
|
+
} catch {
|
|
2013
|
+
return ""
|
|
2014
|
+
}
|
|
2015
|
+
}
|
|
2016
|
+
|
|
2017
|
+
# Ctrl+C inside a console interrupts the running command instead of copying, so
|
|
2018
|
+
# the clipboard fallback never runs there.
|
|
2019
|
+
function Test-ConsoleForeground {
|
|
2020
|
+
$cls = Get-ForegroundClassName
|
|
2021
|
+
return ($cls -eq "ConsoleWindowClass" -or $cls -eq "CASCADIA_HOSTING_WINDOW_CLASS" -or $cls -eq "mintty")
|
|
2022
|
+
}
|
|
2023
|
+
|
|
2024
|
+
function Show-AutoCapture {
|
|
2025
|
+
param([string]$Text)
|
|
2026
|
+
if ([string]::IsNullOrWhiteSpace($Text)) { return }
|
|
2027
|
+
$Text = $Text -replace "`r`n", "`n"
|
|
2028
|
+
if ($Text.Trim().Length -lt 2) { return }
|
|
2029
|
+
# A whole-page Ctrl+A would otherwise pop a 60k character card nobody asked for.
|
|
2030
|
+
if ($Text.Length -gt $script:MAX_CAPTURE_CHARS) { Write-Trace ("capture truncated " + [string]$Text.Length); $Text = $Text.Substring(0, $script:MAX_CAPTURE_CHARS) + "..." }
|
|
2031
|
+
if ($Text -eq $script:autoShown -and ((Get-Date) - $script:autoShownAt).TotalSeconds -lt 1.2) { return }
|
|
2032
|
+
# A dismissed selection can still be live (the browser keeps it highlighted);
|
|
2033
|
+
# the poll must not reopen the card for it until the user selects again.
|
|
2034
|
+
if ($Text -eq $script:dismissed) { return }
|
|
2035
|
+
$captured = @{ type = "selection"; id = [guid]::NewGuid().ToString("N"); text = $Text; via = "auto"; chars = $Text.Length }
|
|
2036
|
+
if ($env:QUICKASK_DEBUG) { Write-Json @{ type = "auto"; chars = $Text.Length; via = $captured.via } }
|
|
2037
|
+
$script:autoShown = $Text
|
|
2038
|
+
$script:autoShownAt = Get-Date
|
|
2039
|
+
Write-Trace ("auto capture chars=" + $Text.Length + " via=" + $captured.via)
|
|
2040
|
+
Write-Json $captured
|
|
2041
|
+
# A selection only pops the pill: the full card (and the translation round
|
|
2042
|
+
# trip) waits for the user to pick translate.
|
|
2043
|
+
Show-Bar $captured
|
|
2044
|
+
}
|
|
2045
|
+
|
|
2046
|
+
# Mouse and keyboard hooks both land here: give the application a moment to
|
|
2047
|
+
# finish its own selection handling, then retry a few times.
|
|
2048
|
+
function Start-GestureCapture {
|
|
2049
|
+
$script:hb.step = "gesture"
|
|
2050
|
+
if ($null -eq $script:gestureTimer) { return }
|
|
2051
|
+
# Dragging our own card or pill is not a selection gesture.
|
|
2052
|
+
if ((Get-Date) -lt $script:ownGestureUntil) { return }
|
|
2053
|
+
# An explicit gesture means intent, even for text the user just dismissed.
|
|
2054
|
+
$script:dismissed = ""
|
|
2055
|
+
$script:gestureTimer.Stop()
|
|
2056
|
+
$script:gestureAttempt = 0
|
|
2057
|
+
$script:gestureTimer.Interval = 160
|
|
2058
|
+
$script:gestureTimer.Start()
|
|
2059
|
+
}
|
|
2060
|
+
|
|
2061
|
+
function Get-AutoSelectionText {
|
|
2062
|
+
$script:hb.step = "uia"
|
|
2063
|
+
$text = $null
|
|
2064
|
+
try {
|
|
2065
|
+
$focused = [System.Windows.Automation.AutomationElement]::FocusedElement
|
|
2066
|
+
$text = Get-UiaSelectionText -Element $focused
|
|
2067
|
+
if ([string]::IsNullOrWhiteSpace($text)) { $text = Get-UiaSelectionTextDeep -Element $focused -Limit 16 }
|
|
2068
|
+
if ([string]::IsNullOrWhiteSpace($text)) {
|
|
2069
|
+
$fgHwnd = [QuickAsk.Native]::GetForegroundWindow()
|
|
2070
|
+
if ($fgHwnd -ne [IntPtr]::Zero) {
|
|
2071
|
+
$fgRoot = [System.Windows.Automation.AutomationElement]::FromHandle($fgHwnd)
|
|
2072
|
+
if ($null -ne $fgRoot) { $text = Get-UiaSelectionTextDeep -Element $fgRoot -Limit 40 }
|
|
2073
|
+
}
|
|
2074
|
+
}
|
|
2075
|
+
} catch {
|
|
2076
|
+
$text = $null
|
|
2077
|
+
}
|
|
2078
|
+
# Ctrl+C copies in an editor but interrupts a shell, so terminals get
|
|
2079
|
+
# Ctrl+Insert: the copy chord that never reaches the program. When even that
|
|
2080
|
+
# yields nothing we stay quiet for a few seconds instead of poking again.
|
|
2081
|
+
if ([string]::IsNullOrWhiteSpace($text) -and ((Get-Date) -ge $script:clipBlockedUntil)) {
|
|
2082
|
+
$keys = "^c"
|
|
2083
|
+
if ((Test-KeyboardSurface) -or (Test-ConsoleForeground)) { $keys = "^{INSERT}" }
|
|
2084
|
+
try { $text = Get-ClipboardSelectionText -Keys $keys } catch { $text = $null }
|
|
2085
|
+
if ([string]::IsNullOrWhiteSpace($text)) { $script:clipBlockedUntil = (Get-Date).AddSeconds(3) }
|
|
2086
|
+
}
|
|
2087
|
+
return $text
|
|
2088
|
+
}
|
|
2089
|
+
|
|
2090
|
+
|
|
2091
|
+
# Screen capture tools (PixPin, Snipaste, ...) grab the screen with a borderless
|
|
2092
|
+
# overlay that covers a whole monitor; while that overlay is up, a drag is the
|
|
2093
|
+
# user framing a screenshot, not selecting text. Capturing there would also
|
|
2094
|
+
# fire Ctrl+C into their tool and empty the clipboard they are about to use.
|
|
2095
|
+
$script:SKIP_PROCS = @("pixpin", "snipaste", "sharex", "screentogif", "snippingtool", "screenclippinghost", "greenshot", "faststone")
|
|
2096
|
+
|
|
2097
|
+
$script:fgProcPid = 0
|
|
2098
|
+
$script:fgProcName = ""
|
|
2099
|
+
|
|
2100
|
+
function Get-ForegroundProcessName {
|
|
2101
|
+
$hwnd = [QuickAsk.Native]::GetForegroundWindow()
|
|
2102
|
+
if ($hwnd -eq [IntPtr]::Zero) { return "" }
|
|
2103
|
+
$fgPid = 0
|
|
2104
|
+
[void][QuickAsk.Native]::GetWindowThreadProcessId($hwnd, [ref]$fgPid)
|
|
2105
|
+
if ($fgPid -eq $script:fgProcPid) { return $script:fgProcName }
|
|
2106
|
+
$name = ""
|
|
2107
|
+
try { $name = (Get-Process -Id $fgPid -ErrorAction Stop).ProcessName } catch { $name = "" }
|
|
2108
|
+
$script:fgProcPid = $fgPid
|
|
2109
|
+
$script:fgProcName = $name
|
|
2110
|
+
return $name
|
|
2111
|
+
}
|
|
2112
|
+
|
|
2113
|
+
# Terminals treat Ctrl+C as "interrupt", not "copy", so the clipboard fallback
|
|
2114
|
+
# would fire a literal ^C into the user shell. xterm.js (VS Code, Windows
|
|
2115
|
+
# Terminal) focuses a hidden textarea called xterm-helper-textarea, which gives
|
|
2116
|
+
# the case away even though the window class looks like any Chromium window.
|
|
2117
|
+
$script:TERM_PROCS = @("windowsterminal", "conhost", "openconsole", "mintty", "cmd", "powershell", "pwsh", "bash", "wsl", "wt")
|
|
2118
|
+
|
|
2119
|
+
function Test-KeyboardSurface {
|
|
2120
|
+
$name = (Get-ForegroundProcessName).ToLowerInvariant()
|
|
2121
|
+
if ($script:TERM_PROCS -contains $name) { return $true }
|
|
2122
|
+
$cls = (Get-ForegroundClassName).ToLowerInvariant()
|
|
2123
|
+
foreach ($known in @("consolewindowclass", "cascadia_hosting_window_class", "mintty")) {
|
|
2124
|
+
if ($cls -eq $known) { return $true }
|
|
2125
|
+
}
|
|
2126
|
+
try {
|
|
2127
|
+
$focused = [System.Windows.Automation.AutomationElement]::FocusedElement
|
|
2128
|
+
if ($null -ne $focused) {
|
|
2129
|
+
$fc = [string]$focused.Current.ClassName
|
|
2130
|
+
$fn = [string]$focused.Current.Name
|
|
2131
|
+
if ($fc -like "*xterm*" -or $fn -like "*xterm*") { return $true }
|
|
2132
|
+
}
|
|
2133
|
+
} catch { }
|
|
2134
|
+
return $false
|
|
2135
|
+
}
|
|
2136
|
+
|
|
2137
|
+
|
|
2138
|
+
function Test-ForegroundOverlay {
|
|
2139
|
+
$hwnd = [QuickAsk.Native]::GetForegroundWindow()
|
|
2140
|
+
if ($hwnd -eq [IntPtr]::Zero) { return $false }
|
|
2141
|
+
# A maximized app also covers the whole monitor, so "covers the monitor" alone
|
|
2142
|
+
# is not enough: real capture overlays are borderless (no WS_CAPTION).
|
|
2143
|
+
$style = [QuickAsk.Native]::GetWindowLongW($hwnd, -16)
|
|
2144
|
+
if (($style -band 0x00C00000) -ne 0) { return $false }
|
|
2145
|
+
$r = New-Object QuickAsk.RECT
|
|
2146
|
+
if (-not [QuickAsk.Native]::GetWindowRect($hwnd, [ref]$r)) { return $false }
|
|
2147
|
+
foreach ($s in [System.Windows.Forms.Screen]::AllScreens) {
|
|
2148
|
+
$b = $s.Bounds
|
|
2149
|
+
if ($r.Left -le $b.Left -and $r.Top -le $b.Top -and $r.Right -ge $b.Right -and $r.Bottom -ge $b.Bottom) { return $true }
|
|
2150
|
+
}
|
|
2151
|
+
return $false
|
|
2152
|
+
}
|
|
2153
|
+
|
|
2154
|
+
# The DSH window itself is not "another application": polling its UIA tree
|
|
2155
|
+
# makes Chromium rebuild its accessibility tree on every tick, which stalls the
|
|
2156
|
+
# renderer and looks like the whole app freezing.
|
|
2157
|
+
function Test-ForegroundIsHost {
|
|
2158
|
+
$hwnd = [QuickAsk.Native]::GetForegroundWindow()
|
|
2159
|
+
if ($hwnd -eq [IntPtr]::Zero) { return $false }
|
|
2160
|
+
$fgPid = 0
|
|
2161
|
+
[void][QuickAsk.Native]::GetWindowThreadProcessId($hwnd, [ref]$fgPid)
|
|
2162
|
+
if ($script:parentPid -gt 0 -and $fgPid -eq $script:parentPid) { return $true }
|
|
2163
|
+
# Our own card: selecting text inside it is copying, not a new capture.
|
|
2164
|
+
if ($fgPid -eq $PID) { return $true }
|
|
2165
|
+
$name = (Get-ForegroundProcessName).ToLowerInvariant()
|
|
2166
|
+
# The settings window and the desktop shell names look like ours too.
|
|
2167
|
+
return ($name -like "*deepseek*")
|
|
2168
|
+
}
|
|
2169
|
+
|
|
2170
|
+
function Test-CaptureBlocked {
|
|
2171
|
+
$name = (Get-ForegroundProcessName).ToLowerInvariant()
|
|
2172
|
+
if ($script:SKIP_PROCS -contains $name) { return "capture tool " + $name }
|
|
2173
|
+
if (Test-ForegroundOverlay) { return "fullscreen overlay" }
|
|
2174
|
+
return ""
|
|
2175
|
+
}
|
|
2176
|
+
|
|
2177
|
+
function Invoke-AutoCapture {
|
|
2178
|
+
if ($script:busy) { Write-Trace "auto skip busy"; return $false }
|
|
2179
|
+
$owner = Get-ForegroundOwnerPid
|
|
2180
|
+
if ($owner -eq $PID) { Write-Trace "auto skip foreground-self"; return $false }
|
|
2181
|
+
# Selection inside the DSH window is fair game: the user gestured, so this is
|
|
2182
|
+
# a one-shot capture rather than the background polling that used to hammer
|
|
2183
|
+
# Chromium UIA. Watch-Selection below still skips the host window.
|
|
2184
|
+
if (Test-ForegroundIsHost) { Write-Trace ("auto host-window capture allowed pid=" + [string](Get-ForegroundOwnerPid)) }
|
|
2185
|
+
$blocked = Test-CaptureBlocked
|
|
2186
|
+
if ($blocked -ne "") { Write-Trace ("auto skip " + $blocked); return $false }
|
|
2187
|
+
$text = Get-AutoSelectionText
|
|
2188
|
+
Write-Trace ("auto try fg=" + (Get-ForegroundClassName) + " owner=" + $owner + " console=" + (Test-ConsoleForeground) + " len=" + [int]($text.Length))
|
|
2189
|
+
if ([string]::IsNullOrWhiteSpace($text)) { return $false }
|
|
2190
|
+
Show-AutoCapture $text
|
|
2191
|
+
return $true
|
|
2192
|
+
}
|
|
2193
|
+
|
|
2194
|
+
# Runs on its own runspace: it must keep logging even when the UI thread is
|
|
2195
|
+
# stuck inside a blocking UIA or Win32 call.
|
|
2196
|
+
$script:WatchdogScript = @'
|
|
2197
|
+
param($hb, $logPath, $hostHwnd)
|
|
2198
|
+
Add-Type -Namespace Watch -Name Probe -MemberDefinition '[DllImport("user32.dll")] public static extern IntPtr SendMessageTimeout(IntPtr h, uint m, IntPtr w, IntPtr l, uint f, uint t, out IntPtr r);'
|
|
2199
|
+
function Test-Alive([IntPtr]$h) {
|
|
2200
|
+
if ($h -eq [IntPtr]::Zero) { return $true }
|
|
2201
|
+
$res = [IntPtr]::Zero
|
|
2202
|
+
$ok = [Watch.Probe]::SendMessageTimeout($h, 0, [IntPtr]::Zero, [IntPtr]::Zero, 2, 1200, [ref]$res)
|
|
2203
|
+
return ($ok -ne [IntPtr]::Zero)
|
|
2204
|
+
}
|
|
2205
|
+
Add-Content -Path $logPath -Value ((Get-Date).ToString("o") + " watchdog: started host=" + [string]$hostHwnd) -Encoding ASCII
|
|
2206
|
+
$last = -1
|
|
2207
|
+
$same = 0
|
|
2208
|
+
$badRun = 0
|
|
2209
|
+
$iter = 0
|
|
2210
|
+
while ($true) {
|
|
2211
|
+
Start-Sleep -Seconds 2
|
|
2212
|
+
$n = [int]$hb.n
|
|
2213
|
+
if ($n -eq $last) {
|
|
2214
|
+
$same += 1
|
|
2215
|
+
if ($same -ge 2) {
|
|
2216
|
+
Add-Content -Path $logPath -Value ((Get-Date).ToString("o") + " watchdog: UI STALL at step=" + [string]$hb.step + " n=" + [string]$n) -Encoding ASCII
|
|
2217
|
+
$same = 0
|
|
2218
|
+
}
|
|
2219
|
+
} else {
|
|
2220
|
+
$last = $n
|
|
2221
|
+
$same = 0
|
|
2222
|
+
}
|
|
2223
|
+
$iter += 1
|
|
2224
|
+
if (($iter % 15) -eq 0) {
|
|
2225
|
+
Add-Content -Path $logPath -Value ((Get-Date).ToString("o") + " watchdog: alive tick=" + [string]$hb.n + " dsh=" + [string](Test-Alive ([IntPtr]$hostHwnd))) -Encoding ASCII
|
|
2226
|
+
}
|
|
2227
|
+
if (-not (Test-Alive ([IntPtr]$hostHwnd))) {
|
|
2228
|
+
$badRun += 1
|
|
2229
|
+
Add-Content -Path $logPath -Value ((Get-Date).ToString("o") + " watchdog: DSH not answering (#" + $badRun + ")") -Encoding ASCII
|
|
2230
|
+
} elseif ($badRun -gt 0) {
|
|
2231
|
+
Add-Content -Path $logPath -Value ((Get-Date).ToString("o") + " watchdog: DSH recovered after " + $badRun) -Encoding ASCII
|
|
2232
|
+
$badRun = 0
|
|
2233
|
+
$iter = 0
|
|
2234
|
+
}
|
|
2235
|
+
}
|
|
2236
|
+
'@
|
|
2237
|
+
|
|
2238
|
+
function Start-Watchdog {
|
|
2239
|
+
if ($null -ne $script:watchdog) { return }
|
|
2240
|
+
$script:hb = [hashtable]::Synchronized(@{ n = 0; step = "idle" })
|
|
2241
|
+
$runner = [powershell]::Create()
|
|
2242
|
+
$hostHwnd = [IntPtr]::Zero
|
|
2243
|
+
try { $hostHwnd = Get-HostWindow } catch { }
|
|
2244
|
+
[void]$runner.AddScript($script:WatchdogScript).AddArgument($script:hb).AddArgument($script:LogPath).AddArgument($hostHwnd)
|
|
2245
|
+
$script:watchdog = $runner.BeginInvoke()
|
|
2246
|
+
$script:watchdogRunner = $runner
|
|
2247
|
+
}
|
|
2248
|
+
|
|
2249
|
+
function Update-Guarded {
|
|
2250
|
+
# Escape is only swallowed while our own UI is on screen; the hook checks the
|
|
2251
|
+
# handles natively, so they have to be kept current.
|
|
2252
|
+
if ($null -eq $script:keyWatcher) { return }
|
|
2253
|
+
$handles = New-Object "System.IntPtr[]" 3
|
|
2254
|
+
if ($null -ne $script:card) { $handles[0] = $script:card.Handle }
|
|
2255
|
+
if ($null -ne $script:bar) { $handles[1] = $script:bar.Handle }
|
|
2256
|
+
if ($null -ne $script:langMenu) { $handles[2] = $script:langMenu.Handle }
|
|
2257
|
+
$script:keyWatcher.Guarded = $handles
|
|
2258
|
+
}
|
|
2259
|
+
|
|
2260
|
+
function Watch-Selection {
|
|
2261
|
+
param($Element = $null)
|
|
2262
|
+
Update-Guarded
|
|
2263
|
+
# The heartbeat counter lets the watchdog thread prove the UI thread is alive
|
|
2264
|
+
# and name the last step it entered.
|
|
2265
|
+
$script:hb.n = $script:hb.n + 1
|
|
2266
|
+
$script:hb.step = "watch"
|
|
2267
|
+
if ($script:busy) { return }
|
|
2268
|
+
if (-not $CaptureSelf -and (Get-ForegroundOwnerPid) -eq $PID) { return }
|
|
2269
|
+
if (Test-CaptureBlocked -ne "") { return }
|
|
2270
|
+
# See Test-ForegroundIsHost: never hammer the DSH window with UIA queries.
|
|
2271
|
+
if (-not $CaptureSelf -and (Test-ForegroundIsHost)) { return }
|
|
2272
|
+
|
|
2273
|
+
$text = $null
|
|
2274
|
+
try {
|
|
2275
|
+
if ($null -eq $Element) { $Element = [System.Windows.Automation.AutomationElement]::FocusedElement }
|
|
2276
|
+
$text = Get-UiaSelectionText -Element $Element
|
|
2277
|
+
} catch {
|
|
2278
|
+
$text = $null
|
|
2279
|
+
}
|
|
2280
|
+
|
|
2281
|
+
if ([string]::IsNullOrWhiteSpace($text)) {
|
|
2282
|
+
# A deep scan is expensive, so the poll only pays for it occasionally.
|
|
2283
|
+
$script:pollN += 1
|
|
2284
|
+
if (($script:pollN % 6) -eq 0) {
|
|
2285
|
+
try { $text = Get-UiaSelectionTextDeep -Element $Element -Limit 12 } catch { $text = $null }
|
|
2286
|
+
}
|
|
2287
|
+
}
|
|
2288
|
+
if ([string]::IsNullOrWhiteSpace($text) -or $text.Trim().Length -lt 2) {
|
|
2289
|
+
$script:autoCandidate = ""
|
|
2290
|
+
$script:autoCount = 0
|
|
2291
|
+
$script:dismissed = ""
|
|
2292
|
+
return
|
|
2293
|
+
}
|
|
2294
|
+
|
|
2295
|
+
$text = $text -replace "`r`n", "`n"
|
|
2296
|
+
if ($text -eq $script:autoShown) { return }
|
|
2297
|
+
if ($text -eq $script:autoCandidate) { $script:autoCount += 1 } else { $script:autoCandidate = $text; $script:autoCount = 1 }
|
|
2298
|
+
if ($script:autoCount -lt 2) { return }
|
|
2299
|
+
Show-AutoCapture $text
|
|
2300
|
+
}
|
|
2301
|
+
# ---------------------------------------------------------------- translation
|
|
2302
|
+
|
|
2303
|
+
function Get-TaskUrl([string]$Task) {
|
|
2304
|
+
if ([string]::IsNullOrWhiteSpace($TranslateUrl)) { return "" }
|
|
2305
|
+
# Translation keeps using the plain /translate route so an older host (one
|
|
2306
|
+
# that predates the task parameter) still answers; every other task needs
|
|
2307
|
+
# /run, which only newer hosts serve.
|
|
2308
|
+
$base = $TranslateUrl
|
|
2309
|
+
$sep = "?"
|
|
2310
|
+
if ($base.Contains("?")) { $sep = "&" }
|
|
2311
|
+
$url = $base + $sep + "id=" + [uri]::EscapeDataString($script:lastId) + "&to=" + [uri]::EscapeDataString($script:lang)
|
|
2312
|
+
if ($Task -eq "translate") { return $url }
|
|
2313
|
+
if ($base -match '/translate$') {
|
|
2314
|
+
$base = $base -replace '/translate$', '/run'
|
|
2315
|
+
$sep = "?"
|
|
2316
|
+
if ($base.Contains("?")) { $sep = "&" }
|
|
2317
|
+
$url = $base + $sep + "id=" + [uri]::EscapeDataString($script:lastId) + "&to=" + [uri]::EscapeDataString($script:lang)
|
|
2318
|
+
}
|
|
2319
|
+
return $url + "&task=" + [uri]::EscapeDataString($Task)
|
|
2320
|
+
}
|
|
2321
|
+
|
|
2322
|
+
$script:speaker = $null
|
|
2323
|
+
$script:media = $null
|
|
2324
|
+
$script:nodePath = $null
|
|
2325
|
+
$script:lastAudio = ""
|
|
2326
|
+
|
|
2327
|
+
function Get-NodePath {
|
|
2328
|
+
if ($null -ne $script:nodePath) { return $script:nodePath }
|
|
2329
|
+
$script:nodePath = ""
|
|
2330
|
+
$candidates = @(
|
|
2331
|
+
(Join-Path $env:ProgramFiles "nodejs\node.exe"),
|
|
2332
|
+
(Join-Path $env:LOCALAPPDATA "Programs\nodejs\node.exe")
|
|
2333
|
+
)
|
|
2334
|
+
foreach ($candidate in $candidates) {
|
|
2335
|
+
if (Test-Path -LiteralPath $candidate) { $script:nodePath = $candidate; break }
|
|
2336
|
+
}
|
|
2337
|
+
if ($script:nodePath -eq "") {
|
|
2338
|
+
$cmd = Get-Command node.exe -ErrorAction SilentlyContinue
|
|
2339
|
+
if ($null -ne $cmd) { $script:nodePath = [string]$cmd.Source }
|
|
2340
|
+
}
|
|
2341
|
+
return $script:nodePath
|
|
2342
|
+
}
|
|
2343
|
+
|
|
2344
|
+
# Edge neural voices sound far better than the SAPI ones Windows ships with.
|
|
2345
|
+
# Synthesis happens in a node child (see tools/say.mjs), playback through WPF.
|
|
2346
|
+
function Speak-Neural([string]$Text, [string]$Lang) {
|
|
2347
|
+
$node = Get-NodePath
|
|
2348
|
+
if ($node -eq "") { return $false }
|
|
2349
|
+
$tool = Join-Path (Split-Path -Parent $PSScriptRoot) "tools\say.mjs"
|
|
2350
|
+
if (-not (Test-Path -LiteralPath $tool)) { return $false }
|
|
2351
|
+
$voice = "en-US-AriaNeural"
|
|
2352
|
+
if ($Lang -eq "zh") { $voice = "zh-CN-XiaoxiaoNeural" }
|
|
2353
|
+
$base = Join-Path $env:TEMP ("dsh-say-" + [guid]::NewGuid().ToString("N"))
|
|
2354
|
+
$textFile = $base + ".txt"
|
|
2355
|
+
$audio = $base + ".mp3"
|
|
2356
|
+
try {
|
|
2357
|
+
[System.IO.File]::WriteAllText($textFile, $Text, (New-Object System.Text.UTF8Encoding($false)))
|
|
2358
|
+
$psi = New-Object System.Diagnostics.ProcessStartInfo
|
|
2359
|
+
$psi.FileName = $node
|
|
2360
|
+
$psi.Arguments = '"' + $tool + '" --text-file "' + $textFile + '" "' + $audio + '" "' + $voice + '"'
|
|
2361
|
+
$psi.UseShellExecute = $false
|
|
2362
|
+
$psi.CreateNoWindow = $true
|
|
2363
|
+
$psi.RedirectStandardError = $true
|
|
2364
|
+
$psi.RedirectStandardOutput = $true
|
|
2365
|
+
$proc = [System.Diagnostics.Process]::Start($psi)
|
|
2366
|
+
if (-not $proc.WaitForExit(12000)) {
|
|
2367
|
+
try { $proc.Kill() } catch { }
|
|
2368
|
+
Write-Trace "say: node timed out"
|
|
2369
|
+
return $false
|
|
2370
|
+
}
|
|
2371
|
+
if (-not (Test-Path -LiteralPath $audio)) {
|
|
2372
|
+
$err = $proc.StandardError.ReadToEnd()
|
|
2373
|
+
Write-Trace ("say: no audio; " + $err.Trim())
|
|
2374
|
+
return $false
|
|
2375
|
+
}
|
|
2376
|
+
if ($null -eq $script:media) {
|
|
2377
|
+
Add-Type -AssemblyName PresentationCore
|
|
2378
|
+
$script:media = New-Object System.Windows.Media.MediaPlayer
|
|
2379
|
+
}
|
|
2380
|
+
$script:media.Close()
|
|
2381
|
+
$script:media.Open((New-Object System.Uri($audio)))
|
|
2382
|
+
$script:media.Volume = 1.0
|
|
2383
|
+
$script:media.Play()
|
|
2384
|
+
# Only keep the file we are playing; earlier clips are dead weight.
|
|
2385
|
+
if ($script:lastAudio -ne "" -and $script:lastAudio -ne $audio) {
|
|
2386
|
+
try { Remove-Item -LiteralPath $script:lastAudio -Force -ErrorAction SilentlyContinue } catch { }
|
|
2387
|
+
}
|
|
2388
|
+
$script:lastAudio = $audio
|
|
2389
|
+
Write-Trace ("say: neural " + $voice)
|
|
2390
|
+
return $true
|
|
2391
|
+
} catch {
|
|
2392
|
+
Write-Trace ("say: " + $_.Exception.Message)
|
|
2393
|
+
return $false
|
|
2394
|
+
} finally {
|
|
2395
|
+
# Keep the mp3 (it may still be playing), drop the text file.
|
|
2396
|
+
try { Remove-Item -LiteralPath $textFile -Force -ErrorAction SilentlyContinue } catch { }
|
|
2397
|
+
}
|
|
2398
|
+
}
|
|
2399
|
+
|
|
2400
|
+
function Speak-Sapi([string]$Text, [string]$Lang) {
|
|
2401
|
+
try {
|
|
2402
|
+
if ($null -eq $script:speaker) {
|
|
2403
|
+
Add-Type -AssemblyName System.Speech
|
|
2404
|
+
$script:speaker = New-Object System.Speech.Synthesis.SpeechSynthesizer
|
|
2405
|
+
}
|
|
2406
|
+
$prefix = "en-"
|
|
2407
|
+
if ($Lang -eq "zh") { $prefix = "zh-" }
|
|
2408
|
+
$voice = ""
|
|
2409
|
+
foreach ($installed in $script:speaker.GetInstalledVoices()) {
|
|
2410
|
+
if ($installed.VoiceInfo.Culture.Name -like ($prefix + "*")) {
|
|
2411
|
+
$voice = $installed.VoiceInfo.Name
|
|
2412
|
+
break
|
|
2413
|
+
}
|
|
2414
|
+
}
|
|
2415
|
+
# No voice for this language is a normal outcome, not an error.
|
|
2416
|
+
if ($voice -eq "") { return }
|
|
2417
|
+
$script:speaker.SpeakAsyncCancelAll()
|
|
2418
|
+
$script:speaker.SelectVoice($voice)
|
|
2419
|
+
[void]$script:speaker.SpeakAsync($Text)
|
|
2420
|
+
} catch {
|
|
2421
|
+
Write-Trace ("speak failed: " + $_.Exception.Message)
|
|
2422
|
+
}
|
|
2423
|
+
}
|
|
2424
|
+
|
|
2425
|
+
function Speak-Text([string]$Text, [string]$Lang) {
|
|
2426
|
+
if ($NoSpeak) { return }
|
|
2427
|
+
if ([string]::IsNullOrWhiteSpace($Text)) { return }
|
|
2428
|
+
if (Speak-Neural $Text $Lang) { return }
|
|
2429
|
+
Speak-Sapi $Text $Lang
|
|
2430
|
+
}
|
|
2431
|
+
function Invoke-ToolboxJson([string]$Url) {
|
|
2432
|
+
if ([string]::IsNullOrWhiteSpace($Url)) { return $null }
|
|
2433
|
+
try {
|
|
2434
|
+
$request = [System.Net.HttpWebRequest]::Create($Url)
|
|
2435
|
+
$request.Method = "GET"
|
|
2436
|
+
$request.Timeout = 8000
|
|
2437
|
+
$request.ReadWriteTimeout = 8000
|
|
2438
|
+
$response = $request.GetResponse()
|
|
2439
|
+
$reader = New-Object System.IO.StreamReader($response.GetResponseStream(), [System.Text.Encoding]::UTF8)
|
|
2440
|
+
$body = $reader.ReadToEnd()
|
|
2441
|
+
$reader.Dispose()
|
|
2442
|
+
$response.Close()
|
|
2443
|
+
return ($body | ConvertFrom-Json)
|
|
2444
|
+
} catch {
|
|
2445
|
+
Write-Trace ("review request failed: " + $_.Exception.Message)
|
|
2446
|
+
return $null
|
|
2447
|
+
}
|
|
2448
|
+
}
|
|
2449
|
+
|
|
2450
|
+
function Get-ReviewUrl([string]$Query) {
|
|
2451
|
+
$base = $script:TranslateUrl
|
|
2452
|
+
if ([string]::IsNullOrWhiteSpace($base)) { return "" }
|
|
2453
|
+
if ($base -match "/translate$") { $base = $base -replace "/translate$", "/review" }
|
|
2454
|
+
return $base + $Query
|
|
2455
|
+
}
|
|
2456
|
+
|
|
2457
|
+
$script:reviewWord = ""
|
|
2458
|
+
$script:reviewMeaning = ""
|
|
2459
|
+
$script:reviewDetail = ""
|
|
2460
|
+
$script:reviewContext = ""
|
|
2461
|
+
$script:reviewDue = 0
|
|
2462
|
+
$script:reviewTotal = 0
|
|
2463
|
+
|
|
2464
|
+
$script:reviewForm = $null
|
|
2465
|
+
|
|
2466
|
+
function New-ReviewForm {
|
|
2467
|
+
$f = New-Object QuickAsk.CardForm
|
|
2468
|
+
$f.Text = "dsh-external-toolbox-review"
|
|
2469
|
+
$f.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::None
|
|
2470
|
+
$f.StartPosition = [System.Windows.Forms.FormStartPosition]::Manual
|
|
2471
|
+
$f.TopMost = $true
|
|
2472
|
+
$f.ShowInTaskbar = $false
|
|
2473
|
+
$f.BackColor = $CARD_BG
|
|
2474
|
+
$f.Font = Fs 12
|
|
2475
|
+
$f.ClientSize = New-Object System.Drawing.Size((Sz 420), (Sz 358))
|
|
2476
|
+
|
|
2477
|
+
$head = New-Object System.Windows.Forms.Panel
|
|
2478
|
+
$head.Dock = [System.Windows.Forms.DockStyle]::Top
|
|
2479
|
+
$head.Height = (Sz 34)
|
|
2480
|
+
$head.BackColor = $BAR_BG
|
|
2481
|
+
$f.Controls.Add($head)
|
|
2482
|
+
|
|
2483
|
+
$heading = New-Object System.Windows.Forms.Label
|
|
2484
|
+
$heading.Text = (U 0x751F, 0x8BCD, 0x672C) + " " + (U 0x00B7) + " " + (U 0x590D, 0x4E60)
|
|
2485
|
+
$heading.Font = FsB 12
|
|
2486
|
+
$heading.ForeColor = $ACCENT
|
|
2487
|
+
$heading.AutoSize = $true
|
|
2488
|
+
$heading.Location = New-Object System.Drawing.Point((Sz 14), (Sz 8))
|
|
2489
|
+
$head.Controls.Add($heading)
|
|
2490
|
+
|
|
2491
|
+
$close = New-CardButton (U 0x2715) 22
|
|
2492
|
+
$close.AutoSize = $false
|
|
2493
|
+
$close.Size = New-Object System.Drawing.Size((Sz 22), (Sz 18))
|
|
2494
|
+
$close.Location = New-Object System.Drawing.Point((Sz 384), (Sz 8))
|
|
2495
|
+
$close.FlatAppearance.BorderSize = 1
|
|
2496
|
+
$close.FlatAppearance.BorderColor = $LINE
|
|
2497
|
+
$close.BackColor = $BTN_BG
|
|
2498
|
+
$close.Font = Fs 12
|
|
2499
|
+
$close.Add_Click({ $script:reviewForm.Hide() })
|
|
2500
|
+
$head.Controls.Add($close)
|
|
2501
|
+
|
|
2502
|
+
# The book itself stays one click away, but in the header so the body keeps a
|
|
2503
|
+
# single action ("show answer") that the grades then replace.
|
|
2504
|
+
$openBtn = New-CardButton (U 0x6587, 0x4EF6) 56
|
|
2505
|
+
$openBtn.AutoSize = $false
|
|
2506
|
+
$openBtn.Size = New-Object System.Drawing.Size((Sz 56), (Sz 18))
|
|
2507
|
+
$openBtn.Location = New-Object System.Drawing.Point((Sz 320), (Sz 8))
|
|
2508
|
+
$openBtn.FlatAppearance.BorderSize = 1
|
|
2509
|
+
$openBtn.FlatAppearance.BorderColor = $LINE
|
|
2510
|
+
$openBtn.BackColor = $BTN_BG
|
|
2511
|
+
$openBtn.ForeColor = $INK_DIM
|
|
2512
|
+
$openBtn.Font = Fs 12
|
|
2513
|
+
$openBtn.Add_Click({ Open-VocabBook })
|
|
2514
|
+
$head.Controls.Add($openBtn)
|
|
2515
|
+
|
|
2516
|
+
$wordLabel = New-Object System.Windows.Forms.Label
|
|
2517
|
+
$wordLabel.Text = ""
|
|
2518
|
+
$wordLabel.Font = FsB 26
|
|
2519
|
+
$wordLabel.ForeColor = $INK
|
|
2520
|
+
$wordLabel.TextAlign = [System.Drawing.ContentAlignment]::MiddleCenter
|
|
2521
|
+
$wordLabel.Location = New-Object System.Drawing.Point((Sz 16), (Sz 42))
|
|
2522
|
+
$wordLabel.Size = New-Object System.Drawing.Size((Sz 320), (Sz 48))
|
|
2523
|
+
$f.Controls.Add($wordLabel)
|
|
2524
|
+
|
|
2525
|
+
$ctxLabel = New-Object System.Windows.Forms.Label
|
|
2526
|
+
$ctxLabel.Text = ""
|
|
2527
|
+
$ctxLabel.Font = Fs 11
|
|
2528
|
+
$ctxLabel.ForeColor = $INK_DIM
|
|
2529
|
+
$ctxLabel.TextAlign = [System.Drawing.ContentAlignment]::TopLeft
|
|
2530
|
+
$ctxLabel.Location = New-Object System.Drawing.Point((Sz 16), (Sz 92))
|
|
2531
|
+
$ctxLabel.Size = New-Object System.Drawing.Size((Sz 388), (Sz 30))
|
|
2532
|
+
$f.Controls.Add($ctxLabel)
|
|
2533
|
+
|
|
2534
|
+
$sayWord = New-CardButton (U 0x25B6) 30
|
|
2535
|
+
$sayWord.AutoSize = $false
|
|
2536
|
+
$sayWord.Size = New-Object System.Drawing.Size((Sz 30), (Sz 26))
|
|
2537
|
+
$sayWord.Location = New-Object System.Drawing.Point((Sz 348), (Sz 50))
|
|
2538
|
+
$sayWord.FlatAppearance.BorderSize = 1
|
|
2539
|
+
$sayWord.FlatAppearance.BorderColor = $LINE
|
|
2540
|
+
$sayWord.BackColor = $BTN_BG
|
|
2541
|
+
$sayWord.ForeColor = $INK_DIM
|
|
2542
|
+
$sayWord.Font = Fs 12
|
|
2543
|
+
$sayWord.Add_Click({
|
|
2544
|
+
# Everything here runs inside a WinForms event: an exception would take the
|
|
2545
|
+
# whole helper down with a .NET dialog, so it never escapes.
|
|
2546
|
+
try {
|
|
2547
|
+
$text = [string]$script:reviewWord
|
|
2548
|
+
# Only speak the example once the answer is on screen; reading it out
|
|
2549
|
+
# while the card still hides it gives the meaning away.
|
|
2550
|
+
$revealed = ($null -ne $script:reviewMeaningLabel -and $script:reviewMeaningLabel.Visible)
|
|
2551
|
+
if ($revealed -and $script:reviewDetail -match "(?m)^\u4F8B\u53E5\s*[\u003A\uFF1A]\s*(.+)$") {
|
|
2552
|
+
$text = [string]$script:reviewWord + ". " + $Matches[1]
|
|
2553
|
+
}
|
|
2554
|
+
$script:lastSpoken = $text
|
|
2555
|
+
Speak-Text $text "en"
|
|
2556
|
+
} catch {
|
|
2557
|
+
Write-Trace ("say failed: " + $_.Exception.Message)
|
|
2558
|
+
}
|
|
2559
|
+
})
|
|
2560
|
+
$f.Controls.Add($sayWord)
|
|
2561
|
+
|
|
2562
|
+
$meanLabel = New-Object System.Windows.Forms.Label
|
|
2563
|
+
$meanLabel.Text = ""
|
|
2564
|
+
$meanLabel.Font = Fs 13
|
|
2565
|
+
$meanLabel.ForeColor = $OK_INK
|
|
2566
|
+
$meanLabel.TextAlign = [System.Drawing.ContentAlignment]::TopLeft
|
|
2567
|
+
$meanLabel.Location = New-Object System.Drawing.Point((Sz 16), (Sz 126))
|
|
2568
|
+
$meanLabel.Size = New-Object System.Drawing.Size((Sz 388), (Sz 112))
|
|
2569
|
+
$meanLabel.Visible = $false
|
|
2570
|
+
$f.Controls.Add($meanLabel)
|
|
2571
|
+
|
|
2572
|
+
$showBtn = New-CardButton (U 0x770B, 0x7B54, 0x6848) 96
|
|
2573
|
+
$showBtn.Location = New-Object System.Drawing.Point((Sz 16), (Sz 244))
|
|
2574
|
+
$showBtn.Size = New-Object System.Drawing.Size((Sz 96), (Sz 26))
|
|
2575
|
+
$showBtn.Font = Fs 12
|
|
2576
|
+
$showBtn.Add_Click({
|
|
2577
|
+
# The enriched entry reads better than the one-line translation; fall back
|
|
2578
|
+
# to the translation while the lookup is still running (or unavailable).
|
|
2579
|
+
$script:reviewMeaningLabel.Text = if ($script:reviewDetail -ne "") { $script:reviewDetail } else { $script:reviewMeaning }
|
|
2580
|
+
$script:reviewMeaningLabel.Visible = $true
|
|
2581
|
+
$script:reviewTranslate.Visible = $false
|
|
2582
|
+
$script:reviewGrades.Visible = $true
|
|
2583
|
+
})
|
|
2584
|
+
$f.Controls.Add($showBtn)
|
|
2585
|
+
|
|
2586
|
+
|
|
2587
|
+
|
|
2588
|
+
$gradePanel = New-Object System.Windows.Forms.Panel
|
|
2589
|
+
$gradePanel.Location = New-Object System.Drawing.Point((Sz 16), (Sz 246))
|
|
2590
|
+
$gradePanel.Size = New-Object System.Drawing.Size((Sz 388), (Sz 30))
|
|
2591
|
+
$gradePanel.Visible = $false
|
|
2592
|
+
$f.Controls.Add($gradePanel)
|
|
2593
|
+
|
|
2594
|
+
$gx = 0
|
|
2595
|
+
foreach ($spec in @(
|
|
2596
|
+
@{ Text = (U 0x5FD8, 0x4E86); Grade = "again"; Color = $ERR_INK },
|
|
2597
|
+
@{ Text = (U 0x6A21, 0x7CCA); Grade = "hard"; Color = $INK },
|
|
2598
|
+
@{ Text = (U 0x8BB0, 0x5F97); Grade = "good"; Color = $OK_INK }
|
|
2599
|
+
)) {
|
|
2600
|
+
$b = New-CardButton $spec.Text 110
|
|
2601
|
+
$b.Location = New-Object System.Drawing.Point((Sz $gx), 0)
|
|
2602
|
+
$b.Size = New-Object System.Drawing.Size((Sz 110), (Sz 28))
|
|
2603
|
+
$b.Font = Fs 12
|
|
2604
|
+
$b.ForeColor = $spec.Color
|
|
2605
|
+
$grade = $spec.Grade
|
|
2606
|
+
$b.Add_Click({
|
|
2607
|
+
Send-ReviewGrade $grade
|
|
2608
|
+
}.GetNewClosure())
|
|
2609
|
+
$gradePanel.Controls.Add($b)
|
|
2610
|
+
$gx += 126
|
|
2611
|
+
}
|
|
2612
|
+
|
|
2613
|
+
$status = New-Object System.Windows.Forms.Label
|
|
2614
|
+
$status.Text = ""
|
|
2615
|
+
$status.ForeColor = $INK_DIM
|
|
2616
|
+
$status.Font = Fs 11
|
|
2617
|
+
$status.Location = New-Object System.Drawing.Point((Sz 16), (Sz 300))
|
|
2618
|
+
$status.Size = New-Object System.Drawing.Size((Sz 388), (Sz 22))
|
|
2619
|
+
$f.Controls.Add($status)
|
|
2620
|
+
|
|
2621
|
+
$f.MakeDraggable($head)
|
|
2622
|
+
$f.MakeDraggable($heading)
|
|
2623
|
+
|
|
2624
|
+
$script:reviewWordLabel = $wordLabel
|
|
2625
|
+
$script:reviewCtxLabel = $ctxLabel
|
|
2626
|
+
$script:reviewSay = $sayWord
|
|
2627
|
+
$script:reviewMeaningLabel = $meanLabel
|
|
2628
|
+
$script:reviewTranslate = $showBtn
|
|
2629
|
+
$script:reviewGrades = $gradePanel
|
|
2630
|
+
$script:reviewStatus = $status
|
|
2631
|
+
return $f
|
|
2632
|
+
}
|
|
2633
|
+
function Show-Review {
|
|
2634
|
+
if ($null -eq $script:reviewForm) {
|
|
2635
|
+
$script:reviewForm = New-ReviewForm
|
|
2636
|
+
# Centre it on the screen that holds the mouse, like the capture card.
|
|
2637
|
+
$cp = New-Object QuickAsk.POINT
|
|
2638
|
+
[void][QuickAsk.Native]::GetCursorPos([ref]$cp)
|
|
2639
|
+
$wa = [System.Windows.Forms.Screen]::FromPoint((New-Object System.Drawing.Point($cp.X, $cp.Y))).WorkingArea
|
|
2640
|
+
$x = [int](($wa.Width - $script:reviewForm.Width) / 2 + $wa.Left)
|
|
2641
|
+
$y = [int](($wa.Height - $script:reviewForm.Height) / 2 + $wa.Top)
|
|
2642
|
+
$script:reviewForm.Location = New-Object System.Drawing.Point($x, $y)
|
|
2643
|
+
}
|
|
2644
|
+
$script:reviewTranslate.Visible = $false
|
|
2645
|
+
$script:reviewGrades.Visible = $false
|
|
2646
|
+
$script:reviewMeaningLabel.Visible = $false
|
|
2647
|
+
$script:reviewMeaningLabel.Text = ""
|
|
2648
|
+
$script:reviewWordLabel.Text = "..."
|
|
2649
|
+
$script:reviewStatus.Text = ""
|
|
2650
|
+
$script:reviewForm.Show()
|
|
2651
|
+
$script:reviewForm.Refresh()
|
|
2652
|
+
Update-ReviewCard
|
|
2653
|
+
}
|
|
2654
|
+
|
|
2655
|
+
function Update-ReviewCard {
|
|
2656
|
+
$data = Invoke-ToolboxJson (Get-ReviewUrl "")
|
|
2657
|
+
if ($null -eq $data -or $data.ok -ne $true) {
|
|
2658
|
+
$script:reviewWordLabel.Text = (U 0x8BFB, 0x53D6, 0x5931, 0x8D25)
|
|
2659
|
+
return
|
|
2660
|
+
}
|
|
2661
|
+
$script:reviewDue = [int]$data.due
|
|
2662
|
+
$script:reviewTotal = [int]$data.total
|
|
2663
|
+
$item = $data.item
|
|
2664
|
+
if ($null -eq $item) {
|
|
2665
|
+
$script:reviewWordLabel.Text = (U 0x6CA1, 0x6709, 0x8981, 0x590D, 0x4E60, 0x7684, 0x5355, 0x8BCD)
|
|
2666
|
+
$script:reviewStatus.Text = (U 0x5171) + " " + [string]$script:reviewTotal + " " + (U 0x4E2A)
|
|
2667
|
+
$script:reviewTranslate.Visible = $false
|
|
2668
|
+
$script:reviewGrades.Visible = $false
|
|
2669
|
+
$script:reviewMeaningLabel.Visible = $false
|
|
2670
|
+
$script:reviewMeaningLabel.Text = ""
|
|
2671
|
+
$script:reviewCtxLabel.Text = ""
|
|
2672
|
+
return
|
|
2673
|
+
}
|
|
2674
|
+
$script:reviewWord = [string]$item.word
|
|
2675
|
+
$script:reviewMeaning = [string]$item.translation
|
|
2676
|
+
$script:reviewDetail = [string]$item.detail
|
|
2677
|
+
$script:reviewContext = [string]$item.context
|
|
2678
|
+
# A new card starts from the question side again: the previous answer must
|
|
2679
|
+
# not linger and spoil the recall.
|
|
2680
|
+
$script:reviewMeaningLabel.Text = ""
|
|
2681
|
+
$script:reviewMeaningLabel.Visible = $false
|
|
2682
|
+
$script:reviewWordLabel.Text = $script:reviewWord
|
|
2683
|
+
$script:reviewCtxLabel.Text = $script:reviewContext
|
|
2684
|
+
$dot = [string][char]0x00B7
|
|
2685
|
+
$script:reviewStatus.Text = (U 0x4ECA, 0x5929, 0x8FD8, 0x6709) + " " + [string]$script:reviewDue + " " + (U 0x4E2A) + " " + $dot + " " + (U 0x5171) + " " + [string]$script:reviewTotal + " " + (U 0x4E2A)
|
|
2686
|
+
$script:reviewTranslate.Visible = $true
|
|
2687
|
+
$script:reviewGrades.Visible = $false
|
|
2688
|
+
}
|
|
2689
|
+
|
|
2690
|
+
function Send-ReviewGrade([string]$Grade) {
|
|
2691
|
+
if ($script:reviewWord -eq "") { return }
|
|
2692
|
+
$q = "?word=" + [uri]::EscapeDataString($script:reviewWord) + "&grade=" + [uri]::EscapeDataString($Grade)
|
|
2693
|
+
[void](Invoke-ToolboxJson (Get-ReviewUrl $q))
|
|
2694
|
+
Update-ReviewCard
|
|
2695
|
+
}
|
|
2696
|
+
function Open-VocabBook {
|
|
2697
|
+
$dir = Join-Path $env:APPDATA "dsh-external-toolbox"
|
|
2698
|
+
$book = Join-Path $dir ((U 0x751F, 0x8BCD, 0x672C) + ".md")
|
|
2699
|
+
if (Test-Path -LiteralPath $book) {
|
|
2700
|
+
# .md has no handler on plenty of machines, so go straight to notepad:
|
|
2701
|
+
# predictable, and it is always installed.
|
|
2702
|
+
try {
|
|
2703
|
+
Start-Process -FilePath "notepad.exe" -ArgumentList ('"' + $book + '"') | Out-Null
|
|
2704
|
+
return
|
|
2705
|
+
} catch {
|
|
2706
|
+
Write-Trace ("open vocab failed: " + $_.Exception.Message)
|
|
2707
|
+
}
|
|
2708
|
+
try {
|
|
2709
|
+
Start-Process -FilePath "explorer.exe" -ArgumentList ('/select,"' + $book + '"') | Out-Null
|
|
2710
|
+
return
|
|
2711
|
+
} catch {
|
|
2712
|
+
Write-Trace ("reveal vocab failed: " + $_.Exception.Message)
|
|
2713
|
+
}
|
|
2714
|
+
}
|
|
2715
|
+
if ($null -ne $script:status) {
|
|
2716
|
+
Set-CardStatus (U 0x8FD8, 0x6CA1, 0x6709, 0x6536, 0x85CF, 0x8FC7, 0x5355, 0x8BCD) $INK_DIM
|
|
2717
|
+
}
|
|
2718
|
+
}
|
|
2719
|
+
function Start-Task {
|
|
2720
|
+
param([string]$Task = "translate")
|
|
2721
|
+
if ($script:busy) { return }
|
|
2722
|
+
if ([string]::IsNullOrEmpty($script:lastId)) { return }
|
|
2723
|
+
$url = Get-TaskUrl $Task
|
|
2724
|
+
if ($url -eq "") {
|
|
2725
|
+
Show-CardTranslation $T_NO_SERVICE $ERR_INK
|
|
2726
|
+
return
|
|
2727
|
+
}
|
|
2728
|
+
|
|
2729
|
+
$script:activeTask = $Task
|
|
2730
|
+
if ($Task -eq "explain") {
|
|
2731
|
+
$script:activeBtn = $script:btnExplain
|
|
2732
|
+
$script:activeLabel = $T_EXPLAIN
|
|
2733
|
+
$busyText = $T_EXPLAINING
|
|
2734
|
+
} else {
|
|
2735
|
+
$script:activeBtn = $script:btnTranslate
|
|
2736
|
+
$script:activeLabel = $T_TRANSLATE
|
|
2737
|
+
$busyText = $T_TRANSLATING
|
|
2738
|
+
}
|
|
2739
|
+
|
|
2740
|
+
$script:busy = $true
|
|
2741
|
+
$script:btnTranslate.Enabled = $false
|
|
2742
|
+
$script:btnExplain.Enabled = $false
|
|
2743
|
+
$script:activeBtn.Text = $busyText
|
|
2744
|
+
Show-CardTranslation $busyText $INK_DIM
|
|
2745
|
+
Set-CardStatus "" $INK_DIM
|
|
2746
|
+
|
|
2747
|
+
$script:runner = [powershell]::Create()
|
|
2748
|
+
[void]$script:runner.AddScript({
|
|
2749
|
+
param($address)
|
|
2750
|
+
try {
|
|
2751
|
+
$request = [System.Net.HttpWebRequest]::Create($address)
|
|
2752
|
+
$request.Method = "GET"
|
|
2753
|
+
$request.Timeout = 90000
|
|
2754
|
+
$request.ReadWriteTimeout = 90000
|
|
2755
|
+
$response = $request.GetResponse()
|
|
2756
|
+
try {
|
|
2757
|
+
$stream = $response.GetResponseStream()
|
|
2758
|
+
$reader = New-Object System.IO.StreamReader($stream, [System.Text.Encoding]::UTF8)
|
|
2759
|
+
$body = $reader.ReadToEnd()
|
|
2760
|
+
$reader.Dispose()
|
|
2761
|
+
return $body
|
|
2762
|
+
} finally { $response.Close() }
|
|
2763
|
+
} catch {
|
|
2764
|
+
return "@@ERROR@@" + $_.Exception.Message
|
|
2765
|
+
}
|
|
2766
|
+
}).AddArgument($url)
|
|
2767
|
+
$script:async = $script:runner.BeginInvoke()
|
|
2768
|
+
$script:poll.Start()
|
|
2769
|
+
}
|
|
2770
|
+
|
|
2771
|
+
function Poll-Translate {
|
|
2772
|
+
if ($null -eq $script:async -or -not $script:async.IsCompleted) { return }
|
|
2773
|
+
$script:poll.Stop()
|
|
2774
|
+
$body = ""
|
|
2775
|
+
try {
|
|
2776
|
+
$out = $script:runner.EndInvoke($script:async)
|
|
2777
|
+
$body = (@($out) | ForEach-Object { "$_" }) -join ""
|
|
2778
|
+
} catch {
|
|
2779
|
+
$body = "@@ERROR@@" + $_.Exception.Message
|
|
2780
|
+
}
|
|
2781
|
+
try { $script:runner.Dispose() } catch { }
|
|
2782
|
+
$script:runner = $null
|
|
2783
|
+
$script:async = $null
|
|
2784
|
+
$script:busy = $false
|
|
2785
|
+
$script:btnTranslate.Enabled = $true
|
|
2786
|
+
$script:btnExplain.Enabled = $true
|
|
2787
|
+
if ($null -ne $script:activeBtn) {
|
|
2788
|
+
$script:activeBtn.Text = $script:activeLabel
|
|
2789
|
+
} else {
|
|
2790
|
+
$script:btnTranslate.Text = $T_TRANSLATE
|
|
2791
|
+
}
|
|
2792
|
+
|
|
2793
|
+
if ($body.StartsWith("@@ERROR@@")) {
|
|
2794
|
+
Show-CardTranslation ($T_FAILED + ": " + $body.Substring(9)) $ERR_INK
|
|
2795
|
+
return
|
|
2796
|
+
}
|
|
2797
|
+
|
|
2798
|
+
$parsed = $null
|
|
2799
|
+
try { $parsed = $body | ConvertFrom-Json } catch { $parsed = $null }
|
|
2800
|
+
if ($null -eq $parsed) {
|
|
2801
|
+
Show-CardTranslation ($T_FAILED + ": bad response") $ERR_INK
|
|
2802
|
+
return
|
|
2803
|
+
}
|
|
2804
|
+
if ($parsed.ok -eq $true -and -not [string]::IsNullOrWhiteSpace([string]$parsed.text)) {
|
|
2805
|
+
Show-CardTranslation ([string]$parsed.text) $OK_INK
|
|
2806
|
+
# Reading the result aloud belongs to translation, not to a separate action.
|
|
2807
|
+
if ($script:activeTask -eq "translate") {
|
|
2808
|
+
if ($null -ne $parsed.target -and [string]$parsed.target -ne "") { $script:dstLang = [string]$parsed.target }
|
|
2809
|
+
}
|
|
2810
|
+
# In auto mode the host decides the direction, so show what it picked.
|
|
2811
|
+
if ($parsed.auto -eq $true -and $null -ne $parsed.target -and "$($parsed.target)" -ne "") {
|
|
2812
|
+
Set-CardStatus ("-> " + ([string]$parsed.target).ToUpper()) $INK_DIM
|
|
2813
|
+
} else {
|
|
2814
|
+
Set-CardStatus "" $INK_DIM
|
|
2815
|
+
}
|
|
2816
|
+
} else {
|
|
2817
|
+
$detail = "unknown"
|
|
2818
|
+
if ($null -ne $parsed.error) { $detail = [string]$parsed.error }
|
|
2819
|
+
Show-CardTranslation ($T_FAILED + ": " + $detail) $ERR_INK
|
|
2820
|
+
}
|
|
2821
|
+
}
|
|
2822
|
+
|
|
2823
|
+
# ---------------------------------------------------------------- hotkey parsing
|
|
2824
|
+
|
|
2825
|
+
function ConvertTo-Hotkey([string]$Spec) {
|
|
2826
|
+
$mods = 0
|
|
2827
|
+
$key = $null
|
|
2828
|
+
foreach ($part in ($Spec -split "\+")) {
|
|
2829
|
+
$p = $part.Trim()
|
|
2830
|
+
switch -Regex ($p) {
|
|
2831
|
+
'^(ctrl|control)$' { $mods = $mods -bor 0x2; continue }
|
|
2832
|
+
'^(alt)$' { $mods = $mods -bor 0x1; continue }
|
|
2833
|
+
'^(shift)$' { $mods = $mods -bor 0x4; continue }
|
|
2834
|
+
'^(win|meta)$' { $mods = $mods -bor 0x8; continue }
|
|
2835
|
+
default { $key = $p.ToUpper() }
|
|
2836
|
+
}
|
|
2837
|
+
}
|
|
2838
|
+
if ($null -eq $key) { throw "hotkey has no key: $Spec" }
|
|
2839
|
+
$code = [int][char]$key
|
|
2840
|
+
if ($key.Length -gt 1) {
|
|
2841
|
+
$map = @{ "F1"=112; "F2"=113; "F3"=114; "F4"=115; "F5"=116; "F6"=117; "F7"=118; "F8"=119;
|
|
2842
|
+
"F9"=120; "F10"=121; "F11"=122; "F12"=123; "SPACE"=32; "INSERT"=45; "DELETE"=46;
|
|
2843
|
+
"HOME"=36; "END"=35; "PGUP"=33; "PGDN"=34 }
|
|
2844
|
+
if (-not $map.ContainsKey($key)) { throw "unsupported hotkey key: $key" }
|
|
2845
|
+
$code = $map[$key]
|
|
2846
|
+
}
|
|
2847
|
+
return @{ mods = $mods; key = $code }
|
|
2848
|
+
}
|
|
2849
|
+
|
|
2850
|
+
# ---------------------------------------------------------------- self test
|
|
2851
|
+
|
|
2852
|
+
|
|
2853
|
+
if ($SurfaceTest) {
|
|
2854
|
+
# Which clipboard-fallback guard fires for whatever is in front right now.
|
|
2855
|
+
$fgCls = Get-ForegroundClassName
|
|
2856
|
+
$visible = ($null -ne $script:reviewForm -and $script:reviewForm.Visible)
|
|
2857
|
+
Write-Json @{
|
|
2858
|
+
type = "surface"
|
|
2859
|
+
proc = (Get-ForegroundProcessName)
|
|
2860
|
+
class = $fgCls
|
|
2861
|
+
console = (Test-ConsoleForeground)
|
|
2862
|
+
keyboard = (Test-KeyboardSurface)
|
|
2863
|
+
cooldown = ((Get-Date) -lt $script:clipBlockedUntil)
|
|
2864
|
+
selfFocus = $visible
|
|
2865
|
+
}
|
|
2866
|
+
exit 0
|
|
2867
|
+
}
|
|
2868
|
+
|
|
2869
|
+
if ($SelfTest) {
|
|
2870
|
+
$form = New-Object System.Windows.Forms.Form
|
|
2871
|
+
$form.Text = "external-toolbox-selftest"
|
|
2872
|
+
$form.Size = New-Object System.Drawing.Size(320, 160)
|
|
2873
|
+
$form.StartPosition = "Manual"
|
|
2874
|
+
$form.Location = New-Object System.Drawing.Point(-4000, -4000)
|
|
2875
|
+
$form.TopMost = $true
|
|
2876
|
+
$box = New-Object System.Windows.Forms.TextBox
|
|
2877
|
+
$box.Multiline = $true
|
|
2878
|
+
$box.Dock = "Fill"
|
|
2879
|
+
$box.Text = "The quick brown fox jumps over the lazy dog. Hello, world."
|
|
2880
|
+
$form.Controls.Add($box)
|
|
2881
|
+
$script:timer = New-Object System.Windows.Forms.Timer
|
|
2882
|
+
$script:timer.Interval = 500
|
|
2883
|
+
$script:timer.Add_Tick({
|
|
2884
|
+
$script:timer.Stop()
|
|
2885
|
+
try {
|
|
2886
|
+
$result = Invoke-Capture
|
|
2887
|
+
if ($null -eq $result) { Write-Json @{ type = "error"; message = "selftest captured nothing" } }
|
|
2888
|
+
else { Write-Json $result }
|
|
2889
|
+
} catch {
|
|
2890
|
+
Write-Json @{ type = "error"; message = $_.Exception.Message }
|
|
2891
|
+
}
|
|
2892
|
+
$form.Close()
|
|
2893
|
+
})
|
|
2894
|
+
$form.Add_Shown({
|
|
2895
|
+
$form.Activate()
|
|
2896
|
+
$box.Focus()
|
|
2897
|
+
$box.SelectAll()
|
|
2898
|
+
$script:timer.Start()
|
|
2899
|
+
})
|
|
2900
|
+
[void]$form.ShowDialog()
|
|
2901
|
+
exit 0
|
|
2902
|
+
}
|
|
2903
|
+
|
|
2904
|
+
# ---------------------------------------------------------------- auto test
|
|
2905
|
+
|
|
2906
|
+
if ($AutoTest) {
|
|
2907
|
+
$CaptureSelf = $true
|
|
2908
|
+
New-Card
|
|
2909
|
+
|
|
2910
|
+
# The hook needs a message loop, which this branch has; whether a global hook
|
|
2911
|
+
# installs at all is the first thing worth knowing on a locked down machine.
|
|
2912
|
+
$script:mouseWatcher = New-Object QuickAsk.MouseWatcher
|
|
2913
|
+
$hookOk = [bool]$script:mouseWatcher.Start()
|
|
2914
|
+
|
|
2915
|
+
$script:autoCount = 0
|
|
2916
|
+
$script:autoSeen = 0
|
|
2917
|
+
$probeText = "Selected text in another application: the quick brown fox jumps over the lazy dog."
|
|
2918
|
+
$script:probeTimer = New-Object System.Windows.Forms.Timer
|
|
2919
|
+
$script:probeTimer.Interval = 800
|
|
2920
|
+
$script:probeTimer.Add_Tick({
|
|
2921
|
+
$script:probeTimer.Stop()
|
|
2922
|
+
Show-AutoCapture $probeText
|
|
2923
|
+
# A selection pops the pill, not the card, so that is what gets checked here.
|
|
2924
|
+
$firstVisible = ($null -ne $script:bar) -and $script:bar.Visible
|
|
2925
|
+
$firstChars = if ($null -ne $script:barCapture) { ([string]$script:barCapture.text).Length } else { 0 }
|
|
2926
|
+
# Same text again must not re-open or re-print the card.
|
|
2927
|
+
$beforeSeq = $script:lastId
|
|
2928
|
+
Show-AutoCapture $probeText
|
|
2929
|
+
$againVisible = ($null -ne $script:bar) -and $script:bar.Visible
|
|
2930
|
+
Write-Json @{
|
|
2931
|
+
type = "autotest"
|
|
2932
|
+
hook = $hookOk
|
|
2933
|
+
barVisible = $firstVisible
|
|
2934
|
+
cardVisible = (($null -ne $script:card) -and $script:card.Visible)
|
|
2935
|
+
srcChars = $firstChars
|
|
2936
|
+
sameAsSelection = ($script:autoShown -eq $probeText)
|
|
2937
|
+
dedupe = ($beforeSeq -eq $script:lastId) -and $againVisible
|
|
2938
|
+
}
|
|
2939
|
+
Hide-Bar
|
|
2940
|
+
Hide-Card
|
|
2941
|
+
$script:mouseWatcher.Stop()
|
|
2942
|
+
[System.Windows.Forms.Application]::Exit()
|
|
2943
|
+
})
|
|
2944
|
+
$script:probeTimer.Start()
|
|
2945
|
+
[System.Windows.Forms.Application]::Run()
|
|
2946
|
+
exit 0
|
|
2947
|
+
}
|
|
2948
|
+
# ---------------------------------------------------------------- card test
|
|
2949
|
+
|
|
2950
|
+
if ($DragTest) {
|
|
2951
|
+
New-Card
|
|
2952
|
+
$script:srcText = "drag test source"
|
|
2953
|
+
$script:txtSrc.Text = $script:srcText
|
|
2954
|
+
$script:card.Location = New-Object System.Drawing.Point(120, 120)
|
|
2955
|
+
$script:card.Show()
|
|
2956
|
+
for ($i = 0; $i -lt 10; $i++) { [System.Windows.Forms.Application]::DoEvents(); Start-Sleep -Milliseconds 40 }
|
|
2957
|
+
$before = $script:card.Location.ToString()
|
|
2958
|
+
Write-Json @{ type = "dragtest"; stage = "shown"; bounds = $script:card.Bounds.ToString() }
|
|
2959
|
+
$lp = [IntPtr]((10 -shl 16) -bor 60)
|
|
2960
|
+
[void][QuickAsk.Native]::PostMessage($script:head.Handle, 0x0201, [IntPtr]1, $lp)
|
|
2961
|
+
for ($i = 0; $i -lt 12; $i++) { [System.Windows.Forms.Application]::DoEvents(); Start-Sleep -Milliseconds 40 }
|
|
2962
|
+
[void][QuickAsk.Native]::PostMessage($script:card.Handle, 0x0202, [IntPtr]0, $lp)
|
|
2963
|
+
for ($i = 0; $i -lt 12; $i++) { [System.Windows.Forms.Application]::DoEvents(); Start-Sleep -Milliseconds 40 }
|
|
2964
|
+
Write-Json @{ type = "dragtest"; stage = "done"; before = $before; after = $script:card.Location.ToString(); alive = $script:card.Visible }
|
|
2965
|
+
$script:card.Close()
|
|
2966
|
+
exit 0
|
|
2967
|
+
}
|
|
2968
|
+
|
|
2969
|
+
if ($HideTest) {
|
|
2970
|
+
# Same story as -MinimizeTest, but the window is hidden (tray-like) instead
|
|
2971
|
+
# of iconic: that is the case the title lookup used to miss entirely.
|
|
2972
|
+
$hwnd = Get-HostWindow
|
|
2973
|
+
Write-Json @{ type = "hide"; hwnd = [string]$hwnd }
|
|
2974
|
+
if ($hwnd -ne [IntPtr]::Zero) { [void][QuickAsk.Native]::ShowWindow($hwnd, 0) }
|
|
2975
|
+
Start-Sleep -Milliseconds 600
|
|
2976
|
+
Write-Json @{ type = "hide"; vis = [string]([QuickAsk.Native]::IsWindowVisible($hwnd)); title_hit = [string]([QuickAsk.Native]::FindWindowByTitle("DeepSeek Harness")); proc_hit = [string]([QuickAsk.Native]::FindWindowByProcessName("DeepSeek Harness")) }
|
|
2977
|
+
$found = Get-HostWindow
|
|
2978
|
+
Write-Json @{ type = "hide"; found = [string]$found }
|
|
2979
|
+
Show-HostWindow
|
|
2980
|
+
Start-Sleep -Milliseconds 600
|
|
2981
|
+
Write-Json @{ type = "hide"; ok = ([QuickAsk.Native]::GetForegroundWindow() -eq $hwnd); vis = [string]([QuickAsk.Native]::IsWindowVisible($hwnd)); after = [string]([QuickAsk.Native]::GetForegroundWindow()) }
|
|
2982
|
+
exit 0
|
|
2983
|
+
}
|
|
2984
|
+
|
|
2985
|
+
if ($MinimizeTest) {
|
|
2986
|
+
# Simulates the "DSH is in the background" case that has been failing.
|
|
2987
|
+
$hwnd = Get-HostWindow
|
|
2988
|
+
Write-Json @{ type = "minimize"; hwnd = [string]$hwnd; iconic_before = [string]([QuickAsk.Native]::IsIconic($hwnd)) }
|
|
2989
|
+
if ($hwnd -ne [IntPtr]::Zero) { [void][QuickAsk.Native]::ShowWindow($hwnd, 6) }
|
|
2990
|
+
Start-Sleep -Milliseconds 600
|
|
2991
|
+
Write-Json @{ type = "minimize"; iconic_after = [string]([QuickAsk.Native]::IsIconic($hwnd)); fg = [string]([QuickAsk.Native]::GetForegroundWindow()) }
|
|
2992
|
+
Show-HostWindow
|
|
2993
|
+
Start-Sleep -Milliseconds 600
|
|
2994
|
+
Write-Json @{ type = "minimize"; ok = ([QuickAsk.Native]::GetForegroundWindow() -eq $hwnd); after = [string]([QuickAsk.Native]::GetForegroundWindow()); iconic = [string]([QuickAsk.Native]::IsIconic($hwnd)) }
|
|
2995
|
+
exit 0
|
|
2996
|
+
}
|
|
2997
|
+
|
|
2998
|
+
if ($ActivateTest -or $ProbeWindows) {
|
|
2999
|
+
foreach ($line in [QuickAsk.Native]::DescribeWindows("DeepSeek")) { Write-Json @{ type = "window"; line = $line } }
|
|
3000
|
+
foreach ($line in [QuickAsk.Native]::DescribeWindows("DeepseekHaeness")) { Write-Json @{ type = "window"; line = $line } }
|
|
3001
|
+
if ($ProbeWindows) { exit 0 }
|
|
3002
|
+
$hwnd = Get-HostWindow
|
|
3003
|
+
Write-Json @{ type = "activate"; hwnd = [string]$hwnd; before = [string]([QuickAsk.Native]::GetForegroundWindow()) }
|
|
3004
|
+
Show-HostWindow
|
|
3005
|
+
# Activation runs in a background runspace (the dsh://open handoff alone takes
|
|
3006
|
+
# the better part of a second), so keep this process alive long enough to see
|
|
3007
|
+
# the outcome instead of reporting a race.
|
|
3008
|
+
for ($i = 0; $i -lt 12; $i++) {
|
|
3009
|
+
Start-Sleep -Milliseconds 400
|
|
3010
|
+
if (([QuickAsk.Native]::IsWindowVisible($hwnd)) -and ([QuickAsk.Native]::GetForegroundWindow() -eq $hwnd)) { break }
|
|
3011
|
+
}
|
|
3012
|
+
Write-Json @{ type = "activate"; hwnd = [string]$hwnd; after = [string]([QuickAsk.Native]::GetForegroundWindow()); ok = ([QuickAsk.Native]::GetForegroundWindow() -eq $hwnd); visible = [QuickAsk.Native]::IsWindowVisible($hwnd) }
|
|
3013
|
+
# The background runspace still has to paint and photograph; give it room.
|
|
3014
|
+
Start-Sleep -Milliseconds 1600
|
|
3015
|
+
exit 0
|
|
3016
|
+
}
|
|
3017
|
+
|
|
3018
|
+
if ($BarTest) {
|
|
3019
|
+
$captured = @{ type = "selection"; id = "bartest"; text = "The quick brown fox jumps over the lazy dog."; via = "auto"; chars = 44 }
|
|
3020
|
+
Show-Bar $captured
|
|
3021
|
+
$script:bar.Location = New-Object System.Drawing.Point(200, 200)
|
|
3022
|
+
for ($i = 0; $i -lt 15; $i++) { [System.Windows.Forms.Application]::DoEvents(); Start-Sleep -Milliseconds 40 }
|
|
3023
|
+
if ($ShotPath -ne "") {
|
|
3024
|
+
$script:bar.Refresh()
|
|
3025
|
+
[System.Windows.Forms.Application]::DoEvents()
|
|
3026
|
+
Start-Sleep -Milliseconds 120
|
|
3027
|
+
$rect = $script:bar.Bounds
|
|
3028
|
+
$bmp = New-Object System.Drawing.Bitmap -ArgumentList $rect.Width, $rect.Height
|
|
3029
|
+
$g = [System.Drawing.Graphics]::FromImage($bmp)
|
|
3030
|
+
$g.CopyFromScreen($rect.Location, [System.Drawing.Point]::Empty, $rect.Size)
|
|
3031
|
+
$g.Dispose()
|
|
3032
|
+
$bmp.Save($ShotPath, [System.Drawing.Imaging.ImageFormat]::Png)
|
|
3033
|
+
$bmp.Dispose()
|
|
3034
|
+
Write-Json @{ type = "shot"; path = $ShotPath; size = $rect.Size.ToString() }
|
|
3035
|
+
}
|
|
3036
|
+
$script:bar.Close()
|
|
3037
|
+
exit 0
|
|
3038
|
+
}
|
|
3039
|
+
|
|
3040
|
+
if ($ReviewTest) {
|
|
3041
|
+
Show-Review
|
|
3042
|
+
$script:reviewForm.Location = New-Object System.Drawing.Point(200, 200)
|
|
3043
|
+
if ($ReviewAnswer) {
|
|
3044
|
+
for ($i = 0; $i -lt 10; $i++) { [System.Windows.Forms.Application]::DoEvents(); Start-Sleep -Milliseconds 40 }
|
|
3045
|
+
$script:reviewTranslate.PerformClick()
|
|
3046
|
+
}
|
|
3047
|
+
if ($ReviewSpeak) {
|
|
3048
|
+
for ($i = 0; $i -lt 10; $i++) { [System.Windows.Forms.Application]::DoEvents(); Start-Sleep -Milliseconds 40 }
|
|
3049
|
+
$script:reviewSay.PerformClick()
|
|
3050
|
+
Write-Json @{ type = "spoke"; word = $script:reviewWord; revealed = [bool]$script:reviewMeaningLabel.Visible; chars = ([string]$script:lastSpoken).Length; hasExample = ($script:reviewDetail -match "\u4F8B\u53E5") }
|
|
3051
|
+
}
|
|
3052
|
+
if ($ReviewGrade -ne "") {
|
|
3053
|
+
for ($i = 0; $i -lt 10; $i++) { [System.Windows.Forms.Application]::DoEvents(); Start-Sleep -Milliseconds 40 }
|
|
3054
|
+
Send-ReviewGrade $ReviewGrade
|
|
3055
|
+
}
|
|
3056
|
+
for ($i = 0; $i -lt 20; $i++) { [System.Windows.Forms.Application]::DoEvents(); Start-Sleep -Milliseconds 40 }
|
|
3057
|
+
if ($ShotPath -ne "") {
|
|
3058
|
+
$script:reviewForm.Refresh()
|
|
3059
|
+
[System.Windows.Forms.Application]::DoEvents()
|
|
3060
|
+
Start-Sleep -Milliseconds 150
|
|
3061
|
+
$rect = $script:reviewForm.Bounds
|
|
3062
|
+
$bmp = New-Object System.Drawing.Bitmap -ArgumentList $rect.Width, $rect.Height
|
|
3063
|
+
$g = [System.Drawing.Graphics]::FromImage($bmp)
|
|
3064
|
+
$g.CopyFromScreen($rect.Location, [System.Drawing.Point]::Empty, $rect.Size)
|
|
3065
|
+
$g.Dispose()
|
|
3066
|
+
$bmp.Save($ShotPath, [System.Drawing.Imaging.ImageFormat]::Png)
|
|
3067
|
+
$bmp.Dispose()
|
|
3068
|
+
Write-Json @{ type = "shot"; path = $ShotPath; word = $script:reviewWord; due = $script:reviewDue; total = $script:reviewTotal }
|
|
3069
|
+
}
|
|
3070
|
+
$script:reviewForm.Close()
|
|
3071
|
+
exit 0
|
|
3072
|
+
}
|
|
3073
|
+
if ($CardTest) {
|
|
3074
|
+
New-Card
|
|
3075
|
+
$script:lastId = "cardtest"
|
|
3076
|
+
$script:srcText = "The card shows the captured selection here. It keeps the original layout, including line breaks and empty lines, so quoting still reads like the source."
|
|
3077
|
+
$script:txtSrc.Text = $script:srcText
|
|
3078
|
+
Hide-CardTranslation
|
|
3079
|
+
if (-not [string]::IsNullOrWhiteSpace($TranslateUrl)) { Start-Task $Task }
|
|
3080
|
+
$script:card.Location = New-Object System.Drawing.Point(120, 120)
|
|
3081
|
+
$script:card.Show()
|
|
3082
|
+
$script:card.BringToFront()
|
|
3083
|
+
$script:card.Activate()
|
|
3084
|
+
for ($i = 0; $i -lt 20; $i++) {
|
|
3085
|
+
[System.Windows.Forms.Application]::DoEvents()
|
|
3086
|
+
Start-Sleep -Milliseconds 40
|
|
3087
|
+
}
|
|
3088
|
+
if (-not [string]::IsNullOrWhiteSpace($TranslateUrl)) {
|
|
3089
|
+
for ($i = 0; $i -lt 300 -and $script:busy; $i++) {
|
|
3090
|
+
[System.Windows.Forms.Application]::DoEvents()
|
|
3091
|
+
Start-Sleep -Milliseconds 50
|
|
3092
|
+
}
|
|
3093
|
+
$script:card.BringToFront()
|
|
3094
|
+
[System.Windows.Forms.Application]::DoEvents()
|
|
3095
|
+
}
|
|
3096
|
+
if ($LangTest) {
|
|
3097
|
+
Show-LangMenu
|
|
3098
|
+
for ($i = 0; $i -lt 10; $i++) { [System.Windows.Forms.Application]::DoEvents(); Start-Sleep -Milliseconds 40 }
|
|
3099
|
+
}
|
|
3100
|
+
if ($ShotPath -ne "") {
|
|
3101
|
+
$script:card.Refresh()
|
|
3102
|
+
[System.Windows.Forms.Application]::DoEvents()
|
|
3103
|
+
Start-Sleep -Milliseconds 120
|
|
3104
|
+
$rect = $script:card.Bounds
|
|
3105
|
+
$bmp = New-Object System.Drawing.Bitmap -ArgumentList $rect.Width, $rect.Height
|
|
3106
|
+
$g = [System.Drawing.Graphics]::FromImage($bmp)
|
|
3107
|
+
# PrintWindow renders the window itself, so the shot is right even when
|
|
3108
|
+
# another always-on-top app happens to overlap ours on screen.
|
|
3109
|
+
$hdc = $g.GetHdc()
|
|
3110
|
+
try { [void][QuickAsk.Native]::PrintWindow($script:card.Handle, $hdc, 2) } finally { $g.ReleaseHdc($hdc) }
|
|
3111
|
+
$g.Dispose()
|
|
3112
|
+
$bmp.Save($ShotPath, [System.Drawing.Imaging.ImageFormat]::Png)
|
|
3113
|
+
$bmp.Dispose()
|
|
3114
|
+
if ($LangTest -and $null -ne $script:langMenu -and $script:langMenu.Visible) {
|
|
3115
|
+
$mr = $script:langMenu.Bounds
|
|
3116
|
+
$mb = New-Object System.Drawing.Bitmap -ArgumentList $mr.Width, $mr.Height
|
|
3117
|
+
$mg = [System.Drawing.Graphics]::FromImage($mb)
|
|
3118
|
+
$mhdc = $mg.GetHdc()
|
|
3119
|
+
try { [void][QuickAsk.Native]::PrintWindow($script:langMenu.Handle, $mhdc, 2) } finally { $mg.ReleaseHdc($mhdc) }
|
|
3120
|
+
$mg.Dispose()
|
|
3121
|
+
$mb.Save(($ShotPath + ".menu.png"), [System.Drawing.Imaging.ImageFormat]::Png)
|
|
3122
|
+
$mb.Dispose()
|
|
3123
|
+
}
|
|
3124
|
+
Write-Json @{ type = "shot"; path = $ShotPath; copy = $script:btnCopy.Text; dst = $script:dstText; target = $script:lang; chip = $script:btnLang.Text }
|
|
3125
|
+
$geo = (Get-ScrollGeometry $script:txtDst $script:sbDst)
|
|
3126
|
+
Write-Json @{ type = "lane"; over = $geo.over; total = $geo.total; visible = $geo.visible; height = $geo.height; top = $geo.top }
|
|
3127
|
+
[void][QuickAsk.Native]::SendMessage($script:txtDst.Handle, 0x00B6, [IntPtr]::Zero, [IntPtr]5)
|
|
3128
|
+
Update-AllScrollbars
|
|
3129
|
+
[System.Windows.Forms.Application]::DoEvents()
|
|
3130
|
+
$geo2 = (Get-ScrollGeometry $script:txtDst $script:sbDst)
|
|
3131
|
+
Write-Json @{ type = "lane2"; first = $geo2.first; top = $geo2.top }
|
|
3132
|
+
$bmp2 = New-Object System.Drawing.Bitmap -ArgumentList $script:card.Width, $script:card.Height
|
|
3133
|
+
$script:card.Refresh()
|
|
3134
|
+
$g2 = [System.Drawing.Graphics]::FromImage($bmp2)
|
|
3135
|
+
$g2.CopyFromScreen($script:card.Location, [System.Drawing.Point]::Empty, $script:card.Size)
|
|
3136
|
+
$g2.Dispose()
|
|
3137
|
+
$bmp2.Save(($ShotPath + ".scrolled.png"), [System.Drawing.Imaging.ImageFormat]::Png)
|
|
3138
|
+
$bmp2.Dispose()
|
|
3139
|
+
}
|
|
3140
|
+
$script:card.Close()
|
|
3141
|
+
exit 0
|
|
3142
|
+
}
|
|
3143
|
+
|
|
3144
|
+
# ---------------------------------------------------------------- one shot
|
|
3145
|
+
|
|
3146
|
+
if ($Once) {
|
|
3147
|
+
try {
|
|
3148
|
+
$result = Invoke-Capture
|
|
3149
|
+
if ($null -eq $result) { Write-Json @{ type = "error"; message = "no selection" }; exit 2 }
|
|
3150
|
+
Write-Json $result
|
|
3151
|
+
exit 0
|
|
3152
|
+
} catch {
|
|
3153
|
+
Write-Json @{ type = "error"; message = $_.Exception.Message }
|
|
3154
|
+
exit 1
|
|
3155
|
+
}
|
|
3156
|
+
}
|
|
3157
|
+
|
|
3158
|
+
# ---------------------------------------------------------------- hotkey loop
|
|
3159
|
+
|
|
3160
|
+
$hotkeyInfo = ConvertTo-Hotkey $Hotkey
|
|
3161
|
+
$window = New-Object QuickAsk.HotkeyWindow -ArgumentList 1
|
|
3162
|
+
$script:active = $window.Register([uint32]$hotkeyInfo.mods, [uint32]$hotkeyInfo.key)
|
|
3163
|
+
if (-not $script:active) {
|
|
3164
|
+
# Auto watch still works without a hotkey, so a taken shortcut is not fatal.
|
|
3165
|
+
Write-Json @{ type = "error"; message = "RegisterHotKey failed (hotkey already taken?)" }
|
|
3166
|
+
if ($NoAuto) { exit 1 }
|
|
3167
|
+
}
|
|
3168
|
+
New-Card
|
|
3169
|
+
Write-Trace ("ready hwnd=" + [string]$window.Handle.ToInt64() + " auto=" + [string](-not $NoAuto))
|
|
3170
|
+
Write-Json @{ type = "ready"; hotkey = $Hotkey; auto = (-not $NoAuto); pid = $PID; hwnd = [string]$window.Handle.ToInt64() }
|
|
3171
|
+
|
|
3172
|
+
if (-not $NoAuto) {
|
|
3173
|
+
# Selection made with the mouse: the hook fires right after the button comes
|
|
3174
|
+
# up, so the card can open while the text is still selected. A short delay
|
|
3175
|
+
# lets the application finish its own selection handling (and hides the card
|
|
3176
|
+
# from a plain click that produced no selection).
|
|
3177
|
+
# A selection is not readable the instant the button comes up: the app may
|
|
3178
|
+
# still be finishing its own handling. Retry a few times before giving up.
|
|
3179
|
+
$script:gestureAttempt = 0
|
|
3180
|
+
$script:gestureTimer = New-Object System.Windows.Forms.Timer
|
|
3181
|
+
$script:gestureTimer.Interval = 160
|
|
3182
|
+
$script:gestureTimer.Add_Tick({
|
|
3183
|
+
$script:gestureTimer.Stop()
|
|
3184
|
+
$script:gestureAttempt += 1
|
|
3185
|
+
if (Invoke-AutoCapture) { $script:gestureAttempt = 0; return }
|
|
3186
|
+
if ($script:gestureAttempt -ge 4) { $script:gestureAttempt = 0; return }
|
|
3187
|
+
$script:gestureTimer.Interval = 260
|
|
3188
|
+
$script:gestureTimer.Start()
|
|
3189
|
+
})
|
|
3190
|
+
$script:keyWatcher = New-Object QuickAsk.KeyboardWatcher
|
|
3191
|
+
$keyHookOk = [bool]$script:keyWatcher.Start()
|
|
3192
|
+
Write-Trace ("keyboard hook=" + [string]$keyHookOk)
|
|
3193
|
+
|
|
3194
|
+
$script:mouseWatcher = New-Object QuickAsk.MouseWatcher
|
|
3195
|
+
$hookOk = $script:mouseWatcher.Start()
|
|
3196
|
+
Write-Trace ("mouse hook=" + [string]$hookOk)
|
|
3197
|
+
if (-not $hookOk) {
|
|
3198
|
+
Write-Json @{ type = "error"; message = "mouse hook failed" }
|
|
3199
|
+
}
|
|
3200
|
+
|
|
3201
|
+
# The hook callbacks only post a message (a slow hook freezes mouse input for
|
|
3202
|
+
# every application), so the script side is driven from here.
|
|
3203
|
+
$script:mouseWatcher.Notify = $window.Handle
|
|
3204
|
+
$script:keyWatcher.Notify = $window.Handle
|
|
3205
|
+
$window.Mouse = $script:mouseWatcher
|
|
3206
|
+
$window.Keyboard = $script:keyWatcher
|
|
3207
|
+
$script:keyWatcher.Guarded = @([IntPtr]::Zero, [IntPtr]::Zero, [IntPtr]::Zero)
|
|
3208
|
+
|
|
3209
|
+
$window.Add_HookPing({
|
|
3210
|
+
param($code)
|
|
3211
|
+
switch ([int]$code) {
|
|
3212
|
+
1 {
|
|
3213
|
+
$cp = New-Object QuickAsk.POINT
|
|
3214
|
+
[void][QuickAsk.Native]::GetCursorPos([ref]$cp)
|
|
3215
|
+
$pt = New-Object System.Drawing.Point($cp.X, $cp.Y)
|
|
3216
|
+
$onCard = ($null -ne $script:card -and $script:card.Visible -and $script:card.Bounds.Contains($pt))
|
|
3217
|
+
$onBar = ($null -ne $script:bar -and $script:bar.Visible -and $script:bar.Bounds.Contains($pt))
|
|
3218
|
+
$onMenu = ($null -ne $script:langMenu -and $script:langMenu.Visible -and $script:langMenu.Bounds.Contains($pt))
|
|
3219
|
+
if ($onMenu -or $onCard -or $onBar) {
|
|
3220
|
+
# Pressing inside our own UI must not look like a selection gesture
|
|
3221
|
+
# (dragging the card used to pop the pill again).
|
|
3222
|
+
$script:ownGestureUntil = (Get-Date).AddSeconds(2)
|
|
3223
|
+
return
|
|
3224
|
+
}
|
|
3225
|
+
Hide-LangMenu
|
|
3226
|
+
if ($null -eq $script:bar -or -not $script:bar.Visible) { return }
|
|
3227
|
+
if ($null -ne $script:barCapture) { $script:dismissed = [string]$script:barCapture.text }
|
|
3228
|
+
Hide-Bar
|
|
3229
|
+
}
|
|
3230
|
+
2 { Write-Trace "gesture mouse"; Start-GestureCapture }
|
|
3231
|
+
3 { Write-Trace "gesture key"; Start-GestureCapture }
|
|
3232
|
+
6 { Write-Trace "wheel scroll"; Update-AllScrollbars }
|
|
3233
|
+
4 {
|
|
3234
|
+
Write-Trace "escape"
|
|
3235
|
+
Hide-LangMenu
|
|
3236
|
+
Hide-Bar
|
|
3237
|
+
Hide-Card
|
|
3238
|
+
}
|
|
3239
|
+
}
|
|
3240
|
+
})
|
|
3241
|
+
|
|
3242
|
+
|
|
3243
|
+
# Selection made with the keyboard: nothing to hook, so poll the focused
|
|
3244
|
+
# element instead (cheap; runs only while the helper lives).
|
|
3245
|
+
if ($ParentPid -gt 0) { $script:parentPid = $ParentPid }
|
|
3246
|
+
$script:autoTimer = New-Object System.Windows.Forms.Timer
|
|
3247
|
+
$script:autoTimer.Interval = [Math]::Max(200, $AutoInterval)
|
|
3248
|
+
$script:autoTimer.Add_Tick({ Watch-Selection })
|
|
3249
|
+
$script:autoTimer.Start()
|
|
3250
|
+
Start-Watchdog
|
|
3251
|
+
}
|
|
3252
|
+
|
|
3253
|
+
# A helper outlives a killed DSH process: it would keep the hotkey registered and
|
|
3254
|
+
# the next DSH start could not take it. Watch the parent and leave with it.
|
|
3255
|
+
if ($ParentPid -gt 0) {
|
|
3256
|
+
$script:parentPid = $ParentPid
|
|
3257
|
+
$script:watch = New-Object System.Windows.Forms.Timer
|
|
3258
|
+
$script:watch.Interval = 3000
|
|
3259
|
+
$script:watch.Add_Tick({
|
|
3260
|
+
if ($null -eq (Get-Process -Id $script:parentPid -ErrorAction SilentlyContinue)) {
|
|
3261
|
+
$script:watch.Stop()
|
|
3262
|
+
$window.Unregister()
|
|
3263
|
+
exit 0
|
|
3264
|
+
}
|
|
3265
|
+
})
|
|
3266
|
+
$script:watch.Start()
|
|
3267
|
+
}
|
|
3268
|
+
|
|
3269
|
+
$window.Add_Pressed({
|
|
3270
|
+
param($id)
|
|
3271
|
+
if ($env:QUICKASK_DEBUG) { Write-Json @{ type = "hotkey" } }
|
|
3272
|
+
try {
|
|
3273
|
+
# never read the card's own text back as the selection
|
|
3274
|
+
if ($null -ne $script:card -and $script:card.Visible) { $script:card.Hide() }
|
|
3275
|
+
$captured = Invoke-Capture
|
|
3276
|
+
if ($null -ne $captured) {
|
|
3277
|
+
$script:autoShown = [string]$captured.text
|
|
3278
|
+
Write-Json $captured
|
|
3279
|
+
}
|
|
3280
|
+
Hide-Bar
|
|
3281
|
+
Show-Card $captured
|
|
3282
|
+
} catch {
|
|
3283
|
+
Write-Json @{ type = "error"; message = $_.Exception.Message }
|
|
3284
|
+
}
|
|
3285
|
+
})
|
|
3286
|
+
|
|
3287
|
+
try {
|
|
3288
|
+
[System.Windows.Forms.Application]::Run()
|
|
3289
|
+
} finally {
|
|
3290
|
+
$window.Unregister()
|
|
3291
|
+
}
|