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

window.ts

485 lines18.6 KB

1import {
2 ContextMenuItemSchema,
3 DesktopAppBrandingSchema,
4 DesktopEnvironmentBootstrapSchema,
5 DesktopMediaReadSchema,
6 DesktopThemeSchema,
7 EDITORS,
8 EditorId,
9 PickedThemeFileSchema,
10 PickFolderOptionsSchema,
11 PRIMARY_LOCAL_ENVIRONMENT_ID,
12 REMOTE_CAPABLE_EDITOR_IDS,
13 SystemSettingsPaneSchema,
14 type DesktopEnvironmentBootstrap,
15 type PickedThemeFile,
16} from "@t3tools/contracts";
17import { PROJECT_FAVICON_EXTENSIONS } from "@t3tools/shared/projectFavicon";
18import { resolveEditorCommand } from "@t3tools/shared/editor";
19import * as HostProcess from "@t3tools/shared/HostProcess";
20import { isRelayTracingEnabled } from "@t3tools/shared/otelEnvironment";
21import * as FileSystem from "effect/FileSystem";
22import * as Path from "effect/Path";
23import * as Effect from "effect/Effect";
24import * as Option from "effect/Option";
25import * as Schema from "effect/Schema";
26​
27import * as DesktopBackendConfiguration from "../../backend/DesktopBackendConfiguration.ts";
28import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
29import * as DesktopLocalEnvironmentAuth from "../../backend/DesktopLocalEnvironmentAuth.ts";
30import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
31import * as DesktopManagedPolicy from "../../app/DesktopManagedPolicy.ts";
32import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
33import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
34import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
35import * as ElectronApp from "../../electron/ElectronApp.ts";
36import * as ElectronDialog from "../../electron/ElectronDialog.ts";
37import * as ElectronMenu from "../../electron/ElectronMenu.ts";
38import * as ElectronShell from "../../electron/ElectronShell.ts";
39import * as ElectronTheme from "../../electron/ElectronTheme.ts";
40import * as ElectronWindow from "../../electron/ElectronWindow.ts";
41import * as Electron from "electron";
42import * as MacPermissions from "../../permissions/MacPermissions.ts";
43import { safariPermissionCheck } from "../../preview/BrowserImport/SafariPermission.ts";
44import * as IpcChannels from "../channels.ts";
45import * as DesktopIpc from "../DesktopIpc.ts";
46import {
47 extractDistroFromUncPath,
48 resolveWslPickFolderDefaultPath,
49 wslUncPathToLinuxPath,
50} from "../../wsl/wslPathParsing.ts";
51​
52const ContextMenuPosition = Schema.Struct({
53 x: Schema.Number,
54 y: Schema.Number,
55});
56​
57const ContextMenuInput = Schema.Struct({
58 items: Schema.Array(ContextMenuItemSchema),
59 position: Schema.optionalKey(ContextMenuPosition),
60});
61​
62function toWebSocketBaseUrl(httpBaseUrl: URL): string {
63 const url = new URL(httpBaseUrl.href);
64 url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
65 return url.href;
67​
68export const getAppBranding = DesktopIpc.makeSyncIpcMethod({
69 channel: IpcChannels.GET_APP_BRANDING_CHANNEL,
70 result: Schema.NullOr(DesktopAppBrandingSchema),
71 handler: Effect.fn("desktop.ipc.window.getAppBranding")(function* () {
72 const environment = yield* DesktopEnvironment.DesktopEnvironment;
73 return environment.branding;
74 }),
75});
76​
77/**
78 * Relay traces leave the machine, so a policy with `telemetry: false`, or one that cannot be read,
79 * stops them. Read once here: a sync IPC handler cannot wait on the filesystem.
80 */
81export const installRelayTelemetryEnabled = Effect.fn("desktop.ipc.window.installRelayTelemetry")(
82 function* () {
83 const ipc = yield* DesktopIpc.DesktopIpc;
84 const enabled =
85 isRelayTracingEnabled(yield* HostProcess.Environment) &&
86 (yield* (yield* DesktopManagedPolicy.DesktopManagedPolicy).read.pipe(
87 Effect.map((found) => found?.document.limits?.telemetry !== false),
88 Effect.orElseSucceed(() => false),
89 ));
90 yield* ipc.handleSync(
91 DesktopIpc.makeSyncIpcMethod({
92 channel: IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL,
93 result: Schema.Boolean,
94 handler: () => Effect.succeed(enabled),
95 }),
96 );
97 },
98);
99​
100export const getSystemLocale = DesktopIpc.makeSyncIpcMethod({
101 channel: IpcChannels.GET_SYSTEM_LOCALE_CHANNEL,
102 result: Schema.String,
103 handler: Effect.fn("desktop.ipc.window.getSystemLocale")(function* () {
104 const electronApp = yield* ElectronApp.ElectronApp;
105 return yield* electronApp.systemLocale;
106 }),
107});
108​
109export const getWindowFullscreenState = DesktopIpc.makeSyncIpcMethod({
110 channel: IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL,
111 result: Schema.Boolean,
112 handler: Effect.fn("desktop.ipc.window.getWindowFullscreenState")(function* () {
113 const electronWindow = yield* ElectronWindow.ElectronWindow;
114 const window = yield* electronWindow.currentMainOrFirst;
115 return Option.isSome(window) && window.value.isFullScreen();
116 }),
117});
118​
119export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({
120 channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,
121 result: Schema.Array(DesktopEnvironmentBootstrapSchema),
122 handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBootstraps")(function* () {
123 const pool = yield* DesktopBackendPool.DesktopBackendPool;
124 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
125 const instances = yield* pool.list;
126 const bootstraps: DesktopEnvironmentBootstrap[] = [];
127 for (const instance of instances) {
128 const isPrimary = instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID;
129 const config = yield* instance.currentConfig;
130 const snapshot = yield* instance.snapshot;
131 if (Option.isNone(config) || Option.isSome(config.value.preflightFailure)) {
132 const fatalPreflight =
133 Option.isSome(config) &&
134 Option.isSome(config.value.preflightFailure) &&
135 config.value.preflightFailure.value.fatal;
136 const stoppedPreflight =
137 Option.isSome(config) &&
138 Option.isSome(config.value.preflightFailure) &&
139 (!snapshot.desiredRunning || !snapshot.restartScheduled);
140 if (isPrimary || fatalPreflight || stoppedPreflight) continue;
141 bootstraps.push({
142 id: instance.id,
143 label: yield* instance.label,
144 runningDistro: null,
145 httpBaseUrl: null,
146 wsBaseUrl: null,
147 });
148 continue;
149 }
150 const { bootstrap, httpBaseUrl } = config.value;
151 const runningDistro = config.value.runningDistro ?? null;
152 bootstraps.push({
153 id: instance.id,
154 label: runningDistro === null ? yield* instance.label : `WSL (${runningDistro})`,
155 runningDistro,
156 httpBaseUrl: httpBaseUrl.href,
157 wsBaseUrl: toWebSocketBaseUrl(httpBaseUrl),
158 // Use the current window's derived token; the launch config's token may be stale.
159 ...(bootstrap.desktopBootstrapSecret
160 ? { bootstrapToken: yield* configuration.currentBootstrapToken }
161 : bootstrap.desktopBootstrapToken
162 ? { bootstrapToken: bootstrap.desktopBootstrapToken }
163 : {}),
164 });
165 }
166 return bootstraps;
167 }),
168});
169​
170function extractWslDistroFromEnvironmentId(envId: string): string | null {
171 if (!envId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX)) {
172 return null;
173 }
174 const suffix = envId.slice(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX.length);
175 return suffix === "default" || suffix.length === 0 ? null : suffix;
177​
178export const getLocalEnvironmentBearerToken = DesktopIpc.makeIpcMethod({
179 channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL,
180 payload: Schema.Void,
181 result: Schema.String,
182 handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBearerToken")(function* () {
183 const localAuth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth;
184 return yield* localAuth.getBearerToken;
185 }),
186});
187​
188export const pickFolder = DesktopIpc.makeIpcMethod({
189 channel: IpcChannels.PICK_FOLDER_CHANNEL,
190 payload: Schema.UndefinedOr(PickFolderOptionsSchema),
191 result: Schema.NullOr(Schema.String),
192 handler: Effect.fn("desktop.ipc.window.pickFolder")(function* (options) {
193 const dialog = yield* ElectronDialog.ElectronDialog;
194 const electronWindow = yield* ElectronWindow.ElectronWindow;
195 const environment = yield* DesktopEnvironment.DesktopEnvironment;
196 const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
197 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
198 const settings = yield* appSettings.get;
199 // A picked path only means something to a backend on this machine.
200 if (!settings.localEnvironmentEnabled) {
201 return null;
202 }
203 const targetId = options?.targetEnvironmentId;
204 const wslDistroFromTarget =
205 targetId !== undefined && targetId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX)
206 ? extractWslDistroFromEnvironmentId(targetId)
207 : null;
208 const useWsl =
209 targetId !== undefined &&
210 targetId !== PRIMARY_LOCAL_ENVIRONMENT_ID &&
211 targetId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX);
212 // Match the orchestrator's persisted distro fallback for wsl:default.
213 const wslDistro = useWsl ? (wslDistroFromTarget ?? settings.wslDistro) : null;
214 const defaultPath = useWsl
215 ? Option.fromNullishOr(
216 resolveWslPickFolderDefaultPath(
217 options,
218 { distro: wslDistro },
219 yield* wslEnvironment.listDistros,
220 Option.getOrNull(yield* wslEnvironment.getUserHome(wslDistro)),
221 ),
222 )
223 : environment.resolvePickFolderDefaultPath(options);
224 const selectedPath = yield* dialog.pickFolder({
225 owner: yield* electronWindow.focusedMainOrFirst,
226 defaultPath,
227 });
228 if (Option.isNone(selectedPath)) {
229 return null;
230 }
231 if (!useWsl) {
232 return selectedPath.value;
233 }
234​
235 const linuxUncPath = wslUncPathToLinuxPath(selectedPath.value);
236 if (linuxUncPath !== null) {
237 return linuxUncPath;
238 }
239​
240 const converted = yield* wslEnvironment.windowsToWslPath(
241 extractDistroFromUncPath(selectedPath.value) ?? wslDistro,
242 selectedPath.value,
243 );
244 return Option.getOrElse(converted, () => selectedPath.value);
245 }),
246});
247​
248export const pickProjectFavicon = DesktopIpc.makeIpcMethod({
249 channel: IpcChannels.PICK_PROJECT_FAVICON_CHANNEL,
250 payload: Schema.UndefinedOr(Schema.String),
251 result: Schema.NullOr(Schema.String),
252 handler: Effect.fn("desktop.ipc.window.pickProjectFavicon")(function* (initialPath) {
253 const dialog = yield* ElectronDialog.ElectronDialog;
254 const electronWindow = yield* ElectronWindow.ElectronWindow;
255 const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
256 if (!(yield* appSettings.get).localEnvironmentEnabled) {
257 return null;
258 }
259 const paths = yield* dialog.pickFiles({
260 owner: yield* electronWindow.focusedMainOrFirst,
261 defaultPath: Option.fromNullishOr(initialPath),
262 multiple: false,
263 filters: [
264 {
265 name: "Images",
266 extensions: PROJECT_FAVICON_EXTENSIONS.map((extension) => extension.slice(1)),
267 },
268 ],
269 });
270 return paths[0] ?? null;
271 }),
272});
273​
274export const setTheme = DesktopIpc.makeIpcMethod({
275 channel: IpcChannels.SET_THEME_CHANNEL,
276 payload: DesktopThemeSchema,
277 result: Schema.Void,
278 handler: Effect.fn("desktop.ipc.window.setTheme")(function* (theme) {
279 const electronTheme = yield* ElectronTheme.ElectronTheme;
280 yield* electronTheme.setSource(theme);
281 }),
282});
283​
284export const showContextMenu = DesktopIpc.makeIpcMethod({
285 channel: IpcChannels.CONTEXT_MENU_CHANNEL,
286 payload: ContextMenuInput,
287 result: Schema.NullOr(Schema.String),
288 handler: Effect.fn("desktop.ipc.window.showContextMenu")(function* (input) {
289 const electronMenu = yield* ElectronMenu.ElectronMenu;
290 const electronWindow = yield* ElectronWindow.ElectronWindow;
291 const window = yield* electronWindow.focusedMainOrFirst;
292 if (Option.isNone(window)) {
293 return null;
294 }
295​
296 const selectedItemId = yield* electronMenu.showContextMenu({
297 window: window.value,
298 items: input.items,
299 position: Option.fromNullishOr(input.position),
300 });
301 return Option.getOrNull(selectedItemId);
302 }),
303});
304​
305export const openExternal = DesktopIpc.makeIpcMethod({
306 channel: IpcChannels.OPEN_EXTERNAL_CHANNEL,
307 payload: Schema.String,
308 result: Schema.Boolean,
309 handler: Effect.fn("desktop.ipc.window.openExternal")(function* (url) {
310 const shell = yield* ElectronShell.ElectronShell;
311 return yield* shell.openExternal(url);
312 }),
313});
314​
315const READ_MEDIA_MAX_BYTES = 256 * 1024 * 1024;
316​
317// The renderer can display media it cannot fetch(); reading here keeps Save and Copy working for it.
318export const readMedia = DesktopIpc.makeIpcMethod({
319 channel: IpcChannels.READ_MEDIA_CHANNEL,
320 payload: Schema.String,
321 result: Schema.NullOr(DesktopMediaReadSchema),
322 handler: Effect.fn("desktop.ipc.window.readMedia")(function* (url, event) {
323 const window = yield* (yield* ElectronWindow.ElectronWindow).main;
324 if (
325 event === undefined ||
326 Option.isNone(window) ||
327 window.value.webContents.id !== event.sender.id ||
328 !/^https?:$/.test(URL.parse(url)?.protocol ?? "")
329 ) {
330 return null;
331 }
332 const session = window.value.webContents.session;
333 return yield* Effect.tryPromise(async () => {
334 // Like an <img>, send the session's cookies.
335 const response = await session.fetch(url, { credentials: "include" });
336 const mimeType = response.headers.get("content-type") ?? "";
337 if (!response.ok || !response.body) {
338 await response.body?.cancel();
339 return { status: response.status, mimeType, data: new Uint8Array() };
340 }
341 // The whole body crosses IPC, so stop before a huge file can exhaust main-process memory.
342 const chunks: Uint8Array[] = [];
343 let size = 0;
344 for await (const chunk of response.body) {
345 size += chunk.byteLength;
346 if (size > READ_MEDIA_MAX_BYTES) {
347 return { status: 413, mimeType, data: new Uint8Array() };
348 }
349 chunks.push(chunk);
350 }
351 return { status: response.status, mimeType, data: Buffer.concat(chunks) };
352 }).pipe(Effect.orElseSucceed(() => null));
353 }),
354});
355​
356export const openSystemSettings = DesktopIpc.makeIpcMethod({
357 channel: IpcChannels.OPEN_SYSTEM_SETTINGS_CHANNEL,
358 payload: SystemSettingsPaneSchema,
359 result: Schema.Boolean,
360 handler: Effect.fn("desktop.ipc.window.openSystemSettings")(function* (pane) {
361 const shell = yield* ElectronShell.ElectronShell;
362 const environment = yield* DesktopEnvironment.DesktopEnvironment;
363 if (environment.platform !== "darwin") return false;
364 const owner = Electron.BrowserWindow.getFocusedWindow();
365 const opened = yield* shell.openSystemSettings(pane);
366 if (opened && environment.isPackaged) {
367 const permissions = yield* MacPermissions.MacPermissions;
368 const isGranted = yield* safariPermissionCheck;
369 yield* permissions.showHelper(pane, owner, isGranted);
370 }
371 return opened;
372 }),
373});
374​
375export const probeRemoteEditors = DesktopIpc.makeIpcMethod({
376 channel: IpcChannels.PROBE_REMOTE_EDITORS_CHANNEL,
377 payload: Schema.Undefined,
378 result: Schema.Array(EditorId),
379 handler: Effect.fn("desktop.ipc.window.probeRemoteEditors")(function* () {
380 const available: Array<EditorId> = [];
381 const env = yield* HostProcess.Environment;
382 for (const editorId of REMOTE_CAPABLE_EDITOR_IDS) {
383 const editor = EDITORS.find((editor) => editor.id === editorId);
384 if (editor && Option.isSome(yield* resolveEditorCommand(editor, env))) {
385 available.push(editorId);
386 }
387 }
388 return available;
389 }),
390});
391​
392export const pasteAsText = DesktopIpc.makeIpcMethod({
393 channel: IpcChannels.PASTE_AS_TEXT_CHANNEL,
394 payload: Schema.Undefined,
395 result: Schema.Void,
396 handler: Effect.fn("desktop.ipc.window.pasteAsText")(function* (_input, event) {
397 const electronWindow = yield* ElectronWindow.ElectronWindow;
398 const window = yield* electronWindow.main;
399 if (
400 event === undefined ||
401 Option.isNone(window) ||
402 window.value.isDestroyed() ||
403 window.value.webContents.id !== event.sender.id
404 ) {
405 return;
406 }
407 const focused = Electron.webContents.getFocusedWebContents();
408 if (
409 focused &&
410 !focused.isDestroyed() &&
411 Electron.BrowserWindow.fromWebContents(focused) === window.value
412 ) {
413 focused.paste();
414 }
415 }),
416});
417​
418export const revealWindow = DesktopIpc.makeIpcMethod({
419 channel: IpcChannels.REVEAL_WINDOW_CHANNEL,
420 payload: Schema.Undefined,
421 result: Schema.Void,
422 handler: Effect.fn("desktop.ipc.window.revealWindow")(function* (_input, event) {
423 const electronWindow = yield* ElectronWindow.ElectronWindow;
424 const window = yield* electronWindow.main;
425 if (
426 event === undefined ||
427 Option.isNone(window) ||
428 window.value.webContents.id !== event.sender.id
429 ) {
430 return;
431 }
432 yield* electronWindow.reveal(window.value);
433 }),
434});
435​
436const PICKED_THEME_FILE_MAX_BYTES = 256 * 1024;
437​
438export const pickThemeFiles = DesktopIpc.makeIpcMethod({
439 channel: IpcChannels.PICK_THEME_FILES_CHANNEL,
440 payload: Schema.Undefined,
441 result: Schema.NullOr(Schema.Array(PickedThemeFileSchema)),
442 handler: Effect.fn("desktop.ipc.window.pickThemeFiles")(function* () {
443 const dialog = yield* ElectronDialog.ElectronDialog;
444 const electronWindow = yield* ElectronWindow.ElectronWindow;
445 const fileSystem = yield* FileSystem.FileSystem;
446 const path = yield* Path.Path;
447 const extensionsDir = path.join(yield* HostProcess.HomeDirectory, ".vscode", "extensions");
448 const defaultPath = yield* fileSystem
449 .exists(extensionsDir)
450 .pipe(Effect.orElseSucceed(() => false));
451 const paths = yield* dialog.pickFiles({
452 owner: yield* electronWindow.focusedMainOrFirst,
453 defaultPath: defaultPath ? Option.some(extensionsDir) : Option.none(),
454 filters: [{ name: "JSON", extensions: ["json"] }],
455 multiple: true,
456 });
457 if (paths.length === 0) {
458 return null;
459 }
460 return yield* Effect.forEach(paths, (filePath) => {
461 const name = path.basename(filePath);
462 return Effect.gen(function* () {
463 const info = yield* fileSystem.stat(filePath);
464 const size = Number(info.size);
465 if (size > PICKED_THEME_FILE_MAX_BYTES) {
466 return { name, size, text: "" } satisfies PickedThemeFile;
467 }
468 const text = yield* fileSystem.readFileString(filePath);
469 return { name, size, text } satisfies PickedThemeFile;
470 }).pipe(Effect.orElseSucceed((): PickedThemeFile => ({ name, size: 0, text: "" })));
471 });
472 }),
473});
474​
475export const checkSystemPermission = DesktopIpc.makeIpcMethod({
476 channel: IpcChannels.CHECK_SYSTEM_PERMISSION_CHANNEL,
477 payload: SystemSettingsPaneSchema,
478 result: Schema.Boolean,
479 handler: Effect.fn("desktop.ipc.window.checkSystemPermission")(function* () {
480 const environment = yield* DesktopEnvironment.DesktopEnvironment;
481 if (environment.platform !== "darwin") return false;
482 const check = yield* safariPermissionCheck;
483 return yield* Effect.promise(check);
484 }),
485});