mirror of
https://gitlab.com/vyla-entertainment/home.git
synced 2026-11-12 21:27:22 -05:00
848 lines
30 KiB
Rust
848 lines
30 KiB
Rust
#![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, 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>>);
|
|
|
|
static WINDOW_COUNTER: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(1);
|
|
|
|
static READY_URL: Mutex<Option<String>> = Mutex::new(None);
|
|
|
|
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<BackendMessage>,
|
|
}
|
|
|
|
type SharedGate = Arc<Mutex<UiGate>>;
|
|
|
|
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();
|
|
}
|
|
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##"
|
|
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 = `
|
|
<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.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();
|
|
"##;
|
|
|
|
#[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())
|
|
}
|
|
|
|
fn normalize_url(url: &str) -> Option<tauri::Url> {
|
|
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::<tauri::Url>() {
|
|
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,
|
|
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_opener::init())
|
|
.invoke_handler(tauri::generate_handler![
|
|
win_minimize,
|
|
win_maximize,
|
|
win_close,
|
|
win_drag,
|
|
open_new_window
|
|
])
|
|
.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 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") {
|
|
let known = READY_URL.lock().ok().and_then(|g| g.clone());
|
|
if let Some(u) = known {
|
|
if let Ok(parsed) = u.parse::<tauri::Url>() {
|
|
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<BackendMessage> = 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(());
|
|
}
|
|
};
|
|
|
|
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)
|
|
.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();
|
|
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::<BackendMessage>(&line) {
|
|
Ok(m) => m,
|
|
Err(_) => {
|
|
if !line.trim().is_empty() {
|
|
debug_log(&format!("[NODE RAW] {}", line));
|
|
}
|
|
continue;
|
|
}
|
|
};
|
|
|
|
match msg.event.as_str() {
|
|
"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()),
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
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);
|
|
}
|
|
};
|
|
window.app_handle().exit(0);
|
|
}
|
|
}
|
|
})
|
|
.run(tauri::generate_context!())
|
|
.expect("error while running tauri application");
|
|
}
|