Repository navigation
Expand file tree
/
Copy pathtaskbar-win.js
More file actions
351 lines (323 loc) · 12.8 KB
/
Copy pathtaskbar-win.js
File metadata and controls
351 lines (323 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
// Windows-only helpers for the taskbar overlay widget.
//
// We render the widget as a normal top-level, always-on-top, non-activating,
// layered window positioned *over* the taskbar (rather than reparenting it into
// "Shell_TrayWnd"). So this module's job is just to report taskbar geometry —
// the taskbar rect, the system-tray rect (the right anchor) and the weather /
// Widgets button's right edge (the left anchor) — plus two small helpers used
// while dragging: keep our window's z-order above the (topmost) taskbar, and
// read the physical mouse-button state.
//
// All native calls go through koffi (FFI) and are wrapped so failures degrade
// gracefully. Only require() this module on Windows.
const koffi = require('koffi');
const { execFile } = require('child_process');
const user32 = koffi.load('user32.dll');
const shell32 = koffi.load('shell32.dll');
// ---- Win32 type / function bindings ----
// HWNDs are passed as pointer-sized unsigned integers (uintptr_t); on x64 a
// returned pointer and a uintptr_t share the same register, so this is safe.
const RECT = koffi.struct('RECT', {
left: 'long',
top: 'long',
right: 'long',
bottom: 'long',
});
const POINT = koffi.struct('POINT', {
x: 'long',
y: 'long',
});
const MONITORINFO = koffi.struct('MONITORINFO', {
cbSize: 'uint32',
rcMonitor: RECT,
rcWork: RECT,
dwFlags: 'uint32',
});
const FindWindowW = user32.func('FindWindowW', 'uintptr_t', ['str16', 'str16']);
const FindWindowExW = user32.func('FindWindowExW', 'uintptr_t', [
'uintptr_t', 'uintptr_t', 'str16', 'str16',
]);
const GetWindowRect = user32.func('GetWindowRect', 'bool', [
'uintptr_t', koffi.out(koffi.pointer(RECT)),
]);
const GetClientRect = user32.func('GetClientRect', 'bool', [
'uintptr_t', koffi.out(koffi.pointer(RECT)),
]);
const ClientToScreen = user32.func('ClientToScreen', 'bool', [
'uintptr_t', koffi.inout(koffi.pointer(POINT)),
]);
const SetWindowPos = user32.func('SetWindowPos', 'bool', [
'uintptr_t', 'uintptr_t', 'int', 'int', 'int', 'int', 'uint',
]);
const GetAsyncKeyState = user32.func('GetAsyncKeyState', 'short', ['int']);
const GetForegroundWindow = user32.func('GetForegroundWindow', 'uintptr_t', []);
const EnumWindows = user32.func('EnumWindows', 'bool', [
'void *', 'intptr_t',
]);
const IsWindowVisible = user32.func('IsWindowVisible', 'bool', ['uintptr_t']);
const IsIconic = user32.func('IsIconic', 'bool', ['uintptr_t']);
const MonitorFromWindow = user32.func('MonitorFromWindow', 'uintptr_t', ['uintptr_t', 'uint']);
const GetMonitorInfoW = user32.func('GetMonitorInfoW', 'bool', [
'uintptr_t', koffi.out(koffi.pointer(MONITORINFO)),
]);
// Windows exposes this notification state for fullscreen / presentation
// activity. Window geometry alone is unreliable for many games.
const SHQueryUserNotificationState = shell32.func('SHQueryUserNotificationState', 'long', [
koffi.out(koffi.pointer('int')),
]);
// WinEvent hook: fires whenever the system foreground window changes. We use it
// to re-assert our overlay's z-order the instant another app is activated,
// instead of waiting for the slow (1s) reposition tick.
const WinEventProc = koffi.proto(
'void __stdcall WinEventProc(void* hook, uint32 event, uintptr_t hwnd, ' +
'int32 idObject, int32 idChild, uint32 idEventThread, uint32 dwmsEventTime)'
);
const EnumWindowsProc = koffi.proto(
'bool __stdcall EnumWindowsProc(uintptr_t hwnd, intptr_t lParam)'
);
const SetWinEventHook = user32.func('SetWinEventHook', 'void*', [
'uint32', 'uint32', 'uintptr_t', koffi.pointer(WinEventProc), 'uint32', 'uint32', 'uint32',
]);
const UnhookWinEvent = user32.func('UnhookWinEvent', 'bool', ['void*']);
// ---- Win32 constants ----
const HWND_TOPMOST = 0xffffffffffffffffn; // (HWND)-1
const SWP_NOSIZE = 0x0001;
const SWP_NOMOVE = 0x0002;
const SWP_NOACTIVATE = 0x0010;
const VK_LBUTTON = 0x01;
const MONITOR_DEFAULTTONEAREST = 0x00000002;
const EVENT_SYSTEM_FOREGROUND = 0x0003;
const WINEVENT_OUTOFCONTEXT = 0x0000;
const WINEVENT_SKIPOWNPROCESS = 0x0002;
const S_OK = 0;
const QUNS_BUSY = 2;
const QUNS_RUNNING_D3D_FULL_SCREEN = 3;
const QUNS_PRESENTATION_MODE = 4;
function toHandle(v) {
return typeof v === 'bigint' ? v : BigInt(v);
}
function rectOf(h) {
const r = {};
if (!GetWindowRect(h, r)) return null;
return { left: r.left, top: r.top, right: r.right, bottom: r.bottom };
}
// A fullscreen app's *content* can fill the monitor even when its outer
// window keeps a small invisible resize border. Looking at both rectangles
// prevents those F11 / video-player windows being mistaken for normal windows.
function clientRectOf(h) {
const r = {};
if (!GetClientRect(h, r)) return null;
const topLeft = { x: r.left, y: r.top };
const bottomRight = { x: r.right, y: r.bottom };
if (!ClientToScreen(h, topLeft) || !ClientToScreen(h, bottomRight)) return null;
return {
left: topLeft.x,
top: topLeft.y,
right: bottomRight.x,
bottom: bottomRight.y,
};
}
function coversMonitor(rect, monitorRect) {
if (!rect || !monitorRect) return false;
// Account for the few physical pixels of invisible resize border Windows
// may add around a borderless/fullscreen window.
const tolerance = 8;
return rect.left <= monitorRect.left + tolerance &&
rect.top <= monitorRect.top + tolerance &&
rect.right >= monitorRect.right - tolerance &&
rect.bottom >= monitorRect.bottom - tolerance;
}
function isFullscreenOrPresentationActive() {
try {
const state = [0];
if (SHQueryUserNotificationState(state) !== S_OK) return false;
// Windows Fullscreen Optimizations commonly reports games as QUNS_BUSY
// rather than the narrower QUNS_RUNNING_D3D_FULL_SCREEN. Treat the
// notification-suppression presentation state the same way: the panel
// should not remain over an uninterrupted full-screen experience.
return state[0] === QUNS_BUSY ||
state[0] === QUNS_RUNNING_D3D_FULL_SCREEN ||
state[0] === QUNS_PRESENTATION_MODE;
} catch {
return false;
}
}
function isFullscreenWindow(hwnd) {
const windowRect = rectOf(hwnd);
const clientRect = clientRectOf(hwnd);
const monitor = toHandle(MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST));
if (!windowRect || !monitor) return false;
const info = { cbSize: koffi.sizeof(MONITORINFO) };
if (!GetMonitorInfoW(monitor, info) || !info.rcMonitor) return false;
return coversMonitor(windowRect, info.rcMonitor) || coversMonitor(clientRect, info.rcMonitor);
}
// Some DX12 and borderless games do not report their rendering window as the
// foreground HWND. Look for another visible, non-minimized top-level window
// that fills its monitor as a final fallback. This intentionally excludes our
// own non-activating overlay via `ownHwnd`.
function hasVisibleFullscreenWindow(ownHwnd) {
let callback = null;
let fullscreenFound = false;
try {
callback = koffi.register((hwnd) => {
try {
const candidate = toHandle(hwnd);
if (!candidate || (ownHwnd && candidate === toHandle(ownHwnd)) ||
!IsWindowVisible(candidate) || IsIconic(candidate)) {
return true;
}
if (isFullscreenWindow(candidate)) {
fullscreenFound = true;
return false; // stop enumerating once a match is found
}
} catch {}
return true;
}, koffi.pointer(EnumWindowsProc));
EnumWindows(callback, 0);
} catch {}
finally {
try {
if (callback) koffi.unregister(callback);
} catch {}
}
return fullscreenFound;
}
function findTaskbar() {
return toHandle(FindWindowW('Shell_TrayWnd', null));
}
// ---- Weather / Widgets button (left anchor) ----
// The native weather/Widgets button isn't a real HWND — it lives inside the
// taskbar's XAML/composition surface — so we locate it through UI Automation
// (by its stable AutomationId "WidgetsButton") and read its bounding rect.
// Run out-of-process via PowerShell; the lookup is ~250ms so callers poll it
// occasionally. Output: "x,y,w,h" (screen px) or empty.
const UIA_PROBE = [
"$ErrorActionPreference='SilentlyContinue'",
'Add-Type -AssemblyName UIAutomationClient',
'Add-Type -AssemblyName UIAutomationTypes',
'$ae=[System.Windows.Automation.AutomationElement]',
'$root=$ae::RootElement',
"$tc=New-Object System.Windows.Automation.PropertyCondition($ae::ClassNameProperty,'Shell_TrayWnd')",
'$tray=$root.FindFirst([System.Windows.Automation.TreeScope]::Children,$tc)',
'if($tray){',
" $ic=New-Object System.Windows.Automation.PropertyCondition($ae::AutomationIdProperty,'WidgetsButton')",
' $b=$tray.FindFirst([System.Windows.Automation.TreeScope]::Descendants,$ic)',
" if($b){$r=$b.Current.BoundingRectangle; Write-Output ('{0},{1},{2},{3}' -f [int]$r.X,[int]$r.Y,[int]$r.Width,[int]$r.Height)}",
'}',
].join('\n');
let widgetsButtonRight = null; // screen-x of the weather button's right edge, or null
function refreshWidgetsButton() {
const encoded = Buffer.from(UIA_PROBE, 'utf16le').toString('base64');
execFile(
'powershell.exe',
['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', encoded],
{ timeout: 4000, windowsHide: true },
(err, stdout) => {
if (err) return; // keep the last known value on failure
const m = String(stdout).trim().match(/^(-?\d+),(-?\d+),(-?\d+),(-?\d+)/);
widgetsButtonRight = m ? parseInt(m[1], 10) + parseInt(m[3], 10) : null;
}
);
}
// Current taskbar geometry in physical (screen) pixels, or null if the taskbar
// can't be found. trayRect is the system-tray/clock region (right anchor);
// widgetsRight is the weather button's right edge (left anchor) or null.
function getLayout() {
const tray = findTaskbar();
if (!tray) return null;
const taskbarRect = rectOf(tray);
if (!taskbarRect) return null;
const trayNotify = toHandle(FindWindowExW(tray, 0n, 'TrayNotifyWnd', null));
const trayRect = trayNotify ? rectOf(trayNotify) : null;
return { taskbarRect, trayRect, widgetsRight: widgetsButtonRight };
}
// Re-assert our window's z-order above the (topmost) taskbar without moving,
// resizing, or activating it.
function assertTopmost(hwnd) {
try {
SetWindowPos(toHandle(hwnd), HWND_TOPMOST, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
} catch {}
}
// Physical left-mouse-button state — lets the drag loop detect release even
// when the cursor has left our (non-activating) window.
function isLeftMouseDown() {
try {
return (GetAsyncKeyState(VK_LBUTTON) & 0x8000) !== 0;
} catch {
return false;
}
}
// True when the active, non-IPWindow window covers its entire monitor. A
// maximized normal window only covers the monitor work area (which excludes the
// taskbar), so it is deliberately not treated as fullscreen.
function hasFullscreenForeground(ownHwnd) {
try {
// Exclusive Direct3D games can use a proxy or otherwise non-fullscreen
// top-level HWND, which makes their bounds impossible to trust. Ask the
// shell first; then use geometry as the fallback for browser F11 and
// borderless fullscreen windows.
if (isFullscreenOrPresentationActive()) return true;
const foreground = toHandle(GetForegroundWindow());
if (!foreground) return hasVisibleFullscreenWindow(ownHwnd);
if (ownHwnd && foreground === toHandle(ownHwnd)) {
return hasVisibleFullscreenWindow(ownHwnd);
}
if (isFullscreenWindow(foreground)) return true;
return hasVisibleFullscreenWindow(ownHwnd);
} catch {
return false;
}
}
// ---- Foreground-change watch ----
// Keep references alive so the registered callback isn't garbage-collected while
// the OS still holds the hook.
let foregroundHook = null; // HWINEVENTHOOK pointer
let foregroundCb = null; // koffi-registered callback pointer
// Start watching for foreground-window changes. `onForeground` is invoked (with
// no arguments) on the main thread each time another app is activated, so the
// caller can immediately re-assert the overlay's z-order. Events from our own
// process are skipped. Returns true if the hook was installed. Calling again
// replaces any existing hook.
function startForegroundWatch(onForeground) {
stopForegroundWatch();
try {
foregroundCb = koffi.register(() => {
try {
onForeground();
} catch {}
}, koffi.pointer(WinEventProc));
foregroundHook = SetWinEventHook(
EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND,
0n, foregroundCb, 0, 0,
WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS
);
if (!foregroundHook) {
stopForegroundWatch();
return false;
}
return true;
} catch {
stopForegroundWatch();
return false;
}
}
function stopForegroundWatch() {
try {
if (foregroundHook) UnhookWinEvent(foregroundHook);
} catch {}
try {
if (foregroundCb) koffi.unregister(foregroundCb);
} catch {}
foregroundHook = null;
foregroundCb = null;
}
module.exports = {
getLayout,
refreshWidgetsButton,
assertTopmost,
isLeftMouseDown,
hasFullscreenForeground,
startForegroundWatch,
stopForegroundWatch,
};