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

window.ts

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