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

window.ts

605 lines23.7 KB

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