@mytec: iter2.2 start

This commit is contained in:
2026-01-31 15:25:18 +02:00
parent b62e893abe
commit 013cb155a9
7 changed files with 4655 additions and 65 deletions

View File

@@ -8,36 +8,84 @@ const store = new Store();
let mainWindow;
let splashWindow;
let backendProcess;
let backendLogStream;
// ── Paths ──────────────────────────────────────────────────────────
// Paths
const isDev = process.env.NODE_ENV === 'development';
const getResourcePath = (relativePath) => {
/**
* Get path to a bundled resource (extraResources).
* In production, extraResources live under process.resourcesPath.
* In dev, they live in the repo root.
*/
const getResourcePath = (...segments) => {
if (isDev) {
return path.join(__dirname, '..', relativePath);
return path.join(__dirname, '..', ...segments);
}
return path.join(process.resourcesPath, relativePath);
return path.join(process.resourcesPath, ...segments);
};
/**
* User data directory — writable, persists across updates.
* Windows: %APPDATA%\RFCP\data\
* Linux: ~/.config/RFCP/data/
* macOS: ~/Library/Application Support/RFCP/data/
*/
const getDataPath = () => {
return path.join(app.getPath('userData'), 'data');
};
// Get backend executable name based on platform
const getBackendExeName = () => {
switch (process.platform) {
case 'win32':
return 'rfcp-server.exe';
case 'darwin':
return 'rfcp-server';
case 'linux':
return 'rfcp-server';
default:
return 'rfcp-server';
}
/**
* Log directory for backend output and crash logs.
* Windows: %APPDATA%\RFCP\logs\
* Linux: ~/.config/RFCP/logs/
* macOS: ~/Library/Logs/RFCP/
*/
const getLogPath = () => {
return app.getPath('logs');
};
// Ensure data directories exist
/** Backend executable path */
const getBackendExePath = () => {
const exeName = process.platform === 'win32' ? 'rfcp-server.exe' : 'rfcp-server';
if (isDev) {
return path.join(__dirname, '..', 'backend', exeName);
}
return getResourcePath('backend', exeName);
};
/** Frontend index.html path (production only) */
const getFrontendPath = () => {
return getResourcePath('frontend', 'index.html');
};
// ── Logging ────────────────────────────────────────────────────────
function log(msg) {
const line = `[${new Date().toISOString()}] ${msg}`;
console.log(line);
if (backendLogStream) {
backendLogStream.write(line + '\n');
}
}
function initLogFile() {
const logDir = getLogPath();
if (!fs.existsSync(logDir)) {
fs.mkdirSync(logDir, { recursive: true });
}
const logFile = path.join(logDir, 'rfcp-main.log');
backendLogStream = fs.createWriteStream(logFile, { flags: 'w' });
log(`Log file: ${logFile}`);
log(`Platform: ${process.platform}, Electron: ${process.versions.electron}`);
log(`isDev: ${isDev}`);
log(`userData: ${app.getPath('userData')}`);
log(`resourcesPath: ${isDev ? '(dev mode)' : process.resourcesPath}`);
}
// ── Data directories ───────────────────────────────────────────────
function ensureDataDirs() {
const dirs = ['terrain', 'osm', 'projects', 'cache'];
const dataPath = getDataPath();
@@ -49,10 +97,12 @@ function ensureDataDirs() {
}
});
log(`Data path: ${dataPath}`);
return dataPath;
}
// Create splash window
// ── Splash window ──────────────────────────────────────────────────
function createSplashWindow() {
splashWindow = new BrowserWindow({
width: 400,
@@ -71,21 +121,29 @@ function createSplashWindow() {
splashWindow.center();
}
// Start Python backend
// ── Backend lifecycle ──────────────────────────────────────────────
async function startBackend() {
const dataPath = ensureDataDirs();
const logDir = getLogPath();
// SQLite URL — normalize to forward slashes for cross-platform compatibility
const dbPath = path.join(dataPath, 'rfcp.db').replace(/\\/g, '/');
const env = {
...process.env,
RFCP_DATA_PATH: dataPath,
RFCP_DATABASE_URL: `sqlite:///${path.join(dataPath, 'rfcp.db')}`,
RFCP_DATABASE_URL: `sqlite:///${dbPath}`,
RFCP_HOST: '127.0.0.1',
RFCP_PORT: '8888',
RFCP_LOG_PATH: logDir,
};
if (isDev) {
// Development: run uvicorn
const pythonCmd = process.platform === 'win32' ? 'python' : 'python3';
const backendCwd = path.join(__dirname, '..', 'backend');
log(`Starting dev backend: ${pythonCmd} -m uvicorn ... (cwd: ${backendCwd})`);
backendProcess = spawn(pythonCmd, [
'-m', 'uvicorn',
'app.main:app',
@@ -93,46 +151,63 @@ async function startBackend() {
'--port', '8888',
'--reload'
], {
cwd: path.join(__dirname, '..', 'backend'),
cwd: backendCwd,
env,
stdio: ['ignore', 'pipe', 'pipe']
});
} else {
// Production: run PyInstaller bundle
const backendExe = path.join(
getResourcePath('backend'),
getBackendExeName()
);
const backendExe = getBackendExePath();
const backendDir = path.dirname(backendExe);
log(`Starting production backend: ${backendExe}`);
log(`Backend cwd: ${backendDir}`);
// Verify the exe exists
if (!fs.existsSync(backendExe)) {
log(`FATAL: Backend exe not found at ${backendExe}`);
return false;
}
// Make executable on Unix
if (process.platform !== 'win32') {
try {
fs.chmodSync(backendExe, '755');
} catch (e) {
console.log('chmod failed:', e);
log(`chmod warning: ${e.message}`);
}
}
backendProcess = spawn(backendExe, [], {
cwd: backendDir,
env,
stdio: ['ignore', 'pipe', 'pipe']
});
}
// Log backend output
// Pipe backend output to log
const backendLogFile = path.join(logDir, 'rfcp-backend.log');
const backendLog = fs.createWriteStream(backendLogFile, { flags: 'w' });
backendProcess.stdout?.on('data', (data) => {
console.log(`[Backend] ${data}`);
const text = data.toString().trim();
log(`[Backend] ${text}`);
backendLog.write(text + '\n');
});
backendProcess.stderr?.on('data', (data) => {
console.error(`[Backend Error] ${data}`);
const text = data.toString().trim();
log(`[Backend:err] ${text}`);
backendLog.write(`[err] ${text}\n`);
});
backendProcess.on('error', (err) => {
console.error('Failed to start backend:', err);
log(`Failed to start backend: ${err.message}`);
dialog.showErrorBox('Backend Error', `Failed to start backend: ${err.message}`);
});
backendProcess.on('exit', (code, signal) => {
log(`Backend exited: code=${code}, signal=${signal}`);
});
// Wait for backend to be ready
return new Promise((resolve) => {
const maxAttempts = 60; // 30 seconds
@@ -145,7 +220,7 @@ async function startBackend() {
const response = await fetch('http://127.0.0.1:8888/api/health/');
if (response.ok) {
clearInterval(checkBackend);
console.log('Backend ready!');
log(`Backend ready after ${attempts * 0.5}s`);
resolve(true);
}
} catch (_e) {
@@ -154,14 +229,15 @@ async function startBackend() {
if (attempts >= maxAttempts) {
clearInterval(checkBackend);
console.error('Backend failed to start in time');
log('Backend failed to start within 30s');
resolve(false);
}
}, 500);
});
}
// Create main window
// ── Main window ────────────────────────────────────────────────────
function createMainWindow() {
const windowState = store.get('windowState', {
width: 1400,
@@ -181,9 +257,6 @@ function createMainWindow() {
contextIsolation: true,
preload: path.join(__dirname, 'preload.js')
},
icon: path.join(__dirname, 'assets',
process.platform === 'win32' ? 'icon.ico' : 'icon.png'
),
title: 'RFCP - RF Coverage Planner',
titleBarStyle: process.platform === 'darwin' ? 'hiddenInset' : 'default',
});
@@ -196,10 +269,21 @@ function createMainWindow() {
// Load frontend
if (isDev) {
log('Loading frontend from dev server: http://localhost:5173');
mainWindow.loadURL('http://localhost:5173');
mainWindow.webContents.openDevTools();
} else {
mainWindow.loadFile(path.join(getResourcePath('frontend'), 'index.html'));
const frontendIndex = getFrontendPath();
log(`Loading frontend from: ${frontendIndex}`);
if (!fs.existsSync(frontendIndex)) {
log(`FATAL: Frontend not found at ${frontendIndex}`);
dialog.showErrorBox('Startup Error', `Frontend not found at:\n${frontendIndex}`);
app.quit();
return;
}
mainWindow.loadFile(frontendIndex);
}
mainWindow.once('ready-to-show', () => {
@@ -221,23 +305,26 @@ function createMainWindow() {
});
}
// App lifecycle
// ── App lifecycle ──────────────────────────────────────────────────
app.whenReady().then(async () => {
initLogFile();
createSplashWindow();
const backendStarted = await startBackend();
if (!backendStarted) {
const logDir = getLogPath();
const result = await dialog.showMessageBox({
type: 'error',
title: 'Startup Error',
message: 'Failed to start backend server.',
detail: 'Please check logs and try again. Click "Show Logs" to open the log folder.',
detail: `Check logs at:\n${logDir}\n\nClick "Show Logs" to open the folder.`,
buttons: ['Quit', 'Show Logs']
});
if (result.response === 1) {
shell.openPath(app.getPath('logs'));
shell.openPath(logDir);
}
app.quit();
@@ -268,10 +355,15 @@ app.on('before-quit', () => {
if (backendProcess) {
backendProcess.kill();
}
if (backendLogStream) {
backendLogStream.end();
}
});
// IPC Handlers
// ── IPC Handlers ───────────────────────────────────────────────────
ipcMain.handle('get-data-path', () => getDataPath());
ipcMain.handle('get-log-path', () => getLogPath());
ipcMain.handle('get-app-version', () => app.getVersion());
ipcMain.handle('get-platform', () => process.platform);

4419
desktop/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -3,6 +3,7 @@ const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('rfcp', {
// System info
getDataPath: () => ipcRenderer.invoke('get-data-path'),
getLogPath: () => ipcRenderer.invoke('get-log-path'),
getAppVersion: () => ipcRenderer.invoke('get-app-version'),
getPlatform: () => ipcRenderer.invoke('get-platform'),
getGpuInfo: () => ipcRenderer.invoke('get-gpu-info'),