656 lines
20 KiB
JavaScript
656 lines
20 KiB
JavaScript
const { app, BrowserWindow, Menu, Tray, nativeImage, ipcMain } = 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 backendApp = null; // 开发模式:后端 Main 实例
|
||
let backendWS = null; // 打包模式:后端 WS 桥接
|
||
let backendWSCleanup = []; // 事件取消函数列表
|
||
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');
|
||
const indexModule = await import(pathToFileURL(entryFile).href);
|
||
backendApp = indexModule.default; // 获取 Main 单例
|
||
console.log('[Main] 后端已加载,services:', Object.keys(backendApp.services || {}));
|
||
}
|
||
|
||
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() {
|
||
return isPortReachable(3001);
|
||
}
|
||
|
||
// ─── 打包模式:WS 桥接(连接子进程的本地 WS 服务) ───
|
||
let _bridgeConnectPromise = null;
|
||
async function ensureBackendBridge() {
|
||
if (!app.isPackaged || backendApp) return;
|
||
if (backendWS && backendWS.readyState === 1) return;
|
||
if (_bridgeConnectPromise) return _bridgeConnectPromise;
|
||
|
||
_bridgeConnectPromise = (async function () {
|
||
var config = await readRuntimeConfig();
|
||
var wsPort = config.wsPort || 3001;
|
||
var mod = await import('ws');
|
||
var WebSocketImpl = mod.default || mod.WebSocket || require('ws');
|
||
|
||
return new Promise(function (resolve, reject) {
|
||
var ws = new WebSocketImpl('ws://127.0.0.1:' + wsPort);
|
||
var connected = false;
|
||
ws.on('open', function () {
|
||
connected = true;
|
||
backendWS = ws;
|
||
console.log('[Bridge] 已连接后端 WS, port:', wsPort);
|
||
ws.on('message', function (msg) {
|
||
try {
|
||
var data = JSON.parse(msg.toString());
|
||
if (mainWindow && !mainWindow.isDestroyed()) {
|
||
mainWindow.webContents.send('service:event', data);
|
||
}
|
||
} catch (e) { /* ignore */ }
|
||
});
|
||
ws.on('close', function () { backendWS = null; _bridgeConnectPromise = null; });
|
||
ws.on('error', function () { backendWS = null; _bridgeConnectPromise = null; });
|
||
resolve();
|
||
});
|
||
ws.on('error', function (err) { if (!connected) { _bridgeConnectPromise = null; reject(err); } });
|
||
setTimeout(function () { if (!connected) { _bridgeConnectPromise = null; reject(new Error('Bridge timeout')); } }, 5000);
|
||
});
|
||
})();
|
||
|
||
try { await _bridgeConnectPromise; } catch (e) {
|
||
console.error('[Bridge] 连接失败:', e.message);
|
||
_bridgeConnectPromise = null;
|
||
}
|
||
}
|
||
|
||
async function readRuntimeConfig() {
|
||
const configUtil = (await loadWorkspaceModule('utils/config.js')).default;
|
||
return configUtil.read();
|
||
}
|
||
|
||
// ────────── IPC 处理 ──────────
|
||
|
||
/**
|
||
* 调用后端服务方法(开发模式直接调用,打包模式通过内部 WS 桥接)
|
||
*/
|
||
async function handleServiceCall(method, data, allowRetry) {
|
||
// 特殊方法:获取远端 WSClient 当前状态
|
||
if (method === 'wsClient.getStatus') {
|
||
if (backendApp && backendApp.wsClient) {
|
||
return { success: true, method, result: { status: backendApp.wsClient.status, url: backendApp.wsClient.url } };
|
||
}
|
||
// 打包模式:通过桥接获取
|
||
if (backendWS && backendWS.readyState === 1) {
|
||
var _ws = backendWS;
|
||
return new Promise(function (resolve) {
|
||
var mid = method + '_' + Date.now() + '_' + Math.random().toString(36).slice(2);
|
||
var settled = false;
|
||
var handler = function (raw) {
|
||
if (settled) return;
|
||
try {
|
||
var resp = JSON.parse(raw.toString());
|
||
if (resp.method === method || resp._msgId === mid) {
|
||
settled = true;
|
||
if (_ws && _ws.removeListener) _ws.removeListener('message', handler);
|
||
resolve(resp);
|
||
}
|
||
} catch (e) {}
|
||
};
|
||
_ws.on('message', handler);
|
||
_ws.send(JSON.stringify({ method: method, data: data, _msgId: mid }));
|
||
setTimeout(function () {
|
||
if (settled) return;
|
||
settled = true;
|
||
if (_ws && _ws.removeListener) _ws.removeListener('message', handler);
|
||
resolve({ success: false, method: method, message: 'Bridge timeout' });
|
||
}, 10000);
|
||
});
|
||
}
|
||
return { success: false, method, message: 'WSClient not ready' };
|
||
}
|
||
|
||
// 开发模式:进程内直接调用
|
||
if (backendApp && backendApp.services) {
|
||
var methodPath = method.split('.');
|
||
var fn = backendApp.services;
|
||
for (var i = 0; i < methodPath.length; i++) {
|
||
fn = fn[methodPath[i]];
|
||
if (!fn) break;
|
||
}
|
||
if (typeof fn === 'function') {
|
||
try {
|
||
var result = await fn(data);
|
||
return { success: true, method: method, result: result };
|
||
} catch (err) {
|
||
return { success: false, method: method, message: err.message };
|
||
}
|
||
}
|
||
return { success: false, method: method, message: '服务方法未找到: ' + method };
|
||
}
|
||
|
||
// 打包模式:通过 WS 桥接转发到子进程
|
||
if (backendWS && backendWS.readyState === 1) {
|
||
var _ws2 = backendWS;
|
||
return new Promise(function (resolve) {
|
||
var mid = method + '_' + Date.now() + '_' + Math.random().toString(36).slice(2);
|
||
var settled = false;
|
||
var handler = function (raw) {
|
||
if (settled) return;
|
||
try {
|
||
var resp = JSON.parse(raw.toString());
|
||
if (resp.method === method || resp._msgId === mid) {
|
||
settled = true;
|
||
if (_ws2 && _ws2.removeListener) _ws2.removeListener('message', handler);
|
||
resolve(resp);
|
||
}
|
||
} catch (e) {}
|
||
};
|
||
_ws2.on('message', handler);
|
||
_ws2.send(JSON.stringify({ method: method, data: data, _msgId: mid }));
|
||
setTimeout(function () {
|
||
if (settled) return;
|
||
settled = true;
|
||
if (_ws2 && _ws2.removeListener) _ws2.removeListener('message', handler);
|
||
resolve({ success: false, method: method, message: 'Bridge timeout' });
|
||
}, 10000);
|
||
});
|
||
}
|
||
|
||
// 打包模式:桥接未就绪,尝试重新建立连接(仅重试一次,防止无限递归)
|
||
if (allowRetry !== false && app.isPackaged && !backendApp) {
|
||
await ensureBackendBridge();
|
||
if (backendWS && backendWS.readyState === 1) {
|
||
return handleServiceCall(method, data, false);
|
||
}
|
||
}
|
||
|
||
return { success: false, method: method, message: '后端尚未就绪' };
|
||
}
|
||
|
||
ipcMain.handle('service:call', async (_event, method, data) => {
|
||
return handleServiceCall(method, data, true);
|
||
});
|
||
|
||
/** 获取后端连接状态 */
|
||
ipcMain.handle('service:getBackendStatus', () => {
|
||
if (backendApp) return 'connected';
|
||
if (backendWS && backendWS.readyState === 1) return 'connected';
|
||
return 'connecting';
|
||
});
|
||
|
||
/**
|
||
* 注册后端事件 → 渲染进程转发(替代 WSServer.onConnection / _bindAppEvents)
|
||
*/
|
||
function setupEventForwarding() {
|
||
if (!backendApp) return;
|
||
cleanupEventForwarding();
|
||
|
||
const forward = (eventMethod) => (data) => {
|
||
if (mainWindow && !mainWindow.isDestroyed()) {
|
||
mainWindow.webContents.send('service:event', {
|
||
success: true,
|
||
method: eventMethod,
|
||
result: data
|
||
});
|
||
}
|
||
};
|
||
|
||
// 与 WSServer._bindAppEvents 相同的事件集
|
||
backendApp.on('printerComponentStatusChange', forward('printerComponent.statusChange'));
|
||
|
||
// wsClient 状态变化改用防抖转发,避免短暂断开/重连导致 UI 闪烁
|
||
let wsStatusDebounceTimer = null;
|
||
const forwardWsStatus = (data) => {
|
||
if (wsStatusDebounceTimer) {
|
||
clearTimeout(wsStatusDebounceTimer);
|
||
wsStatusDebounceTimer = null;
|
||
}
|
||
// connected 立即转发;disconnected/error 延迟 2 秒确认
|
||
const delayMs = data.status === 'connected' ? 0 : 2000;
|
||
wsStatusDebounceTimer = setTimeout(() => {
|
||
wsStatusDebounceTimer = null;
|
||
if (mainWindow && !mainWindow.isDestroyed()) {
|
||
mainWindow.webContents.send('service:event', {
|
||
success: true,
|
||
method: 'wsClient.statusChange',
|
||
result: data
|
||
});
|
||
}
|
||
}, delayMs);
|
||
};
|
||
backendApp.on('wsClientStatusChange', forwardWsStatus);
|
||
|
||
// 推送当前 WSClient 状态(弥补监听注册前已连接的时序缺口)
|
||
if (backendApp.wsClient?.status) {
|
||
forwardWsStatus({ status: backendApp.wsClient.status, url: backendApp.wsClient.url });
|
||
}
|
||
|
||
backendApp.on('printerList', forward('printer.getWindowsPrinters'));
|
||
|
||
const generateCodeHandler = (code) => {
|
||
console.log('[IPC] generateCode 事件转发, randomCode:', code?.randomCode);
|
||
if (mainWindow && !mainWindow.isDestroyed()) {
|
||
mainWindow.webContents.send('service:event', {
|
||
success: true,
|
||
method: 'bind.generateCode',
|
||
result: code.randomCode
|
||
});
|
||
console.log('[IPC] service:event 已发送 -> bind.generateCode');
|
||
} else {
|
||
console.log('[IPC] mainWindow 不可用, 无法转发');
|
||
}
|
||
// 码过期前 5 秒自动刷新
|
||
if (code.createdAt && code.expiresIn) {
|
||
var refreshAt = code.createdAt + code.expiresIn * 1000 - 5000;
|
||
var delay = Math.max(0, refreshAt - Date.now());
|
||
if (backendApp._codeRefreshTimer) clearTimeout(backendApp._codeRefreshTimer);
|
||
var remaining = Math.round(delay / 1000);
|
||
console.log('[IPC] 绑定码刷新定时器已设置, ' + remaining + ' 秒后触发');
|
||
backendApp._codeRefreshTimer = setTimeout(function () {
|
||
console.log('[IPC] 绑定码刷新定时器触发');
|
||
console.log('[IPC] hasToken:', !!backendApp.config?.token, 'wsClientStatus:', backendApp.wsClient?.status);
|
||
if (!backendApp.config?.token && backendApp.wsClient?.status === 'connected') {
|
||
console.log('[IPC] 请求新绑定码');
|
||
backendApp.wsClient.send({ method: 'bind.generateCode', data: {} });
|
||
} else {
|
||
console.log('[IPC] 跳过刷新: token=' + !!backendApp.config?.token + ' ws=' + backendApp.wsClient?.status);
|
||
}
|
||
}, delay);
|
||
}
|
||
};
|
||
backendApp.on('generateCode', generateCodeHandler);
|
||
|
||
backendApp.on('updateDownloadProgress', forward('update.downloadProgress'));
|
||
|
||
// ─── 主动请求绑定码(替代 WSServer.onConnection),仅首次未绑定时请求一次 ───
|
||
let bindCodeRequested = false;
|
||
const requestBindCode = () => {
|
||
if (bindCodeRequested || backendApp.config?.token) return;
|
||
bindCodeRequested = true;
|
||
|
||
if (backendApp.randomCode &&
|
||
backendApp.randomCode.createdAt + backendApp.randomCode.expiresIn * 1000 > Date.now() &&
|
||
backendApp.randomCode.randomCode) {
|
||
backendApp.emit('generateCode', backendApp.randomCode);
|
||
} else if (backendApp.wsClient?.status === 'connected') {
|
||
backendApp.randomCode = null;
|
||
backendApp.wsClient.send({ method: 'bind.generateCode', data: {} });
|
||
}
|
||
};
|
||
|
||
// 监听 WSClient 连接事件,连接后尝试请求绑定码
|
||
const wsStatusHandler = (data) => {
|
||
if (data.status === 'connected') {
|
||
requestBindCode();
|
||
}
|
||
};
|
||
backendApp.on('wsClientStatusChange', wsStatusHandler);
|
||
|
||
// 如果 WSClient 已连接,立即尝试
|
||
if (backendApp.wsClient?.status === 'connected') {
|
||
requestBindCode();
|
||
}
|
||
|
||
backendWSCleanup = [
|
||
() => backendApp.off('printerComponentStatusChange'),
|
||
() => {
|
||
if (wsStatusDebounceTimer) { clearTimeout(wsStatusDebounceTimer); wsStatusDebounceTimer = null; }
|
||
backendApp.off('wsClientStatusChange', forwardWsStatus);
|
||
},
|
||
() => backendApp.off('printerList'),
|
||
() => backendApp.off('generateCode', generateCodeHandler),
|
||
() => backendApp.off('updateDownloadProgress'),
|
||
() => backendApp.off('wsClientStatusChange', wsStatusHandler)
|
||
];
|
||
|
||
console.log('[Main] 事件转发已注册');
|
||
}
|
||
|
||
function cleanupEventForwarding() {
|
||
for (const cleanup of backendWSCleanup) {
|
||
try { cleanup(); } catch (_) { /* ignore */ }
|
||
}
|
||
backendWSCleanup = [];
|
||
if (backendApp && backendApp._codeRefreshTimer) {
|
||
clearTimeout(backendApp._codeRefreshTimer);
|
||
backendApp._codeRefreshTimer = null;
|
||
}
|
||
console.log('[Main] 事件转发已清理');
|
||
}
|
||
|
||
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);
|
||
});
|
||
// 同时确保 WS 桥接保持连接
|
||
ensureBackendBridge().catch((error) => {
|
||
console.error('[Bridge] 周期重连失败:', error && error.message);
|
||
});
|
||
}, 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;
|
||
}
|
||
|
||
mainWindow.loadFile(MAIN_FILE).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,
|
||
preload: path.join(__dirname, 'preload.cjs')
|
||
}
|
||
});
|
||
|
||
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();
|
||
await ensureBackendBridge(); // 打包模式:建立与后端子进程的 WS 桥接
|
||
setupEventForwarding();
|
||
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();
|
||
});
|
||
}
|
||
} |