@copylee/dsh-computer-use 0.11.0 → 0.13.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/README.md +31 -9
- package/helper/Capture.cs +682 -0
- package/helper/Input.cs +500 -0
- package/helper/Native.cs +136 -0
- package/helper/Overlay.cs +1685 -0
- package/helper/Program.cs +244 -0
- package/helper/Uia.cs +882 -0
- package/helper/Windows.cs +761 -0
- package/lib/client.js +191 -114
- package/lib/index.js +940 -368
- package/lib/types/access.d.ts +7 -0
- package/lib/types/cdp.d.ts +14 -3
- package/lib/types/client/select.d.ts +1 -1
- package/lib/types/computer.d.ts +25 -5
- package/lib/types/diagnostics.d.ts +3 -0
- package/lib/types/helper-client.d.ts +5 -2
- package/lib/types/index.d.ts +4 -1
- package/lib/types/lease.d.ts +30 -0
- package/lib/types/overlay.d.ts +26 -2
- package/lib/types/ui-diff.d.ts +28 -0
- package/package.json +3 -2
- package/helper/CuHelper.cs +0 -4414
|
@@ -0,0 +1,761 @@
|
|
|
1
|
+
// Window enumeration, focus/manage commands, system tray restore, and Start Menu / Registry app index (C# 5).
|
|
2
|
+
|
|
3
|
+
using System;
|
|
4
|
+
using System.Collections;
|
|
5
|
+
using System.Collections.Generic;
|
|
6
|
+
using System.Diagnostics;
|
|
7
|
+
using System.Drawing;
|
|
8
|
+
using System.Drawing.Drawing2D;
|
|
9
|
+
using System.Drawing.Imaging;
|
|
10
|
+
using System.Drawing.Text;
|
|
11
|
+
using System.IO;
|
|
12
|
+
using System.Reflection;
|
|
13
|
+
using System.Runtime.InteropServices;
|
|
14
|
+
using System.Text;
|
|
15
|
+
using System.Threading;
|
|
16
|
+
using System.Web.Script.Serialization;
|
|
17
|
+
using System.Windows.Automation;
|
|
18
|
+
using System.Windows.Forms;
|
|
19
|
+
using Microsoft.Win32;
|
|
20
|
+
|
|
21
|
+
namespace DshComputerUse
|
|
22
|
+
{
|
|
23
|
+
internal static class Windows
|
|
24
|
+
{
|
|
25
|
+
public static string ExePath(uint pid)
|
|
26
|
+
{
|
|
27
|
+
IntPtr h = Native.OpenProcess(0x1000, false, pid);
|
|
28
|
+
if (h == IntPtr.Zero) return "";
|
|
29
|
+
try
|
|
30
|
+
{
|
|
31
|
+
var sb = new StringBuilder(1024); int size = sb.Capacity;
|
|
32
|
+
return Native.QueryFullProcessImageName(h, 0, sb, ref size) ? sb.ToString() : "";
|
|
33
|
+
}
|
|
34
|
+
finally { Native.CloseHandle(h); }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
public static Dictionary<string, object> Describe(IntPtr hwnd)
|
|
38
|
+
{
|
|
39
|
+
var d = new Dictionary<string, object>();
|
|
40
|
+
if (hwnd == IntPtr.Zero || !Native.IsWindow(hwnd)) return d;
|
|
41
|
+
uint pid; Native.GetWindowThreadProcessId(hwnd, out pid);
|
|
42
|
+
int len = Native.GetWindowTextLength(hwnd);
|
|
43
|
+
var title = new StringBuilder(Math.Max(len + 1, 2)); Native.GetWindowText(hwnd, title, title.Capacity);
|
|
44
|
+
var cls = new StringBuilder(256); Native.GetClassName(hwnd, cls, cls.Capacity);
|
|
45
|
+
Native.RECT rc;
|
|
46
|
+
if (Native.DwmGetWindowAttribute(hwnd, 9, out rc, Marshal.SizeOf(typeof(Native.RECT))) != 0) Native.GetWindowRect(hwnd, out rc);
|
|
47
|
+
string path = ExePath(pid);
|
|
48
|
+
d["hwnd"] = hwnd.ToInt64();
|
|
49
|
+
d["title"] = title.ToString();
|
|
50
|
+
d["className"] = cls.ToString();
|
|
51
|
+
d["pid"] = (long)pid;
|
|
52
|
+
d["exe"] = path.Length > 0 ? Path.GetFileName(path) : "";
|
|
53
|
+
d["path"] = path;
|
|
54
|
+
d["x"] = rc.Left; d["y"] = rc.Top; d["width"] = rc.Right - rc.Left; d["height"] = rc.Bottom - rc.Top;
|
|
55
|
+
d["minimized"] = Native.IsIconic(hwnd);
|
|
56
|
+
d["maximized"] = Native.IsZoomed(hwnd);
|
|
57
|
+
return d;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
public static List<object> List()
|
|
61
|
+
{
|
|
62
|
+
var list = new List<object>();
|
|
63
|
+
IntPtr fg = Native.GetForegroundWindow();
|
|
64
|
+
uint self = (uint)Process.GetCurrentProcess().Id;
|
|
65
|
+
Native.EnumWindowsProc cb = delegate (IntPtr h, IntPtr data)
|
|
66
|
+
{
|
|
67
|
+
if (!Native.IsWindowVisible(h) || Native.GetWindowTextLength(h) == 0) return true;
|
|
68
|
+
if (Native.GetWindow(h, 4) != IntPtr.Zero) return true; // owned popup
|
|
69
|
+
int ex = Native.GetWindowLong(h, -20);
|
|
70
|
+
if ((ex & 0x80) != 0 && (ex & 0x40000) == 0) return true; // tool window
|
|
71
|
+
int cloaked;
|
|
72
|
+
if (Native.DwmGetWindowAttribute(h, 14, out cloaked, 4) == 0 && cloaked != 0) return true;
|
|
73
|
+
uint pid; Native.GetWindowThreadProcessId(h, out pid);
|
|
74
|
+
if (pid == self) return true;
|
|
75
|
+
var d = Describe(h);
|
|
76
|
+
d["foreground"] = h == fg;
|
|
77
|
+
list.Add(d);
|
|
78
|
+
return true;
|
|
79
|
+
};
|
|
80
|
+
Native.EnumWindows(cb, IntPtr.Zero);
|
|
81
|
+
GC.KeepAlive(cb);
|
|
82
|
+
return list;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
public static Dictionary<string, object> At(int x, int y)
|
|
86
|
+
{
|
|
87
|
+
IntPtr h = Native.WindowFromPoint(new Native.POINT(x, y));
|
|
88
|
+
if (h != IntPtr.Zero) h = Native.GetAncestor(h, 2); // GA_ROOT
|
|
89
|
+
uint pid = 0;
|
|
90
|
+
if (h != IntPtr.Zero) Native.GetWindowThreadProcessId(h, out pid);
|
|
91
|
+
uint cardPid = CardLayer.Pid();
|
|
92
|
+
if (h == IntPtr.Zero || pid == (uint)Process.GetCurrentProcess().Id || (cardPid != 0 && pid == cardPid) || SeeThrough(pid))
|
|
93
|
+
{
|
|
94
|
+
// Our own status pill is under the point (it dodges before the
|
|
95
|
+
// click): report the topmost foreign window there instead.
|
|
96
|
+
IntPtr found = IntPtr.Zero;
|
|
97
|
+
uint self = (uint)Process.GetCurrentProcess().Id;
|
|
98
|
+
Native.EnumWindowsProc cb = delegate (IntPtr w, IntPtr data)
|
|
99
|
+
{
|
|
100
|
+
if (!Native.IsWindowVisible(w)) return true;
|
|
101
|
+
uint p; Native.GetWindowThreadProcessId(w, out p);
|
|
102
|
+
if (p == self || (cardPid != 0 && p == cardPid) || SeeThrough(p)) return true; // our overlay, the DSH card, game overlays
|
|
103
|
+
if ((Native.GetWindowLong(w, -20) & 0x20) != 0) return true; // WS_EX_TRANSPARENT
|
|
104
|
+
if (Native.IsIconic(w)) return true;
|
|
105
|
+
int cloaked;
|
|
106
|
+
if (Native.DwmGetWindowAttribute(w, 14, out cloaked, 4) == 0 && cloaked != 0) return true;
|
|
107
|
+
Native.RECT rc; Native.GetWindowRect(w, out rc);
|
|
108
|
+
if (x >= rc.Left && x < rc.Right && y >= rc.Top && y < rc.Bottom) { found = w; return false; }
|
|
109
|
+
return true;
|
|
110
|
+
};
|
|
111
|
+
Native.EnumWindows(cb, IntPtr.Zero);
|
|
112
|
+
GC.KeepAlive(cb);
|
|
113
|
+
h = found;
|
|
114
|
+
}
|
|
115
|
+
return Describe(h);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Full-screen overlays that never take input themselves (NVIDIA / Xbox Game Bar...). */
|
|
119
|
+
static readonly string[] Overlays = { "nvidia overlay.exe", "nvsphelper64.exe", "gamebar.exe", "gamebarftserver.exe" };
|
|
120
|
+
|
|
121
|
+
static bool SeeThrough(uint pid)
|
|
122
|
+
{
|
|
123
|
+
if (pid == 0) return false;
|
|
124
|
+
string exe = Path.GetFileName(ExePath(pid)).ToLowerInvariant();
|
|
125
|
+
return Array.IndexOf(Overlays, exe) >= 0;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Apps that run without any visible window (closed to the system tray):
|
|
130
|
+
* per program, its largest hidden, titled, unowned top-level window.
|
|
131
|
+
*/
|
|
132
|
+
public static List<object> Background(bool withTray)
|
|
133
|
+
{
|
|
134
|
+
uint self = (uint)Process.GetCurrentProcess().Id;
|
|
135
|
+
var visible = new HashSet<uint>();
|
|
136
|
+
var best = new Dictionary<uint, KeyValuePair<IntPtr, int>>();
|
|
137
|
+
Native.EnumWindowsProc cb = delegate (IntPtr h, IntPtr data)
|
|
138
|
+
{
|
|
139
|
+
uint pid; Native.GetWindowThreadProcessId(h, out pid);
|
|
140
|
+
if (pid == self || pid == 0) return true;
|
|
141
|
+
if (Native.GetWindow(h, 4) != IntPtr.Zero) return true; // owned
|
|
142
|
+
if (Native.IsWindowVisible(h))
|
|
143
|
+
{
|
|
144
|
+
int cloaked;
|
|
145
|
+
bool isCloaked = Native.DwmGetWindowAttribute(h, 14, out cloaked, 4) == 0 && cloaked != 0;
|
|
146
|
+
if (!isCloaked && Native.GetWindowTextLength(h) > 0) visible.Add(pid);
|
|
147
|
+
return true;
|
|
148
|
+
}
|
|
149
|
+
if (Native.GetWindowTextLength(h) == 0) return true;
|
|
150
|
+
var cls = new StringBuilder(256); Native.GetClassName(h, cls, cls.Capacity);
|
|
151
|
+
string c = cls.ToString();
|
|
152
|
+
if (c == "ConsoleWindowClass" || c == "IME" || c == "MSCTFIME UI" || c.StartsWith("GDI+")) return true;
|
|
153
|
+
Native.RECT rc; Native.GetWindowRect(h, out rc);
|
|
154
|
+
int area = (rc.Right - rc.Left) * (rc.Bottom - rc.Top);
|
|
155
|
+
if (rc.Right - rc.Left < 240 || rc.Bottom - rc.Top < 160) return true;
|
|
156
|
+
KeyValuePair<IntPtr, int> seen;
|
|
157
|
+
if (!best.TryGetValue(pid, out seen) || seen.Value < area) best[pid] = new KeyValuePair<IntPtr, int>(h, area);
|
|
158
|
+
return true;
|
|
159
|
+
};
|
|
160
|
+
Native.EnumWindows(cb, IntPtr.Zero);
|
|
161
|
+
GC.KeepAlive(cb);
|
|
162
|
+
// Programs whose other process shows a window are not in the background.
|
|
163
|
+
var shownExes = new HashSet<string>();
|
|
164
|
+
foreach (var pid in visible) shownExes.Add(Path.GetFileName(ExePath(pid)).ToLowerInvariant());
|
|
165
|
+
var byExe = new Dictionary<string, Dictionary<string, object>>();
|
|
166
|
+
foreach (var pair in best)
|
|
167
|
+
{
|
|
168
|
+
if (visible.Contains(pair.Key)) continue;
|
|
169
|
+
var d = Describe(pair.Value.Key);
|
|
170
|
+
string exe = ((string)d["exe"]).ToLowerInvariant();
|
|
171
|
+
if (exe.Length == 0 || shownExes.Contains(exe) || exe == "explorer.exe" || exe == "textinputhost.exe" || exe == "shellexperiencehost.exe" || exe == "searchhost.exe" || exe == "startmenuexperiencehost.exe") continue;
|
|
172
|
+
Dictionary<string, object> prev;
|
|
173
|
+
if (byExe.TryGetValue(exe, out prev) && Convert.ToInt32(prev["width"]) * Convert.ToInt32(prev["height"]) >= pair.Value.Value) continue;
|
|
174
|
+
byExe[exe] = d;
|
|
175
|
+
}
|
|
176
|
+
// Looking through the notification area takes a second or more; skip it when only the list matters.
|
|
177
|
+
if (!withTray) return new List<object>(byExe.Values);
|
|
178
|
+
var owners = Tray.WindowsByPid();
|
|
179
|
+
var exeOf = new Dictionary<uint, string>();
|
|
180
|
+
foreach (var pid in owners.Keys) exeOf[pid] = Path.GetFileName(ExePath(pid));
|
|
181
|
+
foreach (var d in byExe.Values) d["tray"] = Tray.HasIcon((string)d["exe"], owners, exeOf);
|
|
182
|
+
return new List<object>(byExe.Values);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Visible, titled, unowned windows of these processes. */
|
|
186
|
+
public static IntPtr ShownWindowOf(HashSet<uint> pids)
|
|
187
|
+
{
|
|
188
|
+
IntPtr found = IntPtr.Zero; int bestArea = 0;
|
|
189
|
+
Native.EnumWindowsProc cb = delegate (IntPtr h, IntPtr data)
|
|
190
|
+
{
|
|
191
|
+
if (!Native.IsWindowVisible(h) || Native.GetWindowTextLength(h) == 0 || Native.GetWindow(h, 4) != IntPtr.Zero) return true;
|
|
192
|
+
uint pid; Native.GetWindowThreadProcessId(h, out pid);
|
|
193
|
+
if (!pids.Contains(pid)) return true;
|
|
194
|
+
int cloaked;
|
|
195
|
+
if (Native.DwmGetWindowAttribute(h, 14, out cloaked, 4) == 0 && cloaked != 0) return true;
|
|
196
|
+
Native.RECT rc; Native.GetWindowRect(h, out rc);
|
|
197
|
+
int area = (rc.Right - rc.Left) * (rc.Bottom - rc.Top);
|
|
198
|
+
if (area > bestArea) { bestArea = area; found = h; }
|
|
199
|
+
return true;
|
|
200
|
+
};
|
|
201
|
+
Native.EnumWindows(cb, IntPtr.Zero);
|
|
202
|
+
GC.KeepAlive(cb);
|
|
203
|
+
return found;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
public static Dictionary<string, object> Focus(IntPtr hwnd)
|
|
207
|
+
{
|
|
208
|
+
if (!Native.IsWindow(hwnd)) throw new Exception("window no longer exists");
|
|
209
|
+
if (Native.IsIconic(hwnd)) { Native.ShowWindow(hwnd, 9); Thread.Sleep(150); }
|
|
210
|
+
if (Native.GetForegroundWindow() != hwnd)
|
|
211
|
+
{
|
|
212
|
+
IntPtr fg = Native.GetForegroundWindow();
|
|
213
|
+
uint pid;
|
|
214
|
+
uint fgThread = Native.GetWindowThreadProcessId(fg, out pid);
|
|
215
|
+
uint cur = Native.GetCurrentThreadId();
|
|
216
|
+
bool attached = fgThread != 0 && fgThread != cur && Native.AttachThreadInput(cur, fgThread, true);
|
|
217
|
+
try
|
|
218
|
+
{
|
|
219
|
+
Native.BringWindowToTop(hwnd);
|
|
220
|
+
Native.SetForegroundWindow(hwnd);
|
|
221
|
+
}
|
|
222
|
+
finally { if (attached) Native.AttachThreadInput(cur, fgThread, false); }
|
|
223
|
+
Thread.Sleep(60);
|
|
224
|
+
if (Native.GetForegroundWindow() != hwnd)
|
|
225
|
+
{
|
|
226
|
+
Native.SwitchToThisWindow(hwnd, true);
|
|
227
|
+
Thread.Sleep(120);
|
|
228
|
+
}
|
|
229
|
+
if (Native.GetForegroundWindow() != hwnd)
|
|
230
|
+
{
|
|
231
|
+
// Holding Alt lifts the foreground lock; a no-op VK keeps the
|
|
232
|
+
// Alt release from opening the target's menu bar.
|
|
233
|
+
var inputs = new Native.INPUT[3];
|
|
234
|
+
var down = new Native.INPUT(); down.type = Native.INPUT_KEYBOARD; down.u.ki.wVk = 0x12; down.u.ki.dwExtraInfo = Native.Marker;
|
|
235
|
+
Native.SendInput(1, new[] { down }, Marshal.SizeOf(typeof(Native.INPUT)));
|
|
236
|
+
Native.SetForegroundWindow(hwnd);
|
|
237
|
+
var noop = new Native.INPUT(); noop.type = Native.INPUT_KEYBOARD; noop.u.ki.wVk = 0xFF; noop.u.ki.dwExtraInfo = Native.Marker;
|
|
238
|
+
var noopUp = noop; noopUp.u.ki.dwFlags = Native.KEYEVENTF_KEYUP;
|
|
239
|
+
var up = down; up.u.ki.dwFlags = Native.KEYEVENTF_KEYUP;
|
|
240
|
+
inputs[0] = noop; inputs[1] = noopUp; inputs[2] = up;
|
|
241
|
+
Native.SendInput(3, inputs, Marshal.SizeOf(typeof(Native.INPUT)));
|
|
242
|
+
Thread.Sleep(120);
|
|
243
|
+
}
|
|
244
|
+
if (Native.GetForegroundWindow() != hwnd)
|
|
245
|
+
{
|
|
246
|
+
// Last resort: restoring a minimized window always activates it.
|
|
247
|
+
bool zoomed = Native.IsZoomed(hwnd);
|
|
248
|
+
Native.ShowWindow(hwnd, 6); // SW_MINIMIZE
|
|
249
|
+
Thread.Sleep(150);
|
|
250
|
+
Native.ShowWindow(hwnd, zoomed ? 3 : 9); // SW_MAXIMIZE / SW_RESTORE
|
|
251
|
+
Thread.Sleep(200);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
var d = Describe(hwnd);
|
|
255
|
+
d["focused"] = Native.GetForegroundWindow() == hwnd;
|
|
256
|
+
return d;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// Values live on the target HWND, not in helper memory. A replacement
|
|
260
|
+
// helper can restore them after a timeout/kill, without stale HWND files.
|
|
261
|
+
const string CardPrefix = "DSH.ComputerUse.Card.v1.";
|
|
262
|
+
static readonly string[] CardFields = { "flags", "show", "minX", "minY", "maxX", "maxY", "left", "top", "right", "bottom", "ex", "key", "alpha", "layerFlags" };
|
|
263
|
+
|
|
264
|
+
static void SaveCard(IntPtr hwnd)
|
|
265
|
+
{
|
|
266
|
+
if (Native.GetProp(hwnd, CardPrefix + "owner") != IntPtr.Zero) return;
|
|
267
|
+
var wp = new Native.WINDOWPLACEMENT(); wp.length = Marshal.SizeOf(wp);
|
|
268
|
+
if (!Native.GetWindowPlacement(hwnd, ref wp)) throw new Exception("Cannot save host window placement");
|
|
269
|
+
uint key, flags; byte alpha;
|
|
270
|
+
Native.GetLayeredWindowAttributes(hwnd, out key, out alpha, out flags);
|
|
271
|
+
int[] values = { wp.flags, wp.showCmd, wp.ptMinPosition.X, wp.ptMinPosition.Y, wp.ptMaxPosition.X, wp.ptMaxPosition.Y,
|
|
272
|
+
wp.rcNormalPosition.Left, wp.rcNormalPosition.Top, wp.rcNormalPosition.Right, wp.rcNormalPosition.Bottom,
|
|
273
|
+
Native.GetWindowLong(hwnd, -20), unchecked((int)key), alpha, unchecked((int)flags) };
|
|
274
|
+
try {
|
|
275
|
+
for (int i = 0; i < values.Length; i++)
|
|
276
|
+
if (!Native.SetProp(hwnd, CardPrefix + CardFields[i], new IntPtr(values[i]))) throw new Exception("Cannot save host window state");
|
|
277
|
+
// Commit marker is written last, before any window mutation.
|
|
278
|
+
if (!Native.SetProp(hwnd, CardPrefix + "owner", new IntPtr(Process.GetCurrentProcess().Id))) throw new Exception("Cannot save host window owner");
|
|
279
|
+
}
|
|
280
|
+
catch { ClearCard(hwnd); throw; }
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
static void ClearCard(IntPtr hwnd)
|
|
284
|
+
{
|
|
285
|
+
Native.RemoveProp(hwnd, CardPrefix + "owner");
|
|
286
|
+
foreach (string field in CardFields) Native.RemoveProp(hwnd, CardPrefix + field);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
public static void RecoverCards(bool own)
|
|
290
|
+
{
|
|
291
|
+
int self = Process.GetCurrentProcess().Id;
|
|
292
|
+
Native.EnumWindowsProc cb = delegate(IntPtr hwnd, IntPtr data) {
|
|
293
|
+
int owner = Native.GetProp(hwnd, CardPrefix + "owner").ToInt32();
|
|
294
|
+
if (owner == 0) return true;
|
|
295
|
+
bool restore = own && owner == self;
|
|
296
|
+
if (!own && owner != self) {
|
|
297
|
+
try { using (var p = Process.GetProcessById(owner)) restore = p.HasExited; }
|
|
298
|
+
catch (ArgumentException) { restore = true; }
|
|
299
|
+
catch (Exception) { return true; } // do not touch a live/inaccessible helper
|
|
300
|
+
}
|
|
301
|
+
if (restore) { try { Uncard(hwnd); } catch (Exception) { } }
|
|
302
|
+
return true;
|
|
303
|
+
};
|
|
304
|
+
Native.EnumWindows(cb, IntPtr.Zero); GC.KeepAlive(cb);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/// Shrink a window into an always-on-top card; Uncard restores it exactly.
|
|
308
|
+
public static object Card(IntPtr hwnd, int x, int y, int w, int h)
|
|
309
|
+
{
|
|
310
|
+
if (!Native.IsWindow(hwnd)) throw new Exception("window no longer exists");
|
|
311
|
+
SaveCard(hwnd);
|
|
312
|
+
CardLayer.Attach(hwnd);
|
|
313
|
+
// A minimized window restores to its previous state, which may be maximized: restore until normal.
|
|
314
|
+
for (int i = 0; i < 2 && (Native.IsIconic(hwnd) || Native.IsZoomed(hwnd)); i++) { Native.ShowWindow(hwnd, 9); Thread.Sleep(150); }
|
|
315
|
+
Native.SetWindowPos(hwnd, new IntPtr(-1), x, y, w, h, 0x0010 | 0x0040); // TOPMOST, NOACTIVATE | SHOWWINDOW
|
|
316
|
+
// Apps enforce a minimum size (Electron does): keep the card anchored bottom-right.
|
|
317
|
+
Native.RECT rc;
|
|
318
|
+
if (Native.GetWindowRect(hwnd, out rc) && (rc.Right - rc.Left != w || rc.Bottom - rc.Top != h))
|
|
319
|
+
{
|
|
320
|
+
int nx = x + w - (rc.Right - rc.Left), ny = y + h - (rc.Bottom - rc.Top);
|
|
321
|
+
Native.SetWindowPos(hwnd, new IntPtr(-1), nx, ny, 0, 0, 0x0001 | 0x0010); // NOSIZE | NOACTIVATE
|
|
322
|
+
}
|
|
323
|
+
return Describe(hwnd);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
public static object Uncard(IntPtr hwnd)
|
|
327
|
+
{
|
|
328
|
+
if (CardLayer.Hwnd == hwnd) CardLayer.Detach();
|
|
329
|
+
if (!Native.IsWindow(hwnd)) return null;
|
|
330
|
+
if (Native.GetProp(hwnd, CardPrefix + "owner") != IntPtr.Zero)
|
|
331
|
+
{
|
|
332
|
+
int[] v = new int[CardFields.Length];
|
|
333
|
+
for (int i = 0; i < v.Length; i++) v[i] = Native.GetProp(hwnd, CardPrefix + CardFields[i]).ToInt32();
|
|
334
|
+
var wp = new Native.WINDOWPLACEMENT(); wp.length = Marshal.SizeOf(wp);
|
|
335
|
+
wp.flags = v[0]; wp.showCmd = v[1];
|
|
336
|
+
wp.ptMinPosition = new Native.POINT(v[2], v[3]); wp.ptMaxPosition = new Native.POINT(v[4], v[5]);
|
|
337
|
+
wp.rcNormalPosition = new Native.RECT { Left = v[6], Top = v[7], Right = v[8], Bottom = v[9] };
|
|
338
|
+
Native.SetWindowLong(hwnd, -20, v[10]);
|
|
339
|
+
if ((v[10] & 0x80000) != 0 && v[13] != 0) Native.SetLayeredWindowAttributes(hwnd, unchecked((uint)v[11]), (byte)v[12], unchecked((uint)v[13]));
|
|
340
|
+
if (!Native.SetWindowPos(hwnd, new IntPtr((v[10] & 8) != 0 ? -1 : -2), 0, 0, 0, 0, 0x0001 | 0x0002 | 0x0010)) throw new Exception("Cannot restore host window style");
|
|
341
|
+
// Restore the normal rectangle first, then the original show state (maximized etc.).
|
|
342
|
+
int show = wp.showCmd;
|
|
343
|
+
wp.showCmd = 1; // SW_SHOWNORMAL
|
|
344
|
+
if (!Native.SetWindowPlacement(hwnd, ref wp)) throw new Exception("Cannot restore host window placement");
|
|
345
|
+
if (show == 3) Native.ShowWindow(hwnd, 3);
|
|
346
|
+
else if (show == 2) Native.ShowWindow(hwnd, 6);
|
|
347
|
+
ClearCard(hwnd);
|
|
348
|
+
}
|
|
349
|
+
return Describe(hwnd);
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
public static object Command(IntPtr hwnd, string op)
|
|
353
|
+
{
|
|
354
|
+
if (!Native.IsWindow(hwnd)) throw new Exception("window no longer exists");
|
|
355
|
+
switch (op)
|
|
356
|
+
{
|
|
357
|
+
case "minimize": Native.ShowWindow(hwnd, 6); break;
|
|
358
|
+
case "maximize": Native.ShowWindow(hwnd, 3); break;
|
|
359
|
+
case "restore": Native.ShowWindow(hwnd, 9); break;
|
|
360
|
+
case "close": Native.PostMessage(hwnd, 0x0010, IntPtr.Zero, IntPtr.Zero); break;
|
|
361
|
+
default: throw new Exception("unknown window op: " + op);
|
|
362
|
+
}
|
|
363
|
+
Thread.Sleep(150);
|
|
364
|
+
return Describe(hwnd);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* Bring a program that lives in the system tray back the way the user
|
|
370
|
+
* would: click its notification-area icon (opening the "show hidden icons"
|
|
371
|
+
* overflow first). Launching it again would start a second instance (QQ
|
|
372
|
+
* shows a second login), and showing its hidden window directly leaves
|
|
373
|
+
* Electron / Qt apps frozen.
|
|
374
|
+
*/
|
|
375
|
+
internal static class Tray
|
|
376
|
+
{
|
|
377
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
378
|
+
struct NOTIFYICONIDENTIFIER { public int cbSize; public IntPtr hWnd; public uint uID; public Guid guidItem; }
|
|
379
|
+
[DllImport("shell32.dll")] static extern int Shell_NotifyIconGetRect(ref NOTIFYICONIDENTIFIER id, out Native.RECT rect);
|
|
380
|
+
[DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string cls, string title);
|
|
381
|
+
|
|
382
|
+
static bool IconRect(IntPtr hwnd, uint id, out Rectangle rect)
|
|
383
|
+
{
|
|
384
|
+
var n = new NOTIFYICONIDENTIFIER(); n.cbSize = Marshal.SizeOf(typeof(NOTIFYICONIDENTIFIER)); n.hWnd = hwnd; n.uID = id;
|
|
385
|
+
Native.RECT rc;
|
|
386
|
+
bool ok = Shell_NotifyIconGetRect(ref n, out rc) == 0 && rc.Right > rc.Left;
|
|
387
|
+
rect = ok ? new Rectangle(rc.Left, rc.Top, rc.Right - rc.Left, rc.Bottom - rc.Top) : Rectangle.Empty;
|
|
388
|
+
return ok;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/** Top-level and message-only windows per process: tray icons are registered on one of them. */
|
|
392
|
+
public static Dictionary<uint, List<IntPtr>> WindowsByPid()
|
|
393
|
+
{
|
|
394
|
+
var map = new Dictionary<uint, List<IntPtr>>();
|
|
395
|
+
Action<IntPtr> add = delegate (IntPtr h)
|
|
396
|
+
{
|
|
397
|
+
uint pid; Native.GetWindowThreadProcessId(h, out pid);
|
|
398
|
+
List<IntPtr> list;
|
|
399
|
+
if (!map.TryGetValue(pid, out list)) map[pid] = list = new List<IntPtr>();
|
|
400
|
+
list.Add(h);
|
|
401
|
+
};
|
|
402
|
+
Native.EnumWindowsProc cb = delegate (IntPtr h, IntPtr data) { add(h); return true; };
|
|
403
|
+
Native.EnumWindows(cb, IntPtr.Zero);
|
|
404
|
+
GC.KeepAlive(cb);
|
|
405
|
+
IntPtr m = IntPtr.Zero;
|
|
406
|
+
while ((m = FindWindowEx(new IntPtr(-3), m, null, null)) != IntPtr.Zero) add(m); // HWND_MESSAGE
|
|
407
|
+
return map;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/** The icon's owner window and id. */
|
|
411
|
+
static bool Find(HashSet<uint> pids, Dictionary<uint, List<IntPtr>> byPid, out IntPtr owner, out uint id)
|
|
412
|
+
{
|
|
413
|
+
var windows = new List<IntPtr>();
|
|
414
|
+
foreach (var pid in pids) { List<IntPtr> list; if (byPid.TryGetValue(pid, out list)) windows.AddRange(list); }
|
|
415
|
+
foreach (var h in windows)
|
|
416
|
+
{
|
|
417
|
+
// Icon ids are small; scan further only on windows that look like tray hosts.
|
|
418
|
+
var cls = new StringBuilder(256); Native.GetClassName(h, cls, cls.Capacity);
|
|
419
|
+
string c = cls.ToString().ToLowerInvariant();
|
|
420
|
+
uint ids = c.Contains("tray") || c.Contains("notify") || c.Contains("icon") ? 128u : 16u;
|
|
421
|
+
for (uint i = 0; i < ids; i++)
|
|
422
|
+
{
|
|
423
|
+
Rectangle r;
|
|
424
|
+
if (IconRect(h, i, out r)) { owner = h; id = i; return true; }
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
owner = IntPtr.Zero; id = 0;
|
|
428
|
+
return false;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
public static bool HasIcon(string exe, Dictionary<uint, List<IntPtr>> byPid, Dictionary<uint, string> exeOf)
|
|
432
|
+
{
|
|
433
|
+
// Process.GetProcessesByName is slow; the processes owning windows are enough here.
|
|
434
|
+
var pids = new HashSet<uint>();
|
|
435
|
+
foreach (var pair in exeOf)
|
|
436
|
+
if (string.Equals(pair.Value, exe, StringComparison.OrdinalIgnoreCase)) pids.Add(pair.Key);
|
|
437
|
+
IntPtr owner; uint id;
|
|
438
|
+
return pids.Count > 0 && Find(pids, byPid, out owner, out id);
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
static HashSet<uint> Pids(string exe)
|
|
442
|
+
{
|
|
443
|
+
var pids = new HashSet<uint>();
|
|
444
|
+
foreach (var p in Process.GetProcessesByName(Path.GetFileNameWithoutExtension(exe))) { pids.Add((uint)p.Id); p.Dispose(); }
|
|
445
|
+
return pids;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/** The taskbar's "show hidden icons" button. */
|
|
449
|
+
static Rectangle Chevron()
|
|
450
|
+
{
|
|
451
|
+
Rectangle found = Rectangle.Empty;
|
|
452
|
+
var worker = new Thread(delegate ()
|
|
453
|
+
{
|
|
454
|
+
try
|
|
455
|
+
{
|
|
456
|
+
var tray = AutomationElement.RootElement.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ClassNameProperty, "Shell_TrayWnd"));
|
|
457
|
+
if (tray == null) return;
|
|
458
|
+
var buttons = tray.FindAll(TreeScope.Descendants, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button));
|
|
459
|
+
AutomationElement pick = null;
|
|
460
|
+
foreach (AutomationElement b in buttons)
|
|
461
|
+
{
|
|
462
|
+
string name = b.Current.Name ?? "";
|
|
463
|
+
if (name.Contains("隐藏的图标") || name.ToLowerInvariant().Contains("hidden icons") || b.Current.ClassName == "NotifyIconOverflowButton") { pick = b; break; }
|
|
464
|
+
}
|
|
465
|
+
if (pick == null)
|
|
466
|
+
foreach (AutomationElement b in buttons)
|
|
467
|
+
if (b.Current.ClassName == "SystemTray.NormalButton") { pick = b; break; }
|
|
468
|
+
if (pick == null) return;
|
|
469
|
+
var r = pick.Current.BoundingRectangle;
|
|
470
|
+
found = new Rectangle((int)r.X, (int)r.Y, (int)r.Width, (int)r.Height);
|
|
471
|
+
}
|
|
472
|
+
catch (Exception) { }
|
|
473
|
+
});
|
|
474
|
+
worker.IsBackground = true;
|
|
475
|
+
worker.SetApartmentState(ApartmentState.MTA);
|
|
476
|
+
worker.Start();
|
|
477
|
+
worker.Join(4000);
|
|
478
|
+
return found;
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
static void Click(Rectangle r, int count)
|
|
482
|
+
{
|
|
483
|
+
var d = new Dictionary<string, object>();
|
|
484
|
+
d["x"] = r.X + r.Width / 2; d["y"] = r.Y + r.Height / 2; d["count"] = count;
|
|
485
|
+
using (new PassThrough()) Input.Click(d);
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
static IntPtr WaitShown(HashSet<uint> pids, int ms)
|
|
489
|
+
{
|
|
490
|
+
var until = DateTime.UtcNow.AddMilliseconds(ms);
|
|
491
|
+
do
|
|
492
|
+
{
|
|
493
|
+
IntPtr h = Windows.ShownWindowOf(pids);
|
|
494
|
+
if (h != IntPtr.Zero) return h;
|
|
495
|
+
Thread.Sleep(120);
|
|
496
|
+
} while (DateTime.UtcNow < until);
|
|
497
|
+
return IntPtr.Zero;
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
public static object Restore(string exe)
|
|
501
|
+
{
|
|
502
|
+
var result = new Dictionary<string, object>();
|
|
503
|
+
var pids = Pids(exe);
|
|
504
|
+
result["running"] = pids.Count > 0;
|
|
505
|
+
IntPtr owner; uint id;
|
|
506
|
+
if (pids.Count == 0 || !Find(pids, WindowsByPid(), out owner, out id)) { result["icon"] = false; return result; }
|
|
507
|
+
result["icon"] = true;
|
|
508
|
+
Rectangle icon; IconRect(owner, id, out icon);
|
|
509
|
+
// An icon in the overflow reports the chevron's rectangle until the overflow is open.
|
|
510
|
+
Rectangle chevron = Chevron();
|
|
511
|
+
if (!chevron.IsEmpty && Math.Abs(chevron.X - icon.X) <= 2 && Math.Abs(chevron.Y - icon.Y) <= 2)
|
|
512
|
+
{
|
|
513
|
+
Click(chevron, 1);
|
|
514
|
+
Thread.Sleep(450);
|
|
515
|
+
IconRect(owner, id, out icon);
|
|
516
|
+
result["overflow"] = true;
|
|
517
|
+
}
|
|
518
|
+
Click(icon, 1);
|
|
519
|
+
IntPtr shown = WaitShown(pids, 1500);
|
|
520
|
+
if (shown == IntPtr.Zero)
|
|
521
|
+
{
|
|
522
|
+
// Some apps restore on a double click only.
|
|
523
|
+
Rectangle again;
|
|
524
|
+
if (IconRect(owner, id, out again) && !(Math.Abs(chevron.X - again.X) <= 2 && Math.Abs(chevron.Y - again.Y) <= 2)) Click(again, 2);
|
|
525
|
+
shown = WaitShown(pids, 1500);
|
|
526
|
+
}
|
|
527
|
+
if (shown != IntPtr.Zero) { result["window"] = Windows.Focus(shown); }
|
|
528
|
+
return result;
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
internal static class Apps
|
|
533
|
+
{
|
|
534
|
+
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
|
|
535
|
+
static extern int AssocQueryString(uint flags, uint str, string association, string verb, StringBuilder output, ref uint length);
|
|
536
|
+
|
|
537
|
+
public static object OpenUrl(string value)
|
|
538
|
+
{
|
|
539
|
+
Uri url;
|
|
540
|
+
if (!Uri.TryCreate(value, UriKind.Absolute, out url) || (url.Scheme != "http" && url.Scheme != "https"))
|
|
541
|
+
throw new Exception("Expected an HTTP(S) URL");
|
|
542
|
+
const uint executable = 2;
|
|
543
|
+
var path = new StringBuilder(32768);
|
|
544
|
+
uint length = (uint)path.Capacity;
|
|
545
|
+
if (AssocQueryString(0, executable, url.Scheme, "open", path, ref length) != 0)
|
|
546
|
+
throw new Exception("Could not resolve the default browser for " + url.Scheme);
|
|
547
|
+
string exe = Path.GetFileName(path.ToString()).ToLowerInvariant();
|
|
548
|
+
string flag;
|
|
549
|
+
switch (exe)
|
|
550
|
+
{
|
|
551
|
+
case "chrome.exe": case "msedge.exe": case "brave.exe": case "vivaldi.exe": case "chromium.exe":
|
|
552
|
+
flag = "--new-window"; break;
|
|
553
|
+
case "firefox.exe": flag = "-new-window"; break;
|
|
554
|
+
default: throw new Exception("Cannot safely open a new window in the default browser (" + exe + ")");
|
|
555
|
+
}
|
|
556
|
+
string escapedUrl = url.AbsoluteUri.Replace("\"", "%22").Replace("\\", "%5C");
|
|
557
|
+
using (var process = Process.Start(new ProcessStartInfo(path.ToString(), flag + " \"" + escapedUrl + "\"") { UseShellExecute = false })) { }
|
|
558
|
+
return new Dictionary<string, object> { { "exe", exe } };
|
|
559
|
+
}
|
|
560
|
+
static List<KeyValuePair<string, string>> cache;
|
|
561
|
+
static DateTime cachedAt;
|
|
562
|
+
static readonly object Gate = new object();
|
|
563
|
+
|
|
564
|
+
/// <summary>
|
|
565
|
+
/// Listing the Start menu takes about two seconds the first time. Do it
|
|
566
|
+
/// while the model is still thinking, not inside its first open_application.
|
|
567
|
+
/// </summary>
|
|
568
|
+
public static void Warm()
|
|
569
|
+
{
|
|
570
|
+
var worker = new Thread(delegate () { try { Windows.List(); } catch (Exception) { } try { All(); } catch (Exception) { } });
|
|
571
|
+
worker.IsBackground = true;
|
|
572
|
+
worker.SetApartmentState(ApartmentState.STA);
|
|
573
|
+
worker.Start();
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
static List<KeyValuePair<string, string>> All()
|
|
577
|
+
{
|
|
578
|
+
lock (Gate) { return Load(); }
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
static void AddIfNew(List<KeyValuePair<string, string>> list, HashSet<string> seen, string name, string id)
|
|
582
|
+
{
|
|
583
|
+
if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(id)) return;
|
|
584
|
+
string key = name.Trim().ToLowerInvariant() + "\u0000" + id.Trim().ToLowerInvariant();
|
|
585
|
+
if (seen.Add(key)) list.Add(new KeyValuePair<string, string>(name.Trim(), id.Trim()));
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
static string ExtractExePath(string raw)
|
|
589
|
+
{
|
|
590
|
+
if (string.IsNullOrEmpty(raw)) return "";
|
|
591
|
+
string s = raw.Trim();
|
|
592
|
+
if (s.StartsWith("\""))
|
|
593
|
+
{
|
|
594
|
+
int end = s.IndexOf('"', 1);
|
|
595
|
+
if (end > 1) s = s.Substring(1, end - 1);
|
|
596
|
+
}
|
|
597
|
+
else
|
|
598
|
+
{
|
|
599
|
+
int comma = s.IndexOf(',');
|
|
600
|
+
if (comma > 0) s = s.Substring(0, comma);
|
|
601
|
+
}
|
|
602
|
+
s = s.Trim();
|
|
603
|
+
if (!s.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) return "";
|
|
604
|
+
return File.Exists(s) ? s : "";
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
static void ScanStartFolder(string dir, int depth, List<KeyValuePair<string, string>> list, HashSet<string> seen)
|
|
608
|
+
{
|
|
609
|
+
if (depth > 3 || string.IsNullOrEmpty(dir) || !Directory.Exists(dir)) return;
|
|
610
|
+
try
|
|
611
|
+
{
|
|
612
|
+
foreach (var f in Directory.GetFiles(dir, "*.lnk"))
|
|
613
|
+
{
|
|
614
|
+
string name = Path.GetFileNameWithoutExtension(f);
|
|
615
|
+
if (name.IndexOf("uninstall", StringComparison.OrdinalIgnoreCase) >= 0 || name.IndexOf("卸载", StringComparison.OrdinalIgnoreCase) >= 0) continue;
|
|
616
|
+
AddIfNew(list, seen, name, "lnk:" + f);
|
|
617
|
+
}
|
|
618
|
+
foreach (var sub in Directory.GetDirectories(dir))
|
|
619
|
+
ScanStartFolder(sub, depth + 1, list, seen);
|
|
620
|
+
}
|
|
621
|
+
catch (Exception) { }
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
static void ScanRegistryApps(List<KeyValuePair<string, string>> list, HashSet<string> seen)
|
|
625
|
+
{
|
|
626
|
+
var roots = new RegistryKey[] { Registry.CurrentUser, Registry.LocalMachine };
|
|
627
|
+
foreach (var root in roots)
|
|
628
|
+
{
|
|
629
|
+
// 1. App Paths (e.g. WeChat.exe, chrome.exe, code.exe)
|
|
630
|
+
try
|
|
631
|
+
{
|
|
632
|
+
using (var ap = root.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths"))
|
|
633
|
+
{
|
|
634
|
+
if (ap != null)
|
|
635
|
+
{
|
|
636
|
+
foreach (var subName in ap.GetSubKeyNames())
|
|
637
|
+
{
|
|
638
|
+
try
|
|
639
|
+
{
|
|
640
|
+
using (var sub = ap.OpenSubKey(subName))
|
|
641
|
+
{
|
|
642
|
+
if (sub == null) continue;
|
|
643
|
+
string exe = ExtractExePath(Convert.ToString(sub.GetValue(null)) ?? "");
|
|
644
|
+
if (exe.Length > 0) AddIfNew(list, seen, Path.GetFileNameWithoutExtension(subName), "exe:" + exe);
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
catch (Exception) { }
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
catch (Exception) { }
|
|
653
|
+
|
|
654
|
+
// 2. Uninstall table DisplayName + DisplayIcon (.exe)
|
|
655
|
+
var uninstallPaths = new string[] {
|
|
656
|
+
@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
|
|
657
|
+
@"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall",
|
|
658
|
+
};
|
|
659
|
+
foreach (var upath in uninstallPaths)
|
|
660
|
+
{
|
|
661
|
+
try
|
|
662
|
+
{
|
|
663
|
+
using (var uk = root.OpenSubKey(upath))
|
|
664
|
+
{
|
|
665
|
+
if (uk == null) continue;
|
|
666
|
+
foreach (var subName in uk.GetSubKeyNames())
|
|
667
|
+
{
|
|
668
|
+
try
|
|
669
|
+
{
|
|
670
|
+
using (var sub = uk.OpenSubKey(subName))
|
|
671
|
+
{
|
|
672
|
+
if (sub == null) continue;
|
|
673
|
+
string displayName = Convert.ToString(sub.GetValue("DisplayName")) ?? "";
|
|
674
|
+
if (displayName.Length == 0) continue;
|
|
675
|
+
string iconExe = ExtractExePath(Convert.ToString(sub.GetValue("DisplayIcon")) ?? "");
|
|
676
|
+
if (iconExe.Length == 0) continue;
|
|
677
|
+
if (iconExe.IndexOf("unins", StringComparison.OrdinalIgnoreCase) >= 0 || iconExe.IndexOf("setup", StringComparison.OrdinalIgnoreCase) >= 0) continue;
|
|
678
|
+
AddIfNew(list, seen, displayName, "exe:" + iconExe);
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
catch (Exception) { }
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
catch (Exception) { }
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
static List<KeyValuePair<string, string>> Load()
|
|
691
|
+
{
|
|
692
|
+
if (cache != null && (DateTime.UtcNow - cachedAt).TotalSeconds < 600) return cache;
|
|
693
|
+
var list = new List<KeyValuePair<string, string>>();
|
|
694
|
+
var seen = new HashSet<string>();
|
|
695
|
+
Type t = Type.GetTypeFromProgID("Shell.Application");
|
|
696
|
+
dynamic shell = Activator.CreateInstance(t);
|
|
697
|
+
try
|
|
698
|
+
{
|
|
699
|
+
dynamic folder = shell.NameSpace("shell:AppsFolder");
|
|
700
|
+
foreach (dynamic item in folder.Items())
|
|
701
|
+
{
|
|
702
|
+
string name = item.Name; string path = item.Path;
|
|
703
|
+
AddIfNew(list, seen, name, path);
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
finally { Marshal.FinalReleaseComObject(shell); }
|
|
707
|
+
// Desktop & Start Menu shortcuts: portable and classic apps often only live there.
|
|
708
|
+
foreach (var folder in new[] {
|
|
709
|
+
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory),
|
|
710
|
+
Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory),
|
|
711
|
+
Environment.GetFolderPath(Environment.SpecialFolder.Programs),
|
|
712
|
+
Environment.GetFolderPath(Environment.SpecialFolder.CommonPrograms),
|
|
713
|
+
})
|
|
714
|
+
{
|
|
715
|
+
ScanStartFolder(folder, 0, list, seen);
|
|
716
|
+
}
|
|
717
|
+
// Registry App Paths & Uninstall executable locations.
|
|
718
|
+
ScanRegistryApps(list, seen);
|
|
719
|
+
cache = list; cachedAt = DateTime.UtcNow;
|
|
720
|
+
return list;
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
public static List<object> Search(string query, int limit)
|
|
724
|
+
{
|
|
725
|
+
string q = query.Trim().ToLowerInvariant();
|
|
726
|
+
var scored = new List<KeyValuePair<int, KeyValuePair<string, string>>>();
|
|
727
|
+
foreach (var app in All())
|
|
728
|
+
{
|
|
729
|
+
string n = app.Key.ToLowerInvariant();
|
|
730
|
+
int score = n == q ? 0 : n.StartsWith(q) ? 1 : n.Contains(q) ? 2 : (q.Length > 0 && q.Contains(n)) ? 3 : app.Value.ToLowerInvariant().Contains(q) ? 4 : -1;
|
|
731
|
+
if (q.Length == 0) score = 5;
|
|
732
|
+
if (score >= 0) scored.Add(new KeyValuePair<int, KeyValuePair<string, string>>(score * 1000 + Math.Min(n.Length, 999), app));
|
|
733
|
+
}
|
|
734
|
+
scored.Sort(delegate (KeyValuePair<int, KeyValuePair<string, string>> a, KeyValuePair<int, KeyValuePair<string, string>> b) { return a.Key.CompareTo(b.Key); });
|
|
735
|
+
var result = new List<object>();
|
|
736
|
+
for (int i = 0; i < scored.Count && i < limit; i++)
|
|
737
|
+
{
|
|
738
|
+
var d = new Dictionary<string, object>();
|
|
739
|
+
d["name"] = scored[i].Value.Key; d["id"] = scored[i].Value.Value;
|
|
740
|
+
result.Add(d);
|
|
741
|
+
}
|
|
742
|
+
return result;
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
public static object Launch(Dictionary<string, object> r)
|
|
746
|
+
{
|
|
747
|
+
string appId = Args.Str(r, "appId", "");
|
|
748
|
+
string target = Args.Str(r, "target", "");
|
|
749
|
+
string args = Args.Str(r, "args", "");
|
|
750
|
+
ProcessStartInfo psi;
|
|
751
|
+
if (appId.StartsWith("lnk:")) psi = new ProcessStartInfo(appId.Substring(4));
|
|
752
|
+
else if (appId.StartsWith("exe:")) psi = new ProcessStartInfo(appId.Substring(4));
|
|
753
|
+
else if (appId.Length > 0) psi = new ProcessStartInfo("explorer.exe", "shell:AppsFolder\\" + appId);
|
|
754
|
+
else { psi = new ProcessStartInfo(target); if (args.Length > 0) psi.Arguments = args; }
|
|
755
|
+
psi.UseShellExecute = true;
|
|
756
|
+
using (var p = Process.Start(psi)) { }
|
|
757
|
+
return null;
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
}
|