calibration-pc/src/main/index.js

230 lines
6.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { app, shell, BrowserWindow, ipcMain, globalShortcut, dialog } from 'electron';
import { join } from 'path';
import { electronApp, optimizer, is } from '@electron-toolkit/utils';
import icon from '../../resources/icon.png?asset';
// const fs = require('fs');
//关闭exe命令
function killProcessByName(processName) {
const command = `taskkill /IM ${processName} /F`;
const { exec } = require('child_process');
exec(command, (error, stdout, stderr) => {
if (error) {
console.error(`执行的错误: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.error(`stderr: ${stderr}`);
});
}
app.commandLine.appendSwitch('disable-web-security');
function createWindow() {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 1280,
height: 1024,
show: false,
autoHideMenuBar: true,
icon,
webPreferences: {
preload: join(__dirname, '../preload/index.js'),
sandbox: false,
nodeIntegration: true,
// 禁用同源策略,允许跨域请求
webSecurity: false,
contextIsolation: false,
// csp: "default-src 'self'; connect-src 'self' *",
// 禁止build环境使用DevTool
// devTools: is.dev ? true : false
devTools: true
}
});
//开发模式 开启调试
if (is.dev) {
mainWindow.webContents.openDevTools();
}
mainWindow.on('ready-to-show', () => {
mainWindow.show();
});
mainWindow.webContents.setWindowOpenHandler(details => {
shell.openExternal(details.url);
return { action: 'deny' };
});
// HMR for renderer base on electron-vite cli.
// Load the remote URL for development or the local html file for production.
if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL']);
} else {
mainWindow.loadFile(join(__dirname, '../renderer/index.html'));
}
// 设置DevTools快捷键
// 设置DevTools快捷键
globalShortcut.register('CommandOrControl+Shift+i', function () {
mainWindow.webContents.openDevTools();
});
return mainWindow;
}
// 程序单例模式
let myWindow = null;
const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
// 如果已经有同样的该程序正在运行,则不启动
app.quit();
} else {
// 如果检测到有同样的该程序正在试图启动...
app.on('second-instance', () => {
if (myWindow) {
// 弹出系统提示对话框
dialog.showMessageBox({
message: '此程序已经正在运行'
});
// 如果该程序窗口处于最小化状态,则恢复窗口
if (myWindow.isMinimized()) myWindow.restore();
// 将该程序窗口置为当前聚焦态
myWindow.focus();
}
});
//当Electron完成时将调用此方法
//初始化并准备创建浏览器窗口。
//某些API只能在此事件发生后使用。
const { spawn } = require('child_process');
let child = null;
let exePluginsExeList = [];
app.whenReady().then(() => {
const fs = require('fs');
const path = require('path');
const logStream = fs.createWriteStream('app.log', { flags: 'a' }); // 日志文件
let exePath = path.resolve('./resources/app.asar.unpacked/resources/service');
let exePluginsPath = path.resolve('./resources/app.asar.unpacked/resources/service/plugins');
//单独配置测试环境
if (process.env.NODE_ENV === 'development') {
exePath = path.resolve('./resources/service');
exePluginsPath = path.resolve('./resources/service/plugins');
}
//查询所有插件目录下的exe文件
fs.readdir(exePluginsPath, (err, files) => {
if (err) {
return console.log('Unable to scan directory: ' + err);
}
// 筛选出以.exe结尾的文件
exePluginsExeList = files.filter(file => path.extname(file).toLowerCase() === '.exe');
});
child = spawn('./main.exe', [], { cwd: exePath, stdio: ['ignore', 'pipe', 'pipe'] });
//监听进程的输出
child.stdout.on('data', data => {
console.log('stdout:', data.toString());
logStream.write(data);
});
child.stderr.on('data', data => {
console.error('stderr:', data.toString());
logStream.write(data);
});
child.on('close', code => {
console.log(`子进程已退出,退出码 ${code}`);
logStream.end();
});
child.on('exit', (code, signal) => {
console.log(`子进程已退出,退出码 ${code},信号: ${signal}`);
logStream.write(`子进程已退出,退出码 ${code},信号: ${signal}`);
logStream.end();
});
// Set app user model id for windows
electronApp.setAppUserModelId('com.electron');
// Default open or close DevTools by F12 in development
// and ignore CommandOrControl + R in production.
// see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
app.on('browser-window-created', (_, window) => {
optimizer.watchWindowShortcuts(window);
});
// IPC test
ipcMain.on('ping', () => console.log('pong'));
myWindow = createWindow();
app.on('activate', function () {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
// 处理来自渲染进程的请求
// ipcMain.handle('readFile', async (event, path) => {
// return new Promise((resolve, reject) => {
// fs.readFile(join(__dirname, path), 'utf8', (err, data) => {
// if (err) {
// reject(err);
// } else {
// resolve(data);
// }
// });
// });
// });
//
// ipcMain.handle('writeFile', async (event, path, content) => {
// return new Promise((resolve, reject) => {
// fs.writeFile(join(__dirname, path), content, 'utf8', (err) => {
// if (err) {
// reject(err);
// } else {
// resolve();
// }
// });
// });
// });
//
// // 处理来自渲染进程的请求
// ipcMain.handle('readDirectory', async (event, directoryPath) => {
// return new Promise((resolve, reject) => {
// fs.readdir(join(__dirname, directoryPath), (err, files) => {
// if (err) {
// reject(err);
// } else {
// resolve(files);
// }
// });
// });
// });
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
// 循环关闭插件 EXE 列表
exePluginsExeList.forEach(exe => {
killProcessByName(exe);
});
// child.kill('SIGTERM'); // 或者使用 'SIGKILL' 来强制关闭
// killProcessByName('gateway.exe');
// 循环关闭后端服务
killProcessByName('main.exe');
app.quit();
}
});
}
// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.
ipcMain.handle('get-app-version', () => {
return app.getVersion();
});