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

window.ts

442 lines18.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 { WORKSPACE_IMAGE_PREVIEW_EXTENSIONS } from "@t3tools/shared/filePreview";
17import { resolveEditorCommand } from "@t3tools/shared/editor";
18import * as HostProcess from "@t3tools/shared/hostProcess";
19import * as NodeOS from "node:os";
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 getSystemLocale = DesktopIpc.makeSyncIpcMethod({
76 channel: IpcChannels.GET_SYSTEM_LOCALE_CHANNEL,
77 result: Schema.String,
78 handler: Effect.fn("desktop.ipc.window.getSystemLocale")(function* () {
79 const electronApp = yield* ElectronApp.ElectronApp;
80 return yield* electronApp.systemLocale;
81 }),
82});
83​
84export const getWindowFullscreenState = DesktopIpc.makeSyncIpcMethod({
85 channel: IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL,
86 result: Schema.Boolean,
87 handler: Effect.fn("desktop.ipc.window.getWindowFullscreenState")(function* () {
88 const electronWindow = yield* ElectronWindow.ElectronWindow;
89 const window = yield* electronWindow.currentMainOrFirst;
90 return Option.isSome(window) && window.value.isFullScreen();
91 }),
92});
93​
94export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({
95 channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,
96 result: Schema.Array(DesktopEnvironmentBootstrapSchema),
97 handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBootstraps")(function* () {
98 const pool = yield* DesktopBackendPool.DesktopBackendPool;
99 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
100 const instances = yield* pool.list;
101 const bootstraps: DesktopEnvironmentBootstrap[] = [];
102 for (const instance of instances) {
103 const isPrimary = instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID;
104 const config = yield* instance.currentConfig;
105 const snapshot = yield* instance.snapshot;
106 // A secondary backend (e.g. a parallel WSL backend) that hasn't produced
107 // a config yet (mid-registration, before its first start cycle) or that
108 // is retrying a *transient* preflight failure (WSL VM still booting, a
109 // not-yet-built linux server entry) is not listening on a port. We
110 // surface it as a *pending* bootstrap (null endpoints, no token) so the
111 // renderer can show a "Connecting…" indicator while it retries — null
112 // endpoints keep the renderer from dialing the dead port, avoiding the
113 // needless /api/auth/bootstrap/bearer error cycles a real endpoint would
114 // trigger.
115 if (Option.isNone(config) || Option.isSome(config.value.preflightFailure)) {
116 // Skip the primary (same-origin, no "connecting" affordance) and skip a
117 // secondary whose preflight failed *fatally* (no node, wrong version,
118 // missing build tools): it has stopped retrying, so an indefinite
119 // "Connecting…" would be misleading — its error is surfaced by the
120 // WSL-state UI instead.
121 const fatalPreflight =
122 Option.isSome(config) &&
123 Option.isSome(config.value.preflightFailure) &&
124 config.value.preflightFailure.value.fatal;
125 const stoppedPreflight =
126 Option.isSome(config) &&
127 Option.isSome(config.value.preflightFailure) &&
128 (!snapshot.desiredRunning || !snapshot.restartScheduled);
129 if (isPrimary || fatalPreflight || stoppedPreflight) continue;
130 bootstraps.push({
131 id: instance.id,
132 label: yield* instance.label,
133 runningDistro: null,
134 httpBaseUrl: null,
135 wsBaseUrl: null,
136 });
137 continue;
138 }
139 const { bootstrap, httpBaseUrl } = config.value;
140 const runningDistro = config.value.runningDistro ?? null;
141 bootstraps.push({
142 id: instance.id,
143 label: runningDistro === null ? yield* instance.label : `WSL (${runningDistro})`,
144 runningDistro,
145 httpBaseUrl: httpBaseUrl.href,
146 wsBaseUrl: toWebSocketBaseUrl(httpBaseUrl),
147 // A backend launched with the desktop secret accepts whichever token
148 // the secret derives for the current window, so hand out that one
149 // rather than the token frozen into its launch config. Every backend
150 // the desktop launches (primary, staged or mounted WSL runtime) is the
151 // server build bundled with this desktop, so it understands the secret.
152 ...(bootstrap.desktopBootstrapSecret
153 ? { bootstrapToken: yield* configuration.currentBootstrapToken }
154 : bootstrap.desktopBootstrapToken
155 ? { bootstrapToken: bootstrap.desktopBootstrapToken }
156 : {}),
157 });
158 }
159 return bootstraps;
160 }),
161});
162​
163// Pull the distro selection out of a backend instance id like
164// "wsl:ubuntu". Returns null for "wsl:default", which is the sentinel
165// for "track the user's WSL default distro" and maps to the
166// wslEnv-derived default at picker time.
167function extractWslDistroFromEnvironmentId(envId: string): string | null {
168 if (!envId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX)) {
169 return null;
170 }
171 const suffix = envId.slice(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX.length);
172 return suffix === "default" || suffix.length === 0 ? null : suffix;
174​
175export const getLocalEnvironmentBearerToken = DesktopIpc.makeIpcMethod({
176 channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL,
177 payload: Schema.Void,
178 result: Schema.String,
179 handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBearerToken")(function* () {
180 const localAuth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth;
181 return yield* localAuth.getBearerToken;
182 }),
183});
184​
185export const pickFolder = DesktopIpc.makeIpcMethod({
186 channel: IpcChannels.PICK_FOLDER_CHANNEL,
187 payload: Schema.UndefinedOr(PickFolderOptionsSchema),
188 result: Schema.NullOr(Schema.String),
189 handler: Effect.fn("desktop.ipc.window.pickFolder")(function* (options) {
190 const dialog = yield* ElectronDialog.ElectronDialog;
191 const electronWindow = yield* ElectronWindow.ElectronWindow;
192 const environment = yield* DesktopEnvironment.DesktopEnvironment;
193 const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
194 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
195 const settings = yield* appSettings.get;
196 // A picked path only means something to a backend on this machine.
197 if (!settings.localEnvironmentEnabled) {
198 return null;
199 }
200 // Three picker modes:
201 // - targetEnvironmentId omitted: default to the primary picker. Keeps
202 // the historical behavior unchanged for users who never enabled the
203 // WSL backend, and is what unfamiliar callers should get out of the
204 // box.
205 // - targetEnvironmentId starts with "wsl:": route to the WSL picker
206 // using the distro encoded in the id (or the user's selected
207 // wslDistro when the id is the "wsl:default" sentinel).
208 // - anything else (incl. PRIMARY_LOCAL_ENVIRONMENT_ID): primary picker.
209 const targetId = options?.targetEnvironmentId;
210 const wslDistroFromTarget =
211 targetId !== undefined && targetId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX)
212 ? extractWslDistroFromEnvironmentId(targetId)
213 : null;
214 const useWsl =
215 targetId !== undefined &&
216 targetId !== PRIMARY_LOCAL_ENVIRONMENT_ID &&
217 targetId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX);
218 // Fall back to the persisted wslDistro when the id is the
219 // "wsl:default" sentinel; the orchestrator uses the same fallback
220 // for the actual backend.
221 const wslDistro = useWsl ? (wslDistroFromTarget ?? settings.wslDistro) : null;
222 const defaultPath = useWsl
223 ? Option.fromNullishOr(
224 resolveWslPickFolderDefaultPath(
225 options,
226 { distro: wslDistro },
227 yield* wslEnvironment.listDistros,
228 Option.getOrNull(yield* wslEnvironment.getUserHome(wslDistro)),
229 ),
230 )
231 : environment.resolvePickFolderDefaultPath(options);
232 const selectedPath = yield* dialog.pickFolder({
233 owner: yield* electronWindow.focusedMainOrFirst,
234 defaultPath,
235 });
236 if (Option.isNone(selectedPath)) {
237 return null;
238 }
239 if (!useWsl) {
240 return selectedPath.value;
241 }
242​
243 const linuxUncPath = wslUncPathToLinuxPath(selectedPath.value);
244 if (linuxUncPath !== null) {
245 return linuxUncPath;
246 }
247​
248 const converted = yield* wslEnvironment.windowsToWslPath(
249 extractDistroFromUncPath(selectedPath.value) ?? wslDistro,
250 selectedPath.value,
251 );
252 return Option.getOrElse(converted, () => selectedPath.value);
253 }),
254});
255​
256export const pickProjectFavicon = DesktopIpc.makeIpcMethod({
257 channel: IpcChannels.PICK_PROJECT_FAVICON_CHANNEL,
258 payload: Schema.UndefinedOr(Schema.String),
259 result: Schema.NullOr(Schema.String),
260 handler: Effect.fn("desktop.ipc.window.pickProjectFavicon")(function* (initialPath) {
261 const dialog = yield* ElectronDialog.ElectronDialog;
262 const electronWindow = yield* ElectronWindow.ElectronWindow;
263 const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
264 if (!(yield* appSettings.get).localEnvironmentEnabled) {
265 return null;
266 }
267 const paths = yield* dialog.pickFiles({
268 owner: yield* electronWindow.focusedMainOrFirst,
269 defaultPath: Option.fromNullishOr(initialPath),
270 multiple: false,
271 filters: [
272 {
273 name: "Images",
274 extensions: WORKSPACE_IMAGE_PREVIEW_EXTENSIONS.map((extension) => extension.slice(1)),
275 },
276 ],
277 });
278 return paths[0] ?? null;
279 }),
280});
281​
282export const setTheme = DesktopIpc.makeIpcMethod({
283 channel: IpcChannels.SET_THEME_CHANNEL,
284 payload: DesktopThemeSchema,
285 result: Schema.Void,
286 handler: Effect.fn("desktop.ipc.window.setTheme")(function* (theme) {
287 const electronTheme = yield* ElectronTheme.ElectronTheme;
288 yield* electronTheme.setSource(theme);
289 }),
290});
291​
292export const showContextMenu = DesktopIpc.makeIpcMethod({
293 channel: IpcChannels.CONTEXT_MENU_CHANNEL,
294 payload: ContextMenuInput,
295 result: Schema.NullOr(Schema.String),
296 handler: Effect.fn("desktop.ipc.window.showContextMenu")(function* (input) {
297 const electronMenu = yield* ElectronMenu.ElectronMenu;
298 const electronWindow = yield* ElectronWindow.ElectronWindow;
299 const window = yield* electronWindow.focusedMainOrFirst;
300 if (Option.isNone(window)) {
301 return null;
302 }
303​
304 const selectedItemId = yield* electronMenu.showContextMenu({
305 window: window.value,
306 items: input.items,
307 position: Option.fromNullishOr(input.position),
308 });
309 return Option.getOrNull(selectedItemId);
310 }),
311});
312​
313export const openExternal = DesktopIpc.makeIpcMethod({
314 channel: IpcChannels.OPEN_EXTERNAL_CHANNEL,
315 payload: Schema.String,
316 result: Schema.Boolean,
317 handler: Effect.fn("desktop.ipc.window.openExternal")(function* (url) {
318 const shell = yield* ElectronShell.ElectronShell;
319 return yield* shell.openExternal(url);
320 }),
321});
322​
323export const openSystemSettings = DesktopIpc.makeIpcMethod({
324 channel: IpcChannels.OPEN_SYSTEM_SETTINGS_CHANNEL,
325 payload: SystemSettingsPaneSchema,
326 result: Schema.Boolean,
327 handler: Effect.fn("desktop.ipc.window.openSystemSettings")(function* (pane) {
328 const shell = yield* ElectronShell.ElectronShell;
329 const environment = yield* DesktopEnvironment.DesktopEnvironment;
330 if (environment.platform !== "darwin") return false;
331 const owner = Electron.BrowserWindow.getFocusedWindow();
332 const opened = yield* shell.openSystemSettings(pane);
333 if (opened && environment.isPackaged) {
334 const permissions = yield* MacPermissions.MacPermissions;
335 const isGranted = yield* safariPermissionCheck;
336 yield* permissions.showHelper(pane, owner, isGranted);
337 }
338 return opened;
339 }),
340});
341​
342export const probeRemoteEditors = DesktopIpc.makeIpcMethod({
343 channel: IpcChannels.PROBE_REMOTE_EDITORS_CHANNEL,
344 payload: Schema.Undefined,
345 result: Schema.Array(EditorId),
346 handler: Effect.fn("desktop.ipc.window.probeRemoteEditors")(function* () {
347 const available: Array<EditorId> = [];
348 const env = yield* HostProcess.HostProcessEnvironment;
349 for (const editorId of REMOTE_CAPABLE_EDITOR_IDS) {
350 const editor = EDITORS.find((editor) => editor.id === editorId);
351 if (editor && Option.isSome(yield* resolveEditorCommand(editor, env))) {
352 available.push(editorId);
353 }
354 }
355 return available;
356 }),
357});
358​
359export const pasteAsText = DesktopIpc.makeIpcMethod({
360 channel: IpcChannels.PASTE_AS_TEXT_CHANNEL,
361 payload: Schema.Undefined,
362 result: Schema.Void,
363 handler: Effect.fn("desktop.ipc.window.pasteAsText")(function* (_input, event) {
364 const electronWindow = yield* ElectronWindow.ElectronWindow;
365 const window = yield* electronWindow.main;
366 if (
367 event === undefined ||
368 Option.isNone(window) ||
369 window.value.isDestroyed() ||
370 window.value.webContents.id !== event.sender.id
371 ) {
372 return;
373 }
374 const focused = Electron.webContents.getFocusedWebContents();
375 if (
376 focused &&
377 !focused.isDestroyed() &&
378 Electron.BrowserWindow.fromWebContents(focused) === window.value
379 ) {
380 focused.paste();
381 }
382 }),
383});
384​
385/** Theme files are a few KB; anything larger returns empty text and lets the
386 * renderer reject it by size without the contents ever crossing the bridge. */
387const PICKED_THEME_FILE_MAX_BYTES = 256 * 1024;
388​
389export const pickThemeFiles = DesktopIpc.makeIpcMethod({
390 channel: IpcChannels.PICK_THEME_FILES_CHANNEL,
391 payload: Schema.Undefined,
392 result: Schema.NullOr(Schema.Array(PickedThemeFileSchema)),
393 handler: Effect.fn("desktop.ipc.window.pickThemeFiles")(function* () {
394 const dialog = yield* ElectronDialog.ElectronDialog;
395 const electronWindow = yield* ElectronWindow.ElectronWindow;
396 const fileSystem = yield* FileSystem.FileSystem;
397 const path = yield* Path.Path;
398 // The VS Code extensions directory is the same dotfolder on Windows,
399 // macOS, and Linux; when it is missing the picker opens wherever the
400 // platform would by default.
401 const extensionsDir = path.join(NodeOS.homedir(), ".vscode", "extensions");
402 const defaultPath = yield* fileSystem
403 .exists(extensionsDir)
404 .pipe(Effect.orElseSucceed(() => false));
405 const paths = yield* dialog.pickFiles({
406 owner: yield* electronWindow.focusedMainOrFirst,
407 defaultPath: defaultPath ? Option.some(extensionsDir) : Option.none(),
408 filters: [{ name: "JSON", extensions: ["json"] }],
409 multiple: true,
410 });
411 if (paths.length === 0) {
412 return null;
413 }
414 return yield* Effect.forEach(paths, (filePath) => {
415 const name = path.basename(filePath);
416 return Effect.gen(function* () {
417 const info = yield* fileSystem.stat(filePath);
418 const size = Number(info.size);
419 if (size > PICKED_THEME_FILE_MAX_BYTES) {
420 return { name, size, text: "" } satisfies PickedThemeFile;
421 }
422 const text = yield* fileSystem.readFileString(filePath);
423 return { name, size, text } satisfies PickedThemeFile;
424 }).pipe(
425 // An unreadable file degrades to an entry the renderer reports.
426 Effect.orElseSucceed((): PickedThemeFile => ({ name, size: 0, text: "" })),
427 );
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});