Package the native web editor as a Tauri Windows test app

This commit is contained in:
gloamxun committed 2026-12-02 07:47:05 +08:00
1 parent 7f068c7a30
commit 65e60a13e2
11 files changed
+4842 -3

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
/backend/
/target/
+4260
View File
File diff suppressed because it is too large. Load diff
+21
View File
@@ -0,0 +1,21 @@
[package]
name = "texrra-desktop"
version = "0.1.0"
edition = "2024"
rust-version = "1.92"
license = "MIT OR Apache-2.0"
[workspace]
[build-dependencies]
tauri-build = "2"
[dependencies]
serde_json = "1"
tauri = "2"
[features]
custom-protocol = ["tauri/custom-protocol"]
[profile.release]
strip = true
+3
View File
@@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

+203
View File
@@ -0,0 +1,203 @@
#![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 DISTRO: &str = "FedoraLinux-44";
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);
command.args(["--distribution", DISTRO, "--exec"]);
command
}
fn linux_path(path: &Path) -> Result<String, String> {
let result = wsl()
.args(["wslpath", "-a", "-u"])
.arg(path)
.output()
.map_err(|e| format!("无法打开 {DISTRO}。{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 => {
format!("本地引擎启动失败。请确认 {DISTRO} 可以正常打开。")
}
})?
}
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)
.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();
}
});
}
+28
View File
@@ -0,0 +1,28 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Texrra",
"version": "0.1.0",
"identifier": "org.texrra.desktop",
"build": {
"frontendDist": "../startup"
},
"app": {
"windows": [],
"security": {
"capabilities": []
}
},
"bundle": {
"active": true,
"targets": ["nsis"],
"resources": {
"backend/": "backend/"
},
"icon": ["icons/icon.ico"],
"windows": {
"nsis": {
"installMode": "currentUser"
}
}
}
}