/* Atlus — Core shell: app switching, WebSocket stats, panel updates */ (function () { 'use strict'; // ===================================================================== // Auth guard // ===================================================================== const TOKEN = localStorage.getItem('atlus_token'); const USER = localStorage.getItem('atlus_user'); if (!TOKEN) { window.location.href = '/'; return; } // ===================================================================== // Globals // ===================================================================== window.Atlus = { token: TOKEN, user: USER, apps: {}, // registered app modules { id: { init, destroy, title } } openApps: [], // ordered list of open app ids activeApp: null, // currently focused app id layout: 'single', // 'single' | 'split' secondaryApp: null, /** Authenticated fetch wrapper */ async apiFetch(url, opts = {}) { opts.headers = Object.assign({ 'Authorization': `Bearer ${TOKEN}` }, opts.headers || {}); if (opts.body && typeof opts.body === 'object' && !(opts.body instanceof FormData)) { opts.headers['Content-Type'] = 'application/json'; opts.body = JSON.stringify(opts.body); } const res = await fetch(url, opts); if (res.status === 401) { localStorage.removeItem('atlus_token'); localStorage.removeItem('atlus_user'); window.location.href = '/'; return; } return res; }, /** Create an authenticated WebSocket URL */ wsUrl(path) { const proto = location.protocol === 'https:' ? 'wss:' : 'ws:'; const sep = path.includes('?') ? '&' : '?'; return `${proto}//${location.host}${path}${sep}token=${TOKEN}`; }, /** Register an app module */ registerApp(id, module) { this.apps[id] = module; }, /** Format bytes to human readable */ formatBytes(bytes) { if (bytes === 0) return '0 B'; const k = 1024; const sizes = ['B', 'KB', 'MB', 'GB', 'TB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]; }, }; // ===================================================================== // DOM refs // ===================================================================== const $ = (sel) => document.querySelector(sel); const $$ = (sel) => document.querySelectorAll(sel); const stageTabs = $('#stageTabs'); const paneA = $('#paneContentA'); const paneB = $('#paneContentB'); const paneTitleA = $('#paneTitleA'); const paneTitleB = $('#paneTitleB'); const paneBEl = $('#paneB'); const welcomeScreen = $('#welcomeScreen'); // ===================================================================== // App switching // ===================================================================== function openApp(appId) { const app = Atlus.apps[appId]; if (!app) return; // Already open — just focus if (Atlus.openApps.includes(appId)) { focusApp(appId); return; } Atlus.openApps.push(appId); addTab(appId, app.title || appId); // Create app container const container = document.createElement('div'); container.className = 'app-view'; container.id = `app-${appId}`; container.style.display = 'none'; paneA.appendChild(container); // Initialize app if (app.init) app.init(container); focusApp(appId); saveDesktopState(); } function focusApp(appId) { if (welcomeScreen) welcomeScreen.style.display = 'none'; // Hide all apps in pane A paneA.querySelectorAll('.app-view').forEach(el => el.style.display = 'none'); // Show target const target = $(`#app-${appId}`); if (target) target.style.display = 'flex'; // Update tabs stageTabs.querySelectorAll('.stage-tab').forEach(tab => { tab.classList.toggle('active', tab.dataset.app === appId); }); // Update dock $$('.dock-item[data-app]').forEach(item => { item.classList.toggle('active', item.dataset.app === appId); }); // Update titlebar const app = Atlus.apps[appId]; paneTitleA.textContent = app ? app.title : appId; Atlus.activeApp = appId; // Notify app it got focus if (app && app.onFocus) app.onFocus(); saveDesktopState(); } function closeApp(appId) { const app = Atlus.apps[appId]; if (app && app.destroy) app.destroy(); // Remove DOM const container = $(`#app-${appId}`); if (container) container.remove(); // Remove from open list Atlus.openApps = Atlus.openApps.filter(id => id !== appId); // Remove tab const tab = stageTabs.querySelector(`.stage-tab[data-app="${appId}"]`); if (tab) tab.remove(); // Update dock const dockItem = $(`.dock-item[data-app="${appId}"]`); if (dockItem) dockItem.classList.remove('active'); // Focus next app or show welcome if (Atlus.activeApp === appId) { if (Atlus.openApps.length > 0) { focusApp(Atlus.openApps[Atlus.openApps.length - 1]); } else { Atlus.activeApp = null; paneTitleA.textContent = ''; if (welcomeScreen) welcomeScreen.style.display = 'flex'; } } saveDesktopState(); } function addTab(appId, title) { const tab = document.createElement('button'); tab.className = 'stage-tab'; tab.dataset.app = appId; tab.innerHTML = `${title}×`; tab.addEventListener('click', (e) => { if (e.target.classList.contains('tab-close')) { closeApp(appId); } else { focusApp(appId); } }); stageTabs.appendChild(tab); } // ===================================================================== // Dock clicks // ===================================================================== $$('.dock-item[data-app]').forEach(item => { item.addEventListener('click', () => openApp(item.dataset.app)); }); // Layout toggle $$('.layout-btn').forEach(btn => { btn.addEventListener('click', () => { const layout = btn.dataset.layout; Atlus.layout = layout; $$('.layout-btn').forEach(b => b.classList.toggle('active', b.dataset.layout === layout)); paneBEl.classList.toggle('hidden', layout === 'single'); }); }); // ===================================================================== // System menu // ===================================================================== const systemMenu = $('#systemMenu'); const logoBtn = $('.dock-logo'); logoBtn.addEventListener('click', () => { systemMenu.classList.toggle('hidden'); }); systemMenu.addEventListener('click', async (e) => { const action = e.target.dataset.action; if (!action) { // Clicked backdrop if (e.target === systemMenu) systemMenu.classList.add('hidden'); return; } systemMenu.classList.add('hidden'); if (action === 'logout') { await Atlus.apiFetch('/api/auth/logout', { method: 'POST' }); localStorage.removeItem('atlus_token'); localStorage.removeItem('atlus_user'); window.location.href = '/'; } }); // ===================================================================== // Panel — Clock // ===================================================================== function updateClock() { const now = new Date(); $('#panelDate').textContent = now.toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' }); $('#panelTime').textContent = now.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: false }); } updateClock(); setInterval(updateClock, 1000); // ===================================================================== // Panel — WebSocket stats // ===================================================================== let statsWs = null; function connectStats() { statsWs = new WebSocket(Atlus.wsUrl('/api/stats/ws')); statsWs.onmessage = (e) => { const data = JSON.parse(e.data); updatePanel(data); }; statsWs.onclose = () => { setTimeout(connectStats, 3000); }; statsWs.onerror = () => { statsWs.close(); }; } function updatePanel(data) { // CPU const cpuPct = Math.round(data.cpu_percent); $('#statCpu').textContent = cpuPct + '%'; updateBar($('#statCpuBar'), cpuPct); // Memory const memPct = Math.round(data.memory.percent); const memUsed = Atlus.formatBytes(data.memory.used); const memTotal = Atlus.formatBytes(data.memory.total); $('#statMem').textContent = `${memUsed} / ${memTotal}`; updateBar($('#statMemBar'), memPct); // Disk const diskPct = Math.round(data.disk.percent); $('#statDisk').textContent = diskPct + '%'; updateBar($('#statDiskBar'), diskPct); // Temp if (data.cpu_temp !== null) { const temp = Math.round(data.cpu_temp); $('#statTemp').textContent = temp + '\u00B0C'; // Temp bar: 0-85°C range const tempPct = Math.min(100, Math.round((temp / 85) * 100)); updateBar($('#statTempBar'), tempPct); } // Network const netContainer = $('#panelNetwork'); netContainer.innerHTML = ''; const ifaces = data.network.interfaces; for (const [name, info] of Object.entries(ifaces)) { const item = document.createElement('div'); item.className = 'panel-net-item'; item.innerHTML = ` ${name} ${info.ipv4 || '--'} `; netContainer.appendChild(item); } } function updateBar(barEl, percent) { barEl.style.width = percent + '%'; barEl.className = 'stat-bar-fill'; if (percent >= 90) barEl.classList.add('crit'); else if (percent >= 70) barEl.classList.add('warn'); } // ===================================================================== // Panel — Hostname // ===================================================================== async function loadHostname() { try { const res = await Atlus.apiFetch('/api/settings/system'); if (res.ok) { const data = await res.json(); $('#panelHostname').textContent = data.hostname; } } catch (e) { /* ignore */ } } // ===================================================================== // Panel — Applications (docked GUI apps) // ===================================================================== async function loadPanelApps() { const container = $('#panelApps'); if (!container) return; let guiApps = []; let runningApps = []; try { const cfgRes = await Atlus.apiFetch('/api/settings'); if (cfgRes && cfgRes.ok) { const cfg = await cfgRes.json(); guiApps = cfg.gui_apps || []; } } catch (e) { console.warn('Panel apps: failed to load config', e); } try { const runRes = await Atlus.apiFetch('/api/display/apps'); if (runRes && runRes.ok) runningApps = await runRes.json(); } catch (e) { /* display may be unavailable */ } // Ensure all GUI apps are registered as Atlus app modules for (const app of guiApps) { try { const appId = 'gui-' + app.id; if (!Atlus.apps[appId] && window._atlusRegisterGuiApp) { window._atlusRegisterGuiApp(app); } } catch (e) { console.warn('Panel apps: failed to register', app.id, e); } } // Clear and rebuild — always append Add button at the end container.innerHTML = ''; if (guiApps.length === 0) { const empty = document.createElement('div'); empty.style.cssText = 'color:var(--text-muted);font-size:12px;font-family:var(--font-mono);padding:4px 0;'; empty.textContent = 'No apps configured'; container.appendChild(empty); } else { for (const app of guiApps) { try { const running = Array.isArray(runningApps) ? runningApps.find(r => r.command === app.command && r.alive) : null; const row = document.createElement('div'); row.className = 'panel-app-row'; const args = Array.isArray(app.args) ? app.args.join(' ') : ''; row.innerHTML = `
${app.name || app.command} `; // Click name/icon to open in tab row.querySelector('.panel-app-name').addEventListener('click', () => { openApp('gui-' + app.id); }); row.querySelector('.panel-app-icon').addEventListener('click', () => { openApp('gui-' + app.id); }); // Action button (launch/stop) const actionBtn = row.querySelector('.panel-app-action'); actionBtn.addEventListener('click', async (e) => { e.stopPropagation(); const isRunning = actionBtn.classList.contains('stop'); actionBtn.disabled = true; try { if (isRunning) { const id = actionBtn.dataset.appId; if (id) await Atlus.apiFetch(`/api/display/apps/${id}`, { method: 'DELETE' }); } else { const a = actionBtn.dataset.args ? actionBtn.dataset.args.split(' ').filter(Boolean) : []; await Atlus.apiFetch('/api/display/apps', { method: 'POST', body: { command: actionBtn.dataset.command, title: actionBtn.dataset.title, args: a, target_fps: parseInt(actionBtn.dataset.fps) || 10, }, }); } } catch (err) { console.warn('Panel app action failed', err); } setTimeout(loadPanelApps, 1500); }); container.appendChild(row); } catch (e) { console.warn('Panel apps: failed to render', app.id, e); } } } // Add App button — ALWAYS appended, regardless of errors above const addBtn = document.createElement('button'); addBtn.className = 'panel-app-add'; addBtn.textContent = '+ Add'; addBtn.addEventListener('click', () => { openApp('settings'); setTimeout(() => { const navItem = document.querySelector('.settings-nav-item[data-section="applications"]'); if (navItem) navItem.click(); }, 200); }); container.appendChild(addBtn); } // ===================================================================== // Panel — Update checker // ===================================================================== async function checkForUpdates() { const panel = $('#panelUpdates'); if (!panel) return; try { const res = await Atlus.apiFetch('/api/updates/check'); if (!res || !res.ok) { // Show error state if endpoint fails (503 = git not found, etc.) panel.classList.remove('hidden'); const status = res ? res.status : 0; const detail = res ? await res.json().catch(() => ({})) : {}; panel.innerHTML = `