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

window.ts

628 lines24.7 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​
250export const pickFolder = DesktopIpc.makeIpcMethod({
251 channel: IpcChannels.PICK_FOLDER_CHANNEL,
252 payload: Schema.UndefinedOr(PickFolderOptionsSchema),
253 result: Schema.NullOr(Schema.String),
254 handler: Effect.fn("desktop.ipc.window.pickFolder")(function* (options) {
255 const dialog = yield* ElectronDialog.ElectronDialog;
256 const electronWindow = yield* ElectronWindow.ElectronWindow;
257 const environment = yield* DesktopEnvironment.DesktopEnvironment;
258 const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
259 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
260 const settings = yield* appSettings.get;
261 // A picked path only means something to a backend on this machine.
262 if (!settings.localEnvironmentEnabled) {
263 return null;
264 }
265 const targetId = options?.targetEnvironmentId;
266 const wslDistroFromTarget =
267 targetId !== undefined && targetId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX)
268 ? extractWslDistroFromEnvironmentId(targetId)
269 : null;
270 const useWsl =
271 targetId !== undefined &&
272 targetId !== PRIMARY_LOCAL_ENVIRONMENT_ID &&
273 targetId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX);
274 // Match the orchestrator's persisted distro fallback for wsl:default.
275 const wslDistro = useWsl ? (wslDistroFromTarget ?? settings.wslDistro) : null;
276 const defaultPath = useWsl
277 ? Option.fromNullishOr(
278 resolveWslPickFolderDefaultPath(
279 options,
280 { distro: wslDistro },
281 yield* wslEnvironment.listDistros,
282 Option.getOrNull(yield* wslEnvironment.getUserHome(wslDistro)),
283 ),
284 )
285 : environment.resolvePickFolderDefaultPath(options);
286 const selectedPath = yield* dialog.pickFolder({
287 owner: yield* electronWindow.focusedMainOrFirst,
288 defaultPath,
289 });
290 if (Option.isNone(selectedPath)) {
291 return null;
292 }
293 if (!useWsl) {
294 return selectedPath.value;
295 }
296 const converted = yield* windowsPathToWsl(wslDistro, selectedPath.value);
297 return Option.getOrElse(converted, () => selectedPath.value);
298 }),
299});
300​
301export const toLocalBackendPath = DesktopIpc.makeIpcMethod({
302 channel: IpcChannels.TO_LOCAL_BACKEND_PATH_CHANNEL,
303 payload: Schema.Struct({ backendId: Schema.String, path: Schema.String }),
304 result: Schema.NullOr(Schema.String),
305 handler: Effect.fn("desktop.ipc.window.toLocalBackendPath")(function* ({ backendId, path }) {
306 const pool = yield* DesktopBackendPool.DesktopBackendPool;
307 const instance = yield* pool.get(DesktopBackendManager.BackendInstanceId(backendId));
308 if (Option.isNone(instance)) return null;
309 const config = yield* instance.value.currentConfig;
310 if (Option.isNone(config) || Option.isSome(config.value.preflightFailure)) return null;
311 const { runningDistro } = config.value;
312 if (runningDistro === undefined) return path;
313 const uncDistro = extractDistroFromUncPath(path);
314 if (uncDistro !== null && uncDistro.toLowerCase() !== runningDistro.toLowerCase()) return null;
315 return Option.getOrNull(yield* windowsPathToWsl(runningDistro, path));
316 }),
317});
318​
319export const pickProjectFavicon = DesktopIpc.makeIpcMethod({
320 channel: IpcChannels.PICK_PROJECT_FAVICON_CHANNEL,
321 payload: Schema.UndefinedOr(Schema.String),
322 result: Schema.NullOr(Schema.String),
323 handler: Effect.fn("desktop.ipc.window.pickProjectFavicon")(function* (initialPath) {
324 const dialog = yield* ElectronDialog.ElectronDialog;
325 const electronWindow = yield* ElectronWindow.ElectronWindow;
326 const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
327 if (!(yield* appSettings.get).localEnvironmentEnabled) {
328 return null;
329 }
330 const paths = yield* dialog.pickFiles({
331 owner: yield* electronWindow.focusedMainOrFirst,
332 defaultPath: Option.fromNullishOr(initialPath),
333 multiple: false,
334 filters: [
335 {
336 name: m(msg("Images")),
337 extensions: PROJECT_FAVICON_EXTENSIONS.map((extension) => extension.slice(1)),
338 },
339 ],
340 });
341 return paths[0] ?? null;
342 }),
343});
344​
345export const setTheme = DesktopIpc.makeIpcMethod({
346 channel: IpcChannels.SET_THEME_CHANNEL,
347 payload: DesktopThemeSchema,
348 result: Schema.Void,
349 handler: Effect.fn("desktop.ipc.window.setTheme")(function* (theme) {
350 const electronTheme = yield* ElectronTheme.ElectronTheme;
351 yield* electronTheme.setSource(theme);
352 }),
353});
354​
355export const showContextMenu = DesktopIpc.makeIpcMethod({
356 channel: IpcChannels.CONTEXT_MENU_CHANNEL,
357 payload: ContextMenuInput,
358 result: Schema.NullOr(Schema.String),
359 handler: Effect.fn("desktop.ipc.window.showContextMenu")(function* (input) {
360 const electronMenu = yield* ElectronMenu.ElectronMenu;
361 const electronWindow = yield* ElectronWindow.ElectronWindow;
362 const window = yield* electronWindow.focusedMainOrFirst;
363 if (Option.isNone(window)) {
364 return null;
365 }
366​
367 const selectedItemId = yield* electronMenu.showContextMenu({
368 window: window.value,
369 items: input.items,
370 position: Option.fromNullishOr(input.position),
371 source: Option.fromNullishOr(input.source),
372 });
373 return Option.getOrNull(selectedItemId);
374 }),
375});
376​
377export const openExternal = DesktopIpc.makeIpcMethod({
378 channel: IpcChannels.OPEN_EXTERNAL_CHANNEL,
379 payload: Schema.String,
380 result: Schema.Boolean,
381 handler: Effect.fn("desktop.ipc.window.openExternal")(function* (url) {
382 const shell = yield* ElectronShell.ElectronShell;
383 return yield* shell.openExternal(url);
384 }),
385});
386​
387const READ_MEDIA_MAX_BYTES = 256 * 1024 * 1024;
388​
389// No URL field: media URLs can carry signed query tokens.
390class MediaReadError extends Schema.TaggedError<MediaReadError>()("MediaReadError", {
391 message: Schema.String,
392 cause: Schema.Defect(),
393}) {}
394​
395// The renderer can display media it cannot fetch(); reading here keeps Save and Copy working for it.
396export const readMedia = DesktopIpc.makeIpcMethod({
397 channel: IpcChannels.READ_MEDIA_CHANNEL,
398 payload: Schema.String,
399 result: Schema.NullOr(DesktopMediaReadSchema),
400 handler: Effect.fn("desktop.ipc.window.readMedia")(function* (url, event) {
401 const window = yield* (yield* ElectronWindow.ElectronWindow).main;
402 if (
403 event === undefined ||
404 Option.isNone(window) ||
405 window.value.webContents.id !== event.sender.id ||
406 !/^https?:$/.test(URL.parse(url)?.protocol ?? "")
407 ) {
408 return null;
409 }
410 const session = window.value.webContents.session;
411 return yield* Effect.tryPromise({
412 try: async () => {
413 // Like an <img>, send the session's cookies.
414 const response = await session.fetch(url, { credentials: "include" });
415 const mimeType = response.headers.get("content-type") ?? "";
416 if (!response.ok || !response.body) {
417 await response.body?.cancel();
418 return { status: response.status, mimeType, data: new Uint8Array() };
419 }
420 // The whole body crosses IPC, so stop before a huge file can exhaust main-process memory.
421 const chunks: Uint8Array[] = [];
422 let size = 0;
423 for await (const chunk of response.body) {
424 size += chunk.byteLength;
425 if (size > READ_MEDIA_MAX_BYTES) {
426 return { status: 413, mimeType, data: new Uint8Array() };
427 }
428 chunks.push(chunk);
429 }
430 return { status: response.status, mimeType, data: Buffer.concat(chunks) };
431 },
432 catch: (cause) => new MediaReadError({ message: "Could not read media.", cause }),
433 }).pipe(Effect.orElseSucceed(() => null));
434 }),
435});
436​
437export const openSystemSettings = DesktopIpc.makeIpcMethod({
438 channel: IpcChannels.OPEN_SYSTEM_SETTINGS_CHANNEL,
439 payload: SystemSettingsPaneSchema,
440 result: Schema.Boolean,
441 handler: Effect.fn("desktop.ipc.window.openSystemSettings")(function* (pane) {
442 const shell = yield* ElectronShell.ElectronShell;
443 const environment = yield* DesktopEnvironment.DesktopEnvironment;
444 if (environment.platform !== "darwin") return false;
445 const owner = Electron.BrowserWindow.getFocusedWindow();
446 const opened = yield* shell.openSystemSettings(pane);
447 if (opened && environment.isPackaged) {
448 const permissions = yield* MacPermissions.MacPermissions;
449 const isGranted = yield* safariPermissionCheck;
450 yield* permissions.showHelper(pane, owner, isGranted);
451 }
452 return opened;
453 }),
454});
455​
456const REMOTE_EDITOR_PROBE_CONCURRENCY = 8;
457​
458export const probeRemoteEditors = DesktopIpc.makeIpcMethod({
459 channel: IpcChannels.PROBE_REMOTE_EDITORS_CHANNEL,
460 payload: Schema.Undefined,
461 result: Schema.Array(EditorId),
462 handler: Effect.fn("desktop.ipc.window.probeRemoteEditors")(function* () {
463 const env = yield* HostProcess.Environment;
464 const resolved = yield* Effect.forEach(
465 REMOTE_CAPABLE_EDITOR_IDS,
466 (editorId) => {
467 const editor = EDITORS.find((editor) => editor.id === editorId);
468 return editor
469 ? resolveEditorCommand(editor, env).pipe(Effect.map(Option.isSome))
470 : Effect.succeed(false);
471 },
472 { concurrency: REMOTE_EDITOR_PROBE_CONCURRENCY },
473 );
474 return REMOTE_CAPABLE_EDITOR_IDS.filter((_, index) => resolved[index]);
475 }),
476});
477​
478export const pasteAsText = DesktopIpc.makeIpcMethod({
479 channel: IpcChannels.PASTE_AS_TEXT_CHANNEL,
480 payload: Schema.Undefined,
481 result: Schema.Void,
482 handler: Effect.fn("desktop.ipc.window.pasteAsText")(function* (_input, event) {
483 const electronWindow = yield* ElectronWindow.ElectronWindow;
484 const window = yield* electronWindow.main;
485 if (
486 event === undefined ||
487 Option.isNone(window) ||
488 window.value.isDestroyed() ||
489 window.value.webContents.id !== event.sender.id
490 ) {
491 return;
492 }
493 const focused = Electron.webContents.getFocusedWebContents();
494 if (
495 focused &&
496 !focused.isDestroyed() &&
497 Electron.BrowserWindow.fromWebContents(focused) === window.value
498 ) {
499 focused.paste();
500 }
501 }),
502});
503​
504export const revealWindow = DesktopIpc.makeIpcMethod({
505 channel: IpcChannels.REVEAL_WINDOW_CHANNEL,
506 payload: Schema.Undefined,
507 result: Schema.Void,
508 handler: Effect.fn("desktop.ipc.window.revealWindow")(function* (_input, event) {
509 const electronWindow = yield* ElectronWindow.ElectronWindow;
510 const window = yield* electronWindow.main;
511 if (
512 event === undefined ||
513 Option.isNone(window) ||
514 window.value.webContents.id !== event.sender.id
515 ) {
516 return;
517 }
518 yield* electronWindow.reveal(window.value);
519 }),
520});
521​
522const htmlFullscreenStates = new WeakMap<
523 Electron.BrowserWindow,
524 { owned: boolean; leaving: boolean }
525>();
526​
527const htmlFullscreenState = (window: Electron.BrowserWindow) => {
528 const existing = htmlFullscreenStates.get(window);
529 if (existing !== undefined) return existing;
530 const state = { owned: false, leaving: false };
531 window.on("leave-full-screen", () => {
532 // Leaving OS fullscreen any other way, such as F11, hands the window back to the user.
533 if (!state.leaving) state.owned = false;
534 state.leaving = false;
535 });
536 htmlFullscreenStates.set(window, state);
537 return state;
538};
539​
540// The main window keeps HTML fullscreen inside itself so preview guests stay in their webview,
541// so the app's own fullscreen elements, such as chat videos, take the screen here.
542export const syncHtmlFullscreen = DesktopIpc.makeIpcMethod({
543 channel: IpcChannels.SYNC_HTML_FULLSCREEN_CHANNEL,
544 payload: Schema.Boolean,
545 result: Schema.Void,
546 handler: Effect.fn("desktop.ipc.window.syncHtmlFullscreen")(function* (fullscreen, event) {
547 const electronWindow = yield* ElectronWindow.ElectronWindow;
548 const main = yield* electronWindow.main;
549 if (
550 event === undefined ||
551 Option.isNone(main) ||
552 main.value.isDestroyed() ||
553 main.value.webContents.id !== event.sender.id
554 ) {
555 return;
556 }
557 const window = main.value;
558 const state = htmlFullscreenState(window);
559 if (fullscreen) {
560 // macOS reports fullscreen until its exit animation ends, and Electron queues the re-entry.
561 if (state.owned || (window.isFullScreen() && !state.leaving)) return;
562 state.owned = true;
563 window.setFullScreen(true);
564 } else if (state.owned) {
565 state.owned = false;
566 state.leaving = window.isFullScreen();
567 window.setFullScreen(false);
568 }
569 }),
570});
571​
572const PICKED_THEME_FILE_MAX_BYTES = 256 * 1024;
573​
574export const pickThemeFiles = DesktopIpc.makeIpcMethod({
575 channel: IpcChannels.PICK_THEME_FILES_CHANNEL,
576 payload: Schema.Undefined,
577 result: Schema.NullOr(Schema.Array(PickedThemeFileSchema)),
578 handler: Effect.fn("desktop.ipc.window.pickThemeFiles")(function* () {
579 const dialog = yield* ElectronDialog.ElectronDialog;
580 const electronWindow = yield* ElectronWindow.ElectronWindow;
581 const fileSystem = yield* FileSystem.FileSystem;
582 const path = yield* Path.Path;
583 const extensionsDir = path.join(yield* HostProcess.HomeDirectory, ".vscode", "extensions");
584 const defaultPath = yield* fileSystem
585 .exists(extensionsDir)
586 .pipe(Effect.orElseSucceed(() => false));
587 const paths = yield* dialog.pickFiles({
588 owner: yield* electronWindow.focusedMainOrFirst,
589 defaultPath: defaultPath ? Option.some(extensionsDir) : Option.none(),
590 filters: [{ name: "JSON", extensions: ["json"] }],
591 multiple: true,
592 });
593 if (paths.length === 0) {
594 return null;
595 }
596 return yield* Effect.forEach(paths, (filePath) => {
597 const name = path.basename(filePath);
598 return Effect.gen(function* () {
599 const info = yield* fileSystem.stat(filePath);
600 const size = Number(info.size);
601 if (size > PICKED_THEME_FILE_MAX_BYTES) {
602 return { name, size, text: "" } satisfies PickedThemeFile;
603 }
604 const text = yield* fileSystem.readFileString(filePath);
605 return { name, size, text } satisfies PickedThemeFile;
606 }).pipe(Effect.orElseSucceed((): PickedThemeFile => ({ name, size: 0, text: "" })));
607 });
608 }),
609});
610​
611export const checkSystemPermission = DesktopIpc.makeIpcMethod({
612 channel: IpcChannels.CHECK_SYSTEM_PERMISSION_CHANNEL,
613 payload: SystemSettingsPaneSchema,
614 result: Schema.Boolean,
615 handler: Effect.fn("desktop.ipc.window.checkSystemPermission")(function* () {
616 const environment = yield* DesktopEnvironment.DesktopEnvironment;
617 if (environment.platform !== "darwin") return false;
618 const check = yield* safariPermissionCheck;
619 return yield* Effect.promise(check);
620 }),
621});
622​
623export const restartAudioService = DesktopIpc.makeIpcMethod({
624 channel: IpcChannels.RESTART_AUDIO_SERVICE_CHANNEL,
625 payload: Schema.Void,
626 result: Schema.Boolean,
627 handler: ElectronAudio.restart,
628});