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