// NEXUS Operating System Core class NexusOS { constructor() { this.windows = []; this.processes = []; this.system = { cpuUsage: 0, memoryUsage: 0, diskUsage: 0, networkSpeed: { up: 0, down: 0 }, batteryLevel: 100 }; this.applications = { 'terminal': { title: 'NEXUS Terminal', icon: 'fas fa-terminal', content: '
', width: 600, height: 400, onOpen: this.initTerminal.bind(this), permissions: ['system_access'] }, 'quantum-explorer': { title: 'Quantum Explorer', icon: 'fas fa-project-diagram', content: '
', width: 800, height: 500, onOpen: this.initFileExplorer.bind(this), permissions: ['filesystem_read'] }, 'kernel-control': { title: 'Kernel Control', icon: 'fas fa-sliders-h', content: '
', width: 700, height: 600, onOpen: this.initSettings.bind(this), permissions: ['system_admin'] }, 'quantum-browser': { title: 'Quantum Browser', icon: 'fas fa-network-wired', content: '
', width: 1024, height: 768, onOpen: this.initBrowser.bind(this), permissions: ['network_access'] }, 'quantum-processor': { title: 'Quantum Processor', icon: 'fas fa-atom', content: '
PIDNameCPUMemoryActions
', width: 800, height: 500, onOpen: this.initProcessManager.bind(this), permissions: ['system_admin'] }, 'quantum-ide': { title: 'Quantum IDE', icon: 'fas fa-code', content: '
', width: 900, height: 600, onOpen: this.initCodeEditor.bind(this), permissions: ['filesystem_write'] }, 'holographic-player': { title: 'Holographic Player', icon: 'fas fa-vr-cardboard', content: '
', width: 800, height: 500, onOpen: this.initMediaPlayer.bind(this), permissions: ['filesystem_read'] } }; this.init(); } init() { // Initialize system monitoring this.updateSystemStats(); setInterval(this.updateSystemStats.bind(this), 2000); // Initialize clock this.updateClock(); setInterval(this.updateClock.bind(this), 1000); // Initialize network monitoring this.initNetworkMonitor(); // Initialize battery monitoring this.initBatteryMonitor(); // Initialize desktop context menu this.initDesktopContextMenu(); // Initialize start menu this.initStartMenu(); // Initialize file system this.initVirtualFileSystem(); // Initialize system processes this.spawnSystemProcess('system-monitor'); this.spawnSystemProcess('network-service'); this.spawnSystemProcess('notification-service'); // Initialize sample apps setTimeout(() => { this.createNotification('System', 'QuantumOS Hypervisor initialized successfully', 'info'); // Start background services this.startBackgroundServices(); }, 1000); } updateClock() { const now = new Date(); const timeStr = now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); const dateStr = now.toLocaleDateString([], { month: 'short', day: 'numeric' }); document.getElementById('clock').textContent = `${timeStr} | ${dateStr}`; } initDesktopContextMenu() { document.getElementById('desktop').addEventListener('contextmenu', (e) => { e.preventDefault(); this.showContextMenu(e.clientX, e.clientY, [ { text: 'New Terminal', icon: 'fas fa-terminal', action: () => this.openApp('terminal') }, { text: 'New Window', icon: 'fas fa-window-maximize', action: () => this.createWindow('Untitled', '', 400, 300) }, { separator: true }, { text: 'Refresh', icon: 'fas fa-sync-alt', action: () => location.reload() }, { text: 'Settings', icon: 'fas fa-cog', action: () => this.openApp('settings') } ]); }); } initStartMenu() { const startButton = document.getElementById('start-button'); const startMenu = document.getElementById('start-menu-content'); startButton.addEventListener('click', (e) => { e.stopPropagation(); startMenu.classList.toggle('hidden'); }); // Populate start menu startMenu.innerHTML = Object.entries(this.applications).map(([id, app]) => `
${app.title}
`).join(''); // Close menu when clicking elsewhere document.addEventListener('click', () => startMenu.classList.add('hidden')); } openApp(appId) { const app = this.applications[appId]; if (!app) return; const window = this.createWindow( app.title, app.content, app.width, app.height, app.icon ); if (app.onOpen) app.onOpen(window); } createWindow(title, content, width, height, icon) { const windowId = 'window-' + Math.random().toString(36).substr(2, 9); const windowElement = document.createElement('div'); windowElement.className = 'window hidden'; windowElement.style.width = width + 'px'; windowElement.style.height = height + 'px'; windowElement.id = windowId; windowElement.innerHTML = `
${icon ? `` : ''} ${title}
_
□
×
${content}
`; document.getElementById('window-manager').appendChild(windowElement); // Position window initially at center with slight random offset const left = Math.max(100, (window.innerWidth - width) / 2 + (Math.random() * 100 - 50)); const top = Math.max(50, (window.innerHeight - height) / 2 + (Math.random() * 100 - 50)); windowElement.style.left = left + 'px'; windowElement.style.top = top + 'px'; // Make window draggable this.makeDraggable(windowElement); // Add window controls const closeBtn = windowElement.querySelector('.window-close'); const minimizeBtn = windowElement.querySelector('.window-minimize'); const maximizeBtn = windowElement.querySelector('.window-maximize'); closeBtn.addEventListener('click', () => { windowElement.style.transform = 'scale(0.8)'; windowElement.style.opacity = '0'; setTimeout(() => windowElement.remove(), 300); }); minimizeBtn.addEventListener('click', () => { windowElement.classList.add('minimized'); }); maximizeBtn.addEventListener('click', () => { windowElement.classList.toggle('maximized'); if (windowElement.classList.contains('maximized')) { windowElement.style.width = 'calc(100% - 20px)'; windowElement.style.height = 'calc(100% - 80px)'; windowElement.style.top = '10px'; windowElement.style.left = '10px'; } else { windowElement.style.width = width + 'px'; windowElement.style.height = height + 'px'; windowElement.style.top = top + 'px'; windowElement.style.left = left + 'px'; } }); // Show window with animation setTimeout(() => { windowElement.classList.remove('hidden'); }, 10); // Add to windows list this.windows.push({ id: windowId, element: windowElement, title: title }); return windowElement; } makeDraggable(element) { const titlebar = element.querySelector('.window-titlebar'); let isDragging = false; let offsetX, offsetY; titlebar.addEventListener('mousedown', (e) => { if (e.target.classList.contains('window-control')) return; isDragging = true; offsetX = e.clientX - element.getBoundingClientRect().left; offsetY = e.clientY - element.getBoundingClientRect().top; element.style.zIndex = 999; }); document.addEventListener('mousemove', (e) => { if (!isDragging) return; let left = e.clientX - offsetX; let top = e.clientY - offsetY; // Boundary checking left = Math.max(0, Math.min(left, window.innerWidth - element.offsetWidth)); top = Math.max(0, Math.min(top, window.innerHeight - element.offsetHeight)); element.style.left = left + 'px'; element.style.top = top + 'px'; }); document.addEventListener('mouseup', () => { isDragging = false; }); } showContextMenu(x, y, items) { // Remove existing context menu const existingMenu = document.querySelector('.context-menu'); if (existingMenu) existingMenu.remove(); // Create new context menu const menu = document.createElement('div'); menu.className = 'context-menu'; menu.style.left = x + 'px'; menu.style.top = y + 'px'; // Add items to menu items.forEach(item => { if (item.separator) { const separator = document.createElement('div'); separator.className = 'border-t border-gray-600 my-1'; menu.appendChild(separator); } else { const menuItem = document.createElement('div'); menuItem.className = 'context-menu-item flex items-center space-x-2'; menuItem.innerHTML = ` ${item.text} `; menuItem.addEventListener('click', item.action); menu.appendChild(menuItem); } }); document.body.appendChild(menu); // Close menu when clicking elsewhere const closeMenu = () => { menu.remove(); document.removeEventListener('click', closeMenu); }; setTimeout(() => { document.addEventListener('click', closeMenu); }, 100); } createNotification(title, message, type = 'info') { const notification = document.createElement('div'); notification.className = 'notification'; notification.innerHTML = `

