365 lines
8.4 KiB
JavaScript
365 lines
8.4 KiB
JavaScript
const { app, BrowserWindow, Menu, Tray, nativeImage } = require('electron');
|
|
const path = require('path');
|
|
const net = require('net');
|
|
const { spawn } = require('child_process');
|
|
const { pathToFileURL } = require('url');
|
|
|
|
let mainWindow = null;
|
|
let tray = null;
|
|
let isQuitting = false;
|
|
let serverStarted = false;
|
|
let backendProcess = null;
|
|
let reconcileTimer = null;
|
|
let reconcilePromise = null;
|
|
|
|
const MAIN_FILE = path.join(__dirname, '..', 'views', 'index.html');
|
|
const BACKEND_RUNNER_ARG = '--backend-runner';
|
|
const SERVICE_RUNNER_ARG = '--service-runner';
|
|
const RECONCILE_INTERVAL_MS = 5000;
|
|
const APP_TITLE = '打印电脑服务';
|
|
const ICON_ICO_PATH = path.join(__dirname, 'assets', 'printserver.ico');
|
|
const ICON_PNG_PATH = path.join(__dirname, 'assets', 'printserver-icon-256.png');
|
|
const TRAY_ICON_FALLBACK_DATA_URL = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAQAAAC1+jfqAAAAV0lEQVR4AWP4TwAw/P//PwMDA8P///8ZGRkYGBgY/v//z8DAwMDA8J8B4v///5kYGRkZGBj+////PwMDw38Ghv9kZGQYGBj+////PwPDfwYGhv8MDAwA0rQYV5vWJ2EAAAAASUVORK5CYII=';
|
|
const BACKGROUND_SERVICE_OPTIONS = { allowElevation: false };
|
|
|
|
function createTrayImage() {
|
|
const icon = nativeImage.createFromPath(ICON_PNG_PATH);
|
|
if (!icon.isEmpty()) {
|
|
return icon.resize({ width: 16, height: 16 });
|
|
}
|
|
|
|
return nativeImage.createFromDataURL(TRAY_ICON_FALLBACK_DATA_URL).resize({ width: 16, height: 16 });
|
|
}
|
|
|
|
async function startLocalServer() {
|
|
if (serverStarted) {
|
|
return;
|
|
}
|
|
|
|
serverStarted = true;
|
|
const entryFile = path.join(__dirname, '..', 'index.js');
|
|
await import(pathToFileURL(entryFile).href);
|
|
}
|
|
|
|
function hasArg(flag) {
|
|
return process.argv.includes(flag);
|
|
}
|
|
|
|
function isHeadlessRunner() {
|
|
return hasArg(BACKEND_RUNNER_ARG) || hasArg(SERVICE_RUNNER_ARG);
|
|
}
|
|
|
|
async function loadWorkspaceModule(relativePath) {
|
|
const filePath = path.join(__dirname, '..', relativePath);
|
|
return import(pathToFileURL(filePath).href);
|
|
}
|
|
|
|
function delay(ms) {
|
|
return new Promise((resolve) => {
|
|
setTimeout(resolve, ms);
|
|
});
|
|
}
|
|
|
|
function isPortReachable(port) {
|
|
return new Promise((resolve) => {
|
|
const socket = net.createConnection({ host: '127.0.0.1', port });
|
|
let settled = false;
|
|
|
|
const finish = (result) => {
|
|
if (settled) {
|
|
return;
|
|
}
|
|
|
|
settled = true;
|
|
socket.destroy();
|
|
resolve(result);
|
|
};
|
|
|
|
socket.setTimeout(1000);
|
|
socket.once('connect', () => finish(true));
|
|
socket.once('timeout', () => finish(false));
|
|
socket.once('error', () => finish(false));
|
|
});
|
|
}
|
|
|
|
async function isBackendReady() {
|
|
const [httpReady, wsReady] = await Promise.all([
|
|
isPortReachable(3000),
|
|
isPortReachable(3001)
|
|
]);
|
|
|
|
return httpReady && wsReady;
|
|
}
|
|
|
|
async function readRuntimeConfig() {
|
|
const configUtil = (await loadWorkspaceModule('utils/config.js')).default;
|
|
return configUtil.read();
|
|
}
|
|
|
|
async function getWindowsServiceHelper() {
|
|
return loadWorkspaceModule('utils/windowsService.js');
|
|
}
|
|
|
|
function getManagedBackendArgs() {
|
|
if (app.isPackaged) {
|
|
return [BACKEND_RUNNER_ARG];
|
|
}
|
|
|
|
return [app.getAppPath(), BACKEND_RUNNER_ARG];
|
|
}
|
|
|
|
function startManagedBackend() {
|
|
if (backendProcess || !app.isPackaged) {
|
|
return;
|
|
}
|
|
|
|
backendProcess = spawn(process.execPath, getManagedBackendArgs(), {
|
|
stdio: 'ignore',
|
|
windowsHide: true
|
|
});
|
|
|
|
backendProcess.once('exit', () => {
|
|
backendProcess = null;
|
|
});
|
|
}
|
|
|
|
async function stopManagedBackend() {
|
|
if (!backendProcess) {
|
|
return;
|
|
}
|
|
|
|
const child = backendProcess;
|
|
backendProcess = null;
|
|
child.kill();
|
|
await delay(800);
|
|
}
|
|
|
|
async function ensureDesiredBackendState() {
|
|
if (!app.isPackaged) {
|
|
await startLocalServer();
|
|
return;
|
|
}
|
|
|
|
const config = await readRuntimeConfig();
|
|
let backendReady = await isBackendReady();
|
|
const serviceHelper = await getWindowsServiceHelper();
|
|
|
|
if (config.isService) {
|
|
try {
|
|
const status = await serviceHelper.ensureServiceInstalled(BACKGROUND_SERVICE_OPTIONS);
|
|
|
|
// 仅在系统服务已接管时才停止本地后端,避免服务未运行时出现周期性停启抖动。
|
|
if (status.running) {
|
|
if (backendProcess) {
|
|
await stopManagedBackend();
|
|
backendReady = await isBackendReady();
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (!backendReady) {
|
|
await serviceHelper.startService(BACKGROUND_SERVICE_OPTIONS);
|
|
const startedStatus = await serviceHelper.getServiceStatus(BACKGROUND_SERVICE_OPTIONS);
|
|
if (startedStatus.running && backendProcess) {
|
|
await stopManagedBackend();
|
|
backendReady = await isBackendReady();
|
|
}
|
|
}
|
|
|
|
// 服务未运行但本地后端可用时,保持本地后端运行,避免 UI 持续断开重连。
|
|
return;
|
|
} catch (error) {
|
|
console.error('[Runtime] 系统服务启动失败,回退到本地后端:', error);
|
|
}
|
|
} else {
|
|
try {
|
|
const status = await serviceHelper.getServiceStatus(BACKGROUND_SERVICE_OPTIONS);
|
|
if (status.installed) {
|
|
await serviceHelper.uninstallService(BACKGROUND_SERVICE_OPTIONS);
|
|
backendReady = await isBackendReady();
|
|
}
|
|
} catch (error) {
|
|
console.error('[Runtime] 清理系统服务失败:', error);
|
|
}
|
|
}
|
|
|
|
if (!backendReady && !backendProcess) {
|
|
startManagedBackend();
|
|
}
|
|
}
|
|
|
|
async function reconcileBackendState() {
|
|
if (reconcilePromise) {
|
|
return reconcilePromise;
|
|
}
|
|
|
|
reconcilePromise = ensureDesiredBackendState().finally(() => {
|
|
reconcilePromise = null;
|
|
});
|
|
|
|
return reconcilePromise;
|
|
}
|
|
|
|
function startReconcileLoop() {
|
|
if (reconcileTimer || !app.isPackaged) {
|
|
return;
|
|
}
|
|
|
|
reconcileTimer = setInterval(() => {
|
|
reconcileBackendState().catch((error) => {
|
|
console.error('[Runtime] 状态同步失败:', error);
|
|
});
|
|
}, RECONCILE_INTERVAL_MS);
|
|
}
|
|
|
|
function stopReconcileLoop() {
|
|
if (!reconcileTimer) {
|
|
return;
|
|
}
|
|
|
|
clearInterval(reconcileTimer);
|
|
reconcileTimer = null;
|
|
}
|
|
|
|
function showMainWindow() {
|
|
if (!mainWindow) {
|
|
return;
|
|
}
|
|
|
|
if (mainWindow.isMinimized()) {
|
|
mainWindow.restore();
|
|
}
|
|
|
|
mainWindow.show();
|
|
mainWindow.focus();
|
|
}
|
|
|
|
function loadMainPage() {
|
|
if (!mainWindow || mainWindow.isDestroyed()) {
|
|
return;
|
|
}
|
|
|
|
readRuntimeConfig()
|
|
.then((config) => {
|
|
const wsPort = Number(config?.wsPort) || 3001;
|
|
return mainWindow.loadFile(MAIN_FILE, {
|
|
query: {
|
|
wsPort: String(wsPort)
|
|
}
|
|
});
|
|
})
|
|
.catch(() => {
|
|
setTimeout(loadMainPage, 1000);
|
|
});
|
|
}
|
|
|
|
function createMainWindow() {
|
|
mainWindow = new BrowserWindow({
|
|
width: 1024,
|
|
height: 720,
|
|
minWidth: 960,
|
|
minHeight: 500,
|
|
show: false,
|
|
autoHideMenuBar: true,
|
|
title: APP_TITLE,
|
|
icon: ICON_ICO_PATH,
|
|
webPreferences: {
|
|
contextIsolation: true,
|
|
nodeIntegration: false
|
|
}
|
|
});
|
|
|
|
mainWindow.once('ready-to-show', () => {
|
|
mainWindow.show();
|
|
});
|
|
|
|
mainWindow.on('close', (event) => {
|
|
if (isQuitting) {
|
|
return;
|
|
}
|
|
|
|
event.preventDefault();
|
|
mainWindow.hide();
|
|
});
|
|
|
|
mainWindow.on('minimize', (event) => {
|
|
event.preventDefault();
|
|
mainWindow.hide();
|
|
});
|
|
|
|
loadMainPage();
|
|
}
|
|
|
|
function createTray() {
|
|
tray = new Tray(createTrayImage());
|
|
tray.setToolTip(APP_TITLE);
|
|
|
|
const contextMenu = Menu.buildFromTemplate([
|
|
{
|
|
label: '打开主界面',
|
|
click: () => showMainWindow()
|
|
},
|
|
{
|
|
label: '退出',
|
|
click: () => {
|
|
isQuitting = true;
|
|
app.quit();
|
|
}
|
|
}
|
|
]);
|
|
|
|
tray.setContextMenu(contextMenu);
|
|
tray.on('double-click', () => showMainWindow());
|
|
tray.on('click', () => showMainWindow());
|
|
}
|
|
|
|
async function bootstrap() {
|
|
if (isHeadlessRunner()) {
|
|
await startLocalServer();
|
|
return;
|
|
}
|
|
|
|
await reconcileBackendState();
|
|
startReconcileLoop();
|
|
createMainWindow();
|
|
createTray();
|
|
}
|
|
|
|
const singleInstanceLock = isHeadlessRunner() ? true : app.requestSingleInstanceLock();
|
|
|
|
if (!singleInstanceLock) {
|
|
app.quit();
|
|
} else {
|
|
if (!isHeadlessRunner()) {
|
|
app.on('second-instance', () => {
|
|
showMainWindow();
|
|
});
|
|
}
|
|
|
|
app.whenReady().then(bootstrap);
|
|
|
|
if (!isHeadlessRunner()) {
|
|
app.on('activate', () => {
|
|
if (BrowserWindow.getAllWindows().length === 0) {
|
|
createMainWindow();
|
|
} else {
|
|
showMainWindow();
|
|
}
|
|
});
|
|
}
|
|
|
|
app.on('before-quit', () => {
|
|
isQuitting = true;
|
|
stopReconcileLoop();
|
|
if (backendProcess) {
|
|
backendProcess.kill();
|
|
backendProcess = null;
|
|
}
|
|
});
|
|
|
|
if (!isHeadlessRunner()) {
|
|
app.on('window-all-closed', (event) => {
|
|
event.preventDefault();
|
|
});
|
|
}
|
|
} |