| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214 |
- use std::collections::HashMap;
- use std::fs;
- use std::path::{Path, PathBuf};
- use std::sync::Mutex;
- use std::time::Duration;
- use serde::{Deserialize, Serialize};
- use serde_json::{json, Value};
- use tauri::menu::{AboutMetadata, MenuBuilder, MenuItemBuilder, PredefinedMenuItem, SubmenuBuilder};
- use tauri::{AppHandle, Emitter, Manager, State};
- use tauri_plugin_dialog::DialogExt;
- use tauri_plugin_opener::OpenerExt;
- use tauri_plugin_shell::process::CommandEvent;
- use tauri_plugin_shell::ShellExt;
- struct FlashState {
- child: Mutex<Option<tauri_plugin_shell::process::CommandChild>>,
- }
- /// Long-running, generic `luatos-cli --format jsonl` jobs (resource download,
- /// project build, ...), keyed by a caller-provided kind such as "resource".
- struct CliStreamState {
- children: Mutex<HashMap<String, tauri_plugin_shell::process::CommandChild>>,
- }
- #[derive(Debug, Deserialize)]
- #[serde(rename_all = "camelCase")]
- struct FlashOptions {
- soc_path: String,
- port: String,
- #[serde(default)]
- mode: Option<String>,
- #[serde(default)]
- script_dir: Option<String>,
- #[serde(default)]
- baud: Option<String>,
- #[serde(default)]
- tail_log_secs: Option<i64>,
- #[serde(default)]
- rts_reset: bool,
- }
- #[derive(Debug, Default, Serialize)]
- #[serde(rename_all = "camelCase")]
- struct SelftestConfig {
- soc: Option<String>,
- flash_port: Option<String>,
- }
- struct Captured {
- success: bool,
- code: Option<i32>,
- stdout: String,
- stderr: String,
- }
- /// Prefer an explicit LUATOS_CLI override, otherwise use the bundled sidecar.
- fn build_command(
- app: &AppHandle,
- args: &[String],
- ) -> Result<tauri_plugin_shell::process::Command, String> {
- if let Ok(path) = std::env::var("LUATOS_CLI") {
- if !path.trim().is_empty() && Path::new(&path).is_file() {
- return Ok(app.shell().command(path).args(args).env("NO_COLOR", "1"));
- }
- }
- let command = app
- .shell()
- .sidecar("luatos-cli")
- .map_err(|error| format!("找不到内置 luatos-cli:{error}"))?;
- Ok(command.args(args).env("NO_COLOR", "1"))
- }
- fn cli_display_path() -> String {
- if let Ok(path) = std::env::var("LUATOS_CLI") {
- if !path.trim().is_empty() && Path::new(&path).is_file() {
- return path;
- }
- }
- if let Ok(exe) = std::env::current_exe() {
- if let Some(dir) = exe.parent() {
- let candidate = dir.join("luatos-cli");
- if candidate.is_file() {
- return candidate.display().to_string();
- }
- }
- }
- if cfg!(debug_assertions) {
- let dev = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
- .join("binaries")
- .join(format!(
- "luatos-cli-{}-apple-darwin",
- std::env::consts::ARCH
- ));
- if dev.is_file() {
- return dev.display().to_string();
- }
- }
- "luatos-cli(内置 sidecar)".to_string()
- }
- async fn run_capture(
- app: &AppHandle,
- args: &[&str],
- timeout: Duration,
- ) -> Result<Captured, String> {
- let owned: Vec<String> = args.iter().map(|arg| (*arg).to_string()).collect();
- let command = build_command(app, &owned)?;
- let output = tokio::time::timeout(timeout, command.output())
- .await
- .map_err(|_| format!("命令超时({}s):{}", timeout.as_secs(), owned.join(" ")))?
- .map_err(|error| format!("无法启动 luatos-cli:{error}"))?;
- Ok(Captured {
- success: output.status.success(),
- code: output.status.code(),
- stdout: String::from_utf8_lossy(&output.stdout).to_string(),
- stderr: String::from_utf8_lossy(&output.stderr).to_string(),
- })
- }
- async fn run_json(
- app: &AppHandle,
- args: &[&str],
- timeout: Duration,
- ) -> Result<Value, String> {
- let captured = run_capture(app, args, timeout).await?;
- if !captured.success {
- let detail = if captured.stderr.trim().is_empty() {
- captured.stdout.trim()
- } else {
- captured.stderr.trim()
- };
- return Err(if detail.is_empty() {
- format!("luatos-cli 退出码 {:?}", captured.code)
- } else {
- detail.to_string()
- });
- }
- serde_json::from_str(captured.stdout.trim())
- .map_err(|error| format!("无法解析 luatos-cli JSON 输出:{error}"))
- }
- async fn run_text(
- app: &AppHandle,
- args: &[&str],
- timeout: Duration,
- ) -> Result<String, String> {
- let captured = run_capture(app, args, timeout).await?;
- if !captured.success {
- let detail = if captured.stderr.trim().is_empty() {
- captured.stdout.trim()
- } else {
- captured.stderr.trim()
- };
- return Err(if detail.is_empty() {
- format!("luatos-cli 退出码 {:?}", captured.code)
- } else {
- detail.to_string()
- });
- }
- let text = if captured.stdout.trim().is_empty() {
- captured.stderr
- } else {
- captured.stdout
- };
- Ok(text.trim().to_string())
- }
- fn normalize_soc(data: &Value) -> Value {
- let chip = data
- .pointer("/chip/type")
- .and_then(Value::as_str)
- .unwrap_or("unknown");
- let rom_file = data.pointer("/rom/file").cloned().unwrap_or(Value::Null);
- let script_file = data
- .pointer("/script/file")
- .cloned()
- .unwrap_or(Value::Null);
- let mut files: Vec<Value> = Vec::new();
- if let Some(entries) = data.pointer("/rom/files").and_then(Value::as_array) {
- for entry in entries {
- if let Some(name) = entry.get("name").or_else(|| entry.get("file")) {
- if !name.is_null() {
- files.push(name.clone());
- }
- }
- }
- }
- if files.is_empty() {
- for file in [&rom_file, &script_file] {
- if !file.is_null() {
- files.push(file.clone());
- }
- }
- }
- json!({
- "chip": chip,
- "version": data.get("version").cloned().unwrap_or(Value::Null),
- "romFile": rom_file,
- "scriptFile": script_file,
- "files": files,
- "raw": data,
- })
- }
- fn signal_name(signal: i32) -> String {
- match signal {
- 2 => "SIGINT".to_string(),
- 9 => "SIGKILL".to_string(),
- 15 => "SIGTERM".to_string(),
- other => format!("signal {other}"),
- }
- }
- fn emit_chunk(app: &AppHandle, chunk: &str, source: &str) {
- for line in chunk.lines() {
- let trimmed = line.trim();
- if trimmed.is_empty() {
- continue;
- }
- if source == "stdout" && trimmed.starts_with('{') {
- if let Ok(value) = serde_json::from_str::<Value>(trimmed) {
- let _ = app.emit("flash:event", value);
- continue;
- }
- }
- let _ = app.emit("flash:line", json!({ "line": trimmed, "source": source }));
- }
- }
- fn emit_chunk_named(app: &AppHandle, kind: &str, chunk: &str, source: &str) {
- let event_name = format!("{kind}:event");
- let line_name = format!("{kind}:line");
- for line in chunk.lines() {
- let trimmed = line.trim();
- if trimmed.is_empty() {
- continue;
- }
- if source == "stdout" && trimmed.starts_with('{') {
- if let Ok(value) = serde_json::from_str::<Value>(trimmed) {
- let _ = app.emit(&event_name, value);
- continue;
- }
- }
- let _ = app.emit(&line_name, json!({ "line": trimmed, "source": source }));
- }
- }
- /// Only expose read-only / local-management commands to the renderer through
- /// the generic bridge. Flashing keeps its dedicated command.
- fn cli_command_allowed(args: &[String]) -> bool {
- matches!(
- args.first().map(String::as_str),
- Some("serial" | "soc" | "resource" | "project" | "guide" | "device" | "log")
- )
- }
- fn json_error(message: impl Into<String>) -> Value {
- json!({ "ok": false, "error": message.into() })
- }
- #[tauri::command]
- async fn cli_info(app: AppHandle) -> Value {
- let path = cli_display_path();
- match run_text(&app, &["--version"], Duration::from_secs(10)).await {
- Ok(text) => {
- let version = text.trim().trim_start_matches("luatos-cli").trim().to_string();
- let models = run_json(
- &app,
- &["--format", "json", "guide", "models"],
- Duration::from_secs(15),
- )
- .await
- .ok()
- .and_then(|value| value.pointer("/data/models").cloned())
- .unwrap_or_else(|| json!([]));
- json!({ "ok": true, "path": path, "version": version, "models": models })
- }
- Err(error) => json!({ "ok": false, "path": path, "error": error }),
- }
- }
- #[tauri::command]
- async fn serial_list(app: AppHandle) -> Value {
- match run_json(
- &app,
- &["--format", "json", "serial", "list"],
- Duration::from_secs(12),
- )
- .await
- {
- Ok(value) => json!({
- "ok": true,
- "ports": value.get("data").cloned().unwrap_or_else(|| json!([])),
- }),
- Err(error) => json!({ "ok": false, "ports": [], "error": error }),
- }
- }
- #[tauri::command]
- async fn soc_info(app: AppHandle, soc_path: String) -> Value {
- if soc_path.trim().is_empty() || !Path::new(&soc_path).is_file() {
- return json!({ "ok": false, "error": "文件不存在" });
- }
- match run_json(
- &app,
- &["--format", "json", "soc", "info", &soc_path],
- Duration::from_secs(20),
- )
- .await
- {
- Ok(value) => {
- let data = value.get("data").cloned().unwrap_or(Value::Null);
- json!({ "ok": true, "info": normalize_soc(&data), "raw": data })
- }
- Err(error) => json!({ "ok": false, "error": error }),
- }
- }
- #[tauri::command]
- async fn flash_start(
- app: AppHandle,
- state: State<'_, FlashState>,
- options: FlashOptions,
- ) -> Result<Value, String> {
- let soc_path = options.soc_path.trim().to_string();
- if soc_path.is_empty() || !Path::new(&soc_path).is_file() {
- return Ok(json!({ "ok": false, "error": "固件文件不存在,请重新选择 .soc 文件" }));
- }
- let port = options.port.trim().to_string();
- if port.is_empty() {
- return Ok(json!({ "ok": false, "error": "请选择串口" }));
- }
- let mode = options.mode.unwrap_or_else(|| "full".to_string());
- let script_dir = options.script_dir.filter(|dir| !dir.trim().is_empty());
- if mode == "script" && script_dir.is_none() {
- return Ok(json!({ "ok": false, "error": "“仅刷脚本区”需要选择一个脚本目录" }));
- }
- if state.child.lock().unwrap().is_some() {
- return Ok(json!({ "ok": false, "error": "已有烧录任务正在运行" }));
- }
- let mut args: Vec<String> = vec![
- "--format".to_string(),
- "jsonl".to_string(),
- "flash".to_string(),
- if mode == "script" {
- "script".to_string()
- } else {
- "run".to_string()
- },
- "--soc".to_string(),
- soc_path.clone(),
- "--port".to_string(),
- port.clone(),
- ];
- if let Some(dir) = &script_dir {
- args.push("--script".to_string());
- args.push(dir.clone());
- }
- if let Some(baud) = options.baud.filter(|baud| !baud.trim().is_empty()) {
- args.push("--baud".to_string());
- args.push(baud);
- }
- if mode != "script" {
- if let Some(secs) = options.tail_log_secs {
- if secs > 0 {
- args.push("--tail-log-secs".to_string());
- args.push(secs.to_string());
- }
- }
- }
- if options.rts_reset {
- args.push("--rts-reset".to_string());
- }
- let command = build_command(&app, &args)?;
- eprintln!("[flash] spawn: luatos-cli {}", args.join(" "));
- let command_line = format!("luatos-cli {}", args.join(" "));
- let _ = app.emit(
- "flash:started",
- json!({
- "commandLine": command_line,
- "port": port,
- "socPath": soc_path,
- "mode": mode,
- }),
- );
- let (mut rx, child) = command
- .spawn()
- .map_err(|error| format!("无法启动 luatos-cli:{error}"))?;
- *state.child.lock().unwrap() = Some(child);
- let mut code: Option<i32> = None;
- let mut signal: Option<i32> = None;
- let mut spawn_error: Option<String> = None;
- while let Some(event) = rx.recv().await {
- match event {
- CommandEvent::Stdout(bytes) => {
- emit_chunk(&app, &String::from_utf8_lossy(&bytes), "stdout")
- }
- CommandEvent::Stderr(bytes) => {
- emit_chunk(&app, &String::from_utf8_lossy(&bytes), "stderr")
- }
- CommandEvent::Error(error) => spawn_error = Some(error),
- CommandEvent::Terminated(payload) => {
- code = payload.code;
- signal = payload.signal;
- }
- _ => {}
- }
- }
- *state.child.lock().unwrap() = None;
- eprintln!("[flash] exit code={code:?} signal={signal:?} error={spawn_error:?}");
- let signal_text = signal.map(signal_name);
- let _ = app.emit(
- "flash:exit",
- json!({
- "code": code.unwrap_or(-1),
- "signal": signal_text,
- "error": spawn_error,
- }),
- );
- Ok(json!({
- "ok": spawn_error.is_none() && code == Some(0),
- "code": code,
- "signal": signal_text,
- "error": spawn_error,
- }))
- }
- #[tauri::command]
- fn flash_cancel(state: State<'_, FlashState>) -> Value {
- let child = state.child.lock().unwrap().take();
- match child {
- Some(child) => match child.kill() {
- Ok(_) => json!({ "ok": true }),
- Err(error) => json!({ "ok": false, "error": error.to_string() }),
- },
- None => json!({ "ok": false, "error": "没有正在运行的烧录任务" }),
- }
- }
- fn file_path_string(path: tauri_plugin_dialog::FilePath) -> Option<String> {
- path.into_path()
- .ok()
- .map(|path| path.display().to_string())
- }
- #[tauri::command]
- async fn open_soc_dialog(app: AppHandle) -> Option<String> {
- let (tx, rx) = tokio::sync::oneshot::channel();
- app.dialog()
- .file()
- .set_title("选择 LuatOS 固件")
- .add_filter("LuatOS 固件", &["soc"])
- .add_filter("所有文件", &["*"])
- .pick_file(move |path| {
- let _ = tx.send(path);
- });
- rx.await.ok().flatten().and_then(file_path_string)
- }
- #[tauri::command]
- async fn open_script_dir_dialog(app: AppHandle) -> Option<String> {
- let (tx, rx) = tokio::sync::oneshot::channel();
- app.dialog()
- .file()
- .set_title("选择脚本目录")
- .pick_folder(move |path| {
- let _ = tx.send(path);
- });
- rx.await.ok().flatten().and_then(file_path_string)
- }
- #[tauri::command]
- async fn save_log(app: AppHandle, content: String) -> Value {
- let name = format!(
- "luatos-flash-{}.log",
- std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .map(|duration| duration.as_secs())
- .unwrap_or(0)
- );
- let (tx, rx) = tokio::sync::oneshot::channel();
- app.dialog()
- .file()
- .set_title("保存烧录日志")
- .set_file_name(&name)
- .add_filter("日志文件", &["log", "txt"])
- .save_file(move |path| {
- let _ = tx.send(path);
- });
- match rx.await.ok().flatten().and_then(file_path_string) {
- Some(path) => match std::fs::write(&path, content) {
- Ok(_) => json!({ "ok": true, "path": path }),
- Err(error) => json!({ "ok": false, "error": error.to_string() }),
- },
- None => json!({ "ok": false }),
- }
- }
- #[tauri::command]
- fn open_external(app: AppHandle, url: String) -> Value {
- if !(url.starts_with("http://") || url.starts_with("https://")) {
- return json!({ "ok": false, "error": "只允许打开 http(s) 链接" });
- }
- match app.opener().open_url(url, None::<&str>) {
- Ok(_) => json!({ "ok": true }),
- Err(error) => json!({ "ok": false, "error": error.to_string() }),
- }
- }
- #[tauri::command]
- fn selftest_config() -> SelftestConfig {
- let mut config = SelftestConfig::default();
- for arg in std::env::args() {
- if let Some(value) = arg.strip_prefix("--selftest-soc=") {
- config.soc = Some(value.to_string());
- } else if let Some(value) = arg.strip_prefix("--selftest-flash-soc=") {
- config.soc = Some(value.to_string());
- } else if let Some(value) = arg.strip_prefix("--selftest-flash-port=") {
- config.flash_port = Some(value.to_string());
- }
- }
- config
- }
- #[tauri::command]
- fn js_log(level: String, message: String) {
- eprintln!("[js:{level}] {message}");
- }
- #[tauri::command]
- fn selftest_report(app: AppHandle, payload: Value) {
- println!(
- "SELFTEST {}",
- serde_json::to_string_pretty(&payload).unwrap_or_else(|_| payload.to_string())
- );
- let handle = app.clone();
- std::thread::spawn(move || {
- std::thread::sleep(Duration::from_millis(200));
- handle.exit(0);
- });
- }
- #[tauri::command]
- async fn cli_json(app: AppHandle, args: Vec<String>) -> Value {
- if !cli_command_allowed(&args) {
- return json_error("不允许的 luatos-cli 子命令");
- }
- let mut full: Vec<String> = vec!["--format".into(), "json".into()];
- full.extend(args);
- let refs: Vec<&str> = full.iter().map(String::as_str).collect();
- match run_json(&app, &refs, Duration::from_secs(300)).await {
- Ok(mut value) => {
- if let Some(object) = value.as_object_mut() {
- object.insert("ok".to_string(), Value::Bool(true));
- }
- value
- }
- Err(error) => json_error(error),
- }
- }
- /// Generic streaming bridge for `luatos-cli --format jsonl`.
- ///
- /// The renderer passes `kind = "resource"` / `"project"` and the CLI args; the
- /// backend emits `<kind>:event`, `<kind>:line` and `<kind>:exit`.
- #[tauri::command]
- async fn cli_stream(
- app: AppHandle,
- state: State<'_, CliStreamState>,
- kind: String,
- args: Vec<String>,
- ) -> Result<Value, String> {
- let safe_kind = !kind.is_empty()
- && kind
- .chars()
- .all(|character| character.is_ascii_alphanumeric() || character == '-' || character == '_');
- if !safe_kind {
- return Ok(json_error("非法的任务类型"));
- }
- if !cli_command_allowed(&args) {
- return Ok(json_error("不允许的 luatos-cli 子命令"));
- }
- if state.children.lock().unwrap().contains_key(&kind) {
- return Ok(json_error(format!("{kind} 任务正在运行")));
- }
- let mut full: Vec<String> = vec!["--format".into(), "jsonl".into()];
- full.extend(args);
- let command = build_command(&app, &full)?;
- let (mut receiver, child) = command
- .spawn()
- .map_err(|error| format!("无法启动 luatos-cli:{error}"))?;
- state.children.lock().unwrap().insert(kind.clone(), child);
- let mut code: Option<i32> = None;
- let mut signal: Option<i32> = None;
- let mut spawn_error: Option<String> = None;
- while let Some(event) = receiver.recv().await {
- match event {
- CommandEvent::Stdout(bytes) => {
- emit_chunk_named(&app, &kind, &String::from_utf8_lossy(&bytes), "stdout")
- }
- CommandEvent::Stderr(bytes) => {
- emit_chunk_named(&app, &kind, &String::from_utf8_lossy(&bytes), "stderr")
- }
- CommandEvent::Error(error) => spawn_error = Some(error),
- CommandEvent::Terminated(payload) => {
- code = payload.code;
- signal = payload.signal;
- }
- _ => {}
- }
- }
- state.children.lock().unwrap().remove(&kind);
- let signal_text = signal.map(signal_name);
- let _ = app.emit(
- &format!("{kind}:exit"),
- json!({
- "code": code.unwrap_or(-1),
- "signal": signal_text,
- "error": spawn_error,
- }),
- );
- Ok(json!({
- "ok": spawn_error.is_none() && code == Some(0),
- "code": code,
- "signal": signal_text,
- "error": spawn_error,
- }))
- }
- #[tauri::command]
- fn stream_cancel(state: State<'_, CliStreamState>, kind: String) -> Value {
- let child = state.children.lock().unwrap().remove(&kind);
- match child {
- Some(child) => match child.kill() {
- Ok(_) => json!({ "ok": true }),
- Err(error) => json_error(error.to_string()),
- },
- None => json_error(format!("{kind} 没有正在运行的任务")),
- }
- }
- fn app_subdir(app: &AppHandle, name: &str) -> PathBuf {
- let base = app
- .path()
- .app_data_dir()
- .unwrap_or_else(|_| PathBuf::from("."));
- let dir = base.join(name);
- let _ = fs::create_dir_all(&dir);
- dir
- }
- #[tauri::command]
- fn app_paths(app: AppHandle) -> Value {
- let base = app
- .path()
- .app_data_dir()
- .unwrap_or_else(|_| PathBuf::from("."));
- let projects = app_subdir(&app, "projects");
- let resources = app_subdir(&app, "resources");
- json!({
- "ok": true,
- "appData": base.display().to_string(),
- "projects": projects.display().to_string(),
- "resources": resources.display().to_string(),
- })
- }
- #[tauri::command]
- fn read_text_file(path: String) -> Value {
- let file_path = Path::new(&path);
- if !file_path.is_file() {
- return json_error("文件不存在");
- }
- let metadata = match fs::metadata(file_path) {
- Ok(metadata) => metadata,
- Err(error) => return json_error(error.to_string()),
- };
- if metadata.len() > 4 * 1024 * 1024 {
- return json_error("文件太大(超过 4MB)");
- }
- match fs::read(file_path) {
- Ok(data) => json!({
- "ok": true,
- "content": String::from_utf8_lossy(&data).to_string(),
- }),
- Err(error) => json_error(error.to_string()),
- }
- }
- #[tauri::command]
- fn write_text_file(path: String, content: String) -> Value {
- let file_path = Path::new(&path);
- if let Some(parent) = file_path.parent() {
- if let Err(error) = fs::create_dir_all(parent) {
- return json_error(error.to_string());
- }
- }
- match fs::write(file_path, content) {
- Ok(_) => json!({ "ok": true }),
- Err(error) => json_error(error.to_string()),
- }
- }
- fn collect_files(root: &Path, current: &Path, output: &mut Vec<Value>, count: &mut usize) {
- if *count >= 4000 {
- return;
- }
- let entries = match fs::read_dir(current) {
- Ok(entries) => entries,
- Err(_) => return,
- };
- for entry in entries.flatten() {
- let name = entry.file_name().to_string_lossy().to_string();
- if matches!(name.as_str(), ".git" | "node_modules" | "target" | ".DS_Store") {
- continue;
- }
- let path = entry.path();
- let metadata = match entry.metadata() {
- Ok(metadata) => metadata,
- Err(_) => continue,
- };
- let relative = path
- .strip_prefix(root)
- .unwrap_or(path.as_path())
- .to_string_lossy()
- .replace('\\', "/");
- if metadata.is_dir() {
- output.push(json!({
- "path": relative,
- "name": name,
- "isDir": true,
- "size": 0,
- }));
- collect_files(root, &path, output, count);
- } else {
- output.push(json!({
- "path": relative,
- "name": name,
- "isDir": false,
- "size": metadata.len(),
- }));
- }
- *count += 1;
- if *count >= 4000 {
- return;
- }
- }
- }
- #[tauri::command]
- fn list_files(path: String) -> Value {
- let root = Path::new(&path);
- if !root.is_dir() {
- return json_error("目录不存在");
- }
- let mut output = Vec::new();
- let mut count = 0usize;
- collect_files(root, root, &mut output, &mut count);
- json!({ "ok": true, "files": output })
- }
- #[tauri::command]
- fn scan_projects(root: String) -> Value {
- let root_path = Path::new(&root);
- if !root_path.is_dir() {
- return json_error("项目目录不存在");
- }
- let mut projects = Vec::new();
- if let Ok(entries) = fs::read_dir(root_path) {
- for entry in entries.flatten() {
- let path = entry.path();
- if path.is_dir() && path.join("luatos-project.toml").is_file() {
- let name = entry.file_name().to_string_lossy().to_string();
- let modified = fs::metadata(&path)
- .and_then(|metadata| metadata.modified())
- .ok()
- .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
- .map(|duration| duration.as_secs())
- .unwrap_or(0);
- projects.push(json!({
- "name": name,
- "path": path.display().to_string(),
- "modified": modified,
- }));
- }
- }
- }
- projects.sort_by(|left, right| {
- right["modified"]
- .as_u64()
- .cmp(&left["modified"].as_u64())
- });
- json!({ "ok": true, "projects": projects })
- }
- #[tauri::command]
- fn delete_project(dir: String) -> Value {
- let path = Path::new(&dir);
- if !path.join("luatos-project.toml").is_file() {
- return json_error("不是有效的 LuatOS 项目目录");
- }
- match fs::remove_dir_all(path) {
- Ok(_) => json!({ "ok": true }),
- Err(error) => json_error(error.to_string()),
- }
- }
- fn copy_dir_all(source: &Path, destination: &Path) -> std::io::Result<()> {
- fs::create_dir_all(destination)?;
- for entry in fs::read_dir(source)? {
- let entry = entry?;
- let file_type = entry.file_type()?;
- let target = destination.join(entry.file_name());
- if file_type.is_dir() {
- copy_dir_all(&entry.path(), &target)?;
- } else {
- fs::copy(entry.path(), &target)?;
- }
- }
- Ok(())
- }
- #[tauri::command]
- fn clone_project(src: String, dst: String) -> Value {
- let source = Path::new(&src);
- let destination = Path::new(&dst);
- if !source.join("luatos-project.toml").is_file() {
- return json_error("源项目无效");
- }
- if destination.exists() {
- return json_error("目标目录已存在");
- }
- match copy_dir_all(source, destination) {
- Ok(_) => json!({ "ok": true }),
- Err(error) => json_error(error.to_string()),
- }
- }
- #[tauri::command]
- fn create_dir(path: String) -> Value {
- match fs::create_dir_all(&path) {
- Ok(_) => json!({ "ok": true }),
- Err(error) => json_error(error.to_string()),
- }
- }
- #[tauri::command]
- fn path_exists(path: String) -> Value {
- json!({ "ok": true, "exists": Path::new(&path).exists() })
- }
- #[tauri::command]
- fn reveal_path(path: String) -> Value {
- let target = Path::new(&path);
- if !target.exists() {
- return json_error("路径不存在");
- }
- #[cfg(target_os = "macos")]
- let result = if target.is_file() {
- std::process::Command::new("open")
- .arg("-R")
- .arg(target)
- .spawn()
- } else {
- std::process::Command::new("open").arg(target).spawn()
- };
- #[cfg(target_os = "windows")]
- let result = if target.is_file() {
- std::process::Command::new("explorer")
- .arg(format!("/select,{}", target.display()))
- .spawn()
- } else {
- std::process::Command::new("explorer").arg(target).spawn()
- };
- #[cfg(all(not(target_os = "macos"), not(target_os = "windows")))]
- let result = std::process::Command::new("xdg-open")
- .arg(if target.is_dir() {
- target
- } else {
- target.parent().unwrap_or(target)
- })
- .spawn();
- match result {
- Ok(_) => json!({ "ok": true }),
- Err(error) => json_error(error.to_string()),
- }
- }
- #[tauri::command]
- async fn open_file_dialog(app: AppHandle, filters: Vec<String>) -> Option<String> {
- let filter_refs: Vec<&str> = filters.iter().map(String::as_str).collect();
- let (tx, rx) = tokio::sync::oneshot::channel();
- let mut builder = app.dialog().file().set_title("选择文件");
- if filter_refs.is_empty() {
- builder = builder.add_filter("所有文件", &["*"]);
- } else {
- builder = builder.add_filter("文件", &filter_refs);
- }
- builder.pick_file(move |path| {
- let _ = tx.send(path);
- });
- rx.await.ok().flatten().and_then(file_path_string)
- }
- #[tauri::command]
- async fn open_folder_dialog(app: AppHandle) -> Option<String> {
- let (tx, rx) = tokio::sync::oneshot::channel();
- app.dialog()
- .file()
- .set_title("选择目录")
- .pick_folder(move |path| {
- let _ = tx.send(path);
- });
- rx.await.ok().flatten().and_then(file_path_string)
- }
- #[tauri::command]
- async fn save_file_dialog(
- app: AppHandle,
- default_name: Option<String>,
- filters: Vec<String>,
- ) -> Option<String> {
- let filter_refs: Vec<&str> = filters.iter().map(String::as_str).collect();
- let (tx, rx) = tokio::sync::oneshot::channel();
- let mut builder = app.dialog().file().set_title("保存文件");
- if let Some(name) = default_name {
- if !name.trim().is_empty() {
- builder = builder.set_file_name(&name);
- }
- }
- if filter_refs.is_empty() {
- builder = builder.add_filter("所有文件", &["*"]);
- } else {
- builder = builder.add_filter("文件", &filter_refs);
- }
- builder.save_file(move |path| {
- let _ = tx.send(path);
- });
- rx.await.ok().flatten().and_then(file_path_string)
- }
- fn find_named_file(root: &Path, file_name: &str, depth: usize) -> Option<PathBuf> {
- if depth == 0 {
- return None;
- }
- let entries = fs::read_dir(root).ok()?;
- for entry in entries.flatten() {
- let path = entry.path();
- if path.is_file()
- && path
- .file_name()
- .and_then(|name| name.to_str())
- .map(|name| name == file_name)
- .unwrap_or(false)
- {
- return Some(path);
- }
- if path.is_dir() {
- if let Some(found) = find_named_file(&path, file_name, depth - 1) {
- return Some(found);
- }
- }
- }
- None
- }
- #[tauri::command]
- fn mcp_info(app: AppHandle) -> Value {
- let mut candidates = Vec::new();
- let mut resource_root: Option<PathBuf> = None;
- if let Ok(resource_dir) = app.path().resource_dir() {
- candidates.push(resource_dir.join("mcp").join("luatos-mcp.mjs"));
- candidates.push(
- resource_dir
- .join("resources")
- .join("mcp")
- .join("luatos-mcp.mjs"),
- );
- resource_root = Some(resource_dir);
- }
- candidates.push(
- PathBuf::from(env!("CARGO_MANIFEST_DIR"))
- .join("mcp")
- .join("luatos-mcp.mjs"),
- );
- let script = candidates
- .into_iter()
- .find(|path| path.is_file())
- .or_else(|| {
- resource_root
- .as_deref()
- .and_then(|root| find_named_file(root, "luatos-mcp.mjs", 4))
- })
- .map(|path| path.display().to_string())
- .unwrap_or_default();
- let cli = cli_display_path();
- let node_version = std::process::Command::new("node")
- .arg("--version")
- .output()
- .ok()
- .filter(|output| output.status.success())
- .map(|output| String::from_utf8_lossy(&output.stdout).trim().to_string())
- .unwrap_or_default();
- let config = if script.is_empty() {
- Value::Null
- } else {
- json!({
- "mcpServers": {
- "luatos": {
- "command": "node",
- "args": [script.clone()],
- "env": { "LUATOS_CLI": cli.clone() }
- }
- }
- })
- };
- json!({
- "ok": !script.is_empty(),
- "script": script,
- "cli": cli,
- "node": node_version,
- "config": config,
- })
- }
- fn build_app_menu(app: &tauri::App) -> tauri::Result<tauri::menu::Menu<tauri::Wry>> {
- let about = PredefinedMenuItem::about(
- app,
- Some("关于 LuatOS Flasher"),
- Some(AboutMetadata {
- name: Some("LuatOS Flasher".to_string()),
- version: Some(env!("CARGO_PKG_VERSION").to_string()),
- credits: Some("烧录内核:luatos-cli (MIT)\n界面:Tauri + WKWebView".to_string()),
- ..Default::default()
- }),
- )?;
- let app_menu = SubmenuBuilder::new(app, "LuatOS Flasher")
- .item(&about)
- .separator()
- .item(&PredefinedMenuItem::services(app, Some("服务"))?)
- .separator()
- .item(&PredefinedMenuItem::hide(app, Some("隐藏 LuatOS Flasher"))?)
- .item(&PredefinedMenuItem::hide_others(app, Some("隐藏其他"))?)
- .item(&PredefinedMenuItem::show_all(app, Some("全部显示"))?)
- .separator()
- .item(&PredefinedMenuItem::quit(app, Some("退出 LuatOS Flasher"))?)
- .build()?;
- let open = MenuItemBuilder::with_id("menu:open-soc", "打开固件…")
- .accelerator("CmdOrCtrl+O")
- .build(app)?;
- let save_log = MenuItemBuilder::with_id("menu:save-log", "保存日志…")
- .accelerator("CmdOrCtrl+S")
- .build(app)?;
- let file_menu = SubmenuBuilder::new(app, "文件")
- .item(&open)
- .item(&save_log)
- .separator()
- .item(&PredefinedMenuItem::close_window(app, Some("关闭窗口"))?)
- .build()?;
- let edit_menu = SubmenuBuilder::new(app, "编辑")
- .undo()
- .redo()
- .separator()
- .cut()
- .copy()
- .paste()
- .select_all()
- .build()?;
- let docs = MenuItemBuilder::with_id("help:docs", "LuatOS 文档").build(app)?;
- let cli = MenuItemBuilder::with_id("help:cli", "luatos-cli 项目").build(app)?;
- let help_menu = SubmenuBuilder::new(app, "帮助")
- .item(&docs)
- .item(&cli)
- .build()?;
- MenuBuilder::new(app)
- .items(&[&app_menu, &file_menu, &edit_menu, &help_menu])
- .build()
- }
- #[cfg_attr(mobile, tauri::mobile_entry_point)]
- pub fn run() {
- tauri::Builder::default()
- .plugin(tauri_plugin_shell::init())
- .plugin(tauri_plugin_dialog::init())
- .plugin(tauri_plugin_opener::init())
- .manage(FlashState {
- child: Mutex::new(None),
- })
- .manage(CliStreamState {
- children: Mutex::new(HashMap::new()),
- })
- .setup(|app| {
- let menu = build_app_menu(app)?;
- app.set_menu(menu)?;
- app.on_menu_event(|app, event| {
- let id = event.id().0.as_str();
- match id {
- "menu:open-soc" => {
- let _ = app.emit("menu", "open-soc");
- }
- "menu:save-log" => {
- let _ = app.emit("menu", "save-log");
- }
- "help:docs" => {
- let _ = app
- .opener()
- .open_url("https://wiki.luatos.com/", None::<&str>);
- }
- "help:cli" => {
- let _ = app
- .opener()
- .open_url("https://github.com/wendal/luatos-cli", None::<&str>);
- }
- _ => {}
- }
- });
- Ok(())
- })
- .invoke_handler(tauri::generate_handler![
- cli_info,
- serial_list,
- soc_info,
- flash_start,
- flash_cancel,
- open_soc_dialog,
- open_script_dir_dialog,
- save_log,
- open_external,
- cli_json,
- cli_stream,
- stream_cancel,
- app_paths,
- read_text_file,
- write_text_file,
- list_files,
- scan_projects,
- delete_project,
- clone_project,
- create_dir,
- path_exists,
- reveal_path,
- open_file_dialog,
- open_folder_dialog,
- save_file_dialog,
- mcp_info,
- selftest_config,
- js_log,
- selftest_report
- ])
- .run(tauri::generate_context!())
- .expect("error while running LuatOS Flasher");
- }
|