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