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