Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 46 additions & 19 deletions runtime/src/js/pgadmin.js
Original file line number Diff line number Diff line change
Expand Up @@ -545,34 +545,61 @@ function notifyUpdateInstalled() {

// Native file dialogs don't reliably remember the last used directory across
// calls, so we track it ourselves and use it as the default when the caller
// hasn't asked for a specific location.
async function withLastVisitedDirectory(options) {
// hasn't asked for a specific location. Callers may pass a purpose (e.g.
// 'backup' or 'erd') so that each kind of dialog remembers its own directory;
// a purpose with nothing saved yet falls back to the last directory used by
// any dialog.
function isValidDialogPurpose(purpose) {
return typeof purpose === 'string' && /^[a-z][a-z0-9_]*$/.test(purpose);
}

async function isExistingDirectory(dirPath) {
if (!dirPath) {
return false;
}
try {
const stats = await fs.promises.stat(dirPath);
return stats.isDirectory();
} catch {
// Remembered directory no longer exists (e.g. removable/network drive).
return false;
}
}

async function withLastVisitedDirectory(options, purpose) {
if (options.defaultPath) {
return options;
}
const lastVisitedDirectory = configStore.get('lastVisitedDirectory');
if (!lastVisitedDirectory) {
return options;
const candidates = [];
if (isValidDialogPurpose(purpose)) {
candidates.push(configStore.get('lastVisitedDirectories')?.[purpose]);
}
try {
const stats = await fs.promises.stat(lastVisitedDirectory);
if (stats.isDirectory()) {
return { ...options, defaultPath: lastVisitedDirectory };
candidates.push(configStore.get('lastVisitedDirectory'));
for (const candidate of candidates) {
if (await isExistingDirectory(candidate)) {
return { ...options, defaultPath: candidate };
}
} catch {
// Remembered directory no longer exists (e.g. removable/network drive) - fall through.
}
return options;
}

function rememberVisitedDirectory(options, result) {
function rememberVisitedDirectory(options, result, purpose) {
const chosenPath = result.filePath || result.filePaths?.[0];
if (!chosenPath) {
return;
}
const isDirectory = options.properties?.includes('openDirectory');
const visitedDirectory = isDirectory ? chosenPath : path.dirname(chosenPath);
try {
configStore.set('lastVisitedDirectory', isDirectory ? chosenPath : path.dirname(chosenPath));
configStore.set('lastVisitedDirectory', visitedDirectory);
if (isValidDialogPurpose(purpose)) {
// Set the whole map rather than a dotted key path, so a purpose can never
// be interpreted as a nested property path by the store.
configStore.set('lastVisitedDirectories', {
...configStore.get('lastVisitedDirectories'),
[purpose]: visitedDirectory,
});
}
} catch (error) {
try {
misc.writeServerLog(`Error remembering last visited directory: ${error}`);
Expand All @@ -583,17 +610,17 @@ function rememberVisitedDirectory(options, result) {
}

// setup preload events.
ipcMain.handle('showOpenDialog', async (e, options) => {
const result = await dialog.showOpenDialog(BrowserWindow.fromWebContents(e.sender), await withLastVisitedDirectory(options));
ipcMain.handle('showOpenDialog', async (e, options, purpose) => {
const result = await dialog.showOpenDialog(BrowserWindow.fromWebContents(e.sender), await withLastVisitedDirectory(options, purpose));
if (!result.canceled) {
rememberVisitedDirectory(options, result);
rememberVisitedDirectory(options, result, purpose);
}
return result;
});
ipcMain.handle('showSaveDialog', async (e, options) => {
const result = await dialog.showSaveDialog(BrowserWindow.fromWebContents(e.sender), await withLastVisitedDirectory(options));
ipcMain.handle('showSaveDialog', async (e, options, purpose) => {
const result = await dialog.showSaveDialog(BrowserWindow.fromWebContents(e.sender), await withLastVisitedDirectory(options, purpose));
if (!result.canceled) {
rememberVisitedDirectory(options, result);
rememberVisitedDirectory(options, result, purpose);
}
return result;
});
Expand Down
4 changes: 2 additions & 2 deletions runtime/src/js/pgadmin_preload.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ contextBridge.exposeInMainWorld('electronUI', {
setMenuItems: (menu, menuItems) => {
ipcRenderer.send('set-menu-items', menu, menuItems);
},
showOpenDialog: (options) => ipcRenderer.invoke('showOpenDialog', options),
showSaveDialog: (options) => ipcRenderer.invoke('showSaveDialog', options),
showOpenDialog: (options, purpose) => ipcRenderer.invoke('showOpenDialog', options, purpose),
showSaveDialog: (options, purpose) => ipcRenderer.invoke('showSaveDialog', options, purpose),
log: (text)=> ipcRenderer.send('log', text),
reloadApp: ()=>{ipcRenderer.send('reloadApp');},
// Download related functions
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ export default class SubscriptionSchema extends BaseUISchema{
group: gettext('SSL'), mode: ['edit', 'create'],
disabled: obj.isSSL,
controlProps: {
dialogType: 'select_file', supportedTypes: ['*'],
dialogType: 'select_file', dialogPurpose: 'certificates', supportedTypes: ['*'],
},
deps: ['sslmode'],
},
Expand All @@ -228,23 +228,23 @@ export default class SubscriptionSchema extends BaseUISchema{
group: gettext('SSL'), mode: ['edit', 'create'],
disabled: obj.isSSL,
controlProps: {
dialogType: 'select_file', supportedTypes: ['*'],
dialogType: 'select_file', dialogPurpose: 'certificates', supportedTypes: ['*'],
},
deps: ['sslmode'],
},{
id: 'sslrootcert', label: gettext('Root certificate'), type: 'file',
group: gettext('SSL'), mode: ['edit', 'create'],
disabled: obj.isSSL,
controlProps: {
dialogType: 'select_file', supportedTypes: ['*'],
dialogType: 'select_file', dialogPurpose: 'certificates', supportedTypes: ['*'],
},
deps: ['sslmode'],
},{
id: 'sslcrl', label: gettext('Certificate revocation list'), type: 'file',
group: gettext('SSL'), mode: ['edit', 'create'],
disabled: obj.isSSL,
controlProps: {
dialogType: 'select_file', supportedTypes: ['*'],
dialogType: 'select_file', dialogPurpose: 'certificates', supportedTypes: ['*'],
},
deps: ['sslmode'],
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -513,7 +513,7 @@ export default class ServerSchema extends BaseUISchema {
id: 'tunnel_identity_file', label: gettext('Identity file'), type: 'file',
group: gettext('SSH Tunnel'), mode: ['properties', 'edit', 'create'],
controlProps: {
dialogType: 'select_file', supportedTypes: ['*'],
dialogType: 'select_file', dialogPurpose: 'ssh_identity', supportedTypes: ['*'],
},
deps: ['tunnel_authentication', 'use_ssh_tunnel'],
depChange: (state)=>{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ export default class VariableSchema extends BaseUISchema {
cell: 'file',
controlProps: {
dialogType: 'select_file',
dialogPurpose: 'certificates',
supportedTypes: ['*'],
placeholder: this.getPlaceHolderMsg(variable)
}
Expand Down
1 change: 1 addition & 0 deletions web/pgadmin/misc/cloud/static/js/google_schema.ui.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ class GoogleCredSchema extends BaseUISchema{
helpMessage: gettext('Select a client secrets file containing the client ID, client secret, and other OAuth 2.0 parameters for Google authentication. See <a href="https://support.google.com/cloud/answer/15549257?hl=en">Manage OAuth Clients</a> in the Google Cloud documentation for how to create one.'),
controlProps: {
dialogType: 'select_file',
dialogPurpose: 'cloud_credentials',
supportedTypes: ['json'],
dialogTitle: 'Select file',
},
Expand Down
6 changes: 4 additions & 2 deletions web/pgadmin/misc/file_manager/static/js/FileManagerModule.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -95,14 +95,16 @@ export default class FileManagerModule {
{name: `${v.toUpperCase()} File .${v}`, extensions:[v]}
));

// The purpose lets the desktop runtime remember the last used folder
// separately for each kind of dialog (e.g. backups vs ERD diagrams).
if(params.dialog_type == 'create_file') {
res = await window.electronUI.showSaveDialog(options);
res = await window.electronUI.showSaveDialog(options, params.purpose);
} else {
options['properties'] = ['openFile'];
if(params.dialog_type == 'select_folder') {
options['properties'] = ['openDirectory'];
}
res = await window.electronUI.showOpenDialog(options);
res = await window.electronUI.showOpenDialog(options, params.purpose);
}

if(res.canceled) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ export default class BinaryPathSchema extends BaseUISchema {
},
controlProps: {
dialogType: 'select_folder',
dialogPurpose: 'binary_path',
supportedTypes: ['*', 'sql', 'backup'],
dialogTitle: gettext('Select folder'),
placeholder: pgAdmin.server_mode == 'False' ? gettext('Select binary path...') : gettext('Enter binary path...')
Expand Down
1 change: 1 addition & 0 deletions web/pgadmin/static/js/components/FormComponents.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -544,6 +544,7 @@ export function InputFileSelect({ controlProps, onChange, disabled, readonly, is
dialog_type: controlProps.dialogType || 'select_file',
dialog_title: controlProps.dialogTitle || '',
btn_primary: controlProps.btnPrimary || '',
purpose: controlProps.dialogPurpose,
};
showFileManager(params, (fileName, dir)=>{
if (dir && dir != MY_STORAGE){
Expand Down
1 change: 1 addition & 0 deletions web/pgadmin/tools/backup/static/js/backup.ui.js
Original file line number Diff line number Diff line change
Expand Up @@ -606,6 +606,7 @@ export default class BackupSchema extends BaseUISchema {
disabled: false,
controlProps: {
dialogType: 'create_file',
dialogPurpose: 'backup',
supportedTypes: ['*', 'sql', 'backup'],
dialogTitle: 'Select file',
},
Expand Down
1 change: 1 addition & 0 deletions web/pgadmin/tools/backup/static/js/backupGlobal.ui.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ export default class BackupGlobalSchema extends BaseUISchema {
disabled: false,
controlProps: {
dialogType: 'create_file',
dialogPurpose: 'backup',
supportedTypes: ['*', 'sql', 'backup'],
dialogTitle: 'Select file',
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -715,6 +715,7 @@ export default class ERDTool extends React.Component {
const params = {
'supported_types': ['*','pgerd'], // file types allowed
'dialog_type': 'select_file', // open select file dialog
'purpose': 'erd',
};
this.props.pgAdmin.Tools.FileManager.show(params, this.openFile.bind(this), null, this.context);
}
Expand Down Expand Up @@ -750,6 +751,7 @@ export default class ERDTool extends React.Component {
'dialog_type': 'create_file',
'dialog_title': 'Save File',
'btn_primary': 'Save',
'purpose': 'erd',
};
this.props.pgAdmin.Tools.FileManager.show(params, this.saveFile.bind(this), null, this.context);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ export default class ImportExportSchema extends BaseUISchema {
type: 'file',
controlProps: {
dialogType: state.is_import && !state?.is_query_export ? 'select_file' : 'create_file',
dialogPurpose: 'import_export_data',
supportedTypes: ['csv', 'text','bin', '*'],
dialogTitle: 'Select file',
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export default class ImportExportSelectionSchema extends BaseUISchema {
type: 'file',
controlProps: {
dialogType: 'create_file',
dialogPurpose: 'import_export_servers',
supportedTypes: ['json'],
dialogTitle: 'Create file',
},
Expand All @@ -51,6 +52,7 @@ export default class ImportExportSelectionSchema extends BaseUISchema {
type: 'file',
controlProps: {
dialogType: 'select_file',
dialogPurpose: 'import_export_servers',
supportedTypes: ['json'],
dialogTitle: 'Select file',
},
Expand Down
1 change: 1 addition & 0 deletions web/pgadmin/tools/restore/static/js/restore.ui.js
Original file line number Diff line number Diff line change
Expand Up @@ -460,6 +460,7 @@ export default class RestoreSchema extends BaseUISchema {
type: 'file',
controlProps: {
dialogType: state.format == 'directory' ? 'select_folder' : 'select_file',
dialogPurpose: 'backup',
supportedTypes: ['*', 'backup', 'sql', 'patch'],
dialogTitle: 'Select file',
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -698,6 +698,7 @@ export default function QueryToolComponent({params, pgWindow, pgAdmin, selectedN
let fileParams = {
'supported_types': ['sql', '*'], // file types allowed
'dialog_type': 'open_file', // open select file dialog
'purpose': 'query_tool',
};
if(openInNewTab){
pgAdmin.Tools.FileManager.show(fileParams, (fileName, storage)=>{
Expand All @@ -718,6 +719,7 @@ export default function QueryToolComponent({params, pgWindow, pgAdmin, selectedN
'dialog_type': 'create_file',
'dialog_title': 'Save File',
'btn_primary': 'Save',
'purpose': 'query_tool',
};
pgAdmin.Tools.FileManager.show(fileParams, (fileName)=>{
eventBus.current.fireEvent(QUERY_TOOL_EVENTS.SAVE_FILE, fileName);
Expand Down
13 changes: 13 additions & 0 deletions web/regression/javascript/components/FormComponents.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,19 @@ describe('FormComponents', ()=>{
expect(onChange).toHaveBeenCalledWith('selected/file');
});

it('file select passes the dialog purpose', ()=>{
ctrlRerender({
controlProps: {
dialogType: 'create_file', dialogPurpose: 'backup', supportedTypes: ['*'],
},
});
fireEvent.click(screen.getByRole('button'));
expect(showFileManager.showFileManager).toHaveBeenLastCalledWith(
expect.objectContaining({dialog_type: 'create_file', purpose: 'backup'}),
expect.any(Function),
);
});

it('accessibility', ()=>{
onAccessibility();
});
Expand Down
73 changes: 73 additions & 0 deletions web/regression/javascript/file_manager/FileManagerModule.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/////////////////////////////////////////////////////////////
//
// pgAdmin 4 - PostgreSQL Tools
//
// Copyright (C) 2013 - 2026, The pgAdmin Development Team
// This software is released under the PostgreSQL Licence
//
//////////////////////////////////////////////////////////////

import FileManagerModule from '../../../pgadmin/misc/file_manager/static/js/FileManagerModule';

// The dialog component is not needed for the native path, and importing it
// here would create a circular import back to the module under test.
jest.mock('../../../pgadmin/misc/file_manager/static/js/components/FileManager', ()=>()=>null);

describe('FileManagerModule', ()=>{
describe('showNative', ()=>{
let fmModule;

beforeEach(()=>{
fmModule = new FileManagerModule({});
window.electronUI = {
showSaveDialog: jest.fn().mockResolvedValue({canceled: false, filePath: '/backups/db.backup'}),
showOpenDialog: jest.fn().mockResolvedValue({canceled: false, filePaths: ['/diagrams/model.pgerd']}),
};
});

afterEach(()=>{
delete window.electronUI;
});

it('passes the purpose to the save dialog', async ()=>{
const onOK = jest.fn();
await fmModule.showNative({dialog_type: 'create_file', supported_types: ['backup'], purpose: 'backup'}, onOK);
expect(window.electronUI.showSaveDialog).toHaveBeenCalledWith(
expect.objectContaining({filters: [{name: 'BACKUP File .backup', extensions: ['backup']}]}),
'backup',
);
expect(onOK).toHaveBeenCalledWith('/backups/db.backup');
});

it('passes the purpose to the open dialog', async ()=>{
const onOK = jest.fn();
await fmModule.showNative({dialog_type: 'select_file', supported_types: ['pgerd'], purpose: 'erd'}, onOK);
expect(window.electronUI.showOpenDialog).toHaveBeenCalledWith(
expect.objectContaining({properties: ['openFile']}),
'erd',
);
expect(onOK).toHaveBeenCalledWith('/diagrams/model.pgerd');
});

it('passes the purpose to the folder dialog', async ()=>{
await fmModule.showNative({dialog_type: 'select_folder', purpose: 'binary_path'});
expect(window.electronUI.showOpenDialog).toHaveBeenCalledWith(
expect.objectContaining({properties: ['openDirectory']}),
'binary_path',
);
});

it('passes no purpose when the caller does not give one', async ()=>{
await fmModule.showNative({dialog_type: 'open_file'});
expect(window.electronUI.showOpenDialog).toHaveBeenCalledWith(expect.any(Object), undefined);
});

it('calls onCancel when the dialog is cancelled', async ()=>{
const onOK = jest.fn(), onCancel = jest.fn();
window.electronUI.showSaveDialog.mockResolvedValue({canceled: true});
await fmModule.showNative({dialog_type: 'create_file', purpose: 'query_tool'}, onOK, onCancel);
expect(onCancel).toHaveBeenCalled();
expect(onOK).not.toHaveBeenCalled();
});
});
});
Loading