207 lines
7.4 KiB
Rust
207 lines
7.4 KiB
Rust
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
|
|
|
use std::{
|
|
io::{BufRead, BufReader},
|
|
os::windows::process::CommandExt,
|
|
path::{Path, PathBuf},
|
|
process::{Child, Command, Stdio},
|
|
sync::{Arc, Mutex, mpsc},
|
|
thread,
|
|
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
|
|
};
|
|
|
|
use tauri::{Manager, RunEvent, Url, WebviewUrl, WebviewWindow, WebviewWindowBuilder};
|
|
|
|
const HIDE_CONSOLE: u32 = 0x08000000;
|
|
const READY_PREFIX: &str = "Native editor ";
|
|
|
|
#[derive(Default)]
|
|
struct Backend(Mutex<Option<Child>>);
|
|
|
|
impl Backend {
|
|
fn stop(&self) {
|
|
let Some(mut child) = self.0.lock().unwrap().take() else {
|
|
return;
|
|
};
|
|
// The private launcher takes EOF as the end of its desktop lease.
|
|
drop(child.stdin.take());
|
|
let deadline = Instant::now() + Duration::from_secs(4);
|
|
while Instant::now() < deadline {
|
|
if !matches!(child.try_wait(), Ok(None)) {
|
|
return;
|
|
}
|
|
thread::sleep(Duration::from_millis(40));
|
|
}
|
|
let _ = child.kill();
|
|
let _ = child.wait();
|
|
}
|
|
}
|
|
|
|
fn wsl() -> Command {
|
|
let mut command = Command::new("wsl.exe");
|
|
command.creation_flags(HIDE_CONSOLE);
|
|
if let Some(distribution) = std::env::var_os("TEXRRA_WSL_DISTRO").filter(|d| !d.is_empty()) {
|
|
command.arg("--distribution").arg(distribution);
|
|
}
|
|
command.arg("--exec");
|
|
command
|
|
}
|
|
|
|
fn linux_path(path: &Path) -> Result<String, String> {
|
|
let result = wsl()
|
|
.args(["wslpath", "-a", "-u"])
|
|
.arg(path)
|
|
.output()
|
|
.map_err(|e| format!("无法启动 Windows 的 WSL 环境。{e}"))?;
|
|
if !result.status.success() {
|
|
return Err(format!(
|
|
"无法读取桌面版引擎资源。{}",
|
|
String::from_utf8_lossy(&result.stderr).trim()
|
|
));
|
|
}
|
|
let converted = String::from_utf8(result.stdout).map_err(|e| e.to_string())?;
|
|
let path = converted.trim();
|
|
if !path.starts_with('/') {
|
|
return Err("桌面版引擎资源路径无效。".into());
|
|
}
|
|
Ok(path.to_owned())
|
|
}
|
|
|
|
fn ready_url(text: &str) -> Option<Url> {
|
|
let url = Url::parse(text.strip_prefix(READY_PREFIX)?.trim()).ok()?;
|
|
(url.scheme() == "http"
|
|
&& url.host_str() == Some("127.0.0.1")
|
|
&& url.port().is_some()
|
|
&& url.path() == "/"
|
|
&& url.query().is_none()
|
|
&& url.fragment().is_none()
|
|
&& url.username().is_empty()
|
|
&& url.password().is_none())
|
|
.then_some(url)
|
|
}
|
|
|
|
fn start_engine(backend: &Backend, launcher: &Path) -> Result<Url, String> {
|
|
let script = linux_path(launcher)?;
|
|
let now = SystemTime::now()
|
|
.duration_since(UNIX_EPOCH)
|
|
.unwrap_or_default();
|
|
let instance = format!("{:08x}{:032x}", std::process::id(), now.as_nanos());
|
|
let mut child = wsl()
|
|
.args(["python3", &script, "launch", "--instance", &instance])
|
|
.stdin(Stdio::piped())
|
|
.stdout(Stdio::piped())
|
|
.spawn()
|
|
.map_err(|e| format!("无法启动本地引擎。{e}"))?;
|
|
let stdout = child.stdout.take().unwrap();
|
|
*backend.0.lock().unwrap() = Some(child);
|
|
|
|
let (send, reply) = mpsc::sync_channel(1);
|
|
thread::spawn(move || {
|
|
let mut send = Some(send);
|
|
for line in BufReader::new(stdout).lines().map_while(Result::ok) {
|
|
let Some(result) = ready_url(&line).map(Ok).or_else(|| {
|
|
line.strip_prefix("Texrra desktop error ")
|
|
.map(|error| Err(error.to_owned()))
|
|
}) else {
|
|
continue;
|
|
};
|
|
if let Some(send) = send.take() {
|
|
let _ = send.send(result);
|
|
}
|
|
}
|
|
});
|
|
reply
|
|
.recv_timeout(Duration::from_secs(60))
|
|
.map_err(|error| match error {
|
|
mpsc::RecvTimeoutError::Timeout => "启动本地引擎超时。".to_owned(),
|
|
mpsc::RecvTimeoutError::Disconnected => {
|
|
"本地引擎启动失败。请确认当前默认的 WSL 发行版可以正常打开。".to_owned()
|
|
}
|
|
})?
|
|
}
|
|
|
|
fn show_error(window: &WebviewWindow, message: &str) {
|
|
if let Ok(text) = serde_json::to_string(message) {
|
|
let _ = window.eval(&format!(
|
|
"if (document.querySelector('#status')) document.querySelector('#status').textContent = {text};"
|
|
));
|
|
}
|
|
}
|
|
|
|
fn backend_launcher(app: &tauri::App) -> Result<PathBuf, String> {
|
|
let bundled = app
|
|
.path()
|
|
.resource_dir()
|
|
.map_err(|e| e.to_string())?
|
|
.join("backend/wsl-launch.py");
|
|
if bundled.is_file() {
|
|
return Ok(bundled);
|
|
}
|
|
let executable = std::env::current_exe().map_err(|e| e.to_string())?;
|
|
let portable = executable.with_file_name("backend").join("wsl-launch.py");
|
|
if portable.is_file() {
|
|
return Ok(portable);
|
|
}
|
|
Err("缺少同目录的 backend 文件夹。请先解压整个 Texrra 桌面版。".into())
|
|
}
|
|
|
|
fn main() {
|
|
tauri::Builder::default()
|
|
.manage(Backend::default())
|
|
.setup(|app| {
|
|
let allowed = Arc::new(Mutex::new(None::<Url>));
|
|
let navigation = Arc::clone(&allowed);
|
|
let startup_error = Arc::new(Mutex::new(None::<String>));
|
|
let deferred_error = Arc::clone(&startup_error);
|
|
let window =
|
|
WebviewWindowBuilder::new(app, "main", WebviewUrl::App("index.html".into()))
|
|
.title("Texrra")
|
|
.inner_size(1280.0, 900.0)
|
|
.min_inner_size(780.0, 540.0)
|
|
.disable_drag_drop_handler()
|
|
.on_navigation(move |url| {
|
|
matches!(
|
|
url.as_str(),
|
|
"http://tauri.localhost/" | "http://tauri.localhost/index.html"
|
|
) || navigation
|
|
.lock()
|
|
.unwrap()
|
|
.as_ref()
|
|
.is_some_and(|origin| origin.origin() == url.origin())
|
|
})
|
|
.on_page_load(move |window, payload| {
|
|
if payload.url().host_str() == Some("tauri.localhost") {
|
|
if let Some(error) = deferred_error.lock().unwrap().as_deref() {
|
|
show_error(&window, error);
|
|
}
|
|
}
|
|
})
|
|
.build()?;
|
|
let launcher = backend_launcher(app);
|
|
let handle = app.handle().clone();
|
|
thread::spawn(move || {
|
|
let backend = handle.state::<Backend>();
|
|
let start = launcher.and_then(|launcher| start_engine(&backend, &launcher));
|
|
let result = start.and_then(|url| {
|
|
*allowed.lock().unwrap() = Some(url.clone());
|
|
window
|
|
.navigate(url)
|
|
.map_err(|error| format!("工作台打开失败。{error}"))
|
|
});
|
|
if let Err(error) = result {
|
|
backend.stop();
|
|
*startup_error.lock().unwrap() = Some(error.clone());
|
|
show_error(&window, &error);
|
|
}
|
|
});
|
|
Ok(())
|
|
})
|
|
.build(tauri::generate_context!())
|
|
.expect("Texrra desktop could not initialize")
|
|
.run(|app, event| {
|
|
if matches!(event, RunEvent::Exit) {
|
|
app.state::<Backend>().stop();
|
|
}
|
|
});
|
|
}
|