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