Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ActiveWindow.ts

135 lines4.2 KB

1// @effect-diagnostics nodeBuiltinImport:off -- This platform boundary asks the OS for its foreground window with Node.
2​
3import * as NodeChildProcess from "node:child_process";
4​
5import * as Schema from "effect/Schema";
6​
7import { loadWindowsForegroundApi } from "../electron/WindowsForeground.ts";
8​
9/** id is CGWindowNumber on macOS or HWND on Windows, matching the capture backend. */
10export type ActiveWindow = {
11 readonly platform: "macos" | "windows";
12 readonly id: number;
13 readonly title: string;
14 readonly bounds: {
15 readonly x: number;
16 readonly y: number;
17 readonly width: number;
18 readonly height: number;
19 };
20 readonly owner: {
21 readonly name: string;
22 readonly processId: number;
23 readonly path: string;
24 readonly bundleId?: string;
25 };
26};
27​
28const MAC_LOOKUP_TIMEOUT_MS = 5_000;
29​
30const MacActiveWindow = Schema.Struct({
31 id: Schema.Number,
32 title: Schema.String,
33 bounds: Schema.Struct({
34 x: Schema.Number,
35 y: Schema.Number,
36 width: Schema.Number,
37 height: Schema.Number,
38 }),
39 owner: Schema.Struct({
40 name: Schema.String,
41 processId: Schema.Number,
42 path: Schema.String,
43 bundleId: Schema.String,
44 }),
45});
46const decodeMacActiveWindow = Schema.decodeUnknownSync(Schema.fromJsonString(MacActiveWindow));
47​
48const MAC_LOOKUP_SCRIPT = `
49ObjC.import("CoreGraphics");
50ObjC.import("AppKit");
51function run() {
52 const app = $.NSWorkspace.sharedWorkspace.frontmostApplication;
53 if (app.isNil()) return "";
54 const pid = app.processIdentifier;
55 const list = $.CGWindowListCopyWindowInfo(
56 $.kCGWindowListOptionOnScreenOnly | $.kCGWindowListExcludeDesktopElements,
57 $.kCGNullWindowID,
58 );
59 $.CFMakeCollectable(list);
60 const count = $.CFArrayGetCount(list);
61 for (let i = 0; i < count; i++) {
62 const w = ObjC.castRefToObject($.CFArrayGetValueAtIndex(list, i));
63 if (w.objectForKey("kCGWindowOwnerPID").js !== pid) continue;
64 if (w.objectForKey("kCGWindowLayer").js !== 0) continue;
65 const b = ObjC.deepUnwrap(w.objectForKey("kCGWindowBounds"));
66 return JSON.stringify({
67 id: w.objectForKey("kCGWindowNumber").js,
68 title: String(ObjC.unwrap(w.objectForKey("kCGWindowName")) || ""),
69 bounds: { x: b.X, y: b.Y, width: b.Width, height: b.Height },
70 owner: {
71 name: String(app.localizedName.js || ObjC.unwrap(w.objectForKey("kCGWindowOwnerName")) || ""),
72 processId: pid,
73 path: String(app.bundleURL.path.js || ""),
74 bundleId: String(app.bundleIdentifier.js || ""),
75 },
76 });
77 }
78 return "";
79}`;
80​
81function runMacLookup(): Promise<string> {
82 return new Promise((resolve, reject) => {
83 NodeChildProcess.execFile(
84 "/usr/bin/osascript",
85 ["-l", "JavaScript", "-e", MAC_LOOKUP_SCRIPT],
86 { timeout: MAC_LOOKUP_TIMEOUT_MS, maxBuffer: 64 * 1024 },
87 (error, stdout) => {
88 if (error) reject(error);
89 else resolve(stdout);
90 },
91 );
92 });
94​
95async function macActiveWindow(): Promise<ActiveWindow | undefined> {
96 const output = (await runMacLookup()).trim();
97 if (!output) return undefined;
98 const window = decodeMacActiveWindow(output);
99 return {
100 platform: "macos",
101 id: window.id,
102 title: window.title,
103 bounds: window.bounds,
104 owner: {
105 name: window.owner.name,
106 processId: window.owner.processId,
107 path: window.owner.path,
108 ...(window.owner.bundleId ? { bundleId: window.owner.bundleId } : {}),
109 },
110 };
112​
113async function windowsActiveWindow(): Promise<ActiveWindow | undefined> {
114 const api = await loadWindowsForegroundApi();
115 const handle = api.getForegroundWindow();
116 if (handle === 0n) return undefined;
117 const bounds = api.getWindowRect(handle);
118 if (!bounds) return undefined;
119 const { processId } = api.getWindowThreadAndProcessId(handle);
120 const path = processId === 0 ? "" : api.getProcessImagePath(processId);
121 const name = path.split(/[\\/]/).pop() ?? "";
122 return {
123 platform: "windows",
124 id: Number(handle),
125 title: api.getWindowText(handle),
126 bounds,
127 owner: { name, processId, path },
128 };
130​
131export function activeWindow(platform: NodeJS.Platform): Promise<ActiveWindow | undefined> {
132 if (platform === "darwin") return macActiveWindow();
133 if (platform === "win32") return windowsActiveWindow();
134 return Promise.resolve(undefined);