${title}

${message}

`; const notificationCenter = document.getElementById('notification-center'); notificationCenter.classList.remove('hidden'); notificationCenter.insertBefore(notification, notificationCenter.firstChild); // Auto-remove after 5 seconds setTimeout(() => { notification.style.animation = 'fadeOut 0.3s forwards'; setTimeout(() => notification.remove(), 300); }, 5000); // Close button notification.querySelector('.close-btn').addEventListener('click', () => { notification.style.animation = 'fadeOut 0.3s forwards'; setTimeout(() => notification.remove(), 300); }); } initTerminal(windowElement) { const terminal = windowElement.querySelector('.terminal'); const commandHistory = []; let historyIndex = -1; // Register as system process const pid = this.spawnProcess('terminal', windowElement); // Initial prompt this.addTerminalLine(terminal, 'Quantum Terminal v1.1.0'); this.addTerminalLine(terminal, 'Connected to QuantumOS Kernel'); this.addTerminalLine(terminal, 'System resources: ' + `CPU: ${this.system.cpuUsage}% | ` + `RAM: ${this.system.memoryUsage}% | ` + `DISK: ${this.system.diskUsage}%`); this.addTerminalLine(terminal, 'Type "help" for available commands'); this.addTerminalLine(terminal, 'Type "man " for detailed help'); this.addPrompt(terminal); terminal.addEventListener('click', () => { const input = terminal.querySelector('.terminal-input:last-child'); if (input) input.focus(); }); terminal.addEventListener('keydown', (e) => { const input = terminal.querySelector('.terminal-input:last-child'); if (!input) return; // Handle up/down for command history if (e.key === 'ArrowUp' && commandHistory.length > 0) { e.preventDefault(); historyIndex = Math.min(historyIndex + 1, commandHistory.length - 1); input.textContent = commandHistory[historyIndex]; placeCaretAtEnd(input); } else if (e.key === 'ArrowDown' && commandHistory.length > 0) { e.preventDefault(); historyIndex = Math.max(historyIndex - 1, -1); input.textContent = historyIndex >= 0 ? commandHistory[historyIndex] : ''; placeCaretAtEnd(input); } else if (e.key === 'Enter') { e.preventDefault(); const command = input.textContent.trim(); if (command) { commandHistory.unshift(command); historyIndex = -1; this.processCommand(terminal, command); } this.addPrompt(terminal); } }); function placeCaretAtEnd(el) { el.focus(); const range = document.createRange(); range.selectNodeContents(el); range.collapse(false); const sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); } } addTerminalLine(terminal, text) { const line = document.createElement('div'); line.className = 'terminal-line'; line.textContent = text; terminal.appendChild(line); terminal.scrollTop = terminal.scrollHeight; } addPrompt(terminal) { const prompt = document.createElement('div'); prompt.className = 'terminal-input'; prompt.innerHTML = ` $ `; prompt.setAttribute('contenteditable', 'true'); terminal.appendChild(prompt); prompt.focus(); terminal.scrollTop = terminal.scrollHeight; } processCommand(terminal, command) { this.addTerminalLine(terminal, `$ ${command}`); const parts = command.split(' ').filter(p => p); const cmd = parts[0].toLowerCase(); const args = parts.slice(1); try { switch (cmd) { case 'help': case '?': this.addTerminalLine(terminal, 'Available commands:'); this.addTerminalLine(terminal, ' help/? - Show this help'); this.addTerminalLine(terminal, ' man - Command manual'); this.addTerminalLine(terminal, ' clear/cls - Clear terminal'); this.addTerminalLine(terminal, ' echo - Print text'); this.addTerminalLine(terminal, ' time/date - Show current time/date'); this.addTerminalLine(terminal, ' apps - List available applications'); this.addTerminalLine(terminal, ' ps - List running processes'); this.addTerminalLine(terminal, ' kill - Terminate process'); this.addTerminalLine(terminal, ' sysinfo - Show system information'); this.addTerminalLine(terminal, ' mkdir - Create directory'); this.addTerminalLine(terminal, ' ls - List files'); this.addTerminalLine(terminal, ' cd - Change directory'); this.addTerminalLine(terminal, ' cat - Show file contents'); break; case 'man': if (args.length === 0) { this.addTerminalLine(terminal, 'Usage: man '); break; } const manCmd = args[0].toLowerCase(); this.showManualPage(terminal, manCmd); break; case 'clear': case 'cls': terminal.innerHTML = ''; break; case 'echo': this.addTerminalLine(terminal, args.join(' ')); break; case 'time': case 'date': this.addTerminalLine(terminal, new Date().toLocaleString()); break; case 'apps': this.addTerminalLine(terminal, 'Available applications:'); Object.entries(this.applications).forEach(([id, app]) => { this.addTerminalLine(terminal, ` ${id} - ${app.title} [${app.permissions.join(', ')}]`); }); break; case 'ps': this.addTerminalLine(terminal, 'Running processes:'); this.addTerminalLine(terminal, 'PID\tName\t\tCPU\tMemory'); this.processes.forEach(proc => { this.addTerminalLine(terminal, `${proc.pid}\t${proc.name}\t${proc.cpuUsage || 0}%\t${proc.memoryUsage || 0}MB`); }); break; case 'kill': if (args.length === 0) { this.addTerminalLine(terminal, 'Usage: kill '); break; } const pid = parseInt(args[0]); this.terminateProcess(pid, terminal); break; case 'sysinfo': this.addTerminalLine(terminal, 'System Information:'); this.addTerminalLine(terminal, `QuantumOS v1.1.0`); this.addTerminalLine(terminal, `CPU: ${this.system.cpuUsage}% usage`); this.addTerminalLine(terminal, `Memory: ${this.system.memoryUsage}% of ${this.totalMemory}MB used`); this.addTerminalLine(terminal, `Disk: ${this.system.diskUsage}% used`); this.addTerminalLine(terminal, `Network: ↑${this.system.networkSpeed.up}KB/s ↓${this.system.networkSpeed.down}KB/s`); this.addTerminalLine(terminal, `Battery: ${this.system.batteryLevel}%`); this.addTerminalLine(terminal, `Processes: ${this.processes.length} running`); break; case 'mkdir': if (args.length === 0) { this.addTerminalLine(terminal, 'Usage: mkdir '); break; } this.createDirectory(args[0], terminal); break; case 'ls': this.listFiles(args[0] || '.', terminal); break; case 'cd': if (args.length === 0) { this.addTerminalLine(terminal, 'Usage: cd '); break; } this.changeDirectory(args[0], terminal); break; case 'cat': if (args.length === 0) { this.addTerminalLine(terminal, 'Usage: cat '); break; } this.showFileContents(args[0], terminal); break; default: this.addTerminalLine(terminal, `Command not found: ${cmd}`); } } catch (err) { this.addTerminalLine(terminal, `Error: ${err.message}`); } } } // System process management spawnProcess(name, windowElement = null) { const pid = Math.floor(Math.random() * 10000) + 1000; this.processes.push({ pid, name, window: windowElement, cpuUsage: 0, memoryUsage: Math.floor(Math.random() * 50) + 10, startTime: new Date() }); return pid; } spawnSystemProcess(name) { return this.spawnProcess(name); } terminateProcess(pid, terminal = null) { const index = this.processes.findIndex(p => p.pid === pid); if (index === -1) { if (terminal) this.addTerminalLine(terminal, `Process ${pid} not found`); return false; } const process = this.processes[index]; if (process.window) { process.window.remove(); } this.processes.splice(index, 1); if (terminal) this.addTerminalLine(terminal, `Terminated process ${pid} (${process.name})`); return true; } // Virtual file system initVirtualFileSystem() { this.fileSystem = { '/': { type: 'directory', children: { 'home': { type: 'directory', children: { 'user': { type: 'directory', children: { 'documents': { type: 'directory', children: {} }, 'downloads': { type: 'directory', children: {} }, 'desktop': { type: 'directory', children: {} } } } } }, 'system': { type: 'directory', children: { 'logs': { type: 'directory', children: {} }, 'config': { type: 'directory', children: { 'system.cfg': { type: 'file', content: 'system.version=1.1.0\nsystem.name=QuantumOS' } } } } } } } }; this.currentDirectory = '/home/user'; } createDirectory(name, terminal) { const path = this.resolvePath(name); if (path.type === 'directory') { this.addTerminalLine(terminal, `Directory already exists: ${name}`); return; } const parent = this.getParentDirectory(name); if (!parent) { this.addTerminalLine(terminal, `Invalid path: ${name}`); return; } const dirName = this.getLastPathComponent(name); parent.children[dirName] = { type: 'directory', children: {} }; this.addTerminalLine(terminal, `Created directory: ${name}`); } listFiles(path, terminal) { const targetPath = path ? this.resolvePath(path) : this.resolvePath(this.currentDirectory); if (!targetPath || targetPath.type !== 'directory') { this.addTerminalLine(terminal, `No such directory: ${path}`); return; } this.addTerminalLine(terminal, `Contents of ${path || '.'}:`); Object.keys(targetPath.children).forEach(name => { const item = targetPath.children[name]; this.addTerminalLine(terminal, ` ${name}${item.type === 'directory' ? '/' : ''}`); }); } // System monitoring updateSystemStats() { // Simulate system resource usage this.system = { cpuUsage: Math.min(100, Math.max(5, Math.floor(Math.random() * 40) + 5)), memoryUsage: Math.min(100, Math.max(10, Math.floor(Math.random() * 60) + 10)), diskUsage: Math.min(100, Math.max(5, Math.floor(Math.random() * 30) + 5)), networkSpeed: { up: Math.floor(Math.random() * 1000), down: Math.floor(Math.random() * 5000) }, batteryLevel: this.system.batteryLevel > 0 ? Math.max(0, this.system.batteryLevel - (Math.random() * 2)) : 0 }; // Update process stats this.processes.forEach(proc => { proc.cpuUsage = Math.floor(Math.random() * 10); }); } initNetworkMonitor() { setInterval(() => { // Simulate network status changes if (Math.random() > 0.95) { this.createNotification('Network', 'Network connection lost', 'warning'); } else if (Math.random() > 0.9) { this.createNotification('Network', 'Network connection restored', 'success'); } }, 30000); } initBatteryMonitor() { setInterval(() => { if (this.system.batteryLevel < 20) { this.createNotification('Battery', `Low battery: ${this.system.batteryLevel}% remaining`, 'warning'); } else if (this.system.batteryLevel < 5) { this.createNotification('Battery', `Critical battery: ${this.system.batteryLevel}% remaining`, 'error'); } }, 60000); } // Quantum Boot Sequence Components class QuantumBootLoader { constructor() { this.steps = [ { name: "Quantum Coherence Check", duration: 1500 }, { name: "Temporal Synchronization", duration: 2000 }, { name: "Neural Network Initialization", duration: 2500 }, { name: "Biosynth Interface Activation", duration: 1800 }, { name: "Consensus Protocol Handshake", duration: 3000 } ]; this.currentStep = 0; } async start() { const bootScreen = document.createElement('div'); bootScreen.id = 'quantum-boot'; bootScreen.innerHTML = `
Press Q + Enter to initialize hypervisor
`; document.body.appendChild(bootScreen); // Wait for Q+Enter return new Promise((resolve) => { const handler = (e) => { if (e.key.toLowerCase() === 'q' && e.keyCode === 13) { e.preventDefault(); document.removeEventListener('keydown', handler); this.runBootSequence().then(resolve); } }; document.addEventListener('keydown', handler); }); } async runBootSequence() { const progressBar = document.querySelector('.boot-progress .progress-bar'); const stepInfo = document.querySelector('.boot-progress .step-info'); for (const [index, step] of this.steps.entries()) { this.currentStep = index; const progress = (index / this.steps.length) * 100; progressBar.style.width = `${progress}%`; stepInfo.textContent = `[${index+1}/${this.steps.length}] ${step.name}...`; // Simulate quantum fluctuations await this.quantumFluctuation(step.duration); } // Complete boot progressBar.style.width = '100%'; stepInfo.textContent = 'Quantum state stabilized - Ready'; await new Promise(r => setTimeout(r, 1000)); document.getElementById('quantum-boot').remove(); } quantumFluctuation(duration) { return new Promise(resolve => { const interval = setInterval(() => { // Add quantum randomness const currentProgress = document.querySelector('.progress-bar').style.width; const currentWidth = parseFloat(currentProgress) || 0; const fluctuation = (Math.random() * 5) - 2.5; document.querySelector('.progress-bar').style.width = `${Math.min(100, Math.max(0, currentWidth + fluctuation))}%`; }, 300); setTimeout(() => { clearInterval(interval); resolve(); }, duration); }); } } // Initialize OS with quantum boot sequence document.addEventListener('DOMContentLoaded', async () => { const bootLoader = new QuantumBootLoader(); await bootLoader.start(); window.os = new QuantumOS(); os.createNotification('System', 'QuantumOS Hypervisor online', 'success'); }); // Register global error handler window.addEventListener('error', (e) => { window.os.createNotification('System Error', e.message, 'error'); console.error(e); }); });