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

window.ts

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