electron#dialog TypeScript Examples
The following examples show how to use
electron#dialog.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: project-utils.ts From kliveide with MIT License | 7 votes |
/**
* Selects a folder form the dialog
*/
export async function selectFolder(
title: string,
defaultPath?: string
): Promise<string | null> {
const result = await dialog.showOpenDialog(AppWindow.focusedWindow.window, {
title,
defaultPath,
properties: ["openDirectory"],
});
return result.canceled ? null : result.filePaths[0];
}
Example #2
Source File: utilities.ts From Creators.TF-Community-Launcher with MIT License | 7 votes |
/**
* Create an error dialog and print the error to the log files.
* @param error The error object/message.
* @param title Title for the error dialog.
*/
public static ErrorDialog(error: any, title: string): any {
log.error(`Error Dialog shown: ${title} : ${error.toString()}`);
//@ts-ignore
dialog.showMessageBox(global.mainWindow, {
type: "error",
title: title,
message: error.toString(),
buttons: ["OK"]
});
}
Example #3
Source File: overlay-window.ts From awakened-poe-trade with MIT License | 6 votes |
function handleOverlayAttached (hasAccess?: boolean) {
if (hasAccess === false) {
logger.error('PoE is running with administrator rights', { source: 'overlay' })
dialog.showErrorBox(
'PoE window - No access',
// ----------------------
'Path of Exile is running with administrator rights.\n' +
'\n' +
'You need to restart Awakened PoE Trade with administrator rights.'
)
}
}
Example #4
Source File: index.ts From electron-playground with MIT License | 6 votes |
openFileDialog = async (oldPath: string = app.getPath('downloads')) => {
if (!win) return oldPath
const { canceled, filePaths } = await dialog.showOpenDialog(win, {
title: '选择保存位置',
properties: ['openDirectory', 'createDirectory'],
defaultPath: oldPath,
})
return !canceled ? filePaths[0] : oldPath
}
Example #5
Source File: main.dev.ts From ExpressLRS-Configurator with GNU General Public License v3.0 | 6 votes |
autoUpdater.on('update-available', async () => {
const response = await dialog.showMessageBox(mainWindow!, {
type: 'info',
title: 'Found Updates',
message: 'Found updates, do you want update now?',
buttons: ['Sure', 'Later'],
});
if (response.response === 0) {
logger.log('Downloading Update');
autoUpdater.downloadUpdate();
await dialog.showMessageBox(mainWindow!, {
type: 'info',
title: 'Update Downloading',
message:
'Update is being downloaded, you will be notified when it is ready to install',
buttons: [],
});
}
});
Example #6
Source File: updater.ts From SpaceEye with MIT License | 6 votes |
/**
* Prompt the user to see if they want to update the app.
*
* @param info - Info about the update
*/
async function promptForUpdate(info: UpdateInfo) {
// Don't alert the user more than once for an update version
if (updateAlertVersions[info.version] === true) {
return
}
updateAlertVersions[info.version] = true
const res = await dialog.showMessageBox({
type: 'info',
buttons: ['Restart', 'Later'],
message: 'Update Ready to Install',
detail:
'A new version of SpaceEye is ready to install. Restart application to apply the update.',
defaultId: 0,
cancelId: 1
})
if (res.response === 0) {
autoUpdater.quitAndInstall()
}
}
Example #7
Source File: electron.service.ts From league-profile-tool with MIT License | 6 votes |
constructor() {
if (this.isElectron) {
this.ipcRenderer = window.require('electron').ipcRenderer;
this.webFrame = window.require('electron').webFrame;
this.shell = window.require('electron').shell;
this.request = window.require('request-promise');
this.dialog = window.require('electron').remote.dialog;
this.childProcess = window.require('child_process');
this.fs = window.require('fs');
this.LCUConnector = window.require('lcu-connector');
}
}
Example #8
Source File: sentry.ts From electron-playground with MIT License | 6 votes |
/**
* Crash listen on the created window
* @param win BrowserWindow
*/
export function addCrashListener(win: BrowserWindow) {
// https://www.electronjs.org/docs/api/web-contents#event-crashed-deprecated
win.webContents.on('crashed', async (event,killed) => {
console.log(event,killed)
const options: MessageBoxOptions = {
type: 'info',
title: 'The renderer process crashes',
message: 'The renderer process crashes.',
buttons: ['quit app', 'reload'],
}
const { response } = await dialog.showMessageBox(win, options)
// 1 reload 0 quit app
response ? win.reload() : app.quit()
})
}
Example #9
Source File: main.dev.ts From ow-mod-manager with MIT License | 6 votes |
autoUpdater.signals.updateDownloaded(({ version }) => {
log.info('CALLED update-available');
const response = dialog.showMessageBoxSync({
type: 'info',
buttons: [updateText.dialogYes, updateText.dialogNo],
title: updateText.dialogTitle,
message: updateText.dialogMessage,
detail: updateText.dialogDetail(version),
});
if (response === 0) autoUpdater.quitAndInstall();
});
Example #10
Source File: config.ts From awakened-poe-trade with MIT License | 6 votes |
config = (() => {
const store = new Store<Config>({
name: 'config',
cwd: 'apt-data',
defaults: defaultConfig()
})
if (store.get('configVersion') > defaultConfig().configVersion) {
dialog.showErrorBox(
'Awakened PoE Trade - Incompatible configuration',
// ----------------------
'You are trying to use an older version of Awakened PoE Trade with a newer incompatible configuration file.\n' +
'You need to install the latest version to continue using it.'
)
app.exit(1)
}
store.store = upgradeConfig(store.store)
return store
})()
Example #11
Source File: ipc.ts From MagicUI with Apache License 2.0 | 6 votes |
handleSaveFile = () => {
ipcMain.handle(IpcEvent.SAVE_FILE, async (event, args: { type: string, data: any }) => {
if (args.type === 'base64') {
const value = await dialog.showSaveDialog({
title: 'EXPORT',
filters: [
{name: 'image', extensions: ['png', 'jpeg', 'jpg']}
]
});
return await saveBase64ToImage(value.filePath as string, args.data);
}
if (args.type === 'code') {
let filters: any[] = [];
if (args.data.codeType === 'HTML') {
filters = [{ name: 'html', extensions: ['html', 'htm'] }]
const value = await dialog.showSaveDialog({
title: 'EXPORT',
filters
});
return await saveCodeFile(value.filePath as string, args.data.code[0]);
}
if (args.data.codeType === 'REACT') {
filters = [{ name: 'react', extensions: [] }]
const value = await dialog.showSaveDialog({
title: 'EXPORT',
filters
});
await mkdir(value.filePath as string);
await saveCodeFile(`${value.filePath}/index.jsx`, args.data.code[0]);
await saveCodeFile(`${value.filePath}/index.scss`, args.data.code[1]);
return;
}
}
});
}
Example #12
Source File: main.dev.ts From ExpressLRS-Configurator with GNU General Public License v3.0 | 6 votes |
handleFatalError = (err: Error | object | null | undefined) => {
logger.error(`handling fatal error: ${err}`);
try {
// eslint-disable-next-line promise/no-promise-in-callback
dialog
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
.showMessageBox(undefined, {
type: 'error',
buttons: ['Okay'],
title: 'Oops! Something went wrong!',
detail: 'Help us improve your experience by sending an error report',
message: `Error: ${err}`,
})
.then(() => {
console.log('received resp from message box');
process.exit(1);
})
.catch((dialogErr) => {
logger.error('failed to show error dialog', dialogErr.stack);
process.exit(1);
});
} catch (e) {
/*
This API can be called safely before the ready event the app module emits, it is usually used to report errors
in early stage of startup. If called before the app readyevent on Linux, the message will be emitted to stderr,
and no GUI dialog will appear.
*/
dialog.showErrorBox('Oops! Something went wrong!', `Error: ${err}`);
process.exit(1);
}
}
Example #13
Source File: ipc.ts From MagicUI with Apache License 2.0 | 6 votes |
handleOpenFile = () => {
ipcMain.handle(IpcEvent.OPEN_FILE, async (event, args: { type: string }) => {
if (args.type === 'image') {
const value = await dialog.showOpenDialog({
title: 'OPEN',
filters: [
{ name: 'image', extensions: ['png', 'jpeg', 'jpg'] }
]
});
return value;
}
return null;
});
}
Example #14
Source File: sapio.ts From sapio-studio with Mozilla Public License 2.0 | 6 votes |
static async command(args: string[]): Promise<Result<string>> {
const binary = preferences.data.sapio_cli.sapio_cli;
const source = preferences.data.sapio_cli.preferences;
let new_args: string[] = [];
if (source === 'Default') {
new_args = args;
} else if ('File' in source) {
new_args = ['--config', source.File, ...args];
} else if ('Here' in source) {
new_args = ['--config', sapio_config_file, ...args];
} else {
dialog.showErrorBox(
'Improper Source',
'This means your config file is corrupt, shutting down.'
);
sys.exit(1);
}
console.debug(['sapio'], binary, new_args);
try {
const ok = (await spawn(binary, new_args)).toString();
return { ok };
} catch (e: any) {
return { err: e.stderr.toString() };
}
}
Example #15
Source File: desktop.ts From shadowsocks-electron with GNU General Public License v3.0 | 6 votes |
async backupConfigurationToFile(params: JSON): Promise<ServiceResult> {
const filePath = dialog.showSaveDialogSync((global as any).win, {
defaultPath: `${app.getPath('downloads')}/gui-config.json`
});
return new Promise(resolve => {
if (filePath) {
fs.writeFile(filePath, JSON.stringify(params, null, 2), (err) => {
if (err) {
console.log(err);
return resolve({
code: 500,
result: err.toString()
});
}
resolve({
code: 200,
result: filePath
});
});
} else {
resolve({
code: 404,
result: null
});
};
});
}
Example #16
Source File: MainIPC.ts From noteworthy with GNU Affero General Public License v3.0 | 6 votes |
// -- Request Folder Open --------------------------- //
dialogFolderOpen() {
if (!this._app.window) { return; }
// open file dialog
const dirPaths: string[] | undefined = dialog.showOpenDialogSync(
this._app.window.window,
{
properties: ['openDirectory', 'createDirectory'],
//filters: FILE_FILTERS
}
);
if (!dirPaths || !dirPaths.length) return;
this._workspaceService.setWorkspaceDir(dirPaths[0]);
}
Example #17
Source File: electron.ts From companion-satellite with MIT License | 6 votes |
function trayQuit() {
console.log('quit click')
dialog
.showMessageBox({
title: 'Companion Satellite',
message: 'Are you sure you want to quit Companion Satellite?',
buttons: ['Quit', 'Cancel'],
})
.then(async (v) => {
console.log('quit: ', v.response)
if (v.response === 0) {
await Promise.allSettled([
// cleanup
client.disconnect(),
devices.close(),
])
app.quit()
}
})
.catch((e) => {
console.error('Failed to do quit', e)
})
}
Example #18
Source File: main.ts From blockcore-hub with MIT License | 6 votes |
ipcMain.on('choose-data-folder', (event, arg: Chain) => {
const paths = dialog.showOpenDialogSync(mainWindow, {
title: 'Choose a data folder',
properties: ['openDirectory']
});
console.log('PATHS:', paths);
if (paths.length > 0) {
event.returnValue = paths[0];
contents.send('choose-data-folder', paths[0]);
} else {
event.returnValue = null;
contents.send('choose-data-folder', null);
}
// dialog.showOpenDialog(null, options, (filePaths) => {
// event.sender.send('open-dialog-paths-selected', filePaths)
// });
});
Example #19
Source File: ViewerHandler.ts From viewer with MIT License | 6 votes |
/**
* Save file dialog
* @param options
* @returns
*/
public async saveFile(
options: SaveDialogOptions
): Promise<SaveDialogReturnValue> {
return dialog.showSaveDialog(options);
}
Example #20
Source File: emu-window.ts From kliveide with MIT License | 6 votes |
/**
* Displays an error message in a pop-up
* @param message
*/
async showError(message: string, title = "Error"): Promise<void> {
await dialog.showMessageBox(this.window, {
title,
message,
type: "error",
});
}
Example #21
Source File: index.ts From bluebubbles-server with Apache License 2.0 | 6 votes |
async initDatabase(): Promise<void> {
this.log("Initializing server database...");
this.repo = new ServerRepository();
await this.repo.initialize();
// Handle when something in the config changes
this.repo.on("config-update", (args: ServerConfigChange) => this.handleConfigUpdate(args));
try {
this.log("Connecting to iMessage database...");
this.iMessageRepo = new MessageRepository();
await this.iMessageRepo.initialize();
} catch (ex: any) {
this.log(ex, "error");
const dialogOpts = {
type: "error",
buttons: ["Restart", "Open System Preferences", "Ignore"],
title: "BlueBubbles Error",
message: "Full-Disk Access Permission Required!",
detail:
`In order to function correctly, BlueBubbles requires full-disk access. ` +
`Please enable Full-Disk Access in System Preferences > Security & Privacy.`
};
dialog.showMessageBox(this.window, dialogOpts).then(returnValue => {
if (returnValue.response === 0) {
this.relaunch();
} else if (returnValue.response === 1) {
FileSystem.executeAppleScript(openSystemPreferences());
app.quit();
}
});
}
}
Example #22
Source File: Log.ts From electron with MIT License | 6 votes |
constructor(logDir: string) {
if (!logDir || !fs.existsSync(logDir)) {
dialog.showErrorBox('系统异常', '日志目录不存在。请检查!');
throw new Error('日志目录不存在。请检查!');
}
this.logDir = logDir;
/**
* from https://github.com/doowb/ansi-colors/blob/master/index.js
*/
// eslint-disable-next-line no-control-regex
this.ANSI_REGEX = /[\u001b\u009b][[\]#;?()]*(?:(?:(?:[^\W_]*;?[^\W_]*)\u0007)|(?:(?:[0-9]{1,4}(;[0-9]{0,4})*)?[~0-9=<>cf-nqrtyA-PRZ]))/g;
this.clear();
}
Example #23
Source File: index.ts From bluebubbles-server with Apache License 2.0 | 6 votes |
async checkForUpdate({ showNoUpdateDialog = false, showUpdateDialog = true } = {}): Promise<boolean> {
const res = await autoUpdater.checkForUpdates();
this.hasUpdate = !!res?.updateInfo && semver.lt(this.currentVersion, res.updateInfo.version);
this.updateInfo = res;
if (this.hasUpdate) {
Server().emitMessage("server-update", res.updateInfo.version);
Server().emitToUI("update-available", res.updateInfo.version);
if (showUpdateDialog) {
const notification = {
title: "BlueBubbles Update Available!",
body: `BlueBubbles macOS Server v${res.updateInfo.version} is now available to be installed!`
};
new Notification(notification).show();
}
}
if (!this.hasUpdate && showNoUpdateDialog) {
const dialogOpts = {
type: "info",
title: "BlueBubbles Update",
message: "You have the latest version installed!",
detail: `You are running the latest version of BlueBubbles! v${this.currentVersion}`
};
dialog.showMessageBox(this.window, dialogOpts);
}
return this.hasUpdate;
}
Example #24
Source File: main.ts From Creators.TF-Community-Launcher with MIT License | 6 votes |
app.on("ready", () => {
try {
ModListLoader.LoadLocalModList();
Main.createWindow();
Main.getClientCurrentVersion();
Main.autoUpdateCheckAndSettings();
Main.logDeviceInfo();
log.info("Launcher was opened/finished initialization.");
}
catch(error) {
log.error(error.toString());
dialog.showMessageBox({
type: "error",
title: "App Ready Error - Major Initial Error",
message: error.toString() + majorErrorMessageEnd,
buttons: ["OK"]
}).then(() => {
app.quit();
});
}
});
Example #25
Source File: index.ts From TidGi-Desktop with Mozilla Public License 2.0 | 6 votes |
public async clearBrowsingDataWithConfirm(): Promise<void> {
const availableWindowToShowDialog = this.windowService.get(WindowNames.preferences) ?? this.windowService.get(WindowNames.main);
if (availableWindowToShowDialog !== undefined) {
await dialog
.showMessageBox(availableWindowToShowDialog, {
type: 'question',
buttons: [i18n.t('Preference.ResetNow'), i18n.t('Cancel')],
message: i18n.t('Preference.ClearBrowsingDataMessage'),
cancelId: 1,
})
.then(({ response }) => {
if (response === 0) {
return this.clearBrowsingData();
}
})
.catch(console.error);
}
}
Example #26
Source File: mod_manager.ts From Creators.TF-Community-Launcher with MIT License | 6 votes |
async function ErrorDialog(error: any, title: string) {
log.error(`Error Dialog shown: ${title} : ${error.toString()}.\nError Stack:${error.stack}`);
await dialog.showMessageBox(Main.mainWindow, {
type: "error",
title: title,
message: error.toString(),
buttons: ["OK"]
});
}
Example #27
Source File: index.ts From TidGi-Desktop with Mozilla Public License 2.0 | 6 votes |
public async resetWithConfirm(): Promise<void> {
const preferenceWindow = this.windowService.get(WindowNames.preferences);
if (preferenceWindow !== undefined) {
await dialog
.showMessageBox(preferenceWindow, {
type: 'question',
buttons: [i18n.t('Preference.ResetNow'), i18n.t('Cancel')],
message: i18n.t('Preference.Reset'),
cancelId: 1,
})
.then(async ({ response }) => {
if (response === 0) {
await this.reset();
await this.windowService.requestRestart();
}
})
.catch(console.error);
}
}
Example #28
Source File: cz88-context.ts From kliveide with MIT License | 6 votes |
/**
* Display a confirm message for reset
*/
private async confirmReset(type: string): Promise<boolean> {
const result = await dialog.showMessageBox(emuWindow.window, {
title: `Confirm Cambridge Z88 ${type} Reset`,
message: "Are you sure you want to reset the machine?",
buttons: ["Yes", "No"],
defaultId: 0,
type: "question",
});
return result.response === 0;
}
Example #29
Source File: index.ts From TidGi-Desktop with Mozilla Public License 2.0 | 6 votes |
private popGitErrorNotificationToUser(step: GitStep, message: string): void {
if (step === GitStep.GitPushFailed && message.includes('403')) {
const mainWindow = this.windowService.get(WindowNames.main);
if (mainWindow !== undefined) {
void dialog.showMessageBox(mainWindow, {
title: i18n.t('Log.GitTokenMissing'),
message: `${i18n.t('Log.GitTokenExpireOrWrong')} (${message})`,
buttons: ['OK'],
cancelId: 0,
defaultId: 0,
});
}
}
}