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

ActiveWindow.ts

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