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

ActiveWindow.ts

177 lines5.7 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 MAC_HELPER_STRIP_MAX_THICKNESS_RATIO = 0.25;
34​
35const MacActiveWindowLookup = Schema.Struct({
36 owner: Schema.Struct({
37 name: Schema.String,
38 processId: Schema.Number,
39 path: Schema.String,
40 bundleId: Schema.String,
41 }),
42 windows: Schema.Array(
43 Schema.Struct({
44 id: Schema.Number,
45 title: Schema.String,
46 bounds: Schema.Struct({
47 x: Schema.Number,
48 y: Schema.Number,
49 width: Schema.Number,
50 height: Schema.Number,
51 }),
52 alpha: Schema.Number,
53 }),
54 ),
55});
56const decodeMacActiveWindowLookup = Schema.decodeUnknownSync(
57 Schema.fromJsonString(MacActiveWindowLookup),
58);
59​
60const MAC_LOOKUP_SCRIPT = `
61ObjC.import("CoreGraphics");
62ObjC.import("AppKit");
63function run() {
64 const app = $.NSWorkspace.sharedWorkspace.frontmostApplication;
65 if (app.isNil()) return "";
66 const pid = app.processIdentifier;
67 let ownerName = String(app.localizedName.js || "");
68 const list = $.CGWindowListCopyWindowInfo(
69 $.kCGWindowListOptionOnScreenOnly | $.kCGWindowListExcludeDesktopElements,
70 $.kCGNullWindowID,
71 );
72 $.CFMakeCollectable(list);
73 const count = $.CFArrayGetCount(list);
74 const windows = [];
75 for (let i = 0; i < count; i++) {
76 const w = ObjC.castRefToObject($.CFArrayGetValueAtIndex(list, i));
77 if (w.objectForKey("kCGWindowOwnerPID").js !== pid) continue;
78 if (w.objectForKey("kCGWindowLayer").js !== 0) continue;
79 if (!ownerName) {
80 ownerName = String(ObjC.unwrap(w.objectForKey("kCGWindowOwnerName")) || "");
81 }
82 const b = ObjC.deepUnwrap(w.objectForKey("kCGWindowBounds"));
83 windows.push({
84 id: w.objectForKey("kCGWindowNumber").js,
85 title: String(ObjC.unwrap(w.objectForKey("kCGWindowName")) || ""),
86 bounds: { x: b.X, y: b.Y, width: b.Width, height: b.Height },
87 alpha: w.objectForKey("kCGWindowAlpha").js,
88 });
89 }
90 return JSON.stringify({
91 owner: {
92 name: ownerName,
93 processId: pid,
94 path: String(app.bundleURL.path.js || ""),
95 bundleId: String(app.bundleIdentifier.js || ""),
96 },
97 windows,
98 });
99}`;
100​
101function runMacLookup(): Promise<string> {
102 return new Promise((resolve, reject) => {
103 NodeChildProcess.execFile(
104 "/usr/bin/osascript",
105 ["-l", "JavaScript", "-e", MAC_LOOKUP_SCRIPT],
106 { timeout: MAC_LOOKUP_TIMEOUT_MS, maxBuffer: 1024 * 1024 },
107 (error, stdout) => {
108 if (error) reject(error);
109 else resolve(stdout);
110 },
111 );
112 });
114​
115async function macActiveWindow(): Promise<ActiveWindow | undefined> {
116 const output = (await runMacLookup()).trim();
117 if (!output) return undefined;
118 const lookup = decodeMacActiveWindowLookup(output);
119 const visible = lookup.windows.filter(
120 (window) => window.alpha > 0 && window.bounds.width > 0 && window.bounds.height > 0,
121 );
122 // Helpers belong to the content behind them, which may not be the app's largest window.
123 const window = visible.find((candidate, index) => {
124 if (candidate.title.trim() !== "") return true;
125 const bounds = candidate.bounds;
126 return !visible.some((reference, referenceIndex) => {
127 if (referenceIndex <= index) return false;
128 return (
129 (bounds.x === reference.bounds.x &&
130 bounds.width === reference.bounds.width &&
131 bounds.height <= bounds.width * MAC_HELPER_STRIP_MAX_THICKNESS_RATIO &&
132 bounds.height <= reference.bounds.height * MAC_HELPER_STRIP_MAX_THICKNESS_RATIO) ||
133 (bounds.y === reference.bounds.y &&
134 bounds.height === reference.bounds.height &&
135 bounds.width <= bounds.height * MAC_HELPER_STRIP_MAX_THICKNESS_RATIO &&
136 bounds.width <= reference.bounds.width * MAC_HELPER_STRIP_MAX_THICKNESS_RATIO)
137 );
138 });
139 });
140 if (!window) return undefined;
141 return {
142 platform: "macos",
143 id: window.id,
144 title: window.title,
145 bounds: window.bounds,
146 owner: {
147 name: lookup.owner.name,
148 processId: lookup.owner.processId,
149 path: lookup.owner.path,
150 ...(lookup.owner.bundleId ? { bundleId: lookup.owner.bundleId } : {}),
151 },
152 };
154​
155async function windowsActiveWindow(): Promise<ActiveWindow | undefined> {
156 const api = await loadWindowsForegroundApi();
157 const handle = api.getForegroundWindow();
158 if (handle === 0n) return undefined;
159 const bounds = api.getWindowRect(handle);
160 if (!bounds) return undefined;
161 const { processId } = api.getWindowThreadAndProcessId(handle);
162 const path = processId === 0 ? "" : api.getProcessImagePath(processId);
163 const name = path.split(/[\\/]/).pop() ?? "";
164 return {
165 platform: "windows",
166 id: Number(handle),
167 title: api.getWindowText(handle),
168 bounds,
169 owner: { name, processId, path },
170 };
172​
173export function activeWindow(platform: NodeJS.Platform): Promise<ActiveWindow | undefined> {
174 if (platform === "darwin") return macActiveWindow();
175 if (platform === "win32") return windowsActiveWindow();
176 return Promise.resolve(undefined);