Open History to see the last commit
1// @effect-diagnostics globalTimers:off -- Poll TCC only while the native permission helper is open.
2import * as Electron from "electron";
3import { MAC_PERMISSION_HELPER_CHANNEL } from "../ipc/channels.ts";
4
5import {
6 settingsHelperBounds,
7 watchMacSettingsWindow,
8 type SettingsWindow,
9} from "./MacSettingsWindow.ts";
10
11import { MAC_PERMISSION_TITLES, type MacPermission } from "./MacPermission.ts";
12
13const permissionGranted = (permission: MacPermission) => {
14 if (permission === "screen-recording")
15 return Electron.systemPreferences.getMediaAccessStatus("screen") === "granted";
16 if (permission === "accessibility")
17 return Electron.systemPreferences.isTrustedAccessibilityClient(false);
18 return false;
19};
20
21function macAppBundlePath(executable: string): string | undefined {
22 return /^(.+\.app)\/Contents\/MacOS\/[^/]+$/.exec(executable)?.[1];
23}
24
25const escapeHtml = (value: string) =>
26 value.replace(/[&<>"']/g, (character) => {
27 switch (character) {
28 case "&":
29 return "&";
30 case "<":
31 return "<";
32 case ">":
33 return ">";
34 case '"':
35 return """;
36 default:
37 return "'";
38 }
39 });
40
41function helperHtml(permission: MacPermission, icon: string) {
42 const title = MAC_PERMISSION_TITLES[permission];
43 return `<!doctype html><html lang="en"><head><meta charset="utf-8">
44<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src data:; style-src 'unsafe-inline'">
45<title>Set up ${title}</title><style>
46:root { color-scheme: light dark; --base: #fff; --row: #e7e7e7; --text: #292929; --line: #e3e3e3; }
47@media (prefers-color-scheme: dark) { :root { --base: #242424; --row: #383838; --text: #f5f5f5; --line: #484848; } }
48* { box-sizing: border-box; }
49html { background: transparent; }
50body { margin: 0; background: transparent; color: var(--text); font: 15px/22px -apple-system, BlinkMacSystemFont, sans-serif; user-select: none; }
51#panel { position: relative; margin: 2px; padding: 20px; height: 136px; border: 1px solid var(--line); border-radius: 24px; background: var(--base); }
52header { font-weight: 600; white-space: nowrap; }
53button { font: inherit; color: inherit; }
54button:focus-visible { outline: 2px solid #007aff; outline-offset: -2px; }
55#close { position: absolute; right: 8px; top: 6px; width: 22px; height: 22px; padding: 0; border: 0; border-radius: 50%; background: var(--base); font-size: 18px; cursor: pointer; opacity: 0; }
56#panel:hover #close, #close:focus-visible { opacity: 1; }
57#app { display: flex; align-items: center; gap: 12px; width: 100%; height: 52px; margin-top: 20px; padding: 8px 12px; border: 0; border-radius: 10px; background: var(--row); cursor: grab; text-align: left; font-size: 16px; font-weight: 600; }
58#app:active { cursor: grabbing; }
59img { width: 32px; height: 32px; pointer-events: none; }
60</style></head><body><main id="panel">
61<button id="close" aria-label="Close permission helper">×</button>
62<header>↑ Drag T3 Code into the list above</header>
63<button id="app" draggable="true" aria-label="Drag T3 Code to System Settings, or click to reveal in Finder"><img src="${escapeHtml(icon)}" alt="" draggable="false">T3 Code</button>
64</main></body></html>`;
65}
66
67export class MacPermissionHelper {
68 private generation = 0;
69 private window: Electron.BrowserWindow | undefined;
70
71 close() {
72 this.generation++;
73 this.window?.destroy();
74 this.window = undefined;
75 }
76
77 async show(
78 permission: MacPermission,
79 preload: string,
80 owner: Electron.BrowserWindow | null,
81 iconPaths: readonly string[],
82 isGranted: () => boolean | Promise<boolean> = () => permissionGranted(permission),
83 ) {
84 this.close();
85 const generation = this.generation;
86 if (await isGranted()) return;
87 if (generation !== this.generation) return;
88 const bundle = macAppBundlePath(Electron.app.getPath("exe"));
89 if (!bundle) return;
90 if (owner?.isDestroyed()) return;
91 // Finder can return generic icons for mounted artifacts; use the packaging PNG.
92 const appIcon = iconPaths
93 .map((iconPath) => Electron.nativeImage.createFromPath(iconPath))
94 .find((image) => !image.isEmpty());
95 if (!appIcon) throw new Error("The packaged T3 Code icon is missing.");
96 const icon = appIcon.resize({ width: 64, height: 64 });
97 const window = new Electron.BrowserWindow({
98 width: 560,
99 height: 140,
100 show: false,
101 frame: false,
102 transparent: true,
103 roundedCorners: false,
104 backgroundColor: "#00000000",
105 hasShadow: false,
106 resizable: false,
107 minimizable: false,
108 maximizable: false,
109 fullscreenable: false,
110 alwaysOnTop: true,
111 skipTaskbar: true,
112 title: `Set up ${MAC_PERMISSION_TITLES[permission]}`,
113 webPreferences: { preload, sandbox: true, contextIsolation: true, nodeIntegration: false },
114 });
115 this.window = window;
116 const finish = () => {
117 window.close();
118 if (owner && !owner.isDestroyed()) {
119 owner.show();
120 owner.focus();
121 }
122 };
123 let checking = false;
124 const check = async () => {
125 if (checking || window.isDestroyed()) return;
126 checking = true;
127 try {
128 if ((await isGranted()) && !window.isDestroyed()) finish();
129 } catch {
130 } finally {
131 checking = false;
132 }
133 };
134 const onMessage = (event: Electron.IpcMainEvent, action: unknown) => {
135 if (event.sender !== window.webContents || event.senderFrame !== window.webContents.mainFrame)
136 return;
137 if (action === "drag") {
138 try {
139 window.webContents.startDrag({ file: bundle, icon });
140 } catch {
141 Electron.shell.showItemInFolder(bundle);
142 }
143 } else if (action === "finder") {
144 Electron.shell.showItemInFolder(bundle);
145 } else if (action === "close") {
146 finish();
147 }
148 };
149 let settingsWindow: SettingsWindow = null;
150 let foundSettings = false;
151 let trackingAvailable = true;
152 const syncPosition = () => {
153 if (window.isDestroyed()) return;
154 if (!trackingAvailable) {
155 window.hide();
156 return;
157 }
158 if (!settingsWindow && foundSettings) {
159 finish();
160 return;
161 }
162 if (!settingsWindow || (!settingsWindow.frontmost && !window.isFocused())) {
163 window.hide();
164 return;
165 }
166 const bounds = settingsHelperBounds(settingsWindow);
167 const current = window.getBounds();
168 if (
169 current.x !== bounds.x ||
170 current.y !== bounds.y ||
171 current.width !== bounds.width ||
172 current.height !== bounds.height
173 ) {
174 window.setBounds(bounds, false);
175 }
176 if (!window.isVisible()) window.showInactive();
177 };
178 let stopTracking = () => {};
179 window.on("blur", syncPosition);
180 const onOwnerClosed = () => window.destroy();
181 Electron.ipcMain.on(MAC_PERMISSION_HELPER_CHANNEL, onMessage);
182 const timer = setInterval(check, 1_000);
183 owner?.once("closed", onOwnerClosed);
184 window.once("closed", () => {
185 clearInterval(timer);
186 stopTracking();
187 Electron.ipcMain.removeListener(MAC_PERMISSION_HELPER_CHANNEL, onMessage);
188 owner?.removeListener("closed", onOwnerClosed);
189 if (this.window === window) this.window = undefined;
190 });
191 window.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
192 window.webContents.on("will-navigate", (event) => event.preventDefault());
193 try {
194 await window.loadURL(
195 `data:text/html;charset=utf-8,${encodeURIComponent(helperHtml(permission, icon.toDataURL()))}`,
196 );
197 if (!window.isDestroyed()) {
198 stopTracking = watchMacSettingsWindow(
199 (current) => {
200 trackingAvailable = true;
201 settingsWindow = current;
202 if (current) foundSettings = true;
203 syncPosition();
204 },
205 () => {
206 trackingAvailable = false;
207 syncPosition();
208 },
209 );
210 }
211 } catch (error) {
212 if (!window.isDestroyed()) window.destroy();
213 throw error;
214 }
215 }
216}