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

window.ts

443 lines17.0 KB

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