Free Motion Capture for Everyone πβ¨
TypeScript
rm old electron
jonmatthisc24bf00d7fee
diff --git a/freemocap-ui/electron-old/main/api.ts b/freemocap-ui/electron-old/main/api.tsdeleted file mode 100644index d7d85f7f..00000000--- a/freemocap-ui/electron-old/main/api.ts+++ /dev/null@@ -1,353 +0,0 @@-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 filediff --git a/freemocap-ui/electron-old/main/app-paths.ts b/freemocap-ui/electron-old/main/app-paths.tsdeleted file mode 100644index c1224e95..00000000--- a/freemocap-ui/electron-old/main/app-paths.ts+++ /dev/null@@ -1,63 +0,0 @@-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.tsdeleted file mode 100644index e6224780..00000000--- a/freemocap-ui/electron-old/main/index.ts+++ /dev/null@@ -1,59 +0,0 @@-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.tsdeleted file mode 100644index cf09c44f..00000000--- a/freemocap-ui/electron-old/main/ipc.ts+++ /dev/null@@ -1,35 +0,0 @@-// 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-old/main/services/app-menu.ts b/freemocap-ui/electron-old/main/services/app-menu.tsdeleted file mode 100644index 15d215ab..00000000--- a/freemocap-ui/electron-old/main/services/app-menu.ts+++ /dev/null@@ -1,144 +0,0 @@-import { Menu, BrowserWindow, shell, app } from 'electron';-import path from 'node:path';-import os from 'node:os';--/**- * Build and set the native application menu.- * Call this once after the main window is created.- */-export function buildAppMenu(mainWindow: BrowserWindow): void {- const isMac = process.platform === 'darwin';-- const template: Electron.MenuItemConstructorOptions[] = [- // macOS app menu- ...(isMac ? [{- label: app.name,- submenu: [- { role: 'about' as const },- { type: 'separator' as const },- {- label: 'Settingsβ¦',- click: () => sendNavigate(mainWindow, '/settings'),- },- { type: 'separator' as const },- { role: 'services' as const },- { type: 'separator' as const },- { role: 'hide' as const },- { role: 'hideOthers' as const },- { role: 'unhide' as const },- { type: 'separator' as const },- { role: 'quit' as const },- ],- }] : []),-- // File- {- label: 'File',- submenu: [- isMac ? { role: 'close' as const } : { role: 'quit' as const },- ],- },-- // Edit- {- label: 'Edit',- submenu: [- { role: 'undo' as const },- { role: 'redo' as const },- { type: 'separator' as const },- { role: 'cut' as const },- { role: 'copy' as const },- { role: 'paste' as const },- { role: 'selectAll' as const },- ],- },-- // View- {- label: 'View',- submenu: [- { role: 'reload' as const },- { role: 'forceReload' as const },- { role: 'toggleDevTools' as const },- { type: 'separator' as const },- { role: 'resetZoom' as const },- { role: 'zoomIn' as const },- { role: 'zoomOut' as const },- { type: 'separator' as const },- { role: 'togglefullscreen' as const },- ],- },-- // Tools- {- label: 'Tools',- submenu: [- {- label: 'Settingsβ¦',- accelerator: isMac ? 'Cmd+Shift+S' : 'Ctrl+Shift+S',- click: () => sendNavigate(mainWindow, '/settings'),- },- { type: 'separator' as const },- {- label: 'Open Config Folder',- click: () => {- const configDir = path.join(os.homedir(), '.freemocap');- shell.openPath(configDir);- },- },- {- label: 'Open Data Folder',- click: () => {- const dataDir = path.join(os.homedir(), 'freemocap_data');- shell.openPath(dataDir);- },- },- ],- },-- // Window- {- label: 'Window',- submenu: [- { role: 'minimize' as const },- { role: 'zoom' as const },- ...(isMac ? [- { type: 'separator' as const },- { role: 'front' as const },- ] : [- { role: 'close' as const },- ]),- ],- },-- // Help- {- label: 'Help',- submenu: [- {- label: 'FreeMoCap Documentation',- click: () => shell.openExternal('https://freemocap.github.io/documentation/'),- },- {- label: 'GitHub Repository',- click: () => shell.openExternal('https://github.com/freemocap/freemocap'),- },- { type: 'separator' as const },- {- label: 'Settingsβ¦',- click: () => sendNavigate(mainWindow, '/settings'),- },- ],- },- ];-- const menu = Menu.buildFromTemplate(template);- Menu.setApplicationMenu(menu);-}--/** Send a navigation request to the renderer process. */-function sendNavigate(window: BrowserWindow, route: string): void {- if (window.isDestroyed()) return;- window.webContents.send('navigate', route);- window.focus();-}\ No newline at end of filediff --git a/freemocap-ui/electron-old/main/services/app-settings.ts b/freemocap-ui/electron-old/main/services/app-settings.tsdeleted file mode 100644index ac3ce52a..00000000--- a/freemocap-ui/electron-old/main/services/app-settings.ts+++ /dev/null@@ -1,81 +0,0 @@-import fs from 'node:fs';-import path from 'node:path';-import os from 'node:os';--const FREEMOCAP_CONFIG_DIR = path.join(os.homedir(), '.freemocap');-const SETTINGS_FILE = path.join(FREEMOCAP_CONFIG_DIR, 'settings.json');--type SettingsData = Record<string, unknown>;--function ensureConfigDir(): void {- if (!fs.existsSync(FREEMOCAP_CONFIG_DIR)) {- fs.mkdirSync(FREEMOCAP_CONFIG_DIR, { recursive: true });- }-}--function readAll(): SettingsData {- ensureConfigDir();- if (!fs.existsSync(SETTINGS_FILE)) {- return {};- }- const raw = fs.readFileSync(SETTINGS_FILE, 'utf-8');- const parsed: unknown = JSON.parse(raw);- if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {- throw new Error(`Corrupted settings file: expected object, got ${typeof parsed}`);- }- return parsed as SettingsData;-}--function writeAll(data: SettingsData): void {- ensureConfigDir();- fs.writeFileSync(SETTINGS_FILE, JSON.stringify(data, null, 2), 'utf-8');-}--export class AppSettings {- /** Get a single value by key. Returns null if the key doesn't exist. */- static get(key: string): unknown {- const data = readAll();- if (!(key in data)) {- return null;- }- return data[key];- }-- /** Set a single key-value pair. */- static set(key: string, value: unknown): void {- const data = readAll();- data[key] = value;- writeAll(data);- }-- /** Delete a single key. */- static delete(key: string): void {- const data = readAll();- if (!(key in data)) {- return;- }- delete data[key];- writeAll(data);- }-- /** Get all settings as a plain object. */- static getAll(): SettingsData {- return readAll();- }-- /** Replace all settings with the given object. */- static setAll(data: SettingsData): void {- writeAll(data);- }-- /** Get the path to the config directory (~/.freemocap/). */- static getConfigDir(): string {- ensureConfigDir();- return FREEMOCAP_CONFIG_DIR;- }-- /** Get the path to the settings file. */- static getSettingsFilePath(): string {- return SETTINGS_FILE;- }-}diff --git a/freemocap-ui/electron-old/main/services/dependency-manager.ts b/freemocap-ui/electron-old/main/services/dependency-manager.tsdeleted file mode 100644index c4aab5f1..00000000--- a/freemocap-ui/electron-old/main/services/dependency-manager.ts+++ /dev/null@@ -1,372 +0,0 @@-import { exec } from 'node:child_process';-import { promisify } from 'node:util';-import fs from 'node:fs';-import path from 'node:path';-import os from 'node:os';--const execAsync = promisify(exec);--// ββ Types ββ--export type DependencyStatus = 'installed' | 'missing' | 'outdated' | 'checking' | 'installing' | 'error';--export interface DependencyInfo {- id: string;- name: string;- description: string;- required: boolean;- status: DependencyStatus;- version: string | null;- installedPath: string | null;- error: string | null;-}--// ββ Constants ββ--const UV_INSTALL_URL_WINDOWS = 'https://astral.sh/uv/install.ps1';-const UV_INSTALL_URL_UNIX = 'https://astral.sh/uv/install.sh';--// ββ Helpers ββ--async function commandExists(command: string): Promise<{ exists: boolean; output: string }> {- try {- const { stdout } = await execAsync(- process.platform === 'win32'- ? `where ${command}`- : `which ${command}`,- { timeout: 10000 },- );- return { exists: true, output: stdout.trim() };- } catch {- return { exists: false, output: '' };- }-}--async function getCommandVersion(command: string, versionFlag: string = '--version'): Promise<string | null> {- try {- const { stdout } = await execAsync(`${command} ${versionFlag}`, { timeout: 15000 });- return stdout.trim().split('\n')[0];- } catch {- return null;- }-}--// ββ Blender Detection ββ--async function detectBlender(): Promise<DependencyInfo> {- const info: DependencyInfo = {- id: 'blender',- name: 'Blender',- description: '3D creation suite β used for viewing and animating motion capture data.',- required: false,- status: 'checking',- version: null,- installedPath: null,- error: null,- };-- // Check PATH- const { exists, output } = await commandExists('blender');- if (exists) {- info.installedPath = output.split('\n')[0].trim();- info.version = await getCommandVersion('blender');- info.status = 'installed';- return info;- }-- // Check common install locations- const candidates: string[] = [];- switch (process.platform) {- case 'win32':- // Common Windows paths- const programFiles = process.env['ProgramFiles'] || 'C:\\Program Files';- try {- const blenderDir = path.join(programFiles, 'Blender Foundation');- if (fs.existsSync(blenderDir)) {- const versions = fs.readdirSync(blenderDir).sort().reverse();- for (const ver of versions) {- candidates.push(path.join(blenderDir, ver, 'blender.exe'));- }- }- } catch { /* dir doesn't exist */ }- break;- case 'darwin':- candidates.push('/Applications/Blender.app/Contents/MacOS/Blender');- candidates.push('/Applications/Blender.app/Contents/MacOS/blender');- break;- case 'linux':- candidates.push('/usr/bin/blender');- candidates.push('/snap/bin/blender');- candidates.push('/var/lib/flatpak/exports/bin/org.blender.Blender');- break;- }-- for (const candidate of candidates) {- if (fs.existsSync(candidate)) {- info.installedPath = candidate;- try {- const { stdout } = await execAsync(`"${candidate}" --version`, { timeout: 15000 });- info.version = stdout.trim().split('\n')[0];- } catch { /* version check failed but binary exists */ }- info.status = 'installed';- return info;- }- }-- info.status = 'missing';- return info;-}--// ββ uv Detection ββ--async function detectUv(): Promise<DependencyInfo> {- const info: DependencyInfo = {- id: 'uv',- name: 'uv',- description: 'Fast Python package manager β useful for development and managing additional processing tools.',- required: false,- status: 'checking',- version: null,- installedPath: null,- error: null,- };-- const { exists, output } = await commandExists('uv');- if (exists) {- info.installedPath = output.split('\n')[0].trim();- info.version = await getCommandVersion('uv');- info.status = 'installed';- return info;- }-- // Check common uv install locations- const home = os.homedir();- const candidates: string[] = [];- switch (process.platform) {- case 'win32':- candidates.push(path.join(home, '.local', 'bin', 'uv.exe'));- candidates.push(path.join(home, '.cargo', 'bin', 'uv.exe'));- break;- case 'darwin':- case 'linux':- candidates.push(path.join(home, '.local', 'bin', 'uv'));- candidates.push(path.join(home, '.cargo', 'bin', 'uv'));- break;- }-- for (const candidate of candidates) {- if (fs.existsSync(candidate)) {- info.installedPath = candidate;- try {- const { stdout } = await execAsync(`"${candidate}" --version`, { timeout: 10000 });- info.version = stdout.trim();- } catch { /* binary found but version check failed */ }- info.status = 'installed';- return info;- }- }-- info.status = 'missing';- return info;-}--// ββ FreeMoCap Server Executable Detection ββ--async function detectFreemocapServer(): Promise<DependencyInfo> {- const info: DependencyInfo = {- id: 'freemocap-server',- name: 'FreeMoCap Server',- description: 'Bundled Python server that handles cameras, processing, and WebSocket communication.',- required: true,- status: 'checking',- version: null,- installedPath: null,- error: null,- };-- // Use the PythonServer candidate validation to find the exe- try {- const { PythonServer } = await import('./python-server');- const candidates = await PythonServer.validateAllCandidates();- const validCandidate = candidates.find(c => c.isValid);-- if (validCandidate) {- info.status = 'installed';- info.installedPath = validCandidate.path;- info.version = validCandidate.name;- } else {- info.status = 'missing';- info.error = 'No valid freemocap_server executable found. Reinstall the application or build the server.';- }- } catch (err) {- info.status = 'error';- info.error = `Detection failed: ${err instanceof Error ? err.message : String(err)}`;- }-- return info;-}--// ββ CUDA Detection ββ--async function detectCuda(): Promise<DependencyInfo> {- const info: DependencyInfo = {- id: 'cuda',- name: 'NVIDIA CUDA',- description: 'GPU acceleration for pose estimation β dramatically speeds up processing.',- required: false,- status: 'checking',- version: null,- installedPath: null,- error: null,- };-- try {- const { stdout } = await execAsync('nvidia-smi', { timeout: 10000 });- // Parse CUDA version from nvidia-smi output- const cudaMatch = stdout.match(/CUDA Version:\s*([\d.]+)/);- if (cudaMatch) {- info.version = `CUDA ${cudaMatch[1]}`;- info.status = 'installed';- } else {- // nvidia-smi works but CUDA version not found β driver exists, CUDA toolkit may not- const driverMatch = stdout.match(/Driver Version:\s*([\d.]+)/);- info.version = driverMatch ? `Driver ${driverMatch[1]}` : 'Driver detected';- info.status = 'installed';- }- } catch {- info.status = 'missing';- }-- return info;-}--// ββ Installation ββ--async function installBlender(): Promise<void> {- switch (process.platform) {- case 'win32': {- // Try winget first- const { exists: hasWinget } = await commandExists('winget');- if (hasWinget) {- const { stderr } = await execAsync(- 'winget install BlenderFoundation.Blender --silent --accept-package-agreements --accept-source-agreements',- { timeout: 600000 }, // 10 min timeout- );- if (stderr && stderr.includes('error')) {- throw new Error(`winget install failed: ${stderr}`);- }- return;- }- throw new Error(- 'winget is not available. Please install Blender manually from https://www.blender.org/download/',- );- }- case 'darwin': {- const { exists: hasBrew } = await commandExists('brew');- if (hasBrew) {- await execAsync('brew install --cask blender', { timeout: 600000 });- return;- }- throw new Error(- 'Homebrew is not available. Please install Blender manually from https://www.blender.org/download/',- );- }- case 'linux': {- // Try flatpak, then snap- const { exists: hasFlatpak } = await commandExists('flatpak');- if (hasFlatpak) {- await execAsync(- 'flatpak install -y flathub org.blender.Blender',- { timeout: 600000 },- );- return;- }- const { exists: hasSnap } = await commandExists('snap');- if (hasSnap) {- await execAsync('sudo snap install blender --classic', { timeout: 600000 });- return;- }- throw new Error(- 'Neither flatpak nor snap is available. Please install Blender using your package manager.',- );- }- default:- throw new Error(`Unsupported platform: ${process.platform}`);- }-}--async function installUv(): Promise<void> {- switch (process.platform) {- case 'win32':- await execAsync(- `powershell -ExecutionPolicy ByPass -c "irm ${UV_INSTALL_URL_WINDOWS} | iex"`,- { timeout: 120000 },- );- break;- case 'darwin':- case 'linux':- await execAsync(- `curl -LsSf ${UV_INSTALL_URL_UNIX} | sh`,- { timeout: 120000 },- );- break;- default:- throw new Error(`Unsupported platform: ${process.platform}`);- }-}--// ββ Public API ββ--export class DependencyManager {- static async detectAll(): Promise<DependencyInfo[]> {- const results = await Promise.all([- detectFreemocapServer(),- detectUv(),- detectCuda(),- detectBlender(),- ]);- return results;- }-- static async detect(dependencyId: string): Promise<DependencyInfo> {- switch (dependencyId) {- case 'freemocap-server':- return detectFreemocapServer();- case 'uv':- return detectUv();- case 'blender':- return detectBlender();- case 'cuda':- return detectCuda();- default:- throw new Error(`Unknown dependency: ${dependencyId}`);- }- }-- static async install(dependencyId: string): Promise<DependencyInfo> {- switch (dependencyId) {- case 'blender':- await installBlender();- return detectBlender();-- case 'uv':- await installUv();- return detectUv();-- case 'freemocap-server':- throw new Error(- 'The FreeMoCap server executable is bundled with the application. ' +- 'Reinstall the app to restore it.',- );-- case 'cuda':- throw new Error(- 'CUDA cannot be installed automatically. ' +- 'Please install the NVIDIA CUDA Toolkit from https://developer.nvidia.com/cuda-downloads',- );-- default:- throw new Error(`Unknown dependency: ${dependencyId}`);- }- }-}\ No newline at end of filediff --git a/freemocap-ui/electron-old/main/services/logger.ts b/freemocap-ui/electron-old/main/services/logger.tsdeleted file mode 100644index deb6a09f..00000000--- a/freemocap-ui/electron-old/main/services/logger.ts+++ /dev/null@@ -1,23 +0,0 @@-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.tsdeleted file mode 100644index 941730c9..00000000--- a/freemocap-ui/electron-old/main/services/python-server.ts+++ /dev/null@@ -1,294 +0,0 @@-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 filediff --git a/freemocap-ui/electron-old/main/services/system-scanner.ts b/freemocap-ui/electron-old/main/services/system-scanner.tsdeleted file mode 100644index f2c4b163..00000000--- a/freemocap-ui/electron-old/main/services/system-scanner.ts+++ /dev/null@@ -1,389 +0,0 @@-import os from 'node:os';-import fs from 'node:fs';-import path from 'node:path';-import { execFile, exec } from 'node:child_process';-import { promisify } from 'node:util';-import { app } from 'electron';--const execFileAsync = promisify(execFile);-const execAsync = promisify(exec);--// ββ Types ββ--export interface CpuInfo {- model: string;- cores: number;- threads: number;- speedMhz: number;-}--export interface RamInfo {- totalGb: number;- availableGb: number;-}--export interface GpuInfo {- name: string;- vendor: string;- vramMb: number | null;- cudaAvailable: boolean;- cudaVersion: string | null;-}--export interface DiskInfo {- /** The drive/mount where freemocap data lives */- path: string;- totalGb: number;- freeGb: number;-}--export interface OsInfo {- platform: string;- release: string;- arch: string;- hostname: string;-}--export type PerformanceTier = 'basic' | 'standard' | 'advanced' | 'pro';--export interface PerformanceRecommendation {- tier: PerformanceTier;- label: string;- description: string;- maxCameras: number;- maxResolution: string;- realtimeTracking: boolean;- warnings: string[];-}--export interface SystemScanResult {- cpu: CpuInfo;- ram: RamInfo;- gpus: GpuInfo[];- disk: DiskInfo;- os: OsInfo;- recommendation: PerformanceRecommendation;- scannedAt: string;-}--// ββ Scanners ββ--function scanCpu(): CpuInfo {- const cpus = os.cpus();- if (cpus.length === 0) {- throw new Error('Failed to detect CPU info');- }- return {- model: cpus[0].model.trim(),- cores: new Set(cpus.map((_, i) => Math.floor(i / 2))).size || cpus.length,- threads: cpus.length,- speedMhz: cpus[0].speed,- };-}--function scanRam(): RamInfo {- const totalBytes = os.totalmem();- const freeBytes = os.freemem();- return {- totalGb: Math.round((totalBytes / (1024 ** 3)) * 10) / 10,- availableGb: Math.round((freeBytes / (1024 ** 3)) * 10) / 10,- };-}--async function scanGpusWindows(): Promise<GpuInfo[]> {- const gpus: GpuInfo[] = [];-- // Try WMIC first for all GPUs- try {- const { stdout } = await execAsync(- 'wmic path win32_videocontroller get Name,AdapterRAM,DriverVersion /format:csv',- { timeout: 10000 },- );- const lines = stdout.trim().split('\n').filter(l => l.trim().length > 0);- // First line is header: Node,AdapterRAM,DriverVersion,Name- for (let i = 1; i < lines.length; i++) {- const parts = lines[i].split(',');- if (parts.length < 4) continue;- const adapterRam = parseInt(parts[1], 10);- const name = parts[3]?.trim() || 'Unknown GPU';- const isNvidia = name.toLowerCase().includes('nvidia');- const isAmd = name.toLowerCase().includes('amd') || name.toLowerCase().includes('radeon');- gpus.push({- name,- vendor: isNvidia ? 'NVIDIA' : isAmd ? 'AMD' : 'Other',- vramMb: isNaN(adapterRam) ? null : Math.round(adapterRam / (1024 * 1024)),- cudaAvailable: false, // Filled in below- cudaVersion: null,- });- }- } catch {- // WMIC not available or failed- }-- // Try nvidia-smi for CUDA info- try {- const { stdout } = await execAsync(- 'nvidia-smi --query-gpu=name,memory.total,driver_version --format=csv,noheader,nounits',- { timeout: 10000 },- );- const lines = stdout.trim().split('\n');- for (const line of lines) {- const [name, vramMb, driverVersion] = line.split(',').map(s => s.trim());- // Try to find matching GPU from WMIC and enrich it- const existing = gpus.find(g => g.vendor === 'NVIDIA');- if (existing) {- existing.cudaAvailable = true;- existing.cudaVersion = driverVersion || null;- if (vramMb) {- existing.vramMb = parseInt(vramMb, 10);- }- } else {- gpus.push({- name: name || 'NVIDIA GPU',- vendor: 'NVIDIA',- vramMb: vramMb ? parseInt(vramMb, 10) : null,- cudaAvailable: true,- cudaVersion: driverVersion || null,- });- }- }- } catch {- // nvidia-smi not available β no CUDA- }-- return gpus;-}--async function scanGpusMac(): Promise<GpuInfo[]> {- const gpus: GpuInfo[] = [];- try {- const { stdout } = await execAsync(- 'system_profiler SPDisplaysDataType',- { timeout: 10000 },- );- // Parse the output for chipset/VRAM info- const chipsetMatch = stdout.match(/Chipset Model:\s*(.+)/g);- const vramMatch = stdout.match(/VRAM.*?:\s*(\d+)\s*(MB|GB)/gi);- if (chipsetMatch) {- for (let i = 0; i < chipsetMatch.length; i++) {- const name = chipsetMatch[i].replace('Chipset Model:', '').trim();- let vramMb: number | null = null;- if (vramMatch && vramMatch[i]) {- const m = vramMatch[i].match(/(\d+)\s*(MB|GB)/i);- if (m) {- vramMb = parseInt(m[1], 10);- if (m[2].toUpperCase() === 'GB') vramMb *= 1024;- }- }- const isApple = name.toLowerCase().includes('apple');- gpus.push({- name,- vendor: isApple ? 'Apple' : 'Other',- vramMb,- cudaAvailable: false,- cudaVersion: null,- });- }- }- } catch {- // system_profiler failed- }- return gpus;-}--async function scanGpusLinux(): Promise<GpuInfo[]> {- const gpus: GpuInfo[] = [];-- // lspci for GPU detection- try {- const { stdout } = await execAsync(- 'lspci | grep -iE "vga|3d|display"',- { timeout: 10000 },- );- for (const line of stdout.trim().split('\n')) {- if (!line.trim()) continue;- const name = line.replace(/^.*:\s*/, '').trim();- const isNvidia = name.toLowerCase().includes('nvidia');- const isAmd = name.toLowerCase().includes('amd') || name.toLowerCase().includes('radeon');- gpus.push({- name,- vendor: isNvidia ? 'NVIDIA' : isAmd ? 'AMD' : 'Other',- vramMb: null,- cudaAvailable: false,- cudaVersion: null,- });- }- } catch {- // lspci not available- }-- // nvidia-smi for CUDA- try {- const { stdout } = await execAsync(- 'nvidia-smi --query-gpu=name,memory.total,driver_version --format=csv,noheader,nounits',- { timeout: 10000 },- );- const lines = stdout.trim().split('\n');- for (const line of lines) {- const [name, vramMb, driverVersion] = line.split(',').map(s => s.trim());- const existing = gpus.find(g => g.vendor === 'NVIDIA');- if (existing) {- existing.cudaAvailable = true;- existing.cudaVersion = driverVersion || null;- if (vramMb) existing.vramMb = parseInt(vramMb, 10);- } else {- gpus.push({- name: name || 'NVIDIA GPU',- vendor: 'NVIDIA',- vramMb: vramMb ? parseInt(vramMb, 10) : null,- cudaAvailable: true,- cudaVersion: driverVersion || null,- });- }- }- } catch {- // no nvidia-smi- }-- return gpus;-}--async function scanGpus(): Promise<GpuInfo[]> {- switch (process.platform) {- case 'win32': return scanGpusWindows();- case 'darwin': return scanGpusMac();- case 'linux': return scanGpusLinux();- default: return [];- }-}--async function scanDisk(): Promise<DiskInfo> {- const dataDir = path.join(app.getPath('home'), 'freemocap_data');- // Use the drive/mount that the data directory lives on- const targetPath = fs.existsSync(dataDir) ? dataDir : app.getPath('home');-- try {- const stats = fs.statfsSync(targetPath);- const blockSize = stats.bsize;- const totalGb = Math.round((stats.blocks * blockSize) / (1024 ** 3) * 10) / 10;- const freeGb = Math.round((stats.bavail * blockSize) / (1024 ** 3) * 10) / 10;- return { path: targetPath, totalGb, freeGb };- } catch {- // statfsSync not available (very old Node) β return unknowns- return { path: targetPath, totalGb: 0, freeGb: 0 };- }-}--function scanOs(): OsInfo {- return {- platform: process.platform,- release: os.release(),- arch: os.arch(),- hostname: os.hostname(),- };-}--// ββ Performance Recommendation ββ--function computeRecommendation(- cpu: CpuInfo,- ram: RamInfo,- gpus: GpuInfo[],- disk: DiskInfo,-): PerformanceRecommendation {- const warnings: string[] = [];- const bestGpu = gpus.reduce<GpuInfo | null>((best, gpu) => {- if (!best) return gpu;- if (gpu.cudaAvailable && !best.cudaAvailable) return gpu;- if ((gpu.vramMb ?? 0) > (best.vramMb ?? 0)) return gpu;- return best;- }, null);-- const hasCuda = bestGpu?.cudaAvailable ?? false;- const vramMb = bestGpu?.vramMb ?? 0;-- // Disk warnings- if (disk.freeGb > 0 && disk.freeGb < 20) {- warnings.push(`Low disk space: ${disk.freeGb} GB free. Recordings can use 1-5 GB each.`);- }-- // RAM warnings- if (ram.totalGb < 8) {- warnings.push('Less than 8 GB RAM β performance may be limited even with few cameras.');- }-- // GPU warnings- if (gpus.length === 0) {- warnings.push('No dedicated GPU detected. Real-time pose tracking will not be available.');- } else if (!hasCuda) {- warnings.push('No NVIDIA GPU with CUDA detected. Mediapipe GPU acceleration will be unavailable.');- }-- // Tier computation- let tier: PerformanceTier;- let label: string;- let description: string;- let maxCameras: number;- let maxResolution: string;- let realtimeTracking: boolean;-- if (cpu.threads >= 12 && ram.totalGb >= 32 && hasCuda && vramMb >= 8000) {- tier = 'pro';- label = 'Pro';- description = 'Excellent system. Handles large multi-camera setups with real-time tracking and post-processing.';- maxCameras = 8;- maxResolution = '1080p';- realtimeTracking = true;- } else if (cpu.threads >= 8 && ram.totalGb >= 16 && hasCuda && vramMb >= 4000) {- tier = 'advanced';- label = 'Advanced';- description = 'Strong system. Supports several cameras with real-time tracking.';- maxCameras = 5;- maxResolution = '1080p';- realtimeTracking = true;- } else if (cpu.threads >= 4 && ram.totalGb >= 12) {- tier = 'standard';- label = 'Standard';- description = 'Good for multi-camera recording with offline processing.';- maxCameras = 3;- maxResolution = '720p';- realtimeTracking = false;- if (!hasCuda) {- warnings.push('Pose estimation will run on CPU β processing will be slower but functional.');- }- } else {- tier = 'basic';- label = 'Basic';- description = 'Can record from one or two cameras. Processing will be slow.';- maxCameras = 2;- maxResolution = '720p';- realtimeTracking = false;- }-- return { tier, label, description, maxCameras, maxResolution, realtimeTracking, warnings };-}--// ββ Public API ββ--export class SystemScanner {- static async scan(): Promise<SystemScanResult> {- const [cpu, ram, gpus, disk] = await Promise.all([- scanCpu(),- scanRam(),- scanGpus(),- scanDisk(),- ]);- const osInfo = scanOs();- const recommendation = computeRecommendation(cpu, ram, gpus, disk);-- return {- cpu,- ram,- gpus,- disk,- os: osInfo,- recommendation,- scannedAt: new Date().toISOString(),- };- }-}diff --git a/freemocap-ui/electron-old/main/services/update-handler.ts b/freemocap-ui/electron-old/main/services/update-handler.tsdeleted file mode 100644index 35bb6182..00000000--- a/freemocap-ui/electron-old/main/services/update-handler.ts+++ /dev/null@@ -1,72 +0,0 @@--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.tsdeleted file mode 100644index 1e2f219a..00000000--- a/freemocap-ui/electron-old/main/services/window-manager.ts+++ /dev/null@@ -1,103 +0,0 @@-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.tsdeleted file mode 100644index 2096156c..00000000--- a/freemocap-ui/electron-old/preload/index.ts+++ /dev/null@@ -1,17 +0,0 @@-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);- };- },-});