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

ActiveWindow.ts

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