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

window.ts

653 lines25.9 KB

1import {
2 ContextMenuItemSchema,
3 ContextMenuSource,
4 DesktopAppBrandingSchema,
5 DatabaseMigrationProgress,
6 DesktopEnvironmentBootstrapSchema,
7 DesktopMediaReadSchema,
8 DesktopThemeSchema,
9 EDITORS,
10 EditorId,
11 PickedThemeFileSchema,
12 PickFolderOptionsSchema,
13 PRIMARY_LOCAL_ENVIRONMENT_ID,
14 REMOTE_CAPABLE_EDITOR_IDS,
15 SystemSettingsPaneSchema,
16 type DesktopEnvironmentBootstrap,
17 type PickedThemeFile,
18} from "@t3tools/contracts";
19import { PROJECT_FAVICON_EXTENSIONS } from "@t3tools/shared/projectFavicon";
20import { resolveEditorCommand } from "@t3tools/shared/editor";
21import * as HostProcess from "@t3tools/shared/HostProcess";
22import { isRelayTracingEnabled } from "@t3tools/shared/otelEnvironment";
23import * as FileSystem from "effect/FileSystem";
24import * as Path from "effect/Path";
25import * as Effect from "effect/Effect";
26import * as Option from "effect/Option";
27import * as Schema from "effect/Schema";
28import * as Ref from "effect/Ref";
29import * as DesktopState from "../../app/DesktopState.ts";
30​
31import * as DesktopBackendConfiguration from "../../backend/DesktopBackendConfiguration.ts";
32import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
33import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
34import * as DesktopLocalEnvironmentAuth from "../../backend/DesktopLocalEnvironmentAuth.ts";
35import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
36import * as DesktopManagedPolicy from "../../app/DesktopManagedPolicy.ts";
37import * as DesktopPrimaryPaste from "../../app/DesktopPrimaryPaste.ts";
38import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
39import * as DesktopShellEnvironment from "../../shell/DesktopShellEnvironment.ts";
40import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
41import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
42import * as ElectronApp from "../../electron/ElectronApp.ts";
43import * as ElectronAudio from "../../electron/ElectronAudio.ts";
44import * as ElectronDialog from "../../electron/ElectronDialog.ts";
45import * as ElectronMenu from "../../electron/ElectronMenu.ts";
46import * as ElectronShell from "../../electron/ElectronShell.ts";
47import * as ElectronTheme from "../../electron/ElectronTheme.ts";
48import * as ElectronWindow from "../../electron/ElectronWindow.ts";
49import * as Electron from "electron";
50import { msg } from "gt-i18n";
51import * as MacPermissions from "../../permissions/MacPermissions.ts";
52import { safariPermissionCheck } from "../../preview/BrowserImport/SafariPermission.ts";
53import { m } from "../../i18n/messages.ts";
54import * as IpcChannels from "../channels.ts";
55import * as DesktopIpc from "../DesktopIpc.ts";
56import {
57 extractDistroFromUncPath,
58 resolveWslPickFolderDefaultPath,
59 wslUncPathToLinuxPath,
60} from "../../wsl/wslPathParsing.ts";
61​
62const ContextMenuPosition = Schema.Struct({
63 x: Schema.Number,
64 y: Schema.Number,
65});
66​
67const ContextMenuInput = Schema.Struct({
68 items: Schema.Array(ContextMenuItemSchema),
69 position: Schema.optionalKey(ContextMenuPosition),
70 source: Schema.optionalKey(ContextMenuSource),
71});
72​
73function toWebSocketBaseUrl(httpBaseUrl: URL): string {
74 const url = new URL(httpBaseUrl.href);
75 url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
76 return url.href;
78​
79export const getDatabaseMigrationProgress = DesktopIpc.makeIpcMethod({
80 channel: IpcChannels.GET_DATABASE_MIGRATION_PROGRESS_CHANNEL,
81 payload: Schema.Void,
82 result: Schema.NullOr(DatabaseMigrationProgress),
83 handler: Effect.fn("desktop.ipc.window.getDatabaseMigrationProgress")(function* () {
84 const state = yield* DesktopState.DesktopState;
85 return yield* Ref.get(state.databaseMigrationProgress);
86 }),
87});
88​
89export const getAppBranding = DesktopIpc.makeSyncIpcMethod({
90 channel: IpcChannels.GET_APP_BRANDING_CHANNEL,
91 result: Schema.NullOr(DesktopAppBrandingSchema),
92 handler: Effect.fn("desktop.ipc.window.getAppBranding")(function* () {
93 const environment = yield* DesktopEnvironment.DesktopEnvironment;
94 return environment.branding;
95 }),
96});
97​
98/**
99 * Relay traces leave the machine, so a policy with `telemetry: false`, or one that cannot be read,
100 * stops them. Read once here: a sync IPC handler cannot wait on the filesystem. Until the login
101 * shell's environment (which may opt out) is known, answer null so the renderer asks again.
102 */
103export const installRelayTelemetryEnabled = Effect.fn("desktop.ipc.window.installRelayTelemetry")(
104 function* () {
105 const ipc = yield* DesktopIpc.DesktopIpc;
106 const env = yield* HostProcess.Environment;
107 const policyAllows = yield* (yield* DesktopManagedPolicy.DesktopManagedPolicy).read.pipe(
108 Effect.map((found) => found?.document.limits?.telemetry !== false),
109 Effect.orElseSucceed(() => false),
110 );
111 const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
112 yield* ipc.handleSync(
113 DesktopIpc.makeSyncIpcMethod({
114 channel: IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL,
115 result: Schema.NullOr(Schema.Boolean),
116 handler: () =>
117 shellEnvironment.discoveryFinished.pipe(
118 Effect.map((known) =>
119 !policyAllows || !isRelayTracingEnabled(env) ? false : known ? true : null,
120 ),
121 ),
122 }),
123 );
124 },
125);
126​
127export const getSystemLocale = DesktopIpc.makeSyncIpcMethod({
128 channel: IpcChannels.GET_SYSTEM_LOCALE_CHANNEL,
129 result: Schema.String,
130 handler: Effect.fn("desktop.ipc.window.getSystemLocale")(function* () {
131 const electronApp = yield* ElectronApp.ElectronApp;
132 return yield* electronApp.systemLocale;
133 }),
134});
135​
136export const getPrimaryPasteEnabled = DesktopIpc.makeSyncIpcMethod({
137 channel: IpcChannels.GET_PRIMARY_PASTE_ENABLED_CHANNEL,
138 result: Schema.Boolean,
139 handler: Effect.fn("desktop.ipc.window.getPrimaryPasteEnabled")(function* () {
140 const primaryPaste = yield* DesktopPrimaryPaste.DesktopPrimaryPaste;
141 return primaryPaste.enabled;
142 }),
143});
144​
145export const getPreferredSystemLanguages = DesktopIpc.makeSyncIpcMethod({
146 channel: IpcChannels.GET_PREFERRED_SYSTEM_LANGUAGES_CHANNEL,
147 result: Schema.Array(Schema.String),
148 handler: Effect.fn("desktop.ipc.window.getPreferredSystemLanguages")(function* () {
149 const electronApp = yield* ElectronApp.ElectronApp;
150 return yield* electronApp.preferredSystemLanguages;
151 }),
152});
153​
154export const getWindowFullscreenState = DesktopIpc.makeSyncIpcMethod({
155 channel: IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL,
156 result: Schema.Boolean,
157 handler: Effect.fn("desktop.ipc.window.getWindowFullscreenState")(function* () {
158 const electronWindow = yield* ElectronWindow.ElectronWindow;
159 const window = yield* electronWindow.currentMainOrFirst;
160 return Option.isSome(window) && window.value.isFullScreen();
161 }),
162});
163​
164export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({
165 channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,
166 result: Schema.Array(DesktopEnvironmentBootstrapSchema),
167 handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBootstraps")(function* () {
168 const pool = yield* DesktopBackendPool.DesktopBackendPool;
169 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
170 const instances = yield* pool.list;
171 const bootstraps: DesktopEnvironmentBootstrap[] = [];
172 for (const instance of instances) {
173 const isPrimary = instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID;
174 const config = yield* instance.currentConfig;
175 const snapshot = yield* instance.snapshot;
176 if (Option.isNone(config) || Option.isSome(config.value.preflightFailure)) {
177 const fatalPreflight =
178 Option.isSome(config) &&
179 Option.isSome(config.value.preflightFailure) &&
180 config.value.preflightFailure.value.fatal;
181 const stoppedPreflight =
182 Option.isSome(config) &&
183 Option.isSome(config.value.preflightFailure) &&
184 (!snapshot.desiredRunning || !snapshot.restartScheduled);
185 if (isPrimary || fatalPreflight || stoppedPreflight) continue;
186 bootstraps.push({
187 id: instance.id,
188 label: yield* instance.label,
189 runningDistro: null,
190 httpBaseUrl: null,
191 wsBaseUrl: null,
192 });
193 continue;
194 }
195 const { bootstrap, httpBaseUrl } = config.value;
196 const runningDistro = config.value.runningDistro ?? null;
197 bootstraps.push({
198 id: instance.id,
199 label: runningDistro === null ? yield* instance.label : `WSL (${runningDistro})`,
200 runningDistro,
201 httpBaseUrl: httpBaseUrl.href,
202 wsBaseUrl: toWebSocketBaseUrl(httpBaseUrl),
203 // The renderer uses this token with httpBaseUrl once the backend has reported ready.
204 // Use the current window's derived token; the launch config's token may be stale.
205 ...(!snapshot.ready
206 ? {}
207 : bootstrap.desktopBootstrapSecret
208 ? { bootstrapToken: yield* configuration.currentBootstrapToken }
209 : bootstrap.desktopBootstrapToken
210 ? { bootstrapToken: bootstrap.desktopBootstrapToken }
211 : {}),
212 });
213 }
214 return bootstraps;
215 }),
216});
217​
218function extractWslDistroFromEnvironmentId(envId: string): string | null {
219 if (!envId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX)) {
220 return null;
221 }
222 const suffix = envId.slice(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX.length);
223 return suffix === "default" || suffix.length === 0 ? null : suffix;
225​
226export const getLocalEnvironmentBearerToken = DesktopIpc.makeIpcMethod({
227 channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL,
228 payload: Schema.Void,
229 result: Schema.String,
230 handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBearerToken")(function* () {
231 const localAuth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth;
232 return yield* localAuth.getBearerToken;
233 }),
234});
235​
236// Ask the distro: its automount root is configurable, so /mnt/<drive> is only the default.
237const windowsPathToWsl = Effect.fn("desktop.ipc.window.windowsPathToWsl")(function* (
238 distro: string | null,
239 windowsPath: string,
240) {
241 const linuxUncPath = wslUncPathToLinuxPath(windowsPath);
242 if (linuxUncPath !== null) return Option.some(linuxUncPath);
243 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
244 return yield* wslEnvironment.windowsToWslPath(
245 extractDistroFromUncPath(windowsPath) ?? distro,
246 windowsPath,
247 );
248});
249​
250// WSL-only mode runs the WSL backend as the primary instance, so a wsl:* target may not be pooled.
251const targetRunningDistro = Effect.fn("desktop.ipc.window.targetRunningDistro")(function* (
252 targetId: string,
253 settings: DesktopAppSettings.DesktopSettings,
254) {
255 const pool = yield* DesktopBackendPool.DesktopBackendPool;
256 const pooled = yield* pool.get(DesktopBackendManager.BackendInstanceId(targetId));
257 const instance = Option.isSome(pooled)
258 ? pooled
259 : settings.wslOnly && settings.wslBackendEnabled
260 ? Option.some(yield* pool.primary)
261 : Option.none();
262 if (Option.isNone(instance)) return undefined;
263 const config = yield* instance.value.currentConfig;
264 if (Option.isNone(config) || Option.isSome(config.value.preflightFailure)) return undefined;
265 return config.value.runningDistro;
266});
267​
268export const pickFolder = DesktopIpc.makeIpcMethod({
269 channel: IpcChannels.PICK_FOLDER_CHANNEL,
270 payload: Schema.UndefinedOr(PickFolderOptionsSchema),
271 result: Schema.NullOr(Schema.String),
272 handler: Effect.fn("desktop.ipc.window.pickFolder")(function* (options) {
273 const dialog = yield* ElectronDialog.ElectronDialog;
274 const electronWindow = yield* ElectronWindow.ElectronWindow;
275 const environment = yield* DesktopEnvironment.DesktopEnvironment;
276 const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
277 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
278 const settings = yield* appSettings.get;
279 // A picked path only means something to a backend on this machine.
280 if (!settings.localEnvironmentEnabled) {
281 return null;
282 }
283 const targetId = options?.targetEnvironmentId;
284 const wslDistroFromTarget =
285 targetId !== undefined && targetId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX)
286 ? extractWslDistroFromEnvironmentId(targetId)
287 : null;
288 const useWsl =
289 targetId !== undefined &&
290 targetId !== PRIMARY_LOCAL_ENVIRONMENT_ID &&
291 targetId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX);
292 // Match the orchestrator's persisted distro fallback for wsl:default.
293 const wslDistro = useWsl ? (wslDistroFromTarget ?? settings.wslDistro) : null;
294 const defaultPath = useWsl
295 ? Option.fromNullishOr(
296 resolveWslPickFolderDefaultPath(
297 options,
298 { distro: wslDistro },
299 yield* wslEnvironment.listDistros,
300 Option.getOrNull(yield* wslEnvironment.getUserHome(wslDistro)),
301 ),
302 )
303 : environment.resolvePickFolderDefaultPath(options);
304 const selectedPath = yield* dialog.pickFolder({
305 owner: yield* electronWindow.focusedMainOrFirst,
306 defaultPath,
307 });
308 if (Option.isNone(selectedPath)) {
309 return null;
310 }
311 if (!useWsl) {
312 return selectedPath.value;
313 }
314 // Only the target backend's running distro can take a Linux path; any other UNC folder keeps its
315 // distro so the renderer routes it, or asks for that distro's backend.
316 const uncDistro = extractDistroFromUncPath(selectedPath.value);
317 if (uncDistro !== null) {
318 const runningDistro = yield* targetRunningDistro(targetId, settings);
319 if (runningDistro?.toLowerCase() !== uncDistro.toLowerCase()) return selectedPath.value;
320 }
321 const converted = yield* windowsPathToWsl(wslDistro, selectedPath.value);
322 return Option.getOrElse(converted, () => selectedPath.value);
323 }),
324});
325​
326export const toLocalBackendPath = DesktopIpc.makeIpcMethod({
327 channel: IpcChannels.TO_LOCAL_BACKEND_PATH_CHANNEL,
328 payload: Schema.Struct({ backendId: Schema.String, path: Schema.String }),
329 result: Schema.NullOr(Schema.String),
330 handler: Effect.fn("desktop.ipc.window.toLocalBackendPath")(function* ({ backendId, path }) {
331 const pool = yield* DesktopBackendPool.DesktopBackendPool;
332 const instance = yield* pool.get(DesktopBackendManager.BackendInstanceId(backendId));
333 if (Option.isNone(instance)) return null;
334 const config = yield* instance.value.currentConfig;
335 if (Option.isNone(config) || Option.isSome(config.value.preflightFailure)) return null;
336 const { runningDistro } = config.value;
337 if (runningDistro === undefined) return path;
338 const uncDistro = extractDistroFromUncPath(path);
339 if (uncDistro !== null && uncDistro.toLowerCase() !== runningDistro.toLowerCase()) return null;
340 return Option.getOrNull(yield* windowsPathToWsl(runningDistro, path));
341 }),
342});
343​
344export const pickProjectFavicon = DesktopIpc.makeIpcMethod({
345 channel: IpcChannels.PICK_PROJECT_FAVICON_CHANNEL,
346 payload: Schema.UndefinedOr(Schema.String),
347 result: Schema.NullOr(Schema.String),
348 handler: Effect.fn("desktop.ipc.window.pickProjectFavicon")(function* (initialPath) {
349 const dialog = yield* ElectronDialog.ElectronDialog;
350 const electronWindow = yield* ElectronWindow.ElectronWindow;
351 const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
352 if (!(yield* appSettings.get).localEnvironmentEnabled) {
353 return null;
354 }
355 const paths = yield* dialog.pickFiles({
356 owner: yield* electronWindow.focusedMainOrFirst,
357 defaultPath: Option.fromNullishOr(initialPath),
358 multiple: false,
359 filters: [
360 {
361 name: m(msg("Images")),
362 extensions: PROJECT_FAVICON_EXTENSIONS.map((extension) => extension.slice(1)),
363 },
364 ],
365 });
366 return paths[0] ?? null;
367 }),
368});
369​
370export const setTheme = DesktopIpc.makeIpcMethod({
371 channel: IpcChannels.SET_THEME_CHANNEL,
372 payload: DesktopThemeSchema,
373 result: Schema.Void,
374 handler: Effect.fn("desktop.ipc.window.setTheme")(function* (theme) {
375 const electronTheme = yield* ElectronTheme.ElectronTheme;
376 yield* electronTheme.setSource(theme);
377 }),
378});
379​
380export const showContextMenu = DesktopIpc.makeIpcMethod({
381 channel: IpcChannels.CONTEXT_MENU_CHANNEL,
382 payload: ContextMenuInput,
383 result: Schema.NullOr(Schema.String),
384 handler: Effect.fn("desktop.ipc.window.showContextMenu")(function* (input) {
385 const electronMenu = yield* ElectronMenu.ElectronMenu;
386 const electronWindow = yield* ElectronWindow.ElectronWindow;
387 const window = yield* electronWindow.focusedMainOrFirst;
388 if (Option.isNone(window)) {
389 return null;
390 }
391​
392 const selectedItemId = yield* electronMenu.showContextMenu({
393 window: window.value,
394 items: input.items,
395 position: Option.fromNullishOr(input.position),
396 source: Option.fromNullishOr(input.source),
397 });
398 return Option.getOrNull(selectedItemId);
399 }),
400});
401​
402export const openExternal = DesktopIpc.makeIpcMethod({
403 channel: IpcChannels.OPEN_EXTERNAL_CHANNEL,
404 payload: Schema.String,
405 result: Schema.Boolean,
406 handler: Effect.fn("desktop.ipc.window.openExternal")(function* (url) {
407 const shell = yield* ElectronShell.ElectronShell;
408 return yield* shell.openExternal(url);
409 }),
410});
411​
412const READ_MEDIA_MAX_BYTES = 256 * 1024 * 1024;
413​
414// No URL field: media URLs can carry signed query tokens.
415class MediaReadError extends Schema.TaggedError<MediaReadError>()("MediaReadError", {
416 message: Schema.String,
417 cause: Schema.Defect(),
418}) {}
419​
420// The renderer can display media it cannot fetch(); reading here keeps Save and Copy working for it.
421export const readMedia = DesktopIpc.makeIpcMethod({
422 channel: IpcChannels.READ_MEDIA_CHANNEL,
423 payload: Schema.String,
424 result: Schema.NullOr(DesktopMediaReadSchema),
425 handler: Effect.fn("desktop.ipc.window.readMedia")(function* (url, event) {
426 const window = yield* (yield* ElectronWindow.ElectronWindow).main;
427 if (
428 event === undefined ||
429 Option.isNone(window) ||
430 window.value.webContents.id !== event.sender.id ||
431 !/^https?:$/.test(URL.parse(url)?.protocol ?? "")
432 ) {
433 return null;
434 }
435 const session = window.value.webContents.session;
436 return yield* Effect.tryPromise({
437 try: async () => {
438 // Like an <img>, send the session's cookies.
439 const response = await session.fetch(url, { credentials: "include" });
440 const mimeType = response.headers.get("content-type") ?? "";
441 if (!response.ok || !response.body) {
442 await response.body?.cancel();
443 return { status: response.status, mimeType, data: new Uint8Array() };
444 }
445 // The whole body crosses IPC, so stop before a huge file can exhaust main-process memory.
446 const chunks: Uint8Array[] = [];
447 let size = 0;
448 for await (const chunk of response.body) {
449 size += chunk.byteLength;
450 if (size > READ_MEDIA_MAX_BYTES) {
451 return { status: 413, mimeType, data: new Uint8Array() };
452 }
453 chunks.push(chunk);
454 }
455 return { status: response.status, mimeType, data: Buffer.concat(chunks) };
456 },
457 catch: (cause) => new MediaReadError({ message: "Could not read media.", cause }),
458 }).pipe(Effect.orElseSucceed(() => null));
459 }),
460});
461​
462export const openSystemSettings = DesktopIpc.makeIpcMethod({
463 channel: IpcChannels.OPEN_SYSTEM_SETTINGS_CHANNEL,
464 payload: SystemSettingsPaneSchema,
465 result: Schema.Boolean,
466 handler: Effect.fn("desktop.ipc.window.openSystemSettings")(function* (pane) {
467 const shell = yield* ElectronShell.ElectronShell;
468 const environment = yield* DesktopEnvironment.DesktopEnvironment;
469 if (environment.platform !== "darwin") return false;
470 const owner = Electron.BrowserWindow.getFocusedWindow();
471 const opened = yield* shell.openSystemSettings(pane);
472 if (opened && environment.isPackaged) {
473 const permissions = yield* MacPermissions.MacPermissions;
474 const isGranted = yield* safariPermissionCheck;
475 yield* permissions.showHelper(pane, owner, isGranted);
476 }
477 return opened;
478 }),
479});
480​
481const REMOTE_EDITOR_PROBE_CONCURRENCY = 8;
482​
483export const probeRemoteEditors = DesktopIpc.makeIpcMethod({
484 channel: IpcChannels.PROBE_REMOTE_EDITORS_CHANNEL,
485 payload: Schema.Undefined,
486 result: Schema.Array(EditorId),
487 handler: Effect.fn("desktop.ipc.window.probeRemoteEditors")(function* () {
488 const env = yield* HostProcess.Environment;
489 const resolved = yield* Effect.forEach(
490 REMOTE_CAPABLE_EDITOR_IDS,
491 (editorId) => {
492 const editor = EDITORS.find((editor) => editor.id === editorId);
493 return editor
494 ? resolveEditorCommand(editor, env).pipe(Effect.map(Option.isSome))
495 : Effect.succeed(false);
496 },
497 { concurrency: REMOTE_EDITOR_PROBE_CONCURRENCY },
498 );
499 return REMOTE_CAPABLE_EDITOR_IDS.filter((_, index) => resolved[index]);
500 }),
501});
502​
503export const pasteAsText = DesktopIpc.makeIpcMethod({
504 channel: IpcChannels.PASTE_AS_TEXT_CHANNEL,
505 payload: Schema.Undefined,
506 result: Schema.Void,
507 handler: Effect.fn("desktop.ipc.window.pasteAsText")(function* (_input, event) {
508 const electronWindow = yield* ElectronWindow.ElectronWindow;
509 const window = yield* electronWindow.main;
510 if (
511 event === undefined ||
512 Option.isNone(window) ||
513 window.value.isDestroyed() ||
514 window.value.webContents.id !== event.sender.id
515 ) {
516 return;
517 }
518 const focused = Electron.webContents.getFocusedWebContents();
519 if (
520 focused &&
521 !focused.isDestroyed() &&
522 Electron.BrowserWindow.fromWebContents(focused) === window.value
523 ) {
524 focused.paste();
525 }
526 }),
527});
528​
529export const revealWindow = DesktopIpc.makeIpcMethod({
530 channel: IpcChannels.REVEAL_WINDOW_CHANNEL,
531 payload: Schema.Undefined,
532 result: Schema.Void,
533 handler: Effect.fn("desktop.ipc.window.revealWindow")(function* (_input, event) {
534 const electronWindow = yield* ElectronWindow.ElectronWindow;
535 const window = yield* electronWindow.main;
536 if (
537 event === undefined ||
538 Option.isNone(window) ||
539 window.value.webContents.id !== event.sender.id
540 ) {
541 return;
542 }
543 yield* electronWindow.reveal(window.value);
544 }),
545});
546​
547const htmlFullscreenStates = new WeakMap<
548 Electron.BrowserWindow,
549 { owned: boolean; leaving: boolean }
550>();
551​
552const htmlFullscreenState = (window: Electron.BrowserWindow) => {
553 const existing = htmlFullscreenStates.get(window);
554 if (existing !== undefined) return existing;
555 const state = { owned: false, leaving: false };
556 window.on("leave-full-screen", () => {
557 // Leaving OS fullscreen any other way, such as F11, hands the window back to the user.
558 if (!state.leaving) state.owned = false;
559 state.leaving = false;
560 });
561 htmlFullscreenStates.set(window, state);
562 return state;
563};
564​
565// The main window keeps HTML fullscreen inside itself so preview guests stay in their webview,
566// so the app's own fullscreen elements, such as chat videos, take the screen here.
567export const syncHtmlFullscreen = DesktopIpc.makeIpcMethod({
568 channel: IpcChannels.SYNC_HTML_FULLSCREEN_CHANNEL,
569 payload: Schema.Boolean,
570 result: Schema.Void,
571 handler: Effect.fn("desktop.ipc.window.syncHtmlFullscreen")(function* (fullscreen, event) {
572 const electronWindow = yield* ElectronWindow.ElectronWindow;
573 const main = yield* electronWindow.main;
574 if (
575 event === undefined ||
576 Option.isNone(main) ||
577 main.value.isDestroyed() ||
578 main.value.webContents.id !== event.sender.id
579 ) {
580 return;
581 }
582 const window = main.value;
583 const state = htmlFullscreenState(window);
584 if (fullscreen) {
585 // macOS reports fullscreen until its exit animation ends, and Electron queues the re-entry.
586 if (state.owned || (window.isFullScreen() && !state.leaving)) return;
587 state.owned = true;
588 window.setFullScreen(true);
589 } else if (state.owned) {
590 state.owned = false;
591 state.leaving = window.isFullScreen();
592 window.setFullScreen(false);
593 }
594 }),
595});
596​
597const PICKED_THEME_FILE_MAX_BYTES = 256 * 1024;
598​
599export const pickThemeFiles = DesktopIpc.makeIpcMethod({
600 channel: IpcChannels.PICK_THEME_FILES_CHANNEL,
601 payload: Schema.Undefined,
602 result: Schema.NullOr(Schema.Array(PickedThemeFileSchema)),
603 handler: Effect.fn("desktop.ipc.window.pickThemeFiles")(function* () {
604 const dialog = yield* ElectronDialog.ElectronDialog;
605 const electronWindow = yield* ElectronWindow.ElectronWindow;
606 const fileSystem = yield* FileSystem.FileSystem;
607 const path = yield* Path.Path;
608 const extensionsDir = path.join(yield* HostProcess.HomeDirectory, ".vscode", "extensions");
609 const defaultPath = yield* fileSystem
610 .exists(extensionsDir)
611 .pipe(Effect.orElseSucceed(() => false));
612 const paths = yield* dialog.pickFiles({
613 owner: yield* electronWindow.focusedMainOrFirst,
614 defaultPath: defaultPath ? Option.some(extensionsDir) : Option.none(),
615 filters: [{ name: "JSON", extensions: ["json"] }],
616 multiple: true,
617 });
618 if (paths.length === 0) {
619 return null;
620 }
621 return yield* Effect.forEach(paths, (filePath) => {
622 const name = path.basename(filePath);
623 return Effect.gen(function* () {
624 const info = yield* fileSystem.stat(filePath);
625 const size = Number(info.size);
626 if (size > PICKED_THEME_FILE_MAX_BYTES) {
627 return { name, size, text: "" } satisfies PickedThemeFile;
628 }
629 const text = yield* fileSystem.readFileString(filePath);
630 return { name, size, text } satisfies PickedThemeFile;
631 }).pipe(Effect.orElseSucceed((): PickedThemeFile => ({ name, size: 0, text: "" })));
632 });
633 }),
634});
635​
636export const checkSystemPermission = DesktopIpc.makeIpcMethod({
637 channel: IpcChannels.CHECK_SYSTEM_PERMISSION_CHANNEL,
638 payload: SystemSettingsPaneSchema,
639 result: Schema.Boolean,
640 handler: Effect.fn("desktop.ipc.window.checkSystemPermission")(function* () {
641 const environment = yield* DesktopEnvironment.DesktopEnvironment;
642 if (environment.platform !== "darwin") return false;
643 const check = yield* safariPermissionCheck;
644 return yield* Effect.promise(check);
645 }),
646});
647​
648export const restartAudioService = DesktopIpc.makeIpcMethod({
649 channel: IpcChannels.RESTART_AUDIO_SERVICE_CHANNEL,
650 payload: Schema.Void,
651 result: Schema.Boolean,
652 handler: ElectronAudio.restart,
653});