Files
Home/src-tauri/src/main.rs
2026-10-24 18:28:09 -07:00

788 lines
29 KiB
Rust

#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
use std::sync::Mutex;
use tauri::{Emitter, 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<Option<Child>>);
#[derive(serde::Deserialize, serde::Serialize, Clone)]
struct BackendMessage {
event: String,
data: serde_json::Value,
}
fn clean_path(path: &std::path::Path) -> String {
let s = path.to_string_lossy().to_string();
if s.starts_with("\\\\?\\") {
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();
}
let _ = child.kill();
let _ = child.wait();
}
fn find_node_binary(app: &tauri::App) -> Option<String> {
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##"
window.vylaHome = {
sendUpdateChoice: function(choice) {
var action = choice ? 'yes' : 'no';
[4891, 4892].forEach(function(port) {
['127.0.0.1', 'localhost'].forEach(function(host) {
fetch('http://' + host + ':' + port + '/update/' + action, { method: 'POST' }).catch(function() {});
fetch('http://' + host + ':' + port + '/update/' + action, { method: 'GET' }).catch(function() {});
fetch('http://' + host + ':' + port + '/__tauri_cmd/update_' + action, { method: 'GET' }).catch(function() {});
});
});
}
};
document.addEventListener('click', function(e) {
var el = e.target.closest('button, a, .btn');
if (!el) return;
var text = (el.innerText || el.textContent || '').toLowerCase();
var id = (el.id || '').toLowerCase();
if (id.includes('install') || id.includes('update-yes') || text.includes('install update')) {
window.vylaHome.sendUpdateChoice(true);
} else if (id.includes('skip') || id.includes('update-no') || text.includes('skip')) {
window.vylaHome.sendUpdateChoice(false);
}
}, true);
function doInvoke(cmd, args) {
if (window.__TAURI__ && window.__TAURI__.core) {
return window.__TAURI__.core.invoke(cmd, args || {});
}
return Promise.resolve(null);
}
function minimizeWindow() { doInvoke('win_minimize'); }
function maximizeWindow() { doInvoke('win_maximize'); }
function closeWindow() { doInvoke('win_close'); }
function dragWindow() { doInvoke('win_drag'); }
function openExternalUrl(url) {
if (window.__TAURI__ && window.__TAURI__.opener) {
window.__TAURI__.opener.openUrl(url);
} else if (window.__TAURI__ && window.__TAURI__.shell) {
window.__TAURI__.shell.open(url);
} else {
window.open(url, '_blank');
}
}
window.open = function(url, target, features) {
doInvoke('open_new_window', { url: url });
return null;
};
document.addEventListener('click', (e) => {
const a = 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();
doInvoke('open_new_window', { url: a.href });
}
}, 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;
}
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; }
`;
document.head.appendChild(style);
const tb = document.createElement('div');
tb.id = 'tauri-custom-titlebar';
tb.innerHTML = `
<div class="tauri-drag-region"></div>
<div class="tauri-window-controls">
<button class="tauri-btn" id="tauri-btn-min" title="Minimize"><svg viewBox="0 0 10 10"><rect x="1" y="4" width="8" height="1"/></svg></button>
<button class="tauri-btn" id="tauri-btn-max" title="Maximize"><svg viewBox="0 0 10 10"><path d="M1,1v8h8V1H1z M8,8H2V2h6V8z"/></svg></button>
<button class="tauri-btn" id="tauri-btn-close" title="Close"><svg viewBox="0 0 10 10"><path d="M10,1.4L8.6,0L5,3.6L1.4,0L0,1.4L3.6,5L0,8.6L1.4,10L5,6.4L8.6,10L10,8.6L6.4,5L10,1.4z"/></svg></button>
</div>
`;
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.onclick = (e) => { e.preventDefault(); e.stopPropagation(); minimizeWindow(); };
if (btnMax) btnMax.onclick = (e) => { e.preventDefault(); e.stopPropagation(); maximizeWindow(); };
if (btnClose) btnClose.onclick = (e) => { e.preventDefault(); e.stopPropagation(); closeWindow(); };
if (dragEl) {
dragEl.onmousedown = (e) => {
if (e.buttons === 1) {
e.preventDefault();
dragWindow();
}
};
}
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', injectLiquidNavBar);
} else {
injectLiquidNavBar();
}
const navObserver = new MutationObserver(() => {
if (!document.getElementById('vyla-floating-nav')) {
injectLiquidNavBar();
}
});
navObserver.observe(document.documentElement, { childList: true, subtree: true });
"##;
#[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]
fn open_new_window(app: tauri::AppHandle, url: String) -> Result<(), String> {
debug_log(&format!("[SAME-TAB] Redirecting main window to: {}", url));
let final_url = if url.starts_with("http") || url.starts_with("tauri://") {
url.clone()
} else if url.starts_with('/') {
format!("http://127.0.0.1:4890{}", url)
} else {
format!("http://127.0.0.1:4890/{}", url)
};
if let Some(window) = app.get_webview_window("main") {
window
.eval(&format!(
"window.location.href = '{}';",
final_url.replace('\'', "\\'")
))
.map_err(|e| e.to_string())?;
Ok(())
} else {
Err("main window not found".to_string())
}
}
#[tauri::command]
async fn kill_orphans() -> Result<(), String> {
debug_log("[KILL] User requested orphan process kill");
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x08000000;
let _ = std::process::Command::new("taskkill")
.args(&["/F", "/T", "/IM", "node.exe"])
.creation_flags(CREATE_NO_WINDOW)
.output();
}
#[cfg(not(windows))]
{
let _ = std::process::Command::new("pkill")
.args(&["-9", "-f", "node"])
.output();
}
Ok(())
}
#[tauri::command]
fn get_logo_base64(app: tauri::AppHandle) -> Result<String, String> {
use std::io::Read;
let mut candidate_paths = Vec::new();
if let Ok(res_dir) = app.path().resource_dir() {
candidate_paths.push(res_dir.join("build").join("icon_white.png"));
candidate_paths.push(res_dir.join("_up_").join("build").join("icon_white.png"));
}
if let Ok(mut cur) = std::env::current_dir() {
candidate_paths.push(cur.join("build").join("icon_white.png"));
if cur.ends_with("src-tauri") {
cur.pop();
candidate_paths.push(cur.join("build").join("icon_white.png"));
}
}
for path in candidate_paths {
if path.exists() {
if let Ok(mut file) = std::fs::File::open(&path) {
let mut buffer = Vec::new();
if file.read_to_end(&mut buffer).is_ok() {
use base64::Engine;
return Ok(base64::engine::general_purpose::STANDARD.encode(buffer));
}
}
}
}
Err("icon_white.png not found".to_string())
}
fn handle_tauri_cmd(w: &tauri::WebviewWindow, msg: &BackendMessage) {
let window_label = msg
.data
.get("window")
.and_then(|v| v.as_str())
.unwrap_or("main");
debug_log(&format!("[MAIN-DEBUG] Finding window by label: {}", window_label));
let cmd_window = match w.app_handle().get_webview_window(window_label) {
Some(win) => win,
None => {
debug_log(&format!("[TAURI-CMD] Window '{}' NOT FOUND!", window_label));
return;
}
};
let cmd = match msg.data.get("cmd").and_then(|c| c.as_str()) {
Some(c) => c,
None => return,
};
debug_log(&format!("[TAURI-CMD] Executing action: {}", cmd));
match cmd {
"win_minimize" => {
let res = cmd_window.minimize();
debug_log(&format!("[TAURI-CMD] Minimize result: {:?}", res));
}
"win_maximize" => {
let is_max = cmd_window.is_maximized().unwrap_or(false);
debug_log(&format!("[TAURI-CMD] Currently maximized: {}", is_max));
let res = if is_max {
cmd_window.unmaximize()
} else {
cmd_window.maximize()
};
debug_log(&format!("[TAURI-CMD] Maximize/Unmaximize result: {:?}", res));
}
"win_close" => {
let res = cmd_window.close();
debug_log(&format!("[TAURI-CMD] Close result: {:?}", res));
}
"win_drag" => {
let res = cmd_window.start_dragging();
debug_log(&format!("[TAURI-CMD] Drag result: {:?}", res));
}
"open_new_window" => {
debug_log("[TAURI-CMD-DEBUG] open_new_window command received");
debug_log(&format!(
"[TAURI-CMD-DEBUG] Full message data: {}",
serde_json::to_string(&msg.data).unwrap_or_default()
));
let url = match msg.data.get("url").and_then(|u| u.as_str()) {
Some(u) => u.to_string(),
None => {
debug_log("[TAURI-CMD-DEBUG] ERROR: No URL found in message data");
debug_log(&format!(
"[TAURI-CMD-DEBUG] Available keys: {:?}",
msg.data.as_object().map(|o| o.keys().collect::<Vec<_>>())
));
return;
}
};
debug_log(&format!("[TAURI-CMD-DEBUG] URL extracted: {}", url));
debug_log(&format!("[TAURI-CMD-DEBUG] URL length: {}", url.len()));
debug_log("[TAURI-CMD-DEBUG] Attempting to dispatch to main thread");
let app_handle = w.app_handle().clone();
let closure_handle = app_handle.clone();
match app_handle.run_on_main_thread(move || {
debug_log("[TAURI-CMD-DEBUG] Now on main thread, calling open_new_window");
match open_new_window(closure_handle, url) {
Ok(_) => debug_log("[TAURI-CMD-DEBUG] open_new_window succeeded"),
Err(e) => debug_log(&format!("[TAURI-CMD-DEBUG] open_new_window error: {}", e)),
}
}) {
Ok(_) => debug_log("[TAURI-CMD-DEBUG] Main thread dispatch succeeded"),
Err(e) => debug_log(&format!("[TAURI-CMD-DEBUG] Main thread dispatch failed: {}", e)),
}
}
_ => {}
}
}
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,
None => return,
};
let url_parsed = match url_str.parse::<tauri::Url>() {
Ok(u) => u,
Err(_) => return,
};
#[cfg(target_os = "macos")]
{
use objc2::msg_send;
use objc2::runtime::AnyObject;
debug_log("Attempting with_webview on ready event");
let result = w.with_webview(|webview| unsafe {
debug_log("Inside with_webview closure");
let wk_webview = webview.inner() as *mut AnyObject;
let config: *mut AnyObject = msg_send![wk_webview, configuration];
let _: () = msg_send![config, setUpgradeKnownHostsToHTTPS: false];
debug_log("setUpgradeKnownHostsToHTTPS set to false");
});
debug_log(&format!("with_webview result: {:?}", result));
}
let _ = w.navigate(url_parsed);
}
fn main() {
debug_log("=== Vyla Home Executable Started ===");
tauri::Builder::default()
.plugin(tauri_plugin_shell::init())
.plugin(tauri_plugin_process::init())
.plugin(tauri_plugin_opener::init())
.invoke_handler(tauri::generate_handler![
win_minimize,
win_maximize,
win_close,
win_drag,
open_new_window,
get_logo_base64,
kill_orphans
])
.manage(NodeServices(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 window = WebviewWindowBuilder::new(app, "main", WebviewUrl::App("index.html".into()))
.title("Vyla Home")
.inner_size(1280.0, 800.0)
.decorations(false)
.resizable(true)
.devtools(true)
.initialization_script("window.__VYLA_WINDOW_LABEL = 'main';")
.initialization_script(LINK_HANDLER_SCRIPT)
.build()?;
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.");
std::thread::sleep(std::time::Duration::from_millis(600));
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(());
}
};
let vyla_files_str = clean_path(&vyla_files);
std::thread::sleep(std::time::Duration::from_millis(400));
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)
.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);
}
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();
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")
{
let _ = w.emit(
"error",
serde_json::json!({ "message": format!("Backend failed: {}", line) }),
);
}
}
});
}
if let Some(stdout) = child.stdout.take() {
let w = window.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::<BackendMessage>(&line) {
Ok(m) => m,
Err(_) => {
if !line.trim().is_empty() {
debug_log(&format!("[NODE RAW] {}", line));
}
continue;
}
};
debug_log(&format!("[MAIN-DEBUG] Received event: {}", msg.event));
debug_log(&format!(
"[MAIN-DEBUG] Event data: {}",
serde_json::to_string(&msg.data).unwrap_or_default()
));
match msg.event.as_str() {
"tauri-cmd" => handle_tauri_cmd(&w, &msg),
"ready" => handle_ready(&w, &msg),
_ => {
let _ = w.emit(&msg.event, msg.data.clone());
}
}
}
});
}
let state: State<NodeServices> = 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);
}
}
Ok(())
})
.on_window_event(|window, event| {
if let tauri::WindowEvent::Destroyed = event {
if window.label() == "main" {
let state: State<NodeServices> = 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);
}
};
}
}
})
.run(tauri::generate_context!())
.expect("error while running tauri application");
}