api.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. 'use strict';
  2. /**
  3. * Tauri bridge for the existing renderer.
  4. *
  5. * The renderer only knows `window.api` (Electron used contextBridge). Here the
  6. * same shape is implemented on top of Tauri's WKWebView -> Rust IPC. Nothing in
  7. * app.js needs to change.
  8. */
  9. (() => {
  10. const tauri = window.__TAURI__;
  11. if (!tauri) {
  12. console.error('Tauri 全局 API 未注入,界面无法工作');
  13. return;
  14. }
  15. const invoke = tauri.core.invoke;
  16. const listen = tauri.event.listen;
  17. const subscribers = {
  18. flashEvent: new Set(),
  19. flashLine: new Set(),
  20. flashStarted: new Set(),
  21. flashExit: new Set(),
  22. menuOpenSoc: new Set(),
  23. menuSaveLog: new Set(),
  24. };
  25. function on(kind, callback) {
  26. subscribers[kind].add(callback);
  27. return () => subscribers[kind].delete(callback);
  28. }
  29. function emit(kind, payload) {
  30. for (const callback of subscribers[kind]) {
  31. try {
  32. callback(payload);
  33. } catch (error) {
  34. console.error(`[${kind}] 回调失败`, error);
  35. }
  36. }
  37. }
  38. window.api = {
  39. getInfo: () => invoke('cli_info'),
  40. listPorts: () => invoke('serial_list'),
  41. socInfo: (socPath) => invoke('soc_info', { socPath }),
  42. startFlash: (options) => invoke('flash_start', { options }),
  43. cancelFlash: () => invoke('flash_cancel'),
  44. openSocDialog: () => invoke('open_soc_dialog'),
  45. openScriptDirDialog: () => invoke('open_script_dir_dialog'),
  46. saveLog: (content) => invoke('save_log', { content }),
  47. openExternal: (url) => invoke('open_external', { url }),
  48. // Generic bridge for resource download / project management.
  49. runCliJson: (args) => invoke('cli_json', { args }),
  50. startCliStream: (kind, args) => invoke('cli_stream', { kind, args }),
  51. cancelCliStream: (kind) => invoke('stream_cancel', { kind }),
  52. onCliEvent: (kind, callback) =>
  53. listen(`${kind}:event`, (event) => callback(event.payload)),
  54. onCliLine: (kind, callback) =>
  55. listen(`${kind}:line`, (event) => callback(event.payload)),
  56. onCliExit: (kind, callback) =>
  57. listen(`${kind}:exit`, (event) => callback(event.payload)),
  58. appPaths: () => invoke('app_paths'),
  59. readTextFile: (path) => invoke('read_text_file', { path }),
  60. writeTextFile: (path, content) => invoke('write_text_file', { path, content }),
  61. listFiles: (path) => invoke('list_files', { path }),
  62. scanProjects: (root) => invoke('scan_projects', { root }),
  63. deleteProject: (dir) => invoke('delete_project', { dir }),
  64. cloneProject: (src, dst) => invoke('clone_project', { src, dst }),
  65. createDir: (path) => invoke('create_dir', { path }),
  66. pathExists: (path) => invoke('path_exists', { path }),
  67. revealPath: (path) => invoke('reveal_path', { path }),
  68. openFileDialog: (filters) => invoke('open_file_dialog', { filters }),
  69. openFolderDialog: () => invoke('open_folder_dialog'),
  70. saveFileDialog: (defaultName, filters) =>
  71. invoke('save_file_dialog', { defaultName, filters }),
  72. mcpInfo: () => invoke('mcp_info'),
  73. // WKWebView does not expose File.path. Drag & drop is handled below via
  74. // Tauri's native drag-drop event, and file picking goes through Rust.
  75. getPathForFile: (file) => (file && file.path) || '',
  76. onFlashEvent: (callback) => on('flashEvent', callback),
  77. onFlashLine: (callback) => on('flashLine', callback),
  78. onFlashStarted: (callback) => on('flashStarted', callback),
  79. onFlashExit: (callback) => on('flashExit', callback),
  80. onMenuOpenSoc: (callback) => on('menuOpenSoc', callback),
  81. onMenuSaveLog: (callback) => on('menuSaveLog', callback),
  82. };
  83. async function wireEvents() {
  84. await listen('flash:event', (event) => emit('flashEvent', event.payload));
  85. await listen('flash:line', (event) => emit('flashLine', event.payload));
  86. await listen('flash:started', (event) => emit('flashStarted', event.payload));
  87. await listen('flash:exit', (event) => emit('flashExit', event.payload));
  88. await listen('menu', (event) => {
  89. if (event.payload === 'open-soc') emit('menuOpenSoc');
  90. else if (event.payload === 'save-log') emit('menuSaveLog');
  91. });
  92. // Tauri intercepts native file drops; the DOM drop event has no paths.
  93. await listen('tauri://drag-drop', (event) => {
  94. const paths = event?.payload?.paths || [];
  95. const soc = paths.find((path) => /\.soc$/i.test(path));
  96. if (soc && window.__luatos) window.__luatos.loadSoc(soc);
  97. });
  98. }
  99. wireEvents().catch((error) => console.error('事件通道初始化失败', error));
  100. // Dev-only self test, mirroring the Electron --selftest-* harness.
  101. const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
  102. function reportError(error) {
  103. const message = error && error.stack ? error.stack : String(error);
  104. invoke('js_log', { level: 'error', message }).catch(() => {});
  105. }
  106. window.addEventListener('error', (event) => reportError(event.error || event.message));
  107. window.addEventListener('unhandledrejection', (event) => reportError(event.reason));
  108. function snapshot(extra) {
  109. const state = window.__luatos?.state || {};
  110. return {
  111. api: typeof window.api?.getInfo === 'function',
  112. cliStatus: document.querySelector('#cli-status')?.textContent,
  113. fwPath: document.querySelector('#fw-path')?.textContent,
  114. fwInfo: document.querySelector('#fw-info')?.innerText,
  115. fwError: document.querySelector('#fw-error')?.textContent,
  116. bootTip: document.querySelector('#boot-tip')?.innerText,
  117. stage: document.querySelector('#stage')?.textContent,
  118. percent: document.querySelector('#percent')?.textContent,
  119. message: document.querySelector('#message')?.textContent,
  120. flashDisabled: document.querySelector('#btn-flash')?.disabled,
  121. flashing: state.isFlashing,
  122. port: state.port,
  123. socPath: state.socPath,
  124. cliOk: state.cliOk,
  125. portHint: document.querySelector('#port-hint')?.textContent,
  126. portCount: document.querySelector('#port-count')?.textContent,
  127. portOptions: Array.from(document.querySelectorAll('#port-select option')).map(
  128. (option) => option.value,
  129. ),
  130. log: document.querySelector('#log')?.innerText.slice(-1500),
  131. ...extra,
  132. };
  133. }
  134. (async () => {
  135. let config = null;
  136. try {
  137. config = await invoke('selftest_config');
  138. } catch (error) {
  139. reportError(error);
  140. return;
  141. }
  142. if (!config || (!config.soc && !config.view)) return;
  143. try {
  144. if (config.view) {
  145. await wait(600);
  146. const tab = document.querySelector(`#tabs .tab[data-view="${config.view}"]`);
  147. tab?.click();
  148. await wait(config.view === 'resources' ? 4500 : 1600);
  149. if (config.selectPort) {
  150. const select = document.querySelector('#port-select');
  151. if (select && Array.from(select.options).some((option) => option.value === config.selectPort)) {
  152. select.value = config.selectPort;
  153. select.dispatchEvent(new Event('change', { bubbles: true }));
  154. await wait(350);
  155. }
  156. }
  157. const panel = document.querySelector(`#view-${config.view}`);
  158. await invoke('selftest_report', {
  159. payload: snapshot({
  160. view: config.view,
  161. activeTab: document.querySelector('#tabs .tab.active')?.textContent,
  162. viewVisible: panel ? !panel.classList.contains('hidden') : false,
  163. viewText: panel?.innerText.slice(0, 1500),
  164. }),
  165. });
  166. return;
  167. }
  168. await wait(600);
  169. await window.__luatos.loadSoc(config.soc);
  170. await wait(1200);
  171. let timedOut = false;
  172. if (config.flashPort) {
  173. window.__luatos.state.port = config.flashPort;
  174. window.__luatos.updateFlashButton();
  175. const timeout = wait(20000).then(() => {
  176. timedOut = true;
  177. });
  178. await Promise.race([window.__luatos.startFlash(), timeout]);
  179. await wait(500);
  180. }
  181. await invoke('selftest_report', { payload: snapshot({ timedOut }) });
  182. } catch (error) {
  183. await invoke('selftest_report', { payload: snapshot({ error: String(error && error.stack ? error.stack : error) }) }).catch(reportError);
  184. }
  185. })();
  186. })();