lib.rs 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214
  1. use std::collections::HashMap;
  2. use std::fs;
  3. use std::path::{Path, PathBuf};
  4. use std::sync::Mutex;
  5. use std::time::Duration;
  6. use serde::{Deserialize, Serialize};
  7. use serde_json::{json, Value};
  8. use tauri::menu::{AboutMetadata, MenuBuilder, MenuItemBuilder, PredefinedMenuItem, SubmenuBuilder};
  9. use tauri::{AppHandle, Emitter, Manager, State};
  10. use tauri_plugin_dialog::DialogExt;
  11. use tauri_plugin_opener::OpenerExt;
  12. use tauri_plugin_shell::process::CommandEvent;
  13. use tauri_plugin_shell::ShellExt;
  14. struct FlashState {
  15. child: Mutex<Option<tauri_plugin_shell::process::CommandChild>>,
  16. }
  17. /// Long-running, generic `luatos-cli --format jsonl` jobs (resource download,
  18. /// project build, ...), keyed by a caller-provided kind such as "resource".
  19. struct CliStreamState {
  20. children: Mutex<HashMap<String, tauri_plugin_shell::process::CommandChild>>,
  21. }
  22. #[derive(Debug, Deserialize)]
  23. #[serde(rename_all = "camelCase")]
  24. struct FlashOptions {
  25. soc_path: String,
  26. port: String,
  27. #[serde(default)]
  28. mode: Option<String>,
  29. #[serde(default)]
  30. script_dir: Option<String>,
  31. #[serde(default)]
  32. baud: Option<String>,
  33. #[serde(default)]
  34. tail_log_secs: Option<i64>,
  35. #[serde(default)]
  36. rts_reset: bool,
  37. }
  38. #[derive(Debug, Default, Serialize)]
  39. #[serde(rename_all = "camelCase")]
  40. struct SelftestConfig {
  41. soc: Option<String>,
  42. flash_port: Option<String>,
  43. }
  44. struct Captured {
  45. success: bool,
  46. code: Option<i32>,
  47. stdout: String,
  48. stderr: String,
  49. }
  50. /// Prefer an explicit LUATOS_CLI override, otherwise use the bundled sidecar.
  51. fn build_command(
  52. app: &AppHandle,
  53. args: &[String],
  54. ) -> Result<tauri_plugin_shell::process::Command, String> {
  55. if let Ok(path) = std::env::var("LUATOS_CLI") {
  56. if !path.trim().is_empty() && Path::new(&path).is_file() {
  57. return Ok(app.shell().command(path).args(args).env("NO_COLOR", "1"));
  58. }
  59. }
  60. let command = app
  61. .shell()
  62. .sidecar("luatos-cli")
  63. .map_err(|error| format!("找不到内置 luatos-cli:{error}"))?;
  64. Ok(command.args(args).env("NO_COLOR", "1"))
  65. }
  66. fn cli_display_path() -> String {
  67. if let Ok(path) = std::env::var("LUATOS_CLI") {
  68. if !path.trim().is_empty() && Path::new(&path).is_file() {
  69. return path;
  70. }
  71. }
  72. if let Ok(exe) = std::env::current_exe() {
  73. if let Some(dir) = exe.parent() {
  74. let candidate = dir.join("luatos-cli");
  75. if candidate.is_file() {
  76. return candidate.display().to_string();
  77. }
  78. }
  79. }
  80. if cfg!(debug_assertions) {
  81. let dev = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
  82. .join("binaries")
  83. .join(format!(
  84. "luatos-cli-{}-apple-darwin",
  85. std::env::consts::ARCH
  86. ));
  87. if dev.is_file() {
  88. return dev.display().to_string();
  89. }
  90. }
  91. "luatos-cli(内置 sidecar)".to_string()
  92. }
  93. async fn run_capture(
  94. app: &AppHandle,
  95. args: &[&str],
  96. timeout: Duration,
  97. ) -> Result<Captured, String> {
  98. let owned: Vec<String> = args.iter().map(|arg| (*arg).to_string()).collect();
  99. let command = build_command(app, &owned)?;
  100. let output = tokio::time::timeout(timeout, command.output())
  101. .await
  102. .map_err(|_| format!("命令超时({}s):{}", timeout.as_secs(), owned.join(" ")))?
  103. .map_err(|error| format!("无法启动 luatos-cli:{error}"))?;
  104. Ok(Captured {
  105. success: output.status.success(),
  106. code: output.status.code(),
  107. stdout: String::from_utf8_lossy(&output.stdout).to_string(),
  108. stderr: String::from_utf8_lossy(&output.stderr).to_string(),
  109. })
  110. }
  111. async fn run_json(
  112. app: &AppHandle,
  113. args: &[&str],
  114. timeout: Duration,
  115. ) -> Result<Value, String> {
  116. let captured = run_capture(app, args, timeout).await?;
  117. if !captured.success {
  118. let detail = if captured.stderr.trim().is_empty() {
  119. captured.stdout.trim()
  120. } else {
  121. captured.stderr.trim()
  122. };
  123. return Err(if detail.is_empty() {
  124. format!("luatos-cli 退出码 {:?}", captured.code)
  125. } else {
  126. detail.to_string()
  127. });
  128. }
  129. serde_json::from_str(captured.stdout.trim())
  130. .map_err(|error| format!("无法解析 luatos-cli JSON 输出:{error}"))
  131. }
  132. async fn run_text(
  133. app: &AppHandle,
  134. args: &[&str],
  135. timeout: Duration,
  136. ) -> Result<String, String> {
  137. let captured = run_capture(app, args, timeout).await?;
  138. if !captured.success {
  139. let detail = if captured.stderr.trim().is_empty() {
  140. captured.stdout.trim()
  141. } else {
  142. captured.stderr.trim()
  143. };
  144. return Err(if detail.is_empty() {
  145. format!("luatos-cli 退出码 {:?}", captured.code)
  146. } else {
  147. detail.to_string()
  148. });
  149. }
  150. let text = if captured.stdout.trim().is_empty() {
  151. captured.stderr
  152. } else {
  153. captured.stdout
  154. };
  155. Ok(text.trim().to_string())
  156. }
  157. fn normalize_soc(data: &Value) -> Value {
  158. let chip = data
  159. .pointer("/chip/type")
  160. .and_then(Value::as_str)
  161. .unwrap_or("unknown");
  162. let rom_file = data.pointer("/rom/file").cloned().unwrap_or(Value::Null);
  163. let script_file = data
  164. .pointer("/script/file")
  165. .cloned()
  166. .unwrap_or(Value::Null);
  167. let mut files: Vec<Value> = Vec::new();
  168. if let Some(entries) = data.pointer("/rom/files").and_then(Value::as_array) {
  169. for entry in entries {
  170. if let Some(name) = entry.get("name").or_else(|| entry.get("file")) {
  171. if !name.is_null() {
  172. files.push(name.clone());
  173. }
  174. }
  175. }
  176. }
  177. if files.is_empty() {
  178. for file in [&rom_file, &script_file] {
  179. if !file.is_null() {
  180. files.push(file.clone());
  181. }
  182. }
  183. }
  184. json!({
  185. "chip": chip,
  186. "version": data.get("version").cloned().unwrap_or(Value::Null),
  187. "romFile": rom_file,
  188. "scriptFile": script_file,
  189. "files": files,
  190. "raw": data,
  191. })
  192. }
  193. fn signal_name(signal: i32) -> String {
  194. match signal {
  195. 2 => "SIGINT".to_string(),
  196. 9 => "SIGKILL".to_string(),
  197. 15 => "SIGTERM".to_string(),
  198. other => format!("signal {other}"),
  199. }
  200. }
  201. fn emit_chunk(app: &AppHandle, chunk: &str, source: &str) {
  202. for line in chunk.lines() {
  203. let trimmed = line.trim();
  204. if trimmed.is_empty() {
  205. continue;
  206. }
  207. if source == "stdout" && trimmed.starts_with('{') {
  208. if let Ok(value) = serde_json::from_str::<Value>(trimmed) {
  209. let _ = app.emit("flash:event", value);
  210. continue;
  211. }
  212. }
  213. let _ = app.emit("flash:line", json!({ "line": trimmed, "source": source }));
  214. }
  215. }
  216. fn emit_chunk_named(app: &AppHandle, kind: &str, chunk: &str, source: &str) {
  217. let event_name = format!("{kind}:event");
  218. let line_name = format!("{kind}:line");
  219. for line in chunk.lines() {
  220. let trimmed = line.trim();
  221. if trimmed.is_empty() {
  222. continue;
  223. }
  224. if source == "stdout" && trimmed.starts_with('{') {
  225. if let Ok(value) = serde_json::from_str::<Value>(trimmed) {
  226. let _ = app.emit(&event_name, value);
  227. continue;
  228. }
  229. }
  230. let _ = app.emit(&line_name, json!({ "line": trimmed, "source": source }));
  231. }
  232. }
  233. /// Only expose read-only / local-management commands to the renderer through
  234. /// the generic bridge. Flashing keeps its dedicated command.
  235. fn cli_command_allowed(args: &[String]) -> bool {
  236. matches!(
  237. args.first().map(String::as_str),
  238. Some("serial" | "soc" | "resource" | "project" | "guide" | "device" | "log")
  239. )
  240. }
  241. fn json_error(message: impl Into<String>) -> Value {
  242. json!({ "ok": false, "error": message.into() })
  243. }
  244. #[tauri::command]
  245. async fn cli_info(app: AppHandle) -> Value {
  246. let path = cli_display_path();
  247. match run_text(&app, &["--version"], Duration::from_secs(10)).await {
  248. Ok(text) => {
  249. let version = text.trim().trim_start_matches("luatos-cli").trim().to_string();
  250. let models = run_json(
  251. &app,
  252. &["--format", "json", "guide", "models"],
  253. Duration::from_secs(15),
  254. )
  255. .await
  256. .ok()
  257. .and_then(|value| value.pointer("/data/models").cloned())
  258. .unwrap_or_else(|| json!([]));
  259. json!({ "ok": true, "path": path, "version": version, "models": models })
  260. }
  261. Err(error) => json!({ "ok": false, "path": path, "error": error }),
  262. }
  263. }
  264. #[tauri::command]
  265. async fn serial_list(app: AppHandle) -> Value {
  266. match run_json(
  267. &app,
  268. &["--format", "json", "serial", "list"],
  269. Duration::from_secs(12),
  270. )
  271. .await
  272. {
  273. Ok(value) => json!({
  274. "ok": true,
  275. "ports": value.get("data").cloned().unwrap_or_else(|| json!([])),
  276. }),
  277. Err(error) => json!({ "ok": false, "ports": [], "error": error }),
  278. }
  279. }
  280. #[tauri::command]
  281. async fn soc_info(app: AppHandle, soc_path: String) -> Value {
  282. if soc_path.trim().is_empty() || !Path::new(&soc_path).is_file() {
  283. return json!({ "ok": false, "error": "文件不存在" });
  284. }
  285. match run_json(
  286. &app,
  287. &["--format", "json", "soc", "info", &soc_path],
  288. Duration::from_secs(20),
  289. )
  290. .await
  291. {
  292. Ok(value) => {
  293. let data = value.get("data").cloned().unwrap_or(Value::Null);
  294. json!({ "ok": true, "info": normalize_soc(&data), "raw": data })
  295. }
  296. Err(error) => json!({ "ok": false, "error": error }),
  297. }
  298. }
  299. #[tauri::command]
  300. async fn flash_start(
  301. app: AppHandle,
  302. state: State<'_, FlashState>,
  303. options: FlashOptions,
  304. ) -> Result<Value, String> {
  305. let soc_path = options.soc_path.trim().to_string();
  306. if soc_path.is_empty() || !Path::new(&soc_path).is_file() {
  307. return Ok(json!({ "ok": false, "error": "固件文件不存在,请重新选择 .soc 文件" }));
  308. }
  309. let port = options.port.trim().to_string();
  310. if port.is_empty() {
  311. return Ok(json!({ "ok": false, "error": "请选择串口" }));
  312. }
  313. let mode = options.mode.unwrap_or_else(|| "full".to_string());
  314. let script_dir = options.script_dir.filter(|dir| !dir.trim().is_empty());
  315. if mode == "script" && script_dir.is_none() {
  316. return Ok(json!({ "ok": false, "error": "“仅刷脚本区”需要选择一个脚本目录" }));
  317. }
  318. if state.child.lock().unwrap().is_some() {
  319. return Ok(json!({ "ok": false, "error": "已有烧录任务正在运行" }));
  320. }
  321. let mut args: Vec<String> = vec![
  322. "--format".to_string(),
  323. "jsonl".to_string(),
  324. "flash".to_string(),
  325. if mode == "script" {
  326. "script".to_string()
  327. } else {
  328. "run".to_string()
  329. },
  330. "--soc".to_string(),
  331. soc_path.clone(),
  332. "--port".to_string(),
  333. port.clone(),
  334. ];
  335. if let Some(dir) = &script_dir {
  336. args.push("--script".to_string());
  337. args.push(dir.clone());
  338. }
  339. if let Some(baud) = options.baud.filter(|baud| !baud.trim().is_empty()) {
  340. args.push("--baud".to_string());
  341. args.push(baud);
  342. }
  343. if mode != "script" {
  344. if let Some(secs) = options.tail_log_secs {
  345. if secs > 0 {
  346. args.push("--tail-log-secs".to_string());
  347. args.push(secs.to_string());
  348. }
  349. }
  350. }
  351. if options.rts_reset {
  352. args.push("--rts-reset".to_string());
  353. }
  354. let command = build_command(&app, &args)?;
  355. eprintln!("[flash] spawn: luatos-cli {}", args.join(" "));
  356. let command_line = format!("luatos-cli {}", args.join(" "));
  357. let _ = app.emit(
  358. "flash:started",
  359. json!({
  360. "commandLine": command_line,
  361. "port": port,
  362. "socPath": soc_path,
  363. "mode": mode,
  364. }),
  365. );
  366. let (mut rx, child) = command
  367. .spawn()
  368. .map_err(|error| format!("无法启动 luatos-cli:{error}"))?;
  369. *state.child.lock().unwrap() = Some(child);
  370. let mut code: Option<i32> = None;
  371. let mut signal: Option<i32> = None;
  372. let mut spawn_error: Option<String> = None;
  373. while let Some(event) = rx.recv().await {
  374. match event {
  375. CommandEvent::Stdout(bytes) => {
  376. emit_chunk(&app, &String::from_utf8_lossy(&bytes), "stdout")
  377. }
  378. CommandEvent::Stderr(bytes) => {
  379. emit_chunk(&app, &String::from_utf8_lossy(&bytes), "stderr")
  380. }
  381. CommandEvent::Error(error) => spawn_error = Some(error),
  382. CommandEvent::Terminated(payload) => {
  383. code = payload.code;
  384. signal = payload.signal;
  385. }
  386. _ => {}
  387. }
  388. }
  389. *state.child.lock().unwrap() = None;
  390. eprintln!("[flash] exit code={code:?} signal={signal:?} error={spawn_error:?}");
  391. let signal_text = signal.map(signal_name);
  392. let _ = app.emit(
  393. "flash:exit",
  394. json!({
  395. "code": code.unwrap_or(-1),
  396. "signal": signal_text,
  397. "error": spawn_error,
  398. }),
  399. );
  400. Ok(json!({
  401. "ok": spawn_error.is_none() && code == Some(0),
  402. "code": code,
  403. "signal": signal_text,
  404. "error": spawn_error,
  405. }))
  406. }
  407. #[tauri::command]
  408. fn flash_cancel(state: State<'_, FlashState>) -> Value {
  409. let child = state.child.lock().unwrap().take();
  410. match child {
  411. Some(child) => match child.kill() {
  412. Ok(_) => json!({ "ok": true }),
  413. Err(error) => json!({ "ok": false, "error": error.to_string() }),
  414. },
  415. None => json!({ "ok": false, "error": "没有正在运行的烧录任务" }),
  416. }
  417. }
  418. fn file_path_string(path: tauri_plugin_dialog::FilePath) -> Option<String> {
  419. path.into_path()
  420. .ok()
  421. .map(|path| path.display().to_string())
  422. }
  423. #[tauri::command]
  424. async fn open_soc_dialog(app: AppHandle) -> Option<String> {
  425. let (tx, rx) = tokio::sync::oneshot::channel();
  426. app.dialog()
  427. .file()
  428. .set_title("选择 LuatOS 固件")
  429. .add_filter("LuatOS 固件", &["soc"])
  430. .add_filter("所有文件", &["*"])
  431. .pick_file(move |path| {
  432. let _ = tx.send(path);
  433. });
  434. rx.await.ok().flatten().and_then(file_path_string)
  435. }
  436. #[tauri::command]
  437. async fn open_script_dir_dialog(app: AppHandle) -> Option<String> {
  438. let (tx, rx) = tokio::sync::oneshot::channel();
  439. app.dialog()
  440. .file()
  441. .set_title("选择脚本目录")
  442. .pick_folder(move |path| {
  443. let _ = tx.send(path);
  444. });
  445. rx.await.ok().flatten().and_then(file_path_string)
  446. }
  447. #[tauri::command]
  448. async fn save_log(app: AppHandle, content: String) -> Value {
  449. let name = format!(
  450. "luatos-flash-{}.log",
  451. std::time::SystemTime::now()
  452. .duration_since(std::time::UNIX_EPOCH)
  453. .map(|duration| duration.as_secs())
  454. .unwrap_or(0)
  455. );
  456. let (tx, rx) = tokio::sync::oneshot::channel();
  457. app.dialog()
  458. .file()
  459. .set_title("保存烧录日志")
  460. .set_file_name(&name)
  461. .add_filter("日志文件", &["log", "txt"])
  462. .save_file(move |path| {
  463. let _ = tx.send(path);
  464. });
  465. match rx.await.ok().flatten().and_then(file_path_string) {
  466. Some(path) => match std::fs::write(&path, content) {
  467. Ok(_) => json!({ "ok": true, "path": path }),
  468. Err(error) => json!({ "ok": false, "error": error.to_string() }),
  469. },
  470. None => json!({ "ok": false }),
  471. }
  472. }
  473. #[tauri::command]
  474. fn open_external(app: AppHandle, url: String) -> Value {
  475. if !(url.starts_with("http://") || url.starts_with("https://")) {
  476. return json!({ "ok": false, "error": "只允许打开 http(s) 链接" });
  477. }
  478. match app.opener().open_url(url, None::<&str>) {
  479. Ok(_) => json!({ "ok": true }),
  480. Err(error) => json!({ "ok": false, "error": error.to_string() }),
  481. }
  482. }
  483. #[tauri::command]
  484. fn selftest_config() -> SelftestConfig {
  485. let mut config = SelftestConfig::default();
  486. for arg in std::env::args() {
  487. if let Some(value) = arg.strip_prefix("--selftest-soc=") {
  488. config.soc = Some(value.to_string());
  489. } else if let Some(value) = arg.strip_prefix("--selftest-flash-soc=") {
  490. config.soc = Some(value.to_string());
  491. } else if let Some(value) = arg.strip_prefix("--selftest-flash-port=") {
  492. config.flash_port = Some(value.to_string());
  493. }
  494. }
  495. config
  496. }
  497. #[tauri::command]
  498. fn js_log(level: String, message: String) {
  499. eprintln!("[js:{level}] {message}");
  500. }
  501. #[tauri::command]
  502. fn selftest_report(app: AppHandle, payload: Value) {
  503. println!(
  504. "SELFTEST {}",
  505. serde_json::to_string_pretty(&payload).unwrap_or_else(|_| payload.to_string())
  506. );
  507. let handle = app.clone();
  508. std::thread::spawn(move || {
  509. std::thread::sleep(Duration::from_millis(200));
  510. handle.exit(0);
  511. });
  512. }
  513. #[tauri::command]
  514. async fn cli_json(app: AppHandle, args: Vec<String>) -> Value {
  515. if !cli_command_allowed(&args) {
  516. return json_error("不允许的 luatos-cli 子命令");
  517. }
  518. let mut full: Vec<String> = vec!["--format".into(), "json".into()];
  519. full.extend(args);
  520. let refs: Vec<&str> = full.iter().map(String::as_str).collect();
  521. match run_json(&app, &refs, Duration::from_secs(300)).await {
  522. Ok(mut value) => {
  523. if let Some(object) = value.as_object_mut() {
  524. object.insert("ok".to_string(), Value::Bool(true));
  525. }
  526. value
  527. }
  528. Err(error) => json_error(error),
  529. }
  530. }
  531. /// Generic streaming bridge for `luatos-cli --format jsonl`.
  532. ///
  533. /// The renderer passes `kind = "resource"` / `"project"` and the CLI args; the
  534. /// backend emits `<kind>:event`, `<kind>:line` and `<kind>:exit`.
  535. #[tauri::command]
  536. async fn cli_stream(
  537. app: AppHandle,
  538. state: State<'_, CliStreamState>,
  539. kind: String,
  540. args: Vec<String>,
  541. ) -> Result<Value, String> {
  542. let safe_kind = !kind.is_empty()
  543. && kind
  544. .chars()
  545. .all(|character| character.is_ascii_alphanumeric() || character == '-' || character == '_');
  546. if !safe_kind {
  547. return Ok(json_error("非法的任务类型"));
  548. }
  549. if !cli_command_allowed(&args) {
  550. return Ok(json_error("不允许的 luatos-cli 子命令"));
  551. }
  552. if state.children.lock().unwrap().contains_key(&kind) {
  553. return Ok(json_error(format!("{kind} 任务正在运行")));
  554. }
  555. let mut full: Vec<String> = vec!["--format".into(), "jsonl".into()];
  556. full.extend(args);
  557. let command = build_command(&app, &full)?;
  558. let (mut receiver, child) = command
  559. .spawn()
  560. .map_err(|error| format!("无法启动 luatos-cli:{error}"))?;
  561. state.children.lock().unwrap().insert(kind.clone(), child);
  562. let mut code: Option<i32> = None;
  563. let mut signal: Option<i32> = None;
  564. let mut spawn_error: Option<String> = None;
  565. while let Some(event) = receiver.recv().await {
  566. match event {
  567. CommandEvent::Stdout(bytes) => {
  568. emit_chunk_named(&app, &kind, &String::from_utf8_lossy(&bytes), "stdout")
  569. }
  570. CommandEvent::Stderr(bytes) => {
  571. emit_chunk_named(&app, &kind, &String::from_utf8_lossy(&bytes), "stderr")
  572. }
  573. CommandEvent::Error(error) => spawn_error = Some(error),
  574. CommandEvent::Terminated(payload) => {
  575. code = payload.code;
  576. signal = payload.signal;
  577. }
  578. _ => {}
  579. }
  580. }
  581. state.children.lock().unwrap().remove(&kind);
  582. let signal_text = signal.map(signal_name);
  583. let _ = app.emit(
  584. &format!("{kind}:exit"),
  585. json!({
  586. "code": code.unwrap_or(-1),
  587. "signal": signal_text,
  588. "error": spawn_error,
  589. }),
  590. );
  591. Ok(json!({
  592. "ok": spawn_error.is_none() && code == Some(0),
  593. "code": code,
  594. "signal": signal_text,
  595. "error": spawn_error,
  596. }))
  597. }
  598. #[tauri::command]
  599. fn stream_cancel(state: State<'_, CliStreamState>, kind: String) -> Value {
  600. let child = state.children.lock().unwrap().remove(&kind);
  601. match child {
  602. Some(child) => match child.kill() {
  603. Ok(_) => json!({ "ok": true }),
  604. Err(error) => json_error(error.to_string()),
  605. },
  606. None => json_error(format!("{kind} 没有正在运行的任务")),
  607. }
  608. }
  609. fn app_subdir(app: &AppHandle, name: &str) -> PathBuf {
  610. let base = app
  611. .path()
  612. .app_data_dir()
  613. .unwrap_or_else(|_| PathBuf::from("."));
  614. let dir = base.join(name);
  615. let _ = fs::create_dir_all(&dir);
  616. dir
  617. }
  618. #[tauri::command]
  619. fn app_paths(app: AppHandle) -> Value {
  620. let base = app
  621. .path()
  622. .app_data_dir()
  623. .unwrap_or_else(|_| PathBuf::from("."));
  624. let projects = app_subdir(&app, "projects");
  625. let resources = app_subdir(&app, "resources");
  626. json!({
  627. "ok": true,
  628. "appData": base.display().to_string(),
  629. "projects": projects.display().to_string(),
  630. "resources": resources.display().to_string(),
  631. })
  632. }
  633. #[tauri::command]
  634. fn read_text_file(path: String) -> Value {
  635. let file_path = Path::new(&path);
  636. if !file_path.is_file() {
  637. return json_error("文件不存在");
  638. }
  639. let metadata = match fs::metadata(file_path) {
  640. Ok(metadata) => metadata,
  641. Err(error) => return json_error(error.to_string()),
  642. };
  643. if metadata.len() > 4 * 1024 * 1024 {
  644. return json_error("文件太大(超过 4MB)");
  645. }
  646. match fs::read(file_path) {
  647. Ok(data) => json!({
  648. "ok": true,
  649. "content": String::from_utf8_lossy(&data).to_string(),
  650. }),
  651. Err(error) => json_error(error.to_string()),
  652. }
  653. }
  654. #[tauri::command]
  655. fn write_text_file(path: String, content: String) -> Value {
  656. let file_path = Path::new(&path);
  657. if let Some(parent) = file_path.parent() {
  658. if let Err(error) = fs::create_dir_all(parent) {
  659. return json_error(error.to_string());
  660. }
  661. }
  662. match fs::write(file_path, content) {
  663. Ok(_) => json!({ "ok": true }),
  664. Err(error) => json_error(error.to_string()),
  665. }
  666. }
  667. fn collect_files(root: &Path, current: &Path, output: &mut Vec<Value>, count: &mut usize) {
  668. if *count >= 4000 {
  669. return;
  670. }
  671. let entries = match fs::read_dir(current) {
  672. Ok(entries) => entries,
  673. Err(_) => return,
  674. };
  675. for entry in entries.flatten() {
  676. let name = entry.file_name().to_string_lossy().to_string();
  677. if matches!(name.as_str(), ".git" | "node_modules" | "target" | ".DS_Store") {
  678. continue;
  679. }
  680. let path = entry.path();
  681. let metadata = match entry.metadata() {
  682. Ok(metadata) => metadata,
  683. Err(_) => continue,
  684. };
  685. let relative = path
  686. .strip_prefix(root)
  687. .unwrap_or(path.as_path())
  688. .to_string_lossy()
  689. .replace('\\', "/");
  690. if metadata.is_dir() {
  691. output.push(json!({
  692. "path": relative,
  693. "name": name,
  694. "isDir": true,
  695. "size": 0,
  696. }));
  697. collect_files(root, &path, output, count);
  698. } else {
  699. output.push(json!({
  700. "path": relative,
  701. "name": name,
  702. "isDir": false,
  703. "size": metadata.len(),
  704. }));
  705. }
  706. *count += 1;
  707. if *count >= 4000 {
  708. return;
  709. }
  710. }
  711. }
  712. #[tauri::command]
  713. fn list_files(path: String) -> Value {
  714. let root = Path::new(&path);
  715. if !root.is_dir() {
  716. return json_error("目录不存在");
  717. }
  718. let mut output = Vec::new();
  719. let mut count = 0usize;
  720. collect_files(root, root, &mut output, &mut count);
  721. json!({ "ok": true, "files": output })
  722. }
  723. #[tauri::command]
  724. fn scan_projects(root: String) -> Value {
  725. let root_path = Path::new(&root);
  726. if !root_path.is_dir() {
  727. return json_error("项目目录不存在");
  728. }
  729. let mut projects = Vec::new();
  730. if let Ok(entries) = fs::read_dir(root_path) {
  731. for entry in entries.flatten() {
  732. let path = entry.path();
  733. if path.is_dir() && path.join("luatos-project.toml").is_file() {
  734. let name = entry.file_name().to_string_lossy().to_string();
  735. let modified = fs::metadata(&path)
  736. .and_then(|metadata| metadata.modified())
  737. .ok()
  738. .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
  739. .map(|duration| duration.as_secs())
  740. .unwrap_or(0);
  741. projects.push(json!({
  742. "name": name,
  743. "path": path.display().to_string(),
  744. "modified": modified,
  745. }));
  746. }
  747. }
  748. }
  749. projects.sort_by(|left, right| {
  750. right["modified"]
  751. .as_u64()
  752. .cmp(&left["modified"].as_u64())
  753. });
  754. json!({ "ok": true, "projects": projects })
  755. }
  756. #[tauri::command]
  757. fn delete_project(dir: String) -> Value {
  758. let path = Path::new(&dir);
  759. if !path.join("luatos-project.toml").is_file() {
  760. return json_error("不是有效的 LuatOS 项目目录");
  761. }
  762. match fs::remove_dir_all(path) {
  763. Ok(_) => json!({ "ok": true }),
  764. Err(error) => json_error(error.to_string()),
  765. }
  766. }
  767. fn copy_dir_all(source: &Path, destination: &Path) -> std::io::Result<()> {
  768. fs::create_dir_all(destination)?;
  769. for entry in fs::read_dir(source)? {
  770. let entry = entry?;
  771. let file_type = entry.file_type()?;
  772. let target = destination.join(entry.file_name());
  773. if file_type.is_dir() {
  774. copy_dir_all(&entry.path(), &target)?;
  775. } else {
  776. fs::copy(entry.path(), &target)?;
  777. }
  778. }
  779. Ok(())
  780. }
  781. #[tauri::command]
  782. fn clone_project(src: String, dst: String) -> Value {
  783. let source = Path::new(&src);
  784. let destination = Path::new(&dst);
  785. if !source.join("luatos-project.toml").is_file() {
  786. return json_error("源项目无效");
  787. }
  788. if destination.exists() {
  789. return json_error("目标目录已存在");
  790. }
  791. match copy_dir_all(source, destination) {
  792. Ok(_) => json!({ "ok": true }),
  793. Err(error) => json_error(error.to_string()),
  794. }
  795. }
  796. #[tauri::command]
  797. fn create_dir(path: String) -> Value {
  798. match fs::create_dir_all(&path) {
  799. Ok(_) => json!({ "ok": true }),
  800. Err(error) => json_error(error.to_string()),
  801. }
  802. }
  803. #[tauri::command]
  804. fn path_exists(path: String) -> Value {
  805. json!({ "ok": true, "exists": Path::new(&path).exists() })
  806. }
  807. #[tauri::command]
  808. fn reveal_path(path: String) -> Value {
  809. let target = Path::new(&path);
  810. if !target.exists() {
  811. return json_error("路径不存在");
  812. }
  813. #[cfg(target_os = "macos")]
  814. let result = if target.is_file() {
  815. std::process::Command::new("open")
  816. .arg("-R")
  817. .arg(target)
  818. .spawn()
  819. } else {
  820. std::process::Command::new("open").arg(target).spawn()
  821. };
  822. #[cfg(target_os = "windows")]
  823. let result = if target.is_file() {
  824. std::process::Command::new("explorer")
  825. .arg(format!("/select,{}", target.display()))
  826. .spawn()
  827. } else {
  828. std::process::Command::new("explorer").arg(target).spawn()
  829. };
  830. #[cfg(all(not(target_os = "macos"), not(target_os = "windows")))]
  831. let result = std::process::Command::new("xdg-open")
  832. .arg(if target.is_dir() {
  833. target
  834. } else {
  835. target.parent().unwrap_or(target)
  836. })
  837. .spawn();
  838. match result {
  839. Ok(_) => json!({ "ok": true }),
  840. Err(error) => json_error(error.to_string()),
  841. }
  842. }
  843. #[tauri::command]
  844. async fn open_file_dialog(app: AppHandle, filters: Vec<String>) -> Option<String> {
  845. let filter_refs: Vec<&str> = filters.iter().map(String::as_str).collect();
  846. let (tx, rx) = tokio::sync::oneshot::channel();
  847. let mut builder = app.dialog().file().set_title("选择文件");
  848. if filter_refs.is_empty() {
  849. builder = builder.add_filter("所有文件", &["*"]);
  850. } else {
  851. builder = builder.add_filter("文件", &filter_refs);
  852. }
  853. builder.pick_file(move |path| {
  854. let _ = tx.send(path);
  855. });
  856. rx.await.ok().flatten().and_then(file_path_string)
  857. }
  858. #[tauri::command]
  859. async fn open_folder_dialog(app: AppHandle) -> Option<String> {
  860. let (tx, rx) = tokio::sync::oneshot::channel();
  861. app.dialog()
  862. .file()
  863. .set_title("选择目录")
  864. .pick_folder(move |path| {
  865. let _ = tx.send(path);
  866. });
  867. rx.await.ok().flatten().and_then(file_path_string)
  868. }
  869. #[tauri::command]
  870. async fn save_file_dialog(
  871. app: AppHandle,
  872. default_name: Option<String>,
  873. filters: Vec<String>,
  874. ) -> Option<String> {
  875. let filter_refs: Vec<&str> = filters.iter().map(String::as_str).collect();
  876. let (tx, rx) = tokio::sync::oneshot::channel();
  877. let mut builder = app.dialog().file().set_title("保存文件");
  878. if let Some(name) = default_name {
  879. if !name.trim().is_empty() {
  880. builder = builder.set_file_name(&name);
  881. }
  882. }
  883. if filter_refs.is_empty() {
  884. builder = builder.add_filter("所有文件", &["*"]);
  885. } else {
  886. builder = builder.add_filter("文件", &filter_refs);
  887. }
  888. builder.save_file(move |path| {
  889. let _ = tx.send(path);
  890. });
  891. rx.await.ok().flatten().and_then(file_path_string)
  892. }
  893. fn find_named_file(root: &Path, file_name: &str, depth: usize) -> Option<PathBuf> {
  894. if depth == 0 {
  895. return None;
  896. }
  897. let entries = fs::read_dir(root).ok()?;
  898. for entry in entries.flatten() {
  899. let path = entry.path();
  900. if path.is_file()
  901. && path
  902. .file_name()
  903. .and_then(|name| name.to_str())
  904. .map(|name| name == file_name)
  905. .unwrap_or(false)
  906. {
  907. return Some(path);
  908. }
  909. if path.is_dir() {
  910. if let Some(found) = find_named_file(&path, file_name, depth - 1) {
  911. return Some(found);
  912. }
  913. }
  914. }
  915. None
  916. }
  917. #[tauri::command]
  918. fn mcp_info(app: AppHandle) -> Value {
  919. let mut candidates = Vec::new();
  920. let mut resource_root: Option<PathBuf> = None;
  921. if let Ok(resource_dir) = app.path().resource_dir() {
  922. candidates.push(resource_dir.join("mcp").join("luatos-mcp.mjs"));
  923. candidates.push(
  924. resource_dir
  925. .join("resources")
  926. .join("mcp")
  927. .join("luatos-mcp.mjs"),
  928. );
  929. resource_root = Some(resource_dir);
  930. }
  931. candidates.push(
  932. PathBuf::from(env!("CARGO_MANIFEST_DIR"))
  933. .join("mcp")
  934. .join("luatos-mcp.mjs"),
  935. );
  936. let script = candidates
  937. .into_iter()
  938. .find(|path| path.is_file())
  939. .or_else(|| {
  940. resource_root
  941. .as_deref()
  942. .and_then(|root| find_named_file(root, "luatos-mcp.mjs", 4))
  943. })
  944. .map(|path| path.display().to_string())
  945. .unwrap_or_default();
  946. let cli = cli_display_path();
  947. let node_version = std::process::Command::new("node")
  948. .arg("--version")
  949. .output()
  950. .ok()
  951. .filter(|output| output.status.success())
  952. .map(|output| String::from_utf8_lossy(&output.stdout).trim().to_string())
  953. .unwrap_or_default();
  954. let config = if script.is_empty() {
  955. Value::Null
  956. } else {
  957. json!({
  958. "mcpServers": {
  959. "luatos": {
  960. "command": "node",
  961. "args": [script.clone()],
  962. "env": { "LUATOS_CLI": cli.clone() }
  963. }
  964. }
  965. })
  966. };
  967. json!({
  968. "ok": !script.is_empty(),
  969. "script": script,
  970. "cli": cli,
  971. "node": node_version,
  972. "config": config,
  973. })
  974. }
  975. fn build_app_menu(app: &tauri::App) -> tauri::Result<tauri::menu::Menu<tauri::Wry>> {
  976. let about = PredefinedMenuItem::about(
  977. app,
  978. Some("关于 LuatOS Flasher"),
  979. Some(AboutMetadata {
  980. name: Some("LuatOS Flasher".to_string()),
  981. version: Some(env!("CARGO_PKG_VERSION").to_string()),
  982. credits: Some("烧录内核:luatos-cli (MIT)\n界面:Tauri + WKWebView".to_string()),
  983. ..Default::default()
  984. }),
  985. )?;
  986. let app_menu = SubmenuBuilder::new(app, "LuatOS Flasher")
  987. .item(&about)
  988. .separator()
  989. .item(&PredefinedMenuItem::services(app, Some("服务"))?)
  990. .separator()
  991. .item(&PredefinedMenuItem::hide(app, Some("隐藏 LuatOS Flasher"))?)
  992. .item(&PredefinedMenuItem::hide_others(app, Some("隐藏其他"))?)
  993. .item(&PredefinedMenuItem::show_all(app, Some("全部显示"))?)
  994. .separator()
  995. .item(&PredefinedMenuItem::quit(app, Some("退出 LuatOS Flasher"))?)
  996. .build()?;
  997. let open = MenuItemBuilder::with_id("menu:open-soc", "打开固件…")
  998. .accelerator("CmdOrCtrl+O")
  999. .build(app)?;
  1000. let save_log = MenuItemBuilder::with_id("menu:save-log", "保存日志…")
  1001. .accelerator("CmdOrCtrl+S")
  1002. .build(app)?;
  1003. let file_menu = SubmenuBuilder::new(app, "文件")
  1004. .item(&open)
  1005. .item(&save_log)
  1006. .separator()
  1007. .item(&PredefinedMenuItem::close_window(app, Some("关闭窗口"))?)
  1008. .build()?;
  1009. let edit_menu = SubmenuBuilder::new(app, "编辑")
  1010. .undo()
  1011. .redo()
  1012. .separator()
  1013. .cut()
  1014. .copy()
  1015. .paste()
  1016. .select_all()
  1017. .build()?;
  1018. let docs = MenuItemBuilder::with_id("help:docs", "LuatOS 文档").build(app)?;
  1019. let cli = MenuItemBuilder::with_id("help:cli", "luatos-cli 项目").build(app)?;
  1020. let help_menu = SubmenuBuilder::new(app, "帮助")
  1021. .item(&docs)
  1022. .item(&cli)
  1023. .build()?;
  1024. MenuBuilder::new(app)
  1025. .items(&[&app_menu, &file_menu, &edit_menu, &help_menu])
  1026. .build()
  1027. }
  1028. #[cfg_attr(mobile, tauri::mobile_entry_point)]
  1029. pub fn run() {
  1030. tauri::Builder::default()
  1031. .plugin(tauri_plugin_shell::init())
  1032. .plugin(tauri_plugin_dialog::init())
  1033. .plugin(tauri_plugin_opener::init())
  1034. .manage(FlashState {
  1035. child: Mutex::new(None),
  1036. })
  1037. .manage(CliStreamState {
  1038. children: Mutex::new(HashMap::new()),
  1039. })
  1040. .setup(|app| {
  1041. let menu = build_app_menu(app)?;
  1042. app.set_menu(menu)?;
  1043. app.on_menu_event(|app, event| {
  1044. let id = event.id().0.as_str();
  1045. match id {
  1046. "menu:open-soc" => {
  1047. let _ = app.emit("menu", "open-soc");
  1048. }
  1049. "menu:save-log" => {
  1050. let _ = app.emit("menu", "save-log");
  1051. }
  1052. "help:docs" => {
  1053. let _ = app
  1054. .opener()
  1055. .open_url("https://wiki.luatos.com/", None::<&str>);
  1056. }
  1057. "help:cli" => {
  1058. let _ = app
  1059. .opener()
  1060. .open_url("https://github.com/wendal/luatos-cli", None::<&str>);
  1061. }
  1062. _ => {}
  1063. }
  1064. });
  1065. Ok(())
  1066. })
  1067. .invoke_handler(tauri::generate_handler![
  1068. cli_info,
  1069. serial_list,
  1070. soc_info,
  1071. flash_start,
  1072. flash_cancel,
  1073. open_soc_dialog,
  1074. open_script_dir_dialog,
  1075. save_log,
  1076. open_external,
  1077. cli_json,
  1078. cli_stream,
  1079. stream_cancel,
  1080. app_paths,
  1081. read_text_file,
  1082. write_text_file,
  1083. list_files,
  1084. scan_projects,
  1085. delete_project,
  1086. clone_project,
  1087. create_dir,
  1088. path_exists,
  1089. reveal_path,
  1090. open_file_dialog,
  1091. open_folder_dialog,
  1092. save_file_dialog,
  1093. mcp_info,
  1094. selftest_config,
  1095. js_log,
  1096. selftest_report
  1097. ])
  1098. .run(tauri::generate_context!())
  1099. .expect("error while running LuatOS Flasher");
  1100. }