#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] use std::path::PathBuf; use std::process::{Child, Command, Stdio}; use std::sync::{Arc, Mutex}; use tauri::webview::NewWindowResponse; use tauri::{AppHandle, Emitter, Listener, Manager, State, WebviewUrl, WebviewWindowBuilder}; fn debug_log(msg: &str) { let log_dir = if let Ok(app_data) = std::env::var("APPDATA") { std::path::PathBuf::from(app_data) .join("vyla-home") .join("vyla-home-files") .join("logs") } else if let Ok(_home) = std::env::var("HOME") { std::path::PathBuf::from(_home) .join("Library") .join("Logs") .join("VylaHome") } else if let Ok(user_profile) = std::env::var("USERPROFILE") { std::path::PathBuf::from(user_profile) .join(".vyla-home") .join("logs") } else { std::env::temp_dir().join("vyla-home-logs") }; let _ = std::fs::create_dir_all(&log_dir); let log_path = log_dir.join("rust-debug.log"); if let Ok(mut file) = std::fs::OpenOptions::new() .create(true) .append(true) .open(&log_path) { use std::io::Write; let _ = writeln!(file, "[RUST] {}", msg); } } struct NodeServices(Mutex>); struct NodeStdin(Mutex>); fn write_node_line(state: &NodeStdin, line: &str) -> Result<(), String> { use std::io::Write; let mut lock = state.0.lock().map_err(|e| e.to_string())?; if let Some(stdin) = lock.as_mut() { stdin.write_all(line.as_bytes()).map_err(|e| e.to_string())?; stdin.write_all(b"\n").map_err(|e| e.to_string())?; stdin.flush().map_err(|e| e.to_string())?; } Ok(()) } static WINDOW_COUNTER: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(1); static READY_URL: Mutex> = Mutex::new(None); static APP_LOADED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); fn js_log(app: &AppHandle, msg: &str) { debug_log(msg); if let Some(w) = app.get_webview_window("main") { let text = serde_json::to_string(&format!("[rust] {}", msg)).unwrap_or_default(); let _ = w.eval(&format!("console.log({});", text)); } } #[derive(serde::Deserialize, serde::Serialize, Clone)] struct BackendMessage { event: String, data: serde_json::Value, } struct UiGate { ready: bool, queue: Vec, } type SharedGate = Arc>; fn dispatch(w: &tauri::WebviewWindow, gate: &SharedGate, msg: BackendMessage) { if let Ok(mut lock) = gate.lock() { if lock.ready { let _ = w.emit(&msg.event, msg.data); } else { lock.queue.push(msg); } } } fn clean_path(path: &std::path::Path) -> String { let s = path.to_string_lossy().to_string(); if s.starts_with(r"\\?\") { s[4..].to_string() } else { s } } fn kill_child_process(child: &mut Child) { #[cfg(windows)] { use std::os::windows::process::CommandExt; const CREATE_NO_WINDOW: u32 = 0x08000000; let _ = Command::new("taskkill") .args(&["/F", "/T", "/PID", &child.id().to_string()]) .creation_flags(CREATE_NO_WINDOW) .output(); } #[cfg(unix)] { let pgid = child.id() as i32; unsafe { libc::killpg(pgid, libc::SIGTERM); } std::thread::sleep(std::time::Duration::from_millis(400)); unsafe { libc::killpg(pgid, libc::SIGKILL); } } let _ = child.kill(); let _ = child.wait(); } fn find_node_binary(app: &tauri::App) -> Option { if let Ok(resource_dir) = app.path().resource_dir() { #[cfg(windows)] let candidates = [ resource_dir.join("bin").join("node.exe"), resource_dir.join("node.exe"), resource_dir.join("_up_").join("bin").join("node.exe"), resource_dir.join("_up_").join("node.exe"), resource_dir.join("up").join("bin").join("node.exe"), resource_dir.join("up").join("node.exe"), ]; #[cfg(not(windows))] let candidates = [ resource_dir.join("bin").join("node"), resource_dir.join("node"), resource_dir.join("_up_").join("bin").join("node"), resource_dir.join("_up_").join("node"), resource_dir.join("up").join("bin").join("node"), resource_dir.join("up").join("node"), ]; for candidate in candidates { if candidate.exists() { return Some(clean_path(&candidate)); } } } if let Ok(exe_path) = std::env::current_exe() { if let Some(parent) = exe_path.parent() { let candidates = [ parent.join("bin").join("node.exe"), parent.join("bin").join("node"), parent.join("node.exe"), parent.join("node"), parent.join("resources").join("bin").join("node.exe"), parent.join("resources").join("bin").join("node"), parent.join("resources").join("node.exe"), parent.join("resources").join("node"), ]; for candidate in candidates { if candidate.exists() { return Some(clean_path(&candidate)); } } } } if let Ok(path_var) = std::env::var("PATH") { for p in std::env::split_paths(&path_var) { let node_exe = p.join("node.exe"); if node_exe.exists() { return Some(clean_path(&node_exe)); } let node = p.join("node"); if node.exists() { return Some(clean_path(&node)); } } } #[cfg(windows)] { let default_paths = [ r"C:\Program Files\nodejs\node.exe", r"C:\Program Files (x86)\nodejs\node.exe", ]; for path in default_paths { let candidate = std::path::Path::new(path); if candidate.exists() { return Some(clean_path(candidate)); } } if let Ok(local_app_data) = std::env::var("LOCALAPPDATA") { let candidate = std::path::PathBuf::from(local_app_data) .join("Programs") .join("nodejs") .join("node.exe"); if candidate.exists() { return Some(clean_path(&candidate)); } } } #[cfg(not(windows))] { let default_paths = [ "/usr/local/bin/node", "/usr/bin/node", "/opt/homebrew/bin/node", "/opt/local/bin/node", ]; for path in default_paths { let candidate = std::path::Path::new(path); if candidate.exists() { return Some(clean_path(candidate)); } } } None } fn resolve_script_and_root(app: &tauri::App) -> (String, String) { if let Ok(resource_dir) = app.path().resource_dir() { let candidates = vec![ resource_dir.join("main.js"), resource_dir.join("_up_").join("main.js"), resource_dir.join("up").join("main.js"), ]; for candidate in candidates { if candidate.exists() { let root_dir = candidate.parent().unwrap(); return (clean_path(&candidate), clean_path(root_dir)); } } } let mut dir = std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")); if dir.ends_with("src-tauri") { dir.pop(); } let candidate = dir.join("main.js"); (clean_path(&candidate), clean_path(&dir)) } const LINK_HANDLER_SCRIPT: &str = r##" function doInvoke(cmd, args) { if (window.__TAURI__ && window.__TAURI__.core) { return window.__TAURI__.core.invoke(cmd, args || {}); } return Promise.resolve(null); } function callWindow(method, fallbackCmd) { const fallback = () => doInvoke(fallbackCmd).catch(err => console.error(fallbackCmd + ' failed:', err)); try { if (window.__TAURI__ && window.__TAURI__.window) { return window.__TAURI__.window.getCurrentWindow()[method]().catch(fallback); } } catch (err) {} return fallback(); } function minimizeWindow() { return callWindow('minimize', 'win_minimize'); } function maximizeWindow() { return callWindow('toggleMaximize', 'win_maximize'); } function closeWindow() { return callWindow('close', 'win_close'); } function dragWindow() { return callWindow('startDragging', 'win_drag'); } function openExternalUrl(url) { if (window.__TAURI__ && window.__TAURI__.opener) { window.__TAURI__.opener.openUrl(url); } else { window.open(url, '_blank'); } } const nativeWindowOpen = window.open.bind(window); function openInNewWindow(rawUrl) { let abs; try { abs = new URL(rawUrl, location.href).href; } catch (err) { console.log('[vyla] bad url', rawUrl); return; } console.log('[vyla] open new window', abs); nativeWindowOpen(abs, '_blank'); } window.open = function(url, target, features) { console.log('[vyla] window.open called', url, target, features); const go = (v) => { if (v && !/^(about:|javascript:|blob:|data:)/i.test(String(v))) { openInNewWindow(String(v)); } }; go(url); const stub = { closed: false, close() {}, focus() {}, blur() {}, postMessage() {}, document: { write() {}, writeln() {}, close() {}, open() {} } }; Object.defineProperty(stub, 'location', { get() { return { href: '', replace: go, assign: go }; }, set(v) { go(v); } }); return stub; }; const origAnchorClick = HTMLAnchorElement.prototype.click; HTMLAnchorElement.prototype.click = function() { if (this.href && this.target === '_blank' && !this.isConnected) { console.log('[vyla] detached anchor click', this.href); openInNewWindow(this.href); return; } return origAnchorClick.apply(this, arguments); }; function handleLinkClick(e) { const a = e.target.closest && e.target.closest('a'); if (!a || !a.href) return; if (a.href.includes('discord.gg') || a.href.includes('discord.com')) { e.preventDefault(); e.stopPropagation(); openExternalUrl(a.href); return; } if (a.target === '_blank' || e.ctrlKey || e.metaKey || e.button === 1) { e.preventDefault(); e.stopPropagation(); openInNewWindow(a.href); } } document.addEventListener('click', handleLinkClick, true); document.addEventListener('auxclick', handleLinkClick, true); function injectLiquidNavBar() { if (document.getElementById('tauri-custom-titlebar')) return; if (!document.body) return; const style = document.createElement('style'); style.innerHTML = ` #tauri-custom-titlebar { position: fixed !important; top: 0 !important; left: 0 !important; right: 0 !important; height: 32px !important; max-height: 32px !important; display: flex !important; justify-content: flex-end !important; align-items: center !important; z-index: 2147483647 !important; background: transparent !important; pointer-events: none !important; box-sizing: border-box !important; margin: 0 !important; padding: 0 !important; } .tauri-drag-region { position: absolute !important; inset: 0 !important; height: 32px !important; cursor: default !important; pointer-events: auto !important; } .tauri-window-controls { display: flex !important; height: 32px !important; margin: 0 !important; padding: 0 !important; pointer-events: auto !important; z-index: 2147483648 !important; } button.tauri-btn { width: 46px !important; min-width: 46px !important; max-width: 46px !important; height: 32px !important; background: transparent !important; border: none !important; color: #ffffff !important; display: flex !important; align-items: center !important; justify-content: center !important; cursor: pointer !important; outline: none !important; pointer-events: auto !important; } button.tauri-btn:hover { background: rgba(255, 255, 255, 0.2) !important; } button#tauri-btn-close:hover { background: #e81123 !important; color: #ffffff !important; } button.tauri-btn svg { width: 10px !important; height: 10px !important; fill: currentColor !important; pointer-events: none !important; } `; if (!document.getElementById('tauri-custom-titlebar-style')) { style.id = 'tauri-custom-titlebar-style'; (document.head || document.documentElement).appendChild(style); } const tb = document.createElement('div'); tb.id = 'tauri-custom-titlebar'; tb.innerHTML = `
`; document.body.appendChild(tb); const btnMin = tb.querySelector('#tauri-btn-min'); const btnMax = tb.querySelector('#tauri-btn-max'); const btnClose = tb.querySelector('#tauri-btn-close'); const dragEl = tb.querySelector('.tauri-drag-region'); if (btnMin) { btnMin.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation(); minimizeWindow(); }, true); } if (btnMax) { btnMax.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation(); maximizeWindow(); }, true); } if (btnClose) { btnClose.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation(); closeWindow(); }, true); } if (dragEl) { dragEl.addEventListener('mousedown', (e) => { if (e.button === 0) { e.preventDefault(); dragWindow(); } }); } } function startNavObserver() { const root = document.documentElement; if (!root) { setTimeout(startNavObserver, 5); return; } const navObserver = new MutationObserver(() => { if (!document.getElementById('tauri-custom-titlebar')) { injectLiquidNavBar(); } }); navObserver.observe(root, { childList: true, subtree: true }); } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', injectLiquidNavBar); } else { injectLiquidNavBar(); } startNavObserver(); (function () { let last = ''; let timer = null; function metaImage() { const m = document.querySelector("meta[property='og:image']"); return m && m.content ? m.content : ''; } function send(attempt) { const n = typeof attempt === 'number' ? attempt : 0; const tauri = window.__TAURI__; if (!tauri || !tauri.core) { if (n < 40) setTimeout(() => send(n + 1), 250); return; } const payload = { label: window.__VYLA_WINDOW_LABEL || 'main', url: location.href, title: document.title || '', image: metaImage(), closed: false }; const v = document.querySelector('video'); if (v && Number.isFinite(v.duration) && v.duration > 0) { payload.position = v.currentTime; payload.duration = v.duration; payload.paused = v.paused; } if (!tauri.event) { if (n < 40) setTimeout(() => send(n + 1), 250); return; } tauri.event.emit('vyla-presence', payload).catch((e) => console.error('[vyla] presence emit failed', e)); } function check() { if (location.href === last) return; last = location.href; send(); clearTimeout(timer); timer = setTimeout(send, 1500); } ['pushState', 'replaceState'].forEach((fn) => { const orig = history[fn]; history[fn] = function () { const r = orig.apply(this, arguments); setTimeout(check, 0); return r; }; }); window.addEventListener('popstate', check); window.addEventListener('hashchange', check); window.addEventListener('focus', () => send()); ['play', 'pause', 'seeked'].forEach((name) => { document.addEventListener(name, () => send(), true); }); setInterval(check, 2000); setInterval(() => { if (document.hasFocus()) send(); }, 5000); check(); })(); "##; #[cfg(windows)] const REINSTALL_SCRIPT: &str = r##" param([int]$ProcId,[string]$Installer,[string]$InstallDir,[string]$ExePath) $ErrorActionPreference = 'SilentlyContinue' function Log($m) { Add-Content -LiteralPath (Join-Path $env:TEMP 'vyla-reinstall.log') -Value "$(Get-Date -Format s) $m" } Log "start pid=$ProcId installer=$Installer dir=$InstallDir exe=$ExePath" $setup = Join-Path $env:TEMP 'vyla-setup.exe' Copy-Item -LiteralPath $Installer -Destination $setup -Force if (-not (Test-Path -LiteralPath $setup)) { exit 1 } Wait-Process -Id $ProcId -Timeout 30 Get-Process | Where-Object { $_.Path -and $_.Path.StartsWith($InstallDir, [System.StringComparison]::OrdinalIgnoreCase) } | Stop-Process -Force Start-Sleep -Seconds 2 $un = Join-Path $InstallDir 'uninstall.exe' if (Test-Path -LiteralPath $un) { Start-Process -FilePath $un -ArgumentList '/S', "_?=$InstallDir" -Wait } $targets = @($InstallDir, "$env:APPDATA\vyla-home", "$env:APPDATA\com.vyla.home", "$env:LOCALAPPDATA\com.vyla.home", "$env:LOCALAPPDATA\vyla-home") foreach ($t in $targets) { for ($i = 0; $i -lt 5; $i++) { if (-not (Test-Path -LiteralPath $t)) { break } Remove-Item -LiteralPath $t -Recurse -Force if (Test-Path -LiteralPath $t) { Start-Sleep -Seconds 1 } } } Log "uninstall and cleanup done, installing" Start-Process -FilePath $setup -ArgumentList '/S', "/D=$InstallDir" -Wait Log "installer finished" Remove-Item -LiteralPath $setup -Force $target = $null for ($i = 0; $i -lt 40; $i++) { if (Test-Path -LiteralPath $ExePath) { $target = $ExePath; break } $found = Get-ChildItem -LiteralPath $InstallDir -Filter '*.exe' | Where-Object { $_.Name -notmatch 'uninstall|node' } | Select-Object -First 1 if ($found) { $target = $found.FullName; break } Start-Sleep -Milliseconds 500 } Log "launch target: $target" if ($target) { Start-Process -FilePath $target -WorkingDirectory (Split-Path -Parent $target) Start-Sleep -Seconds 4 if (-not (Get-Process | Where-Object { $_.Path -eq $target })) { Log "not running, retrying via explorer" Start-Process -FilePath 'explorer.exe' -ArgumentList "`"$target`"" } } Log "done" "##; #[cfg(windows)] fn run_clean_reinstall(installer: &std::path::Path) -> bool { use std::os::windows::process::CommandExt; let exe = match std::env::current_exe() { Ok(e) => e, Err(_) => return false, }; let dir = match exe.parent() { Some(d) => d.to_path_buf(), None => return false, }; if !dir.join("uninstall.exe").exists() { return false; } let script = std::env::temp_dir().join("vyla-reinstall.ps1"); if std::fs::write(&script, REINSTALL_SCRIPT).is_err() { return false; } Command::new("powershell") .args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-WindowStyle", "Hidden", "-File"]) .arg(&script) .arg("-ProcId") .arg(std::process::id().to_string()) .arg("-Installer") .arg(installer) .arg("-InstallDir") .arg(clean_path(&dir)) .arg("-ExePath") .arg(clean_path(&exe)) .creation_flags(0x08000000 | 0x00000200) .spawn() .is_ok() } #[tauri::command] fn win_minimize(window: tauri::Window) -> Result<(), String> { window.minimize().map_err(|e| e.to_string()) } #[tauri::command] fn win_maximize(window: tauri::Window) -> Result<(), String> { if let Ok(is_max) = window.is_maximized() { if is_max { window.unmaximize().map_err(|e| e.to_string()) } else { window.maximize().map_err(|e| e.to_string()) } } else { Ok(()) } } #[tauri::command] fn win_close(window: tauri::Window) -> Result<(), String> { window.close().map_err(|e| e.to_string()) } #[tauri::command] fn win_drag(window: tauri::Window) -> Result<(), String> { window.start_dragging().map_err(|e| e.to_string()) } #[tauri::command] async fn report_location(state: State<'_, NodeStdin>, payload: serde_json::Value) -> Result<(), String> { let line = serde_json::json!({ "type": "presence", "payload": payload }).to_string(); debug_log(&format!("[PRESENCE] {}", line)); write_node_line(&state, &line) } fn normalize_url(url: &str) -> Option { let final_url = if url.starts_with("http") || url.starts_with("tauri://") { url.to_string() } else if url.starts_with('/') { format!("http://127.0.0.1:4890{}", url) } else { format!("http://127.0.0.1:4890/{}", url) }; match final_url.parse::() { Ok(u) => Some(u), Err(e) => { debug_log(&format!("[NEW-WINDOW] bad url '{}': {}", final_url, e)); None } } } fn open_app_window(app: &AppHandle, url: tauri::Url) -> Result<(), String> { js_log(app, &format!("[NEW-WINDOW] Opening: {}", url)); let n = WINDOW_COUNTER.fetch_add(1, std::sync::atomic::Ordering::SeqCst); let label = format!("win_{}", n); let nw_handle = app.clone(); let window = WebviewWindowBuilder::new(app, &label, WebviewUrl::External(url)) .title("Vyla Home") .inner_size(1100.0, 700.0) .center() .decorations(false) .resizable(true) .transparent(true) .devtools(true) .focused(true) .initialization_script(&format!("window.__VYLA_WINDOW_LABEL = '{}';", label)) .initialization_script(LINK_HANDLER_SCRIPT) .on_new_window(move |new_url, _features| { js_log(&nw_handle, &format!("[NEW-WINDOW] handler fired (child): {}", new_url)); let h = nw_handle.clone(); std::thread::spawn(move || { let _ = open_app_window(&h, new_url); }); NewWindowResponse::Deny }) .build() .map_err(|e| { js_log(app, &format!("[NEW-WINDOW] build failed: {}", e)); e.to_string() })?; #[cfg(target_os = "windows")] { use window_vibrancy::{apply_acrylic, apply_mica}; if apply_mica(&window, Some(true)).is_err() { let _ = apply_acrylic(&window, Some((15, 18, 25, 125))); } } #[cfg(target_os = "macos")] { use window_vibrancy::{apply_vibrancy, NSVisualEffectMaterial}; let _ = apply_vibrancy(&window, NSVisualEffectMaterial::HudWindow, None, None); } let _ = &window; Ok(()) } #[tauri::command] fn open_new_window(app: AppHandle, url: String) -> Result<(), String> { let parsed = normalize_url(&url).ok_or_else(|| "invalid url".to_string())?; std::thread::spawn(move || { let _ = open_app_window(&app, parsed); }); Ok(()) } fn handle_ready(w: &tauri::WebviewWindow, msg: &BackendMessage) { let url_str = match msg.data.get("url").and_then(|u| u.as_str()) { Some(u) => u.to_string(), None => return, }; let url_parsed = match url_str.parse::() { Ok(u) => u, Err(_) => return, }; #[cfg(target_os = "macos")] { use objc2::msg_send; use objc2::runtime::{AnyObject, Sel}; use objc2::sel; let _ = w.with_webview(|webview| unsafe { let wk_webview = webview.inner() as *mut AnyObject; let config: *mut AnyObject = msg_send![wk_webview, configuration]; let selector: Sel = sel!(setUpgradeKnownHostsToHTTPS:); let supported: bool = msg_send![config, respondsToSelector: selector]; if supported { let _: () = msg_send![config, setUpgradeKnownHostsToHTTPS: false]; } }); } APP_LOADED.store(false, std::sync::atomic::Ordering::SeqCst); let _ = w.navigate(url_parsed.clone()); let watcher = w.clone(); std::thread::spawn(move || { for attempt in 1..=8 { std::thread::sleep(std::time::Duration::from_secs(4)); if APP_LOADED.load(std::sync::atomic::Ordering::SeqCst) { return; } debug_log(&format!("App page not loaded yet, retry {}", attempt)); let target = serde_json::to_string(&url_str).unwrap_or_default(); let _ = watcher.eval(&format!("window.location.replace({});", target)); let _ = watcher.navigate(url_parsed.clone()); } debug_log("App page never loaded after retries"); }); } fn main() { debug_log("=== Vyla Home Executable Started ==="); tauri::Builder::default() .plugin(tauri_plugin_opener::init()) .invoke_handler(tauri::generate_handler![ win_minimize, win_maximize, win_close, win_drag, open_new_window, report_location ]) .manage(NodeServices(Mutex::new(None))) .manage(NodeStdin(Mutex::new(None))) .setup(|app| { debug_log("Tauri setup started"); let app_data = app.path().app_data_dir().unwrap_or_default(); let vyla_files = if let Ok(appdata_env) = std::env::var("APPDATA") { std::path::PathBuf::from(appdata_env) .join("vyla-home") .join("vyla-home-files") } else if let Ok(_home) = std::env::var("HOME") { #[cfg(target_os = "macos")] let base = std::path::PathBuf::from(&_home) .join("Library") .join("Application Support"); #[cfg(target_os = "linux")] let base = std::path::PathBuf::from(&_home) .join(".local") .join("share"); #[cfg(not(any(target_os = "macos", target_os = "linux")))] let base = app_data.clone(); base.join("vyla-home").join("vyla-home-files") } else { app_data.join("vyla-home-files") }; let _ = std::fs::create_dir_all(&vyla_files); let main_nw_handle = app.handle().clone(); let gate: SharedGate = Arc::new(Mutex::new(UiGate { ready: false, queue: Vec::new(), })); let load_gate = gate.clone(); let window = WebviewWindowBuilder::new(app, "main", WebviewUrl::App("index.html".into())) .title("Vyla Home") .inner_size(1280.0, 800.0) .decorations(false) .resizable(true) .transparent(true) .devtools(true) .initialization_script("window.__VYLA_WINDOW_LABEL = 'main';") .on_page_load(move |wv, payload| { if matches!(payload.event(), tauri::webview::PageLoadEvent::Finished) { if payload.url().host_str() == Some("127.0.0.1") { APP_LOADED.store(true, std::sync::atomic::Ordering::SeqCst); } if payload.url().host_str() != Some("127.0.0.1") { let known = READY_URL.lock().ok().and_then(|g| g.clone()); if let Some(u) = known { if let Ok(parsed) = u.parse::() { let _ = wv.navigate(parsed); return; } } } let g = load_gate.clone(); std::thread::spawn(move || { std::thread::sleep(std::time::Duration::from_millis(400)); if let Ok(mut lock) = g.lock() { lock.ready = true; let pending: Vec = lock.queue.drain(..).collect(); for m in pending { let _ = wv.emit(&m.event, m.data); } } }); } }) .initialization_script(LINK_HANDLER_SCRIPT) .on_new_window(move |new_url, _features| { js_log(&main_nw_handle, &format!("[NEW-WINDOW] handler fired (main): {}", new_url)); let h = main_nw_handle.clone(); std::thread::spawn(move || { let _ = open_app_window(&h, new_url); }); NewWindowResponse::Deny }) .build()?; #[cfg(target_os = "windows")] { use window_vibrancy::{apply_acrylic, apply_mica}; if apply_mica(&window, Some(true)).is_err() { let _ = apply_acrylic(&window, Some((15, 18, 25, 125))); } } #[cfg(target_os = "macos")] { use window_vibrancy::{apply_vibrancy, NSVisualEffectMaterial}; let _ = apply_vibrancy(&window, NSVisualEffectMaterial::HudWindow, None, None); } let (main_js, root_dir) = resolve_script_and_root(app); debug_log("Searching for node binary..."); let node_bin = match find_node_binary(app) { Some(bin) => { debug_log(&format!("Found node binary: {}", bin)); bin } None => { debug_log("FATAL: No node binary found in bundle or PATH."); let _ = window.eval("document.getElementById('status-message').textContent='Error: Node runtime missing. Please reinstall.';"); let _ = window.eval("var b=document.getElementById('debug-log-box');b.style.display='block';b.textContent='Node binary not found. bin/node missing from app bundle or not executable.';"); return Ok(()); } }; #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; if let Ok(meta) = std::fs::metadata(&node_bin) { let mut perms = meta.permissions(); perms.set_mode(0o755); let _ = std::fs::set_permissions(&node_bin, perms); } } let vyla_files_str = clean_path(&vyla_files); let mut cmd = Command::new(&node_bin); cmd.arg(&main_js) .current_dir(&root_dir) .env("APPDATA_PATH", &vyla_files_str) .env("NODE_EXE", &node_bin) .env("VYLA_APP_VERSION", env!("CARGO_PKG_VERSION")) .env("VYLA_DEV", if cfg!(debug_assertions) { "1" } else { "0" }) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()); #[cfg(windows)] { use std::os::windows::process::CommandExt; const CREATE_NO_WINDOW: u32 = 0x08000000; cmd.creation_flags(CREATE_NO_WINDOW); } #[cfg(unix)] { use std::os::unix::process::CommandExt; cmd.process_group(0); } match cmd.spawn() { Ok(mut child) => { debug_log(&format!( "Node child process spawned successfully, PID: {}", child.id() )); if let Some(stderr) = child.stderr.take() { let w = window.clone(); let g = gate.clone(); std::thread::spawn(move || { use std::io::{BufRead, BufReader}; let reader = BufReader::new(stderr); for line in reader.lines().flatten() { debug_log(&format!("[NODE STDERR] {}", line)); if line.contains("Error") || line.contains("Exception") || line.contains("MODULE_NOT_FOUND") { dispatch( &w, &g, BackendMessage { event: "error".to_string(), data: serde_json::json!({ "message": format!("Backend failed: {}", line) }), }, ); } } }); } if let Some(stdout) = child.stdout.take() { let w = window.clone(); let g = gate.clone(); std::thread::spawn(move || { use std::io::{BufRead, BufReader}; let reader = BufReader::new(stdout); for line in reader.lines().flatten() { debug_log(&format!("[NODE STDOUT] {}", line)); let msg = match serde_json::from_str::(&line) { Ok(m) => m, Err(_) => { if !line.trim().is_empty() { debug_log(&format!("[NODE RAW] {}", line)); } continue; } }; match msg.event.as_str() { "self-update" => { let target = msg .data .get("path") .and_then(|p| p.as_str()) .map(PathBuf::from); if let Some(p) = target { let name = p .file_name() .and_then(|n| n.to_str()) .unwrap_or("") .to_string(); if name.starts_with("vyla-installer-") && name.ends_with(".exe") && p.exists() { #[cfg(windows)] { if run_clean_reinstall(&p) { let state: State = w.state(); if let Ok(mut lock) = state.0.lock() { if let Some(mut child) = lock.take() { kill_child_process(&mut child); } }; w.app_handle().exit(0); } } } } } "ready" => { if let Some(u) = msg.data.get("url").and_then(|u| u.as_str()) { if let Ok(mut g) = READY_URL.lock() { *g = Some(u.to_string()); } } handle_ready(&w, &msg) } _ => dispatch(&w, &g, msg.clone()), } } }); } if let Some(stdin) = child.stdin.take() { let stdin_state: State = app.state(); if let Ok(mut lock) = stdin_state.0.lock() { *lock = Some(stdin); }; } let state: State = app.state(); if let Ok(mut lock) = state.0.lock() { *lock = Some(child); }; } Err(e) => { debug_log(&format!("Failed to spawn node: {}", e)); let emsg = format!("Failed to spawn node: {}", e); let js = format!( "document.getElementById('status-message').textContent='Spawn Error';var b=document.getElementById('debug-log-box');b.style.display='block';b.textContent={};", serde_json::to_string(&emsg).unwrap_or_default() ); let _ = window.eval(&js); } } let presence_handle = app.handle().clone(); app.listen("vyla-presence", move |event| { debug_log(&format!("[PRESENCE] {}", event.payload())); let line = format!("{{\"type\":\"presence\",\"payload\":{}}}", event.payload()); let state: State = presence_handle.state(); let _ = write_node_line(&state, &line); }); Ok(()) }) .on_window_event(|window, event| { if let tauri::WindowEvent::Destroyed = event { if window.label() == "main" { let state: State = window.state(); if let Ok(mut lock) = state.0.lock() { if let Some(mut child) = lock.take() { debug_log("[SHUTDOWN] Main window destroyed, terminating node process natively"); kill_child_process(&mut child); } }; window.app_handle().exit(0); } else { let label = window.label().to_string(); let line = serde_json::json!({ "type": "presence", "payload": { "label": label, "closed": true } }).to_string(); let state: State = window.state(); let _ = write_node_line(&state, &line); } } }) .build(tauri::generate_context!()) .expect("error while building tauri application") .run(|app, event| { if let tauri::RunEvent::Exit = event { let state: State = app.state(); if let Ok(mut lock) = state.0.lock() { if let Some(mut child) = lock.take() { kill_child_process(&mut child); } }; } }); }