Skip to content

Free Motion Capture for Everyone 💀✨

TypeScript

update electron

jonmatthisf73af989835a
diff --git a/freemocap-ui/electron-old/main/api.ts b/freemocap-ui/electron-old/main/api.ts
new file mode 100644
index 00000000..d7d85f7f
--- /dev/null
+++ b/freemocap-ui/electron-old/main/api.ts
@@ -0,0 +1,353 @@
+import { initTRPC } from '@trpc/server';
+import { z } from 'zod';
+import superjson from 'superjson';
+
+// Services
+import { PythonServer } from './services/python-server';
+import { SystemScanner } from './services/system-scanner';
+import { DependencyManager } from './services/dependency-manager';
+import { AppSettings } from './services/app-settings';
+import { dialog, shell, app } from 'electron';
+import path from 'node:path';
+import fs from 'node:fs';
+import { APP_PATHS } from './app-paths';
+
+// Initialize tRPC
+const t = initTRPC.create({
+ transformer: superjson,
+});
+
+// Helper function to check if a directory contains video files
+function hasVideoFiles(dirPath: string): boolean {
+ if (!fs.existsSync(dirPath)) {
+ return false;
+ }
+
+ try {
+ const entries = fs.readdirSync(dirPath);
+ const videoExtensions = ['.mp4', '.avi', '.mov', '.mkv', '.wmv', '.flv', '.webm'];
+
+ return entries.some(entry => {
+ const fullPath = path.join(dirPath, entry);
+ const stats = fs.statSync(fullPath);
+
+ if (stats.isFile()) {
+ const ext = path.extname(entry).toLowerCase();
+ return videoExtensions.includes(ext);
+ }
+ return false;
+ });
+ } catch (error) {
+ console.error('Error checking for video files:', error);
+ return false;
+ }
+}
+
+// Helper function to find camera calibration TOML file
+function findCameraCalibrationToml(dirPath: string): string | null {
+ if (!fs.existsSync(dirPath)) {
+ return null;
+ }
+
+ try {
+ const entries = fs.readdirSync(dirPath);
+
+ const calibrationFile = entries.find(entry => {
+ const fullPath = path.join(dirPath, entry);
+ const stats = fs.statSync(fullPath);
+
+ return stats.isFile() &&
+ entry.endsWith('_camera_calibration.toml');
+ });
+
+ return calibrationFile ? path.join(dirPath, calibrationFile) : null;
+ } catch (error) {
+ console.error('Error finding calibration TOML:', error);
+ return null;
+ }
+}
+
+// Create the main API router
+export const api = t.router({
+ // Python Server Management
+ pythonServer: t.router({
+ start: t.procedure
+ .input(z.object({ exePath: z.string().nullable() }))
+ .mutation(({ input }) => PythonServer.start(input.exePath)),
+
+ stop: t.procedure
+ .mutation(() => PythonServer.shutdown()),
+
+ getExecutablePath: t.procedure
+ .query(() => PythonServer.getCurrentExecutablePath()),
+
+ getExecutableCandidates: t.procedure
+ .query(() => PythonServer.validateAllCandidates()),
+
+ refreshCandidates: t.procedure
+ .mutation(() => PythonServer.refreshCandidates()),
+
+ isRunning: t.procedure
+ .query(() => PythonServer.isRunning()),
+
+ getProcessInfo: t.procedure
+ .query(() => PythonServer.getProcessInfo()),
+
+ getPort: t.procedure
+ .query(() => PythonServer.getPort()),
+ }),
+
+ // System Scanner
+ system: t.router({
+ scan: t.procedure
+ .query(() => SystemScanner.scan()),
+ }),
+
+ // Dependency Management
+ dependencies: t.router({
+ detectAll: t.procedure
+ .query(() => DependencyManager.detectAll()),
+
+ detect: t.procedure
+ .input(z.object({ dependencyId: z.string() }))
+ .query(({ input }) => DependencyManager.detect(input.dependencyId)),
+
+ install: t.procedure
+ .input(z.object({ dependencyId: z.string() }))
+ .mutation(({ input }) => DependencyManager.install(input.dependencyId)),
+ }),
+
+ // Persistent Settings (file-backed at ~/.freemocap/settings.json)
+ settings: t.router({
+ get: t.procedure
+ .input(z.object({ key: z.string() }))
+ .query(({ input }) => AppSettings.get(input.key)),
+
+ set: t.procedure
+ .input(z.object({ key: z.string(), value: z.unknown() }))
+ .mutation(({ input }) => {
+ AppSettings.set(input.key, input.value);
+ }),
+
+ delete: t.procedure
+ .input(z.object({ key: z.string() }))
+ .mutation(({ input }) => {
+ AppSettings.delete(input.key);
+ }),
+
+ getAll: t.procedure
+ .query(() => AppSettings.getAll()),
+
+ getConfigDir: t.procedure
+ .query(() => AppSettings.getConfigDir()),
+ }),
+
+ // File System Operations
+ fileSystem: t.router({
+ selectDirectory: t.procedure
+ .mutation(async () => {
+ const result = await dialog.showOpenDialog({
+ properties: ['openDirectory'],
+ });
+ return result.canceled ? null : result.filePaths[0];
+ }),
+
+ openFolder: t.procedure
+ .input(z.object({ path: z.string() }))
+ .mutation(async ({ input }) => {
+ await shell.openPath(input.path);
+ return true;
+ }),
+
+ getHomeDirectory: t.procedure
+ .query(() => app.getPath('home')),
+
+ getFolderContents: t.procedure
+ .input(z.object({ path: z.string() }))
+ .query(({ input }) => {
+ if (!fs.existsSync(input.path)) {
+ throw new Error('Folder does not exist');
+ }
+
+ const entries = fs.readdirSync(input.path);
+ return entries.map(entry => {
+ const fullPath = path.join(input.path, entry);
+ const stats = fs.statSync(fullPath);
+ return {
+ name: entry,
+ path: fullPath,
+ isDirectory: stats.isDirectory(),
+ isFile: stats.isFile(),
+ size: stats.size,
+ modified: stats.mtime,
+ };
+ });
+ }),
+
+ selectExecutableFile: t.procedure
+ .mutation(async () => {
+ const result = await dialog.showOpenDialog({
+ properties: ['openFile'],
+ filters: [
+ { name: 'Executable Files', extensions: ['exe'] },
+ { name: 'All Files', extensions: ['*'] },
+ ],
+ });
+ return result.canceled ? null : result.filePaths[0];
+ }),
+
+ validateCalibrationDirectory: t.procedure
+ .input(z.object({ directoryPath: z.string() }))
+ .query(({ input }) => {
+ const result = {
+ exists: false,
+ canRecord: false,
+ canCalibrate: false,
+ cameraCalibrationTomlPath: null as string | null,
+ hasSynchronizedVideos: false,
+ hasVideos: false,
+ errorMessage: null as string | null,
+ };
+
+ try {
+ result.exists = fs.existsSync(input.directoryPath);
+
+ if (!result.exists) {
+ result.canRecord = true;
+ result.canCalibrate = false;
+ return result;
+ }
+
+ const stats = fs.statSync(input.directoryPath);
+
+ if (!stats.isDirectory()) {
+ result.errorMessage = 'Path exists but is not a directory';
+ return result;
+ }
+
+ const synchronizedVideosPath = path.join(input.directoryPath, 'synchronized_videos');
+ result.hasSynchronizedVideos = fs.existsSync(synchronizedVideosPath) &&
+ fs.statSync(synchronizedVideosPath).isDirectory();
+
+ if (result.hasSynchronizedVideos) {
+ result.hasVideos = hasVideoFiles(synchronizedVideosPath);
+ }
+
+ if (!result.hasVideos) {
+ result.hasVideos = hasVideoFiles(input.directoryPath);
+ }
+
+ const entries = fs.readdirSync(input.directoryPath);
+ result.canRecord = entries.length === 0 || !result.hasVideos;
+
+ result.canCalibrate = result.hasVideos;
+
+ result.cameraCalibrationTomlPath = findCameraCalibrationToml(input.directoryPath);
+
+ return result;
+
+ } catch (error) {
+ console.error('Error validating calibration directory:', error);
+ result.errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
+ return result;
+ }
+ }),
+
+ validateMocapDirectory: t.procedure
+ .input(z.object({ directoryPath: z.string() }))
+ .query(({ input }) => {
+ const result = {
+ exists: false,
+ canRecord: false,
+ canProcess: false,
+ cameraCalibrationTomlPath: null as string | null,
+ hasSynchronizedVideos: false,
+ hasVideos: false,
+ errorMessage: null as string | null,
+ };
+
+ try {
+ result.exists = fs.existsSync(input.directoryPath);
+
+ if (!result.exists) {
+ result.canRecord = true;
+ result.canProcess = false;
+ return result;
+ }
+
+ const stats = fs.statSync(input.directoryPath);
+
+ if (!stats.isDirectory()) {
+ result.errorMessage = 'Path exists but is not a directory';
+ return result;
+ }
+
+ const synchronizedVideosPath = path.join(input.directoryPath, 'synchronized_videos');
+ result.hasSynchronizedVideos = fs.existsSync(synchronizedVideosPath) &&
+ fs.statSync(synchronizedVideosPath).isDirectory();
+
+ if (result.hasSynchronizedVideos) {
+ result.hasVideos = hasVideoFiles(synchronizedVideosPath);
+ }
+
+ if (!result.hasVideos) {
+ result.hasVideos = hasVideoFiles(input.directoryPath);
+ }
+
+ const entries = fs.readdirSync(input.directoryPath);
+ result.canRecord = !result.hasVideos;
+ result.cameraCalibrationTomlPath = findCameraCalibrationToml(input.directoryPath);
+
+ result.canProcess = result.hasVideos && result.cameraCalibrationTomlPath !== null;
+
+ return result;
+
+ } catch (error) {
+ console.error('Error validating calibration directory:', error);
+ result.errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
+ return result;
+ }
+ }),
+ }),
+
+ // Asset Management
+ assets: t.router({
+ getLogoBase64: t.procedure
+ .query((): string | null => {
+ try {
+ let logoPath: string | null = null;
+
+ if (fs.existsSync(APP_PATHS.FREEMOCAP_LOGO_PNG_SHARED_PATH)) {
+ logoPath = APP_PATHS.FREEMOCAP_LOGO_PNG_SHARED_PATH;
+ } else if (fs.existsSync(APP_PATHS.FREEMOCAP_LOGO_PNG_RESOURCES_PATH)) {
+ logoPath = APP_PATHS.FREEMOCAP_LOGO_PNG_RESOURCES_PATH;
+ }
+
+ if (!logoPath) {
+ console.error('Logo file not found in any expected location');
+ return null;
+ }
+
+ const imageBuffer = fs.readFileSync(logoPath);
+ const base64String = imageBuffer.toString('base64');
+ const mimeType = 'image/png';
+
+ return `data:${mimeType};base64,${base64String}`;
+ } catch (error) {
+ console.error('Failed to load logo as base64:', error);
+ return null;
+ }
+ }),
+
+ getLogoPngPath: t.procedure
+ .query(() => {
+ if (fs.existsSync(APP_PATHS.FREEMOCAP_LOGO_PNG_SHARED_PATH)) {
+ return APP_PATHS.FREEMOCAP_LOGO_PNG_SHARED_PATH;
+ }
+ return APP_PATHS.FREEMOCAP_LOGO_PNG_RESOURCES_PATH;
+ }),
+ }),
+});
+
+// Export the type for use in renderer
+export type AppAPI = typeof api;
\ No newline at end of file
diff --git a/freemocap-ui/electron-old/main/app-paths.ts b/freemocap-ui/electron-old/main/app-paths.ts
new file mode 100644
index 00000000..c1224e95
--- /dev/null
+++ b/freemocap-ui/electron-old/main/app-paths.ts
@@ -0,0 +1,63 @@
+import path from "node:path";
+import {fileURLToPath} from "node:url";
+import {app} from "electron";
+
+export const __dirname = path.dirname(fileURLToPath(import.meta.url));
+
+
+// Function to get the correct resources path based on environment
+const getResourcesPath = () => {
+ if (app.isPackaged) {
+ const resourcesPath = path.join(process.resourcesPath, "app.asar.unpacked")
+ console.log(`App is packaged. resourcesPath: ${resourcesPath}`);
+ return resourcesPath;
+ } else {
+ const resourcesPath = path.join(__dirname, "../../");
+ console.log(`App is in development. resourcesPath: ${resourcesPath}`);
+ return resourcesPath;
+ }
+
+};
+
+// Python server executable candidates in order of preference
+export const PYTHON_EXECUTABLE_CANDIDATES = [
+ {
+ name: 'development',
+ path: path.join(getResourcesPath(), '../dist/freemocap_server.exe'),
+ description: 'Development build executable'
+ },
+ {
+ name: 'installed',
+ path: path.join(getResourcesPath(), 'freemocap_server.exe'),
+ description: 'Executable in the installation folder'
+ },
+
+ {
+ name: 'portable',
+ path: path.join(process.cwd(), 'freemocap_server.exe'),
+ description: 'Portable executable in current directory'
+ },
+ {
+ name: 'system-path',
+ path: 'freemocap_server.exe', // Will be found via PATH
+ description: 'Executable available in system PATH'
+ }
+];
+
+export const APP_PATHS = {
+ PRELOAD: path.join(__dirname, "../preload/index.mjs"),
+ RENDERER_HTML: path.join(__dirname, "../../dist/index.html"),
+ FREEMOCAP_ICON_PATH: path.resolve(
+ __dirname,
+ "../../../shared/logo/freemocap-logo.ico"
+ ),
+ FREEMOCAP_LOGO_PNG_RESOURCES_PATH: path.join(getResourcesPath(), 'dist/freemocap-logo.png'),
+ FREEMOCAP_LOGO_PNG_SHARED_PATH:path.resolve(
+ __dirname,
+ "../../../shared/logo/freemocap-logo.png"
+ ),
+
+};
+
+
+console.log(`APP_PATHS: ${JSON.stringify(APP_PATHS, null, 2)}`);
diff --git a/freemocap-ui/electron-old/main/index.ts b/freemocap-ui/electron-old/main/index.ts
new file mode 100644
index 00000000..e6224780
--- /dev/null
+++ b/freemocap-ui/electron-old/main/index.ts
@@ -0,0 +1,59 @@
+import { app, BrowserWindow } from 'electron';
+import { setupIPC } from './ipc';
+import { WindowManager } from './services/window-manager';
+import { PythonServer } from './services/python-server';
+import { buildAppMenu } from './services/app-menu';
+import { LifecycleLogger } from './services/logger';
+
+export const APP_ENVIRONMENT = {
+ IS_DEV: process.env.NODE_ENV === 'development',
+ VITE_DEV_SERVER_URL: process.env.VITE_DEV_SERVER_URL,
+};
+
+if (process.platform === 'win32') app.setAppUserModelId(app.getName());
+
+const gotTheLock = app.requestSingleInstanceLock();
+
+if (!gotTheLock) {
+ app.quit();
+} else {
+ app.on('second-instance', () => {
+ const windows = BrowserWindow.getAllWindows();
+ if (windows.length > 0) {
+ const window = windows[0];
+ if (window.isMinimized()) window.restore();
+ window.focus();
+ }
+ });
+
+ app.whenReady().then(async () => {
+ LifecycleLogger.logProcessInfo();
+ console.log('App is ready');
+
+ setupIPC();
+
+ const mainWindow = WindowManager.createMainWindow();
+
+ // Set up the native application menu (File, Edit, View, Tools, etc.)
+ buildAppMenu(mainWindow);
+ });
+
+ app.on('window-all-closed', async () => {
+ console.log('All windows closed, shutting down...');
+ await PythonServer.shutdown();
+ app.quit();
+ });
+
+ app.on('activate', () => {
+ if (BrowserWindow.getAllWindows().length === 0) {
+ WindowManager.createMainWindow();
+ }
+ });
+
+ app.on('before-quit', async (event) => {
+ event.preventDefault();
+ console.log('App is quitting, cleaning up...');
+ await PythonServer.shutdown();
+ app.exit(0);
+ });
+}
diff --git a/freemocap-ui/electron-old/main/ipc.ts b/freemocap-ui/electron-old/main/ipc.ts
new file mode 100644
index 00000000..cf09c44f
--- /dev/null
+++ b/freemocap-ui/electron-old/main/ipc.ts
@@ -0,0 +1,35 @@
+// electron/main/ipc.ts
+import { ipcMain } from 'electron';
+import { api } from './api';
+import superjson from 'superjson';
+
+export function setupIPC(): void {
+ ipcMain.handle('trpc', async (_event, { path, input }) => {
+ try {
+ const caller = api.createCaller({});
+
+ const pathParts = path.split('.');
+ let current: any = caller;
+
+ for (let i = 0; i < pathParts.length - 1; i++) {
+ current = current[pathParts[i]];
+ if (!current) {
+ throw new Error(`Router not found: ${pathParts.slice(0, i + 1).join('.')}`);
+ }
+ }
+
+ const procedureName = pathParts[pathParts.length - 1];
+ const fn = current[procedureName];
+
+ if (typeof fn !== 'function') {
+ throw new Error(`Procedure not found: ${path}`);
+ }
+
+ const result = await fn(input);
+ return superjson.serialize(result);
+ } catch (error) {
+ console.error(`IPC Error for ${path}:`, error);
+ throw error;
+ }
+ });
+}
diff --git a/freemocap-ui/electron/main/services/app-menu.ts b/freemocap-ui/electron-old/main/services/app-menu.ts
similarity index 100%
rename from freemocap-ui/electron/main/services/app-menu.ts
rename to freemocap-ui/electron-old/main/services/app-menu.ts
diff --git a/freemocap-ui/electron/main/services/app-settings.ts b/freemocap-ui/electron-old/main/services/app-settings.ts
similarity index 100%
rename from freemocap-ui/electron/main/services/app-settings.ts
rename to freemocap-ui/electron-old/main/services/app-settings.ts
diff --git a/freemocap-ui/electron/main/services/dependency-manager.ts b/freemocap-ui/electron-old/main/services/dependency-manager.ts
similarity index 100%
rename from freemocap-ui/electron/main/services/dependency-manager.ts
rename to freemocap-ui/electron-old/main/services/dependency-manager.ts
diff --git a/freemocap-ui/electron-old/main/services/logger.ts b/freemocap-ui/electron-old/main/services/logger.ts
new file mode 100644
index 00000000..deb6a09f
--- /dev/null
+++ b/freemocap-ui/electron-old/main/services/logger.ts
@@ -0,0 +1,23 @@
+import { app, BrowserWindow } from 'electron';
+import { exec } from 'child_process';
+
+export class LifecycleLogger {
+ static logProcessInfo() {
+ console.log(`
+ ============================================
+ Starting FreeMoCap v${app.getVersion()}
+ Platform: ${process.platform}-${process.arch}
+ Node: ${process.versions.node}
+ Chrome: ${process.versions.chrome}
+ Electron: ${process.versions.electron}
+ ============================================`);
+ }
+
+ static logWindowCreation(win: BrowserWindow) {
+ console.log(`[Window Manager] Created window ID: ${win.id}`);
+ }
+
+ static logPythonProcess(pythonProcess: ReturnType<typeof exec>) {
+ console.log(`[Python Server] Started process PID: ${pythonProcess.pid}`);
+ }
+}
diff --git a/freemocap-ui/electron-old/main/services/python-server.ts b/freemocap-ui/electron-old/main/services/python-server.ts
new file mode 100644
index 00000000..941730c9
--- /dev/null
+++ b/freemocap-ui/electron-old/main/services/python-server.ts
@@ -0,0 +1,294 @@
+import {exec} from 'child_process';
+import fs from 'node:fs';
+import path from 'node:path';
+import {LifecycleLogger} from "./logger";
+import {promisify} from 'util';
+import treeKill from "tree-kill";
+import {PYTHON_EXECUTABLE_CANDIDATES} from "../app-paths";
+
+const treeKillAsync = promisify(treeKill);
+let pythonProcess: ReturnType<typeof exec> | null = null;
+
+const PORT_SENTINEL = "FREEMOCAP_PORT";
+const DEFAULT_PORT = 53117;
+const PORT_DISCOVERY_TIMEOUT_MS = 30_000;
+
+export interface ExecutableCandidate {
+ name: string;
+ path: string;
+ description: string;
+ isValid?: boolean;
+ error?: string;
+ resolvedPath?: string;
+}
+
+export class PythonServer {
+ private static currentExecutablePath: string | null = null;
+ private static validatedCandidates: ExecutableCandidate[] = [];
+ private static discoveredPort: number | null = null;
+
+ /**
+ * Start the Python server and wait for it to report which port it bound to.
+ * Returns the actual port number.
+ */
+ static async start(exePath: string | null = null): Promise<number> {
+ console.log('Starting python server subprocess...');
+
+ try {
+ await this.shutdown();
+
+ let executablePath: string;
+
+ if (exePath) {
+ this.validateExecutable(exePath);
+ executablePath = exePath;
+ console.log(`Using provided executable path: ${executablePath}`);
+ } else {
+ executablePath = await this.findValidExecutablePath();
+ console.log(`Using auto-detected executable path: ${executablePath}`);
+ }
+
+ this.currentExecutablePath = executablePath;
+ this.discoveredPort = null;
+ console.log(`Launching Python server from: ${executablePath}`);
+ pythonProcess = exec(`"${executablePath}"`, {
+ env: {
+ ...process.env,
+ },
+ maxBuffer: 1024 * 1024 * 100 // 100MB buffer
+ });
+
+ pythonProcess.on('exit', (code) => {
+ console.log(`Python server exited (code: ${code})`);
+ this.currentExecutablePath = null;
+ });
+
+ pythonProcess.on('error', (error) => {
+ console.error('Python server process error:', error);
+ this.currentExecutablePath = null;
+ });
+
+ if (!pythonProcess.pid) {
+ throw new Error('Python server failed to start - no process ID');
+ }
+
+ LifecycleLogger.logPythonProcess(pythonProcess);
+ console.log(`✔ Python server started successfully (PID: ${pythonProcess.pid})`);
+
+ const port = await this.waitForPort(pythonProcess);
+ this.discoveredPort = port;
+ console.log(`✔ Python server bound to port ${port}`);
+
+ return port;
+
+ } catch (error) {
+ console.error('Failed to start Python server:', error);
+ this.currentExecutablePath = null;
+ throw error;
+ }
+ }
+
+ /**
+ * Read stdout line-by-line until we find the port sentinel or time out.
+ */
+ private static waitForPort(proc: ReturnType<typeof exec>): Promise<number> {
+ return new Promise((resolve, reject) => {
+ const timeout = setTimeout(() => {
+ reject(new Error(
+ `Python server did not report a port within ${PORT_DISCOVERY_TIMEOUT_MS}ms`
+ ));
+ }, PORT_DISCOVERY_TIMEOUT_MS);
+
+ const onData = (chunk: Buffer | string): void => {
+ const text = chunk.toString();
+ for (const line of text.split('\n')) {
+ const trimmed = line.trim();
+ if (trimmed.startsWith(`${PORT_SENTINEL}=`)) {
+ const portStr = trimmed.slice(PORT_SENTINEL.length + 1);
+ const port = parseInt(portStr, 10);
+ if (isNaN(port)) {
+ clearTimeout(timeout);
+ reject(new Error(`Invalid port in sentinel line: ${trimmed}`));
+ return;
+ }
+ clearTimeout(timeout);
+ proc.stdout?.off('data', onData);
+ resolve(port);
+ return;
+ }
+ }
+ };
+
+ if (!proc.stdout) {
+ clearTimeout(timeout);
+ reject(new Error('Python process has no stdout stream'));
+ return;
+ }
+
+ proc.stdout.on('data', onData);
+
+ proc.on('exit', (code) => {
+ clearTimeout(timeout);
+ reject(new Error(
+ `Python server exited with code ${code} before reporting a port`
+ ));
+ });
+ });
+ }
+
+ static async shutdown() {
+ if (!pythonProcess || !pythonProcess.pid) {
+ console.log('No Python server process to shutdown');
+ return;
+ }
+
+ console.log(`Shutting down Python server (PID: ${pythonProcess.pid})`);
+
+ try {
+ await treeKillAsync(pythonProcess.pid);
+ console.log('✔ Python server process tree terminated');
+ } catch (error) {
+ console.error('Error killing process tree:', error);
+ try {
+ pythonProcess?.kill('SIGKILL');
+ console.log('✔ Python server force-killed as fallback');
+ } catch (killError) {
+ console.error('Failed to force-kill Python server:', killError);
+ }
+ }
+
+ await new Promise(resolve => setTimeout(resolve, 1000));
+
+ if (pythonProcess && !pythonProcess.killed) {
+ console.warn('Python server may not have exited cleanly');
+ }
+
+ pythonProcess = null;
+ this.currentExecutablePath = null;
+ this.discoveredPort = null;
+ console.log('✔ Python server shutdown complete');
+ }
+
+ /**
+ * Get the port the Python server is currently bound to, or the default if not yet started.
+ */
+ static getPort(): number {
+ return this.discoveredPort ?? DEFAULT_PORT;
+ }
+
+ static getCurrentExecutablePath(): string | null {
+ return this.currentExecutablePath;
+ }
+
+ static async findValidExecutablePath(): Promise<string> {
+ console.log('Searching for valid Python server executable...');
+
+ if (this.validatedCandidates.length === 0) {
+ await this.validateAllCandidates();
+ }
+
+ const validCandidate = this.validatedCandidates.find(candidate => candidate.isValid);
+
+ if (!validCandidate) {
+ const errorMessage = 'No valid Python server executable found in any candidate location:\n' +
+ this.validatedCandidates.map(c => ` - ${c.name}: ${c.error || 'Unknown error'}`).join('\n');
+ throw new Error(errorMessage);
+ }
+
+ console.log(`✔ Selected executable: ${validCandidate.name} (${validCandidate.path})`);
+ return validCandidate.path;
+ }
+
+ static async validateAllCandidates(): Promise<ExecutableCandidate[]> {
+ console.log('Validating all executable candidates...');
+
+ const allValidatedCandidates = await Promise.all(
+ PYTHON_EXECUTABLE_CANDIDATES.map(async (candidate) => {
+ const validatedCandidate: ExecutableCandidate = {
+ ...candidate,
+ isValid: false
+ };
+
+ try {
+ this.validateExecutable(candidate.path);
+ validatedCandidate.isValid = true;
+ validatedCandidate.resolvedPath = fs.existsSync(candidate.path)
+ ? path.resolve(candidate.path)
+ : candidate.path;
+ console.log(` ✔ ${candidate.name}: Valid`);
+ } catch (error) {
+ validatedCandidate.error = error instanceof Error ? error.message : 'Unknown validation error';
+ console.log(` ✗ ${candidate.name}: ${validatedCandidate.error}`);
+ }
+
+ return validatedCandidate;
+ })
+ );
+
+ const seenPaths = new Set<string>();
+ this.validatedCandidates = allValidatedCandidates.filter(candidate => {
+ const pathKey = candidate.resolvedPath || candidate.path;
+
+ if (seenPaths.has(pathKey)) {
+ console.log(` âš  Skipping duplicate: ${candidate.name} (same as another candidate)`);
+ return false;
+ }
+
+ seenPaths.add(pathKey);
+ return true;
+ });
+
+ const validCount = this.validatedCandidates.filter(c => c.isValid).length;
+ console.log(`Validation complete: ${validCount}/${this.validatedCandidates.length} unique candidates are valid`);
+
+ return this.validatedCandidates;
+ }
+
+ static getPythonServerExecutableCandidates(): ExecutableCandidate[] {
+ return [...this.validatedCandidates];
+ }
+
+ static async refreshCandidates(): Promise<ExecutableCandidate[]> {
+ console.log('Refreshing executable candidates validation...');
+ this.validatedCandidates = [];
+ return await this.validateAllCandidates();
+ }
+
+ static isRunning(): boolean {
+ return pythonProcess !== null && pythonProcess.pid !== undefined && !pythonProcess.killed;
+ }
+
+ static getProcessInfo(): { pid: number | undefined; killed: boolean } | null {
+ if (!pythonProcess) return null;
+
+ return {
+ pid: pythonProcess.pid,
+ killed: pythonProcess.killed || false
+ };
+ }
+
+ private static validateExecutable(exePath: string): void {
+ if (!fs.existsSync(exePath)) {
+ throw new Error(`Executable not found at: ${exePath}`);
+ }
+
+ const stats = fs.statSync(exePath);
+ if (!stats.isFile()) {
+ throw new Error(`Path is not a file: ${exePath}`);
+ }
+
+ try {
+ fs.accessSync(exePath, fs.constants.F_OK | fs.constants.R_OK);
+
+ if (process.platform !== 'win32') {
+ fs.accessSync(exePath, fs.constants.X_OK);
+ }
+ } catch (error) {
+ throw new Error(`File is not accessible or executable: ${exePath}`);
+ }
+
+ if (process.platform === 'win32' && !exePath.toLowerCase().endsWith('.exe')) {
+ console.warn(`Warning: Executable doesn't have .exe extension: ${exePath}`);
+ }
+ }
+}
\ No newline at end of file
diff --git a/freemocap-ui/electron/main/services/system-scanner.ts b/freemocap-ui/electron-old/main/services/system-scanner.ts
similarity index 100%
rename from freemocap-ui/electron/main/services/system-scanner.ts
rename to freemocap-ui/electron-old/main/services/system-scanner.ts
diff --git a/freemocap-ui/electron-old/main/services/update-handler.ts b/freemocap-ui/electron-old/main/services/update-handler.ts
new file mode 100644
index 00000000..35bb6182
--- /dev/null
+++ b/freemocap-ui/electron-old/main/services/update-handler.ts
@@ -0,0 +1,72 @@
+
+import { app, ipcMain, BrowserWindow } from 'electron';
+import { autoUpdater } from 'electron-updater';
+
+export class UpdateHandler {
+ private mainWindow: BrowserWindow;
+
+ constructor(window: BrowserWindow) {
+ this.mainWindow = window;
+ this.setupAutoUpdater();
+ this.registerIpcHandlers();
+ }
+
+ private setupAutoUpdater() {
+ autoUpdater.autoDownload = false;
+ autoUpdater.disableWebInstaller = false;
+ autoUpdater.allowDowngrade = false;
+
+ autoUpdater.on('checking-for-update', () => {
+ console.log('Checking for updates...');
+ });
+
+ autoUpdater.on('update-available', (info) => {
+ console.log('Update available:', info);
+ this.mainWindow.webContents.send('update-available', {
+ version: info.version,
+ currentVersion: app.getVersion(),
+ });
+ });
+
+ autoUpdater.on('update-not-available', () => {
+ console.log('No updates available');
+ });
+
+ autoUpdater.on('download-progress', (progress) => {
+ this.mainWindow.webContents.send('download-progress', progress);
+ });
+
+ autoUpdater.on('update-downloaded', () => {
+ this.mainWindow.webContents.send('update-downloaded');
+ });
+
+ autoUpdater.on('error', (error) => {
+ console.error('Update error:', error);
+ this.mainWindow.webContents.send('update-error', error);
+ });
+ }
+
+ private registerIpcHandlers() {
+ ipcMain.handle('check-update', async () => {
+ if (!app.isPackaged) {
+ return {
+ error: 'Updates only work in packaged app',
+ available: false
+ };
+ }
+ return await autoUpdater.checkForUpdatesAndNotify();
+ });
+
+ ipcMain.handle('download-update', async () => {
+ return await autoUpdater.downloadUpdate();
+ });
+
+ ipcMain.handle('install-update', () => {
+ autoUpdater.quitAndInstall(false, true);
+ });
+ }
+
+ static initialize(window: BrowserWindow) {
+ return new UpdateHandler(window);
+ }
+}
diff --git a/freemocap-ui/electron-old/main/services/window-manager.ts b/freemocap-ui/electron-old/main/services/window-manager.ts
new file mode 100644
index 00000000..1e2f219a
--- /dev/null
+++ b/freemocap-ui/electron-old/main/services/window-manager.ts
@@ -0,0 +1,103 @@
+import { BrowserWindow, shell } from 'electron';
+import { LifecycleLogger } from './logger';
+import { APP_ENVIRONMENT } from '../index';
+import { APP_PATHS } from '../app-paths';
+
+export class WindowManager {
+ private static mainWindow: BrowserWindow | null = null;
+
+ static createMainWindow(): BrowserWindow {
+ if (this.mainWindow && !this.mainWindow.isDestroyed()) {
+ return this.mainWindow;
+ }
+
+ const window = new BrowserWindow({
+ title: 'FreeMoCap 💀📸',
+ icon: APP_PATHS.FREEMOCAP_ICON_PATH,
+ width: 1280,
+ height: 720,
+ minWidth: 800,
+ minHeight: 600,
+ webPreferences: {
+ preload: APP_PATHS.PRELOAD,
+ contextIsolation: true,
+ nodeIntegration: false,
+ sandbox: true,
+ },
+ show: false,
+ });
+
+ this.mainWindow = window;
+ this.configureWindowHandlers(window);
+ this.loadContent(window);
+
+ window.once('ready-to-show', () => {
+ window.show();
+ LifecycleLogger.logWindowCreation(window);
+ });
+
+ return window;
+ }
+
+ private static configureWindowHandlers(window: BrowserWindow): void {
+ console.log('Configuring window handlers');
+
+ window.on('closed', () => {
+ console.log('Window closed');
+ this.mainWindow = null;
+ });
+
+ window.webContents.on('did-finish-load', () => {
+ console.log('Window finished loading');
+ window.webContents.send('app-ready', Date.now());
+ });
+
+ window.webContents.setWindowOpenHandler(({ url }) => {
+ if (url.startsWith('http:') || url.startsWith('https:')) {
+ shell.openExternal(url).catch(err =>
+ console.error('Failed to open external link:', err),
+ );
+ }
+ return { action: 'deny' };
+ });
+
+ window.webContents.on('will-navigate', (event, url) => {
+ if (APP_ENVIRONMENT.IS_DEV && url.startsWith(APP_ENVIRONMENT.VITE_DEV_SERVER_URL!)) {
+ return;
+ }
+
+ if (!APP_ENVIRONMENT.IS_DEV && url.startsWith('file://')) {
+ return;
+ }
+
+ if (url.startsWith('http:') || url.startsWith('https:')) {
+ event.preventDefault();
+ shell.openExternal(url).catch(err =>
+ console.error('Failed to open external link via navigation:', err),
+ );
+ }
+ });
+
+ window.webContents.on('render-process-gone', (event, details) => {
+ console.error('Renderer process gone:', details);
+ if (details.reason === 'crashed') {
+ window.reload();
+ }
+ });
+ }
+
+ private static loadContent(window: BrowserWindow): void {
+ console.log('Loading app content - IS_DEV:', APP_ENVIRONMENT.IS_DEV);
+
+ if (APP_ENVIRONMENT.IS_DEV && APP_ENVIRONMENT.VITE_DEV_SERVER_URL) {
+ window.loadURL(APP_ENVIRONMENT.VITE_DEV_SERVER_URL);
+ // window.webContents.openDevTools();
+ } else {
+ window.loadFile(APP_PATHS.RENDERER_HTML);
+ }
+ }
+
+ static getMainWindow(): BrowserWindow | null {
+ return this.mainWindow;
+ }
+}
diff --git a/freemocap-ui/electron-old/preload/index.ts b/freemocap-ui/electron-old/preload/index.ts
new file mode 100644
index 00000000..2096156c
--- /dev/null
+++ b/freemocap-ui/electron-old/preload/index.ts
@@ -0,0 +1,17 @@
+import { contextBridge, ipcRenderer } from 'electron';
+
+contextBridge.exposeInMainWorld('electronAPI', {
+ // tRPC bridge
+ invoke: (path: string, input?: any) =>
+ ipcRenderer.invoke('trpc', { path, input }),
+
+ // Menu-triggered navigation: main process sends 'navigate' with a route string
+ onNavigate: (callback: (route: string) => void) => {
+ const handler = (_event: Electron.IpcRendererEvent, route: string) => callback(route);
+ ipcRenderer.on('navigate', handler);
+ // Return cleanup function
+ return () => {
+ ipcRenderer.removeListener('navigate', handler);
+ };
+ },
+});
diff --git a/freemocap-ui/electron/main/api.ts b/freemocap-ui/electron/main/api.ts
index d7d85f7f..dfcd9030 100644
--- a/freemocap-ui/electron/main/api.ts
+++ b/freemocap-ui/electron/main/api.ts
@@ -1,70 +1,54 @@
+
import { initTRPC } from '@trpc/server';
import { z } from 'zod';
import superjson from 'superjson';
// Services
import { PythonServer } from './services/python-server';
-import { SystemScanner } from './services/system-scanner';
-import { DependencyManager } from './services/dependency-manager';
-import { AppSettings } from './services/app-settings';
import { dialog, shell, app } from 'electron';
+import pkg from 'electron-updater';
+const { autoUpdater } = pkg;
import path from 'node:path';
import fs from 'node:fs';
+import os from 'node:os';
import { APP_PATHS } from './app-paths';
+// Configure auto-updater (user triggers download manually)
+autoUpdater.autoDownload = false;
+autoUpdater.allowDowngrade = false;
+
// Initialize tRPC
const t = initTRPC.create({
- transformer: superjson,
+ transformer: superjson, // Handles Date/undefined/etc serialization
});
-// Helper function to check if a directory contains video files
-function hasVideoFiles(dirPath: string): boolean {
- if (!fs.existsSync(dirPath)) {
- return false;
- }
+// Telemetry config lives in ~/freemocap_data/telemetry_config.json
+const TELEMETRY_CONFIG_PATH = path.join(os.homedir(), 'freemocap_data', 'telemetry_config.json');
- try {
- const entries = fs.readdirSync(dirPath);
- const videoExtensions = ['.mp4', '.avi', '.mov', '.mkv', '.wmv', '.flv', '.webm'];
-
- return entries.some(entry => {
- const fullPath = path.join(dirPath, entry);
- const stats = fs.statSync(fullPath);
-
- if (stats.isFile()) {
- const ext = path.extname(entry).toLowerCase();
- return videoExtensions.includes(ext);
- }
- return false;
- });
- } catch (error) {
- console.error('Error checking for video files:', error);
- return false;
- }
+interface TelemetryConfig {
+ telemetry_enabled: boolean;
}
-// Helper function to find camera calibration TOML file
-function findCameraCalibrationToml(dirPath: string): string | null {
- if (!fs.existsSync(dirPath)) {
- return null;
- }
-
+function readTelemetryConfig(): TelemetryConfig {
try {
- const entries = fs.readdirSync(dirPath);
-
- const calibrationFile = entries.find(entry => {
- const fullPath = path.join(dirPath, entry);
- const stats = fs.statSync(fullPath);
-
- return stats.isFile() &&
- entry.endsWith('_camera_calibration.toml');
- });
+ if (fs.existsSync(TELEMETRY_CONFIG_PATH)) {
+ const raw = fs.readFileSync(TELEMETRY_CONFIG_PATH, 'utf-8');
+ const parsed = JSON.parse(raw);
+ return { telemetry_enabled: Boolean(parsed.telemetry_enabled) };
+ }
+ } catch (err) {
+ console.error('Failed to read telemetry config:', err);
+ }
+ // Default: enabled
+ return { telemetry_enabled: true };
+}
- return calibrationFile ? path.join(dirPath, calibrationFile) : null;
- } catch (error) {
- console.error('Error finding calibration TOML:', error);
- return null;
+function writeTelemetryConfig(config: TelemetryConfig): void {
+ const dir = path.dirname(TELEMETRY_CONFIG_PATH);
+ if (!fs.existsSync(dir)) {
+ fs.mkdirSync(dir, { recursive: true });
}
+ fs.writeFileSync(TELEMETRY_CONFIG_PATH, JSON.stringify(config, null, 2) + '\n');
}
// Create the main API router
@@ -92,54 +76,6 @@ export const api = t.router({
getProcessInfo: t.procedure
.query(() => PythonServer.getProcessInfo()),
-
- getPort: t.procedure
- .query(() => PythonServer.getPort()),
- }),
-
- // System Scanner
- system: t.router({
- scan: t.procedure
- .query(() => SystemScanner.scan()),
- }),
-
- // Dependency Management
- dependencies: t.router({
- detectAll: t.procedure
- .query(() => DependencyManager.detectAll()),
-
- detect: t.procedure
- .input(z.object({ dependencyId: z.string() }))
- .query(({ input }) => DependencyManager.detect(input.dependencyId)),
-
- install: t.procedure
- .input(z.object({ dependencyId: z.string() }))
- .mutation(({ input }) => DependencyManager.install(input.dependencyId)),
- }),
-
- // Persistent Settings (file-backed at ~/.freemocap/settings.json)
- settings: t.router({
- get: t.procedure
- .input(z.object({ key: z.string() }))
- .query(({ input }) => AppSettings.get(input.key)),
-
- set: t.procedure
- .input(z.object({ key: z.string(), value: z.unknown() }))
- .mutation(({ input }) => {
- AppSettings.set(input.key, input.value);
- }),
-
- delete: t.procedure
- .input(z.object({ key: z.string() }))
- .mutation(({ input }) => {
- AppSettings.delete(input.key);
- }),
-
- getAll: t.procedure
- .query(() => AppSettings.getAll()),
-
- getConfigDir: t.procedure
- .query(() => AppSettings.getConfigDir()),
}),
// File System Operations
@@ -195,118 +131,60 @@ export const api = t.router({
});
return result.canceled ? null : result.filePaths[0];
}),
+ }),
- validateCalibrationDirectory: t.procedure
- .input(z.object({ directoryPath: z.string() }))
- .query(({ input }) => {
- const result = {
- exists: false,
- canRecord: false,
- canCalibrate: false,
- cameraCalibrationTomlPath: null as string | null,
- hasSynchronizedVideos: false,
- hasVideos: false,
- errorMessage: null as string | null,
- };
-
- try {
- result.exists = fs.existsSync(input.directoryPath);
-
- if (!result.exists) {
- result.canRecord = true;
- result.canCalibrate = false;
- return result;
- }
-
- const stats = fs.statSync(input.directoryPath);
-
- if (!stats.isDirectory()) {
- result.errorMessage = 'Path exists but is not a directory';
- return result;
- }
+ // Telemetry Settings
+ telemetry: t.router({
+ getEnabled: t.procedure
+ .query((): boolean => {
+ return readTelemetryConfig().telemetry_enabled;
+ }),
- const synchronizedVideosPath = path.join(input.directoryPath, 'synchronized_videos');
- result.hasSynchronizedVideos = fs.existsSync(synchronizedVideosPath) &&
- fs.statSync(synchronizedVideosPath).isDirectory();
+ setEnabled: t.procedure
+ .input(z.object({ enabled: z.boolean() }))
+ .mutation(({ input }): boolean => {
+ writeTelemetryConfig({ telemetry_enabled: input.enabled });
+ return input.enabled;
+ }),
+ }),
- if (result.hasSynchronizedVideos) {
- result.hasVideos = hasVideoFiles(synchronizedVideosPath);
- }
+ // App Info & Updates
+ app: t.router({
+ getVersion: t.procedure
+ .query((): string => {
+ return app.getVersion();
+ }),
- if (!result.hasVideos) {
- result.hasVideos = hasVideoFiles(input.directoryPath);
+ checkForUpdate: t.procedure
+ .mutation(async () => {
+ if (!app.isPackaged) {
+ return { available: false, reason: 'dev-mode' };
+ }
+ try {
+ const result = await autoUpdater.checkForUpdates();
+ if (result && result.updateInfo) {
+ return {
+ available: result.updateInfo.version !== app.getVersion(),
+ version: result.updateInfo.version,
+ currentVersion: app.getVersion(),
+ };
}
-
- const entries = fs.readdirSync(input.directoryPath);
- result.canRecord = entries.length === 0 || !result.hasVideos;
-
- result.canCalibrate = result.hasVideos;
-
- result.cameraCalibrationTomlPath = findCameraCalibrationToml(input.directoryPath);
-
- return result;
-
+ return { available: false };
} catch (error) {
- console.error('Error validating calibration directory:', error);
- result.errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
- return result;
+ console.error('[AutoUpdater] Check failed:', error);
+ return { available: false, error: String(error) };
}
}),
- validateMocapDirectory: t.procedure
- .input(z.object({ directoryPath: z.string() }))
- .query(({ input }) => {
- const result = {
- exists: false,
- canRecord: false,
- canProcess: false,
- cameraCalibrationTomlPath: null as string | null,
- hasSynchronizedVideos: false,
- hasVideos: false,
- errorMessage: null as string | null,
- };
-
- try {
- result.exists = fs.existsSync(input.directoryPath);
-
- if (!result.exists) {
- result.canRecord = true;
- result.canProcess = false;
- return result;
- }
-
- const stats = fs.statSync(input.directoryPath);
-
- if (!stats.isDirectory()) {
- result.errorMessage = 'Path exists but is not a directory';
- return result;
- }
-
- const synchronizedVideosPath = path.join(input.directoryPath, 'synchronized_videos');
- result.hasSynchronizedVideos = fs.existsSync(synchronizedVideosPath) &&
- fs.statSync(synchronizedVideosPath).isDirectory();
-
- if (result.hasSynchronizedVideos) {
- result.hasVideos = hasVideoFiles(synchronizedVideosPath);
- }
-
- if (!result.hasVideos) {
- result.hasVideos = hasVideoFiles(input.directoryPath);
- }
-
- const entries = fs.readdirSync(input.directoryPath);
- result.canRecord = !result.hasVideos;
- result.cameraCalibrationTomlPath = findCameraCalibrationToml(input.directoryPath);
-
- result.canProcess = result.hasVideos && result.cameraCalibrationTomlPath !== null;
-
- return result;
+ downloadUpdate: t.procedure
+ .mutation(async () => {
+ await autoUpdater.downloadUpdate();
+ return true;
+ }),
- } catch (error) {
- console.error('Error validating calibration directory:', error);
- result.errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
- return result;
- }
+ installUpdate: t.procedure
+ .mutation(() => {
+ autoUpdater.quitAndInstall(false, true);
}),
}),
@@ -317,10 +195,11 @@ export const api = t.router({
try {
let logoPath: string | null = null;
- if (fs.existsSync(APP_PATHS.FREEMOCAP_LOGO_PNG_SHARED_PATH)) {
- logoPath = APP_PATHS.FREEMOCAP_LOGO_PNG_SHARED_PATH;
- } else if (fs.existsSync(APP_PATHS.FREEMOCAP_LOGO_PNG_RESOURCES_PATH)) {
- logoPath = APP_PATHS.FREEMOCAP_LOGO_PNG_RESOURCES_PATH;
+ // Check for logo in order of preference
+ if (fs.existsSync(APP_PATHS.SKELLYCAM_LOGO_PNG_SHARED_PATH)) {
+ logoPath = APP_PATHS.SKELLYCAM_LOGO_PNG_SHARED_PATH;
+ } else if (fs.existsSync(APP_PATHS.SKELLYCAM_LOGO_PNG_RESOURCES_PATH)) {
+ logoPath = APP_PATHS.SKELLYCAM_LOGO_PNG_RESOURCES_PATH;
}
if (!logoPath) {
@@ -328,10 +207,12 @@ export const api = t.router({
return null;
}
+ // Read the file and convert to base64
const imageBuffer = fs.readFileSync(logoPath);
const base64String = imageBuffer.toString('base64');
- const mimeType = 'image/png';
+ const mimeType = 'image/png'; // Since we know it's a PNG
+ // Return as a data URL that can be used directly in img src
return `data:${mimeType};base64,${base64String}`;
} catch (error) {
console.error('Failed to load logo as base64:', error);
@@ -341,13 +222,13 @@ export const api = t.router({
getLogoPngPath: t.procedure
.query(() => {
- if (fs.existsSync(APP_PATHS.FREEMOCAP_LOGO_PNG_SHARED_PATH)) {
- return APP_PATHS.FREEMOCAP_LOGO_PNG_SHARED_PATH;
+ if (fs.existsSync(APP_PATHS.SKELLYCAM_LOGO_PNG_SHARED_PATH)) {
+ return APP_PATHS.SKELLYCAM_LOGO_PNG_SHARED_PATH;
}
- return APP_PATHS.FREEMOCAP_LOGO_PNG_RESOURCES_PATH;
+ return APP_PATHS.SKELLYCAM_LOGO_PNG_RESOURCES_PATH;
}),
}),
});
// Export the type for use in renderer
-export type AppAPI = typeof api;
\ No newline at end of file
+export type AppAPI = typeof api;
diff --git a/freemocap-ui/electron/main/app-paths.ts b/freemocap-ui/electron/main/app-paths.ts
index c1224e95..c06a7b04 100644
--- a/freemocap-ui/electron/main/app-paths.ts
+++ b/freemocap-ui/electron/main/app-paths.ts
@@ -1,14 +1,17 @@
import path from "node:path";
+import os from "node:os";
import {fileURLToPath} from "node:url";
import {app} from "electron";
export const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const APP_NAME = 'freemocap';
+const SERVER_EXE_NAME = process.platform === 'win32' ? 'freemocap_server.exe' : 'freemocap_server';
// Function to get the correct resources path based on environment
const getResourcesPath = () => {
if (app.isPackaged) {
- const resourcesPath = path.join(process.resourcesPath, "app.asar.unpacked")
+ const resourcesPath = path.join(process.resourcesPath, "app.asar.unpacked");
console.log(`App is packaged. resourcesPath: ${resourcesPath}`);
return resourcesPath;
} else {
@@ -16,30 +19,51 @@ const getResourcesPath = () => {
console.log(`App is in development. resourcesPath: ${resourcesPath}`);
return resourcesPath;
}
+};
+// Platform-specific default install path where electron-builder puts the app
+const getDefaultInstallUnpackedPath = (): string => {
+ const home = os.homedir();
+ switch (process.platform) {
+ case 'win32':
+ // NSIS per-user install: %LOCALAPPDATA%\Programs\{name}\resources\app.asar.unpacked
+ return path.join(home, 'AppData', 'Local', 'Programs', APP_NAME, 'resources', 'app.asar.unpacked');
+ case 'darwin':
+ // macOS .app bundle: /Applications/{name}.app/Contents/Resources/app.asar.unpacked
+ return path.join('/Applications', `${APP_NAME}.app`, 'Contents', 'Resources', 'app.asar.unpacked');
+ case 'linux':
+ // Linux default: /opt/{name}/resources/app.asar.unpacked
+ return path.join('/opt', APP_NAME, 'resources', 'app.asar.unpacked');
+ default:
+ return path.join(home, APP_NAME, 'resources', 'app.asar.unpacked');
+ }
};
// Python server executable candidates in order of preference
export const PYTHON_EXECUTABLE_CANDIDATES = [
{
- name: 'development',
- path: path.join(getResourcesPath(), '../dist/freemocap_server.exe'),
- description: 'Development build executable'
+ name: 'bundled',
+ path: path.join(getResourcesPath(), SERVER_EXE_NAME),
+ description: 'Executable bundled with the running app (asar-unpacked)'
},
{
- name: 'installed',
- path: path.join(getResourcesPath(), 'freemocap_server.exe'),
- description: 'Executable in the installation folder'
+ name: 'default-install',
+ path: path.join(getDefaultInstallUnpackedPath(), SERVER_EXE_NAME),
+ description: 'Executable in the platform default install location'
+ },
+ {
+ name: 'development',
+ path: path.join(getResourcesPath(), '..', 'dist', SERVER_EXE_NAME),
+ description: 'Development build executable (../dist/)'
},
-
{
name: 'portable',
- path: path.join(process.cwd(), 'freemocap_server.exe'),
- description: 'Portable executable in current directory'
+ path: path.join(process.cwd(), SERVER_EXE_NAME),
+ description: 'Portable executable in the current working directory'
},
{
name: 'system-path',
- path: 'freemocap_server.exe', // Will be found via PATH
+ path: SERVER_EXE_NAME, // Resolved via PATH
description: 'Executable available in system PATH'
}
];
@@ -49,12 +73,12 @@ export const APP_PATHS = {
RENDERER_HTML: path.join(__dirname, "../../dist/index.html"),
FREEMOCAP_ICON_PATH: path.resolve(
__dirname,
- "../../../shared/logo/freemocap-logo.ico"
+ "../../../shared/freemocap-logo/freemocap-favicon.ico"
),
- FREEMOCAP_LOGO_PNG_RESOURCES_PATH: path.join(getResourcesPath(), 'dist/freemocap-logo.png'),
- FREEMOCAP_LOGO_PNG_SHARED_PATH:path.resolve(
+ SKELLYCAM_LOGO_PNG_RESOURCES_PATH: path.join(getResourcesPath(), 'dist/freemocap-logo.png'),
+ SKELLYCAM_LOGO_PNG_SHARED_PATH:path.resolve(
__dirname,
- "../../../shared/logo/freemocap-logo.png"
+ "../../../shared/freemocap-logo/freemocap-logo.png"
),
};
diff --git a/freemocap-ui/electron/main/index.ts b/freemocap-ui/electron/main/index.ts
index e6224780..280f090d 100644
--- a/freemocap-ui/electron/main/index.ts
+++ b/freemocap-ui/electron/main/index.ts
@@ -1,23 +1,32 @@
+// electron/main/index.ts
import { app, BrowserWindow } from 'electron';
import { setupIPC } from './ipc';
import { WindowManager } from './services/window-manager';
import { PythonServer } from './services/python-server';
-import { buildAppMenu } from './services/app-menu';
+import { UpdateHandler } from './services/update-handler';
import { LifecycleLogger } from './services/logger';
+import { buildApplicationMenu } from './services/menu-builder';
+// import os from 'node:os'; // Uncomment if needed for platform-specific checks
+// Export environment configuration
export const APP_ENVIRONMENT = {
IS_DEV: process.env.NODE_ENV === 'development',
VITE_DEV_SERVER_URL: process.env.VITE_DEV_SERVER_URL,
};
+
+// Platform config
+// if (os.release().startsWith('6.1')) app.disableHardwareAcceleration();
if (process.platform === 'win32') app.setAppUserModelId(app.getName());
+// Prevent multiple instances
const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
app.quit();
} else {
app.on('second-instance', () => {
+ // Someone tried to run a second instance, focus our window instead
const windows = BrowserWindow.getAllWindows();
if (windows.length > 0) {
const window = windows[0];
@@ -26,16 +35,25 @@ if (!gotTheLock) {
}
});
+ // App lifecycle
app.whenReady().then(async () => {
LifecycleLogger.logProcessInfo();
console.log('App is ready');
+ // Setup IPC
setupIPC();
+ // Build the native application menu with shortcuts
+ buildApplicationMenu();
+
+ // Create window
const mainWindow = WindowManager.createMainWindow();
- // Set up the native application menu (File, Edit, View, Tools, etc.)
- buildAppMenu(mainWindow);
+ // Initialize auto-updater (only in production)
+ if (!APP_ENVIRONMENT.IS_DEV) {
+ UpdateHandler.initialize(mainWindow);
+ }
+
});
app.on('window-all-closed', async () => {
@@ -53,6 +71,7 @@ if (!gotTheLock) {
app.on('before-quit', async (event) => {
event.preventDefault();
console.log('App is quitting, cleaning up...');
+ UpdateHandler.shutdown();
await PythonServer.shutdown();
app.exit(0);
});
diff --git a/freemocap-ui/electron/main/ipc.ts b/freemocap-ui/electron/main/ipc.ts
index cf09c44f..3e20aa90 100644
--- a/freemocap-ui/electron/main/ipc.ts
+++ b/freemocap-ui/electron/main/ipc.ts
@@ -2,6 +2,8 @@
import { ipcMain } from 'electron';
import { api } from './api';
import superjson from 'superjson';
+import { buildApplicationMenu } from './services/menu-builder';
+import type { MenuBuildParams } from './services/menu-builder';
export function setupIPC(): void {
ipcMain.handle('trpc', async (_event, { path, input }) => {
@@ -32,4 +34,9 @@ export function setupIPC(): void {
throw error;
}
});
+
+ // Rebuild the native menu when the renderer sends translated labels
+ ipcMain.on('update-menu-labels', (_event, params: MenuBuildParams) => {
+ buildApplicationMenu(params);
+ });
}
diff --git a/freemocap-ui/electron/main/services/menu-builder.ts b/freemocap-ui/electron/main/services/menu-builder.ts
new file mode 100644
index 00000000..97745687
--- /dev/null
+++ b/freemocap-ui/electron/main/services/menu-builder.ts
@@ -0,0 +1,349 @@
+// electron/main/services/menu-builder.ts
+import { app, BrowserWindow, Menu, MenuItemConstructorOptions, shell } from 'electron';
+
+// Channel name for menu-triggered actions sent to the renderer
+const MENU_CHANNEL = 'menu-action';
+
+export type MenuAction =
+ | 'navigate-home'
+ | 'navigate-cameras'
+ | 'navigate-playback'
+ | 'navigate-settings'
+ | 'toggle-theme'
+ | 'toggle-sidebar'
+ | 'detect-cameras'
+ | 'connect-cameras'
+ | 'close-cameras'
+ | 'pause-unpause-cameras'
+ | 'start-recording'
+ | 'stop-recording'
+ | 'open-recording-folder'
+ | 'toggle-fullscreen'
+ | 'toggle-locale'
+ | 'check-for-updates'
+ | `change-locale:${string}`;
+
+export interface LocaleEntry {
+ code: string;
+ label: string;
+}
+
+// All translatable menu label keys. Renderer sends these as a Record<MenuLabelKey, string>.
+export interface MenuLabels {
+ menuFile: string;
+ menuView: string;
+ menuCamera: string;
+ menuRecording: string;
+ menuHelp: string;
+ menuDetectCameras: string;
+ menuConnectCameras: string;
+ menuCloseAllCameras: string;
+ menuOpenRecordingFolder: string;
+ menuToggleSidebar: string;
+ menuToggleTheme: string;
+ menuToggleFullScreen: string;
+ menuPauseUnpause: string;
+ menuConnectApplySettings: string;
+ menuCloseAll: string;
+ menuDocumentation: string;
+ menuGitHubRepository: string;
+ menuReportIssue: string;
+ menuAbout: string;
+ menuCheckForUpdates: string;
+ menuPlayback: string;
+ // Keys reused from the existing i18n
+ home: string;
+ cameras: string;
+ settings: string;
+ startRecording: string;
+ stopRecording: string;
+ language: string;
+}
+
+// English fallback labels used until the renderer sends translated ones
+const DEFAULT_LABELS: MenuLabels = {
+ menuFile: 'File',
+ menuView: 'View',
+ menuCamera: 'Camera',
+ menuRecording: 'Recording',
+ menuHelp: 'Help',
+ menuDetectCameras: 'Detect Cameras',
+ menuConnectCameras: 'Connect Cameras',
+ menuCloseAllCameras: 'Close All Cameras',
+ menuOpenRecordingFolder: 'Open Recording Folder…',
+ menuToggleSidebar: 'Toggle Sidebar',
+ menuToggleTheme: 'Toggle Theme',
+ menuToggleFullScreen: 'Toggle Full Screen',
+ menuPauseUnpause: 'Pause / Unpause',
+ menuConnectApplySettings: 'Connect / Apply Settings',
+ menuCloseAll: 'Close All',
+ menuDocumentation: 'Documentation',
+ menuGitHubRepository: 'GitHub Repository',
+ menuReportIssue: 'Report an Issue…',
+ menuAbout: 'About SkellyCam',
+ menuCheckForUpdates: 'Check for Updates…',
+ menuPlayback: 'Playback',
+ home: 'Home',
+ cameras: 'Cameras',
+ settings: 'Settings',
+ startRecording: 'Start Recording',
+ stopRecording: 'Stop Recording',
+ language: 'Language',
+};
+
+function sendMenuAction(action: MenuAction): void {
+ const window = BrowserWindow.getFocusedWindow();
+ if (!window) return;
+ window.webContents.send(MENU_CHANNEL, action);
+}
+
+const isMac = process.platform === 'darwin';
+
+function buildLanguageSubmenu(t: MenuLabels, locales: LocaleEntry[], currentLocale: string): MenuItemConstructorOptions {
+ return {
+ label: t.language,
+ submenu: [
+ {
+ label: 'Toggle Language',
+ accelerator: 'CmdOrCtrl+Shift+L',
+ click: () => sendMenuAction('toggle-locale'),
+ },
+ { type: 'separator' },
+ ...locales.map((locale): MenuItemConstructorOptions => ({
+ label: locale.label,
+ type: 'radio',
+ checked: locale.code === currentLocale,
+ click: () => sendMenuAction(`change-locale:${locale.code}`),
+ })),
+ ],
+ };
+}
+
+function buildFileMenu(t: MenuLabels, locales: LocaleEntry[], currentLocale: string): MenuItemConstructorOptions {
+ return {
+ label: t.menuFile,
+ submenu: [
+ {
+ label: t.menuOpenRecordingFolder,
+ accelerator: 'CmdOrCtrl+O',
+ click: () => sendMenuAction('open-recording-folder'),
+ },
+ { type: 'separator' },
+ buildLanguageSubmenu(t, locales, currentLocale),
+ {
+ label: `${t.settings}…`,
+ accelerator: 'CmdOrCtrl+,',
+ click: () => sendMenuAction('navigate-settings'),
+ },
+ { type: 'separator' },
+ isMac
+ ? { role: 'close' }
+ : { role: 'quit' },
+ ],
+ };
+}
+
+function buildViewMenu(t: MenuLabels): MenuItemConstructorOptions {
+ return {
+ label: t.menuView,
+ submenu: [
+ {
+ label: t.home,
+ accelerator: 'CmdOrCtrl+1',
+ click: () => sendMenuAction('navigate-home'),
+ },
+ {
+ label: t.cameras,
+ accelerator: 'CmdOrCtrl+2',
+ click: () => sendMenuAction('navigate-cameras'),
+ },
+ {
+ label: t.menuPlayback,
+ accelerator: 'CmdOrCtrl+3',
+ click: () => sendMenuAction('navigate-playback'),
+ },
+ { type: 'separator' },
+ {
+ label: t.menuToggleSidebar,
+ accelerator: 'CmdOrCtrl+B',
+ click: () => sendMenuAction('toggle-sidebar'),
+ },
+ {
+ label: t.menuToggleTheme,
+ accelerator: 'CmdOrCtrl+Shift+T',
+ click: () => sendMenuAction('toggle-theme'),
+ },
+ { type: 'separator' },
+ {
+ label: t.menuToggleFullScreen,
+ accelerator: isMac ? 'Ctrl+Cmd+F' : 'F11',
+ click: () => sendMenuAction('toggle-fullscreen'),
+ },
+ { type: 'separator' },
+ { role: 'reload' },
+ { role: 'forceReload' },
+ { role: 'toggleDevTools' },
+ { type: 'separator' },
+ { role: 'resetZoom' },
+ { role: 'zoomIn' },
+ { role: 'zoomOut' },
+ ],
+ };
+}
+
+function buildCameraMenu(t: MenuLabels): MenuItemConstructorOptions {
+ return {
+ label: t.menuCamera,
+ submenu: [
+ {
+ label: t.menuDetectCameras,
+ accelerator: 'CmdOrCtrl+D',
+ click: () => sendMenuAction('detect-cameras'),
+ },
+ {
+ label: t.menuConnectApplySettings,
+ accelerator: 'CmdOrCtrl+Shift+C',
+ click: () => sendMenuAction('connect-cameras'),
+ },
+ {
+ label: t.menuCloseAll,
+ accelerator: 'CmdOrCtrl+Shift+W',
+ click: () => sendMenuAction('close-cameras'),
+ },
+ { type: 'separator' },
+ {
+ label: t.menuPauseUnpause,
+ accelerator: 'Shift+Space',
+ click: () => sendMenuAction('pause-unpause-cameras'),
+ },
+ ],
+ };
+}
+
+function buildRecordingMenu(t: MenuLabels): MenuItemConstructorOptions {
+ return {
+ label: t.menuRecording,
+ submenu: [
+ {
+ label: t.startRecording,
+ accelerator: 'CmdOrCtrl+Shift+S',
+ click: () => sendMenuAction('start-recording'),
+ },
+ {
+ label: t.stopRecording,
+ accelerator: 'CmdOrCtrl+Shift+X',
+ click: () => sendMenuAction('stop-recording'),
+ },
+ { type: 'separator' },
+ {
+ label: t.menuOpenRecordingFolder,
+ click: () => sendMenuAction('open-recording-folder'),
+ },
+ ],
+ };
+}
+
+function buildHelpMenu(t: MenuLabels): MenuItemConstructorOptions {
+ return {
+ label: t.menuHelp,
+ submenu: [
+ {
+ label: t.menuDocumentation,
+ click: () => {
+ // Keep in sync with freemocap-ui/src/constants/external-urls.ts
+ shell.openExternal('https://docs.freemocap.org/freemocap');
+ },
+ },
+ {
+ label: t.menuGitHubRepository,
+ click: () => {
+ shell.openExternal('https://github.com/freemocap/freemocap');
+ },
+ },
+ {
+ label: t.menuReportIssue,
+ click: () => {
+ shell.openExternal('https://github.com/freemocap/freemocap/issues/new');
+ },
+ },
+ { type: 'separator' },
+ {
+ label: 'FreeMoCap Foundation',
+ click: () => {
+ shell.openExternal('https://freemocap.org');
+ },
+ },
+ { type: 'separator' },
+ {
+ label: t.menuCheckForUpdates,
+ click: () => sendMenuAction('check-for-updates'),
+ },
+ { type: 'separator' },
+ {
+ label: t.menuAbout,
+ click: () => sendMenuAction('navigate-settings'),
+ },
+ ],
+ };
+}
+
+export interface MenuBuildParams {
+ labels?: Partial<MenuLabels>;
+ locales?: LocaleEntry[];
+ currentLocale?: string;
+}
+
+export function buildApplicationMenu(params: MenuBuildParams = {}): void {
+ const { labels, locales = [], currentLocale = 'en' } = params;
+ const t: MenuLabels = { ...DEFAULT_LABELS, ...labels };
+ const template: MenuItemConstructorOptions[] = [];
+
+ // macOS app menu
+ if (isMac) {
+ template.push({
+ label: app.getName(),
+ submenu: [
+ { role: 'about' },
+ { type: 'separator' },
+ {
+ label: `${t.settings}…`,
+ accelerator: 'Cmd+,',
+ click: () => sendMenuAction('navigate-settings'),
+ },
+ { type: 'separator' },
+ { role: 'services' },
+ { type: 'separator' },
+ { role: 'hide' },
+ { role: 'hideOthers' },
+ { role: 'unhide' },
+ { type: 'separator' },
+ { role: 'quit' },
+ ],
+ });
+ }
+
+ template.push(buildFileMenu(t, locales, currentLocale));
+ template.push(buildViewMenu(t));
+ template.push(buildCameraMenu(t));
+ template.push(buildRecordingMenu(t));
+
+ // macOS window menu
+ if (isMac) {
+ template.push({
+ label: 'Window',
+ submenu: [
+ { role: 'minimize' },
+ { role: 'zoom' },
+ { type: 'separator' },
+ { role: 'front' },
+ ],
+ });
+ }
+
+ template.push(buildHelpMenu(t));
+
+ const menu = Menu.buildFromTemplate(template);
+ Menu.setApplicationMenu(menu);
+}
+
+export { MENU_CHANNEL };
diff --git a/freemocap-ui/electron/main/services/python-server.ts b/freemocap-ui/electron/main/services/python-server.ts
index 941730c9..c6b16365 100644
--- a/freemocap-ui/electron/main/services/python-server.ts
+++ b/freemocap-ui/electron/main/services/python-server.ts
@@ -9,29 +9,20 @@ import {PYTHON_EXECUTABLE_CANDIDATES} from "../app-paths";
const treeKillAsync = promisify(treeKill);
let pythonProcess: ReturnType<typeof exec> | null = null;
-const PORT_SENTINEL = "FREEMOCAP_PORT";
-const DEFAULT_PORT = 53117;
-const PORT_DISCOVERY_TIMEOUT_MS = 30_000;
-
export interface ExecutableCandidate {
name: string;
path: string;
description: string;
isValid?: boolean;
error?: string;
- resolvedPath?: string;
+ resolvedPath?: string; // Add resolved path for deduplication
}
export class PythonServer {
private static currentExecutablePath: string | null = null;
private static validatedCandidates: ExecutableCandidate[] = [];
- private static discoveredPort: number | null = null;
- /**
- * Start the Python server and wait for it to report which port it bound to.
- * Returns the actual port number.
- */
- static async start(exePath: string | null = null): Promise<number> {
+ static async start(exePath: string | null = null) {
console.log('Starting python server subprocess...');
try {
@@ -40,16 +31,17 @@ export class PythonServer {
let executablePath: string;
if (exePath) {
+ // If specific path provided, validate it
this.validateExecutable(exePath);
executablePath = exePath;
console.log(`Using provided executable path: ${executablePath}`);
} else {
+ // Find first valid executable from candidates
executablePath = await this.findValidExecutablePath();
console.log(`Using auto-detected executable path: ${executablePath}`);
}
this.currentExecutablePath = executablePath;
- this.discoveredPort = null;
console.log(`Launching Python server from: ${executablePath}`);
pythonProcess = exec(`"${executablePath}"`, {
env: {
@@ -75,12 +67,6 @@ export class PythonServer {
LifecycleLogger.logPythonProcess(pythonProcess);
console.log(`✔ Python server started successfully (PID: ${pythonProcess.pid})`);
- const port = await this.waitForPort(pythonProcess);
- this.discoveredPort = port;
- console.log(`✔ Python server bound to port ${port}`);
-
- return port;
-
} catch (error) {
console.error('Failed to start Python server:', error);
this.currentExecutablePath = null;
@@ -88,54 +74,6 @@ export class PythonServer {
}
}
- /**
- * Read stdout line-by-line until we find the port sentinel or time out.
- */
- private static waitForPort(proc: ReturnType<typeof exec>): Promise<number> {
- return new Promise((resolve, reject) => {
- const timeout = setTimeout(() => {
- reject(new Error(
- `Python server did not report a port within ${PORT_DISCOVERY_TIMEOUT_MS}ms`
- ));
- }, PORT_DISCOVERY_TIMEOUT_MS);
-
- const onData = (chunk: Buffer | string): void => {
- const text = chunk.toString();
- for (const line of text.split('\n')) {
- const trimmed = line.trim();
- if (trimmed.startsWith(`${PORT_SENTINEL}=`)) {
- const portStr = trimmed.slice(PORT_SENTINEL.length + 1);
- const port = parseInt(portStr, 10);
- if (isNaN(port)) {
- clearTimeout(timeout);
- reject(new Error(`Invalid port in sentinel line: ${trimmed}`));
- return;
- }
- clearTimeout(timeout);
- proc.stdout?.off('data', onData);
- resolve(port);
- return;
- }
- }
- };
-
- if (!proc.stdout) {
- clearTimeout(timeout);
- reject(new Error('Python process has no stdout stream'));
- return;
- }
-
- proc.stdout.on('data', onData);
-
- proc.on('exit', (code) => {
- clearTimeout(timeout);
- reject(new Error(
- `Python server exited with code ${code} before reporting a port`
- ));
- });
- });
- }
-
static async shutdown() {
if (!pythonProcess || !pythonProcess.pid) {
console.log('No Python server process to shutdown');
@@ -145,10 +83,12 @@ export class PythonServer {
console.log(`Shutting down Python server (PID: ${pythonProcess.pid})`);
try {
+ // Kill entire process tree
await treeKillAsync(pythonProcess.pid);
console.log('✔ Python server process tree terminated');
} catch (error) {
console.error('Error killing process tree:', error);
+ // Fallback to direct kill
try {
pythonProcess?.kill('SIGKILL');
console.log('✔ Python server force-killed as fallback');
@@ -157,6 +97,7 @@ export class PythonServer {
}
}
+ // Wait a moment for cleanup
await new Promise(resolve => setTimeout(resolve, 1000));
if (pythonProcess && !pythonProcess.killed) {
@@ -165,17 +106,9 @@ export class PythonServer {
pythonProcess = null;
this.currentExecutablePath = null;
- this.discoveredPort = null;
console.log('✔ Python server shutdown complete');
}
- /**
- * Get the port the Python server is currently bound to, or the default if not yet started.
- */
- static getPort(): number {
- return this.discoveredPort ?? DEFAULT_PORT;
- }
-
static getCurrentExecutablePath(): string | null {
return this.currentExecutablePath;
}
@@ -183,10 +116,12 @@ export class PythonServer {
static async findValidExecutablePath(): Promise<string> {
console.log('Searching for valid Python server executable...');
+ // Validate all candidates if not done yet
if (this.validatedCandidates.length === 0) {
await this.validateAllCandidates();
}
+ // Find first valid candidate
const validCandidate = this.validatedCandidates.find(candidate => candidate.isValid);
if (!validCandidate) {
@@ -202,6 +137,7 @@ export class PythonServer {
static async validateAllCandidates(): Promise<ExecutableCandidate[]> {
console.log('Validating all executable candidates...');
+ // First, validate all candidates
const allValidatedCandidates = await Promise.all(
PYTHON_EXECUTABLE_CANDIDATES.map(async (candidate) => {
const validatedCandidate: ExecutableCandidate = {
@@ -212,6 +148,7 @@ export class PythonServer {
try {
this.validateExecutable(candidate.path);
validatedCandidate.isValid = true;
+ // Store resolved path for deduplication
validatedCandidate.resolvedPath = fs.existsSync(candidate.path)
? path.resolve(candidate.path)
: candidate.path;
@@ -225,15 +162,18 @@ export class PythonServer {
})
);
+ // Deduplicate by resolved path
const seenPaths = new Set<string>();
this.validatedCandidates = allValidatedCandidates.filter(candidate => {
const pathKey = candidate.resolvedPath || candidate.path;
+ // If we've seen this path before, skip it
if (seenPaths.has(pathKey)) {
console.log(` âš  Skipping duplicate: ${candidate.name} (same as another candidate)`);
return false;
}
+ // Add to seen paths
seenPaths.add(pathKey);
return true;
});
@@ -245,7 +185,7 @@ export class PythonServer {
}
static getPythonServerExecutableCandidates(): ExecutableCandidate[] {
- return [...this.validatedCandidates];
+ return [...this.validatedCandidates]; // Return copy to prevent mutation
}
static async refreshCandidates(): Promise<ExecutableCandidate[]> {
@@ -268,18 +208,23 @@ export class PythonServer {
}
private static validateExecutable(exePath: string): void {
+ // Check if file exists
if (!fs.existsSync(exePath)) {
throw new Error(`Executable not found at: ${exePath}`);
}
+ // Check if it's actually a file (not a directory)
const stats = fs.statSync(exePath);
if (!stats.isFile()) {
throw new Error(`Path is not a file: ${exePath}`);
}
+ // Check if file is executable
try {
fs.accessSync(exePath, fs.constants.F_OK | fs.constants.R_OK);
+ // On Windows, we mainly check if file exists and is readable
+ // On Unix systems, we can check execute permissions
if (process.platform !== 'win32') {
fs.accessSync(exePath, fs.constants.X_OK);
}
@@ -287,6 +232,7 @@ export class PythonServer {
throw new Error(`File is not accessible or executable: ${exePath}`);
}
+ // Additional validation: check file extension on Windows
if (process.platform === 'win32' && !exePath.toLowerCase().endsWith('.exe')) {
console.warn(`Warning: Executable doesn't have .exe extension: ${exePath}`);
}
diff --git a/freemocap-ui/electron/main/services/update-handler.ts b/freemocap-ui/electron/main/services/update-handler.ts
index 35bb6182..9ca06240 100644
--- a/freemocap-ui/electron/main/services/update-handler.ts
+++ b/freemocap-ui/electron/main/services/update-handler.ts
@@ -1,27 +1,28 @@
-import { app, ipcMain, BrowserWindow } from 'electron';
-import { autoUpdater } from 'electron-updater';
+import { app, BrowserWindow } from 'electron';
+import pkg from 'electron-updater';
+const { autoUpdater } = pkg;
+
+const CHECK_INTERVAL_MS = 4 * 60 * 60 * 1000; // 4 hours
+const INITIAL_CHECK_DELAY_MS = 10 * 1000; // 10 seconds after startup
export class UpdateHandler {
- private mainWindow: BrowserWindow;
+ private static instance: UpdateHandler | null = null;
+ private checkInterval: ReturnType<typeof setInterval> | null = null;
+ private initialTimeout: ReturnType<typeof setTimeout> | null = null;
- constructor(window: BrowserWindow) {
- this.mainWindow = window;
- this.setupAutoUpdater();
- this.registerIpcHandlers();
+ private constructor(private mainWindow: BrowserWindow) {
+ this.setupEventForwarding();
+ this.scheduleChecks();
}
- private setupAutoUpdater() {
- autoUpdater.autoDownload = false;
- autoUpdater.disableWebInstaller = false;
- autoUpdater.allowDowngrade = false;
-
+ private setupEventForwarding() {
autoUpdater.on('checking-for-update', () => {
- console.log('Checking for updates...');
+ console.log('[AutoUpdater] Checking for updates...');
});
autoUpdater.on('update-available', (info) => {
- console.log('Update available:', info);
+ console.log('[AutoUpdater] Update available:', info.version);
this.mainWindow.webContents.send('update-available', {
version: info.version,
currentVersion: app.getVersion(),
@@ -29,44 +30,58 @@ export class UpdateHandler {
});
autoUpdater.on('update-not-available', () => {
- console.log('No updates available');
+ console.log('[AutoUpdater] Already up to date');
});
autoUpdater.on('download-progress', (progress) => {
this.mainWindow.webContents.send('download-progress', progress);
});
- autoUpdater.on('update-downloaded', () => {
- this.mainWindow.webContents.send('update-downloaded');
+ autoUpdater.on('update-downloaded', (info) => {
+ console.log('[AutoUpdater] Update downloaded:', info.version);
+ this.mainWindow.webContents.send('update-downloaded', {
+ version: info.version,
+ });
});
autoUpdater.on('error', (error) => {
- console.error('Update error:', error);
- this.mainWindow.webContents.send('update-error', error);
+ console.error('[AutoUpdater] Error:', error.message);
+ this.mainWindow.webContents.send('update-error', {
+ message: error.message,
+ });
});
}
- private registerIpcHandlers() {
- ipcMain.handle('check-update', async () => {
- if (!app.isPackaged) {
- return {
- error: 'Updates only work in packaged app',
- available: false
- };
- }
- return await autoUpdater.checkForUpdatesAndNotify();
- });
+ private scheduleChecks() {
+ // Initial check after a short delay to let the app finish loading
+ this.initialTimeout = setTimeout(() => {
+ autoUpdater.checkForUpdates().catch((err) => {
+ console.error('[AutoUpdater] Initial check failed:', err.message);
+ });
+ }, INITIAL_CHECK_DELAY_MS);
- ipcMain.handle('download-update', async () => {
- return await autoUpdater.downloadUpdate();
- });
+ // Periodic checks
+ this.checkInterval = setInterval(() => {
+ autoUpdater.checkForUpdates().catch((err) => {
+ console.error('[AutoUpdater] Periodic check failed:', err.message);
+ });
+ }, CHECK_INTERVAL_MS);
+ }
- ipcMain.handle('install-update', () => {
- autoUpdater.quitAndInstall(false, true);
- });
+ dispose() {
+ if (this.initialTimeout) clearTimeout(this.initialTimeout);
+ if (this.checkInterval) clearInterval(this.checkInterval);
+ this.initialTimeout = null;
+ this.checkInterval = null;
}
static initialize(window: BrowserWindow) {
- return new UpdateHandler(window);
+ UpdateHandler.instance = new UpdateHandler(window);
+ return UpdateHandler.instance;
+ }
+
+ static shutdown() {
+ UpdateHandler.instance?.dispose();
+ UpdateHandler.instance = null;
}
}
diff --git a/freemocap-ui/electron/main/services/window-manager.ts b/freemocap-ui/electron/main/services/window-manager.ts
index 1e2f219a..9e982505 100644
--- a/freemocap-ui/electron/main/services/window-manager.ts
+++ b/freemocap-ui/electron/main/services/window-manager.ts
@@ -1,18 +1,20 @@
+// electron/main/services/window-manager.ts
import { BrowserWindow, shell } from 'electron';
import { LifecycleLogger } from './logger';
import { APP_ENVIRONMENT } from '../index';
-import { APP_PATHS } from '../app-paths';
+import {APP_PATHS} from "../app-paths";
export class WindowManager {
private static mainWindow: BrowserWindow | null = null;
static createMainWindow(): BrowserWindow {
+ // Return existing window if already created
if (this.mainWindow && !this.mainWindow.isDestroyed()) {
return this.mainWindow;
}
const window = new BrowserWindow({
- title: 'FreeMoCap 💀📸',
+ title: 'FreeMoCap 💀✨',
icon: APP_PATHS.FREEMOCAP_ICON_PATH,
width: 1280,
height: 720,
@@ -24,13 +26,14 @@ export class WindowManager {
nodeIntegration: false,
sandbox: true,
},
- show: false,
+ show: false, // Don't show until ready
});
this.mainWindow = window;
this.configureWindowHandlers(window);
this.loadContent(window);
+ // Show window when ready
window.once('ready-to-show', () => {
window.show();
LifecycleLogger.logWindowCreation(window);
@@ -52,16 +55,21 @@ export class WindowManager {
window.webContents.send('app-ready', Date.now());
});
+ // Handle external links
window.webContents.setWindowOpenHandler(({ url }) => {
if (url.startsWith('http:') || url.startsWith('https:')) {
shell.openExternal(url).catch(err =>
- console.error('Failed to open external link:', err),
+ console.error('Failed to open external link:', err)
);
}
return { action: 'deny' };
});
+ // Intercept navigation to external links
window.webContents.on('will-navigate', (event, url) => {
+ const currentURL = window.webContents.getURL();
+
+ // Allow navigation within the app
if (APP_ENVIRONMENT.IS_DEV && url.startsWith(APP_ENVIRONMENT.VITE_DEV_SERVER_URL!)) {
return;
}
@@ -70,14 +78,16 @@ export class WindowManager {
return;
}
+ // Prevent navigation to external URLs
if (url.startsWith('http:') || url.startsWith('https:')) {
event.preventDefault();
shell.openExternal(url).catch(err =>
- console.error('Failed to open external link via navigation:', err),
+ console.error('Failed to open external link via navigation:', err)
);
}
});
+ // Handle crashes
window.webContents.on('render-process-gone', (event, details) => {
console.error('Renderer process gone:', details);
if (details.reason === 'crashed') {
diff --git a/freemocap-ui/electron/preload/index.ts b/freemocap-ui/electron/preload/index.ts
index 2096156c..337e7e50 100644
--- a/freemocap-ui/electron/preload/index.ts
+++ b/freemocap-ui/electron/preload/index.ts
@@ -1,17 +1,48 @@
import { contextBridge, ipcRenderer } from 'electron';
+// Expose a simple tRPC bridge + menu action listener + menu label updater
contextBridge.exposeInMainWorld('electronAPI', {
- // tRPC bridge
- invoke: (path: string, input?: any) =>
+ invoke: (path: string, input?: unknown) =>
ipcRenderer.invoke('trpc', { path, input }),
- // Menu-triggered navigation: main process sends 'navigate' with a route string
- onNavigate: (callback: (route: string) => void) => {
- const handler = (_event: Electron.IpcRendererEvent, route: string) => callback(route);
- ipcRenderer.on('navigate', handler);
- // Return cleanup function
+ onMenuAction: (callback: (action: string) => void) => {
+ const handler = (_event: Electron.IpcRendererEvent, action: string) => {
+ callback(action);
+ };
+ ipcRenderer.on('menu-action', handler);
+
+ // Return a cleanup function to remove the listener
return () => {
- ipcRenderer.removeListener('navigate', handler);
+ ipcRenderer.removeListener('menu-action', handler);
};
},
+
+ sendMenuLabels: (params: Record<string, unknown>) => {
+ ipcRenderer.send('update-menu-labels', params);
+ },
+
+ // Auto-update event listeners
+ onUpdateAvailable: (callback: (info: { version: string; currentVersion: string }) => void) => {
+ const handler = (_event: Electron.IpcRendererEvent, info: { version: string; currentVersion: string }) => callback(info);
+ ipcRenderer.on('update-available', handler);
+ return () => { ipcRenderer.removeListener('update-available', handler); };
+ },
+
+ onDownloadProgress: (callback: (progress: { percent: number; bytesPerSecond: number; transferred: number; total: number }) => void) => {
+ const handler = (_event: Electron.IpcRendererEvent, progress: any) => callback(progress);
+ ipcRenderer.on('download-progress', handler);
+ return () => { ipcRenderer.removeListener('download-progress', handler); };
+ },
+
+ onUpdateDownloaded: (callback: (info: { version: string }) => void) => {
+ const handler = (_event: Electron.IpcRendererEvent, info: { version: string }) => callback(info);
+ ipcRenderer.on('update-downloaded', handler);
+ return () => { ipcRenderer.removeListener('update-downloaded', handler); };
+ },
+
+ onUpdateError: (callback: (error: { message: string }) => void) => {
+ const handler = (_event: Electron.IpcRendererEvent, error: { message: string }) => callback(error);
+ ipcRenderer.on('update-error', handler);
+ return () => { ipcRenderer.removeListener('update-error', handler); };
+ },
});