|
| 1 | +/** |
| 2 | + * Dialog IPC handlers |
| 3 | + * |
| 4 | + * Handles native file dialog operations. |
| 5 | + */ |
| 6 | + |
| 7 | +import { ipcMain, dialog } from 'electron'; |
| 8 | +import { isPathAllowed, getAllowedRootDirectory } from '@automaker/platform'; |
| 9 | +import { IPC_CHANNELS } from './channels'; |
| 10 | +import { state } from '../state'; |
| 11 | + |
| 12 | +/** |
| 13 | + * Register dialog IPC handlers |
| 14 | + */ |
| 15 | +export function registerDialogHandlers(): void { |
| 16 | + // Open directory dialog |
| 17 | + ipcMain.handle(IPC_CHANNELS.DIALOG.OPEN_DIRECTORY, async () => { |
| 18 | + if (!state.mainWindow) { |
| 19 | + return { canceled: true, filePaths: [] }; |
| 20 | + } |
| 21 | + const result = await dialog.showOpenDialog(state.mainWindow, { |
| 22 | + properties: ['openDirectory', 'createDirectory'], |
| 23 | + }); |
| 24 | + |
| 25 | + // Validate selected path against ALLOWED_ROOT_DIRECTORY if configured |
| 26 | + if (!result.canceled && result.filePaths.length > 0) { |
| 27 | + const selectedPath = result.filePaths[0]; |
| 28 | + if (!isPathAllowed(selectedPath)) { |
| 29 | + const allowedRoot = getAllowedRootDirectory(); |
| 30 | + const errorMessage = allowedRoot |
| 31 | + ? `The selected directory is not allowed. Please select a directory within: ${allowedRoot}` |
| 32 | + : 'The selected directory is not allowed.'; |
| 33 | + |
| 34 | + dialog.showErrorBox('Directory Not Allowed', errorMessage); |
| 35 | + |
| 36 | + return { canceled: true, filePaths: [] }; |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + return result; |
| 41 | + }); |
| 42 | + |
| 43 | + // Open file dialog |
| 44 | + // Filter properties to maintain file-only intent and prevent renderer from requesting directories |
| 45 | + ipcMain.handle( |
| 46 | + IPC_CHANNELS.DIALOG.OPEN_FILE, |
| 47 | + async (_, options: Record<string, unknown> = {}) => { |
| 48 | + if (!state.mainWindow) { |
| 49 | + return { canceled: true, filePaths: [] }; |
| 50 | + } |
| 51 | + // Ensure openFile is always present and filter out directory-related properties |
| 52 | + const inputProperties = (options.properties as string[]) ?? []; |
| 53 | + const properties = ['openFile', ...inputProperties].filter( |
| 54 | + (p) => p !== 'openDirectory' && p !== 'createDirectory' |
| 55 | + ); |
| 56 | + const result = await dialog.showOpenDialog(state.mainWindow, { |
| 57 | + ...options, |
| 58 | + properties: properties as Electron.OpenDialogOptions['properties'], |
| 59 | + }); |
| 60 | + return result; |
| 61 | + } |
| 62 | + ); |
| 63 | + |
| 64 | + // Save file dialog |
| 65 | + ipcMain.handle(IPC_CHANNELS.DIALOG.SAVE_FILE, async (_, options = {}) => { |
| 66 | + if (!state.mainWindow) { |
| 67 | + return { canceled: true, filePath: undefined }; |
| 68 | + } |
| 69 | + const result = await dialog.showSaveDialog(state.mainWindow, options); |
| 70 | + return result; |
| 71 | + }); |
| 72 | +} |
0 commit comments