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's bundle-icon lookup can return the generic app icon for mounted artifacts.
92 // Use the same PNG that packaging uses to generate the app's macOS icon.
93 const appIcon = iconPaths
94 .map((iconPath) => Electron.nativeImage.createFromPath(iconPath))
95 .find((image) => !image.isEmpty());
96 if (!appIcon) throw new Error("The packaged T3 Code icon is missing.");
97 const icon = appIcon.resize({ width: 64, height: 64 });
98 const window = new Electron.BrowserWindow({
99 width: 560,
100 height: 140,
101 show: false,
102 frame: false,
103 transparent: true,
104 roundedCorners: false,
105 backgroundColor: "#00000000",
106 hasShadow: false,
107 resizable: false,
108 minimizable: false,
109 maximizable: false,
110 fullscreenable: false,
111 alwaysOnTop: true,
112 skipTaskbar: true,
113 title: `Set up ${MAC_PERMISSION_TITLES[permission]}`,
114 webPreferences: { preload, sandbox: true, contextIsolation: true, nodeIntegration: false },
115 });
116 this.window = window;
117 const finish = () => {
118 window.close();
119 if (owner && !owner.isDestroyed()) {
120 owner.show();
121 owner.focus();
122 }
123 };
124 let checking = false;
125 const check = async () => {
126 if (checking || window.isDestroyed()) return;
127 checking = true;
128 try {
129 if ((await isGranted()) && !window.isDestroyed()) finish();
130 } catch {
131 } finally {
132 checking = false;
133 }
134 };
135 const onMessage = (event: Electron.IpcMainEvent, action: unknown) => {
136 if (event.sender !== window.webContents || event.senderFrame !== window.webContents.mainFrame)
137 return;
138 if (action === "drag") {
139 try {
140 window.webContents.startDrag({ file: bundle, icon });
141 } catch {
142 Electron.shell.showItemInFolder(bundle);
143 }
144 } else if (action === "finder") {
145 Electron.shell.showItemInFolder(bundle);
146 } else if (action === "close") {
147 finish();
148 }
149 };
150 let settingsWindow: SettingsWindow = null;
151 let foundSettings = false;
152 let trackingAvailable = true;
153 const syncPosition = () => {
154 if (window.isDestroyed()) return;
155 if (!trackingAvailable) {
156 window.hide();
157 return;
158 }
159 if (!settingsWindow && foundSettings) {
160 finish();
161 return;
162 }
163 if (!settingsWindow || (!settingsWindow.frontmost && !window.isFocused())) {
164 window.hide();
165 return;
166 }
167 const bounds = settingsHelperBounds(settingsWindow);
168 const current = window.getBounds();
169 if (
170 current.x !== bounds.x ||
171 current.y !== bounds.y ||
172 current.width !== bounds.width ||
173 current.height !== bounds.height
174 ) {
175 window.setBounds(bounds, false);
176 }
177 if (!window.isVisible()) window.showInactive();
178 };
179 let stopTracking = () => {};
180 window.on("blur", syncPosition);
181 const onOwnerClosed = () => window.destroy();
182 Electron.ipcMain.on(MAC_PERMISSION_HELPER_CHANNEL, onMessage);
183 const timer = setInterval(check, 1_000);
184 owner?.once("closed", onOwnerClosed);
185 window.once("closed", () => {
186 clearInterval(timer);
187 stopTracking();
188 Electron.ipcMain.removeListener(MAC_PERMISSION_HELPER_CHANNEL, onMessage);
189 owner?.removeListener("closed", onOwnerClosed);
190 if (this.window === window) this.window = undefined;
191 });
192 window.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
193 window.webContents.on("will-navigate", (event) => event.preventDefault());
194 try {
195 await window.loadURL(
196 `data:text/html;charset=utf-8,${encodeURIComponent(helperHtml(permission, icon.toDataURL()))}`,
197 );
198 if (!window.isDestroyed()) {
199 stopTracking = watchMacSettingsWindow(
200 (current) => {
201 trackingAvailable = true;
202 settingsWindow = current;
203 if (current) foundSettings = true;
204 syncPosition();
205 },
206 () => {
207 trackingAvailable = false;
208 syncPosition();
209 },
210 );
211 }
212 } catch (error) {
213 if (!window.isDestroyed()) window.destroy();
214 throw error;
215 }
216 }
217}