| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178 |
- 'use strict';
- /**
- * Tauri bridge for the existing renderer.
- *
- * The renderer only knows `window.api` (Electron used contextBridge). Here the
- * same shape is implemented on top of Tauri's WKWebView -> Rust IPC. Nothing in
- * app.js needs to change.
- */
- (() => {
- const tauri = window.__TAURI__;
- if (!tauri) {
- console.error('Tauri 全局 API 未注入,界面无法工作');
- return;
- }
- const invoke = tauri.core.invoke;
- const listen = tauri.event.listen;
- const subscribers = {
- flashEvent: new Set(),
- flashLine: new Set(),
- flashStarted: new Set(),
- flashExit: new Set(),
- menuOpenSoc: new Set(),
- menuSaveLog: new Set(),
- };
- function on(kind, callback) {
- subscribers[kind].add(callback);
- return () => subscribers[kind].delete(callback);
- }
- function emit(kind, payload) {
- for (const callback of subscribers[kind]) {
- try {
- callback(payload);
- } catch (error) {
- console.error(`[${kind}] 回调失败`, error);
- }
- }
- }
- window.api = {
- getInfo: () => invoke('cli_info'),
- listPorts: () => invoke('serial_list'),
- socInfo: (socPath) => invoke('soc_info', { socPath }),
- startFlash: (options) => invoke('flash_start', { options }),
- cancelFlash: () => invoke('flash_cancel'),
- openSocDialog: () => invoke('open_soc_dialog'),
- openScriptDirDialog: () => invoke('open_script_dir_dialog'),
- saveLog: (content) => invoke('save_log', { content }),
- openExternal: (url) => invoke('open_external', { url }),
- // Generic bridge for resource download / project management.
- runCliJson: (args) => invoke('cli_json', { args }),
- startCliStream: (kind, args) => invoke('cli_stream', { kind, args }),
- cancelCliStream: (kind) => invoke('stream_cancel', { kind }),
- onCliEvent: (kind, callback) =>
- listen(`${kind}:event`, (event) => callback(event.payload)),
- onCliLine: (kind, callback) =>
- listen(`${kind}:line`, (event) => callback(event.payload)),
- onCliExit: (kind, callback) =>
- listen(`${kind}:exit`, (event) => callback(event.payload)),
- appPaths: () => invoke('app_paths'),
- readTextFile: (path) => invoke('read_text_file', { path }),
- writeTextFile: (path, content) => invoke('write_text_file', { path, content }),
- listFiles: (path) => invoke('list_files', { path }),
- scanProjects: (root) => invoke('scan_projects', { root }),
- deleteProject: (dir) => invoke('delete_project', { dir }),
- cloneProject: (src, dst) => invoke('clone_project', { src, dst }),
- createDir: (path) => invoke('create_dir', { path }),
- pathExists: (path) => invoke('path_exists', { path }),
- revealPath: (path) => invoke('reveal_path', { path }),
- openFileDialog: (filters) => invoke('open_file_dialog', { filters }),
- openFolderDialog: () => invoke('open_folder_dialog'),
- saveFileDialog: (defaultName, filters) =>
- invoke('save_file_dialog', { defaultName, filters }),
- mcpInfo: () => invoke('mcp_info'),
- // WKWebView does not expose File.path. Drag & drop is handled below via
- // Tauri's native drag-drop event, and file picking goes through Rust.
- getPathForFile: (file) => (file && file.path) || '',
- onFlashEvent: (callback) => on('flashEvent', callback),
- onFlashLine: (callback) => on('flashLine', callback),
- onFlashStarted: (callback) => on('flashStarted', callback),
- onFlashExit: (callback) => on('flashExit', callback),
- onMenuOpenSoc: (callback) => on('menuOpenSoc', callback),
- onMenuSaveLog: (callback) => on('menuSaveLog', callback),
- };
- async function wireEvents() {
- await listen('flash:event', (event) => emit('flashEvent', event.payload));
- await listen('flash:line', (event) => emit('flashLine', event.payload));
- await listen('flash:started', (event) => emit('flashStarted', event.payload));
- await listen('flash:exit', (event) => emit('flashExit', event.payload));
- await listen('menu', (event) => {
- if (event.payload === 'open-soc') emit('menuOpenSoc');
- else if (event.payload === 'save-log') emit('menuSaveLog');
- });
- // Tauri intercepts native file drops; the DOM drop event has no paths.
- await listen('tauri://drag-drop', (event) => {
- const paths = event?.payload?.paths || [];
- const soc = paths.find((path) => /\.soc$/i.test(path));
- if (soc && window.__luatos) window.__luatos.loadSoc(soc);
- });
- }
- wireEvents().catch((error) => console.error('事件通道初始化失败', error));
- // Dev-only self test, mirroring the Electron --selftest-* harness.
- const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
- function reportError(error) {
- const message = error && error.stack ? error.stack : String(error);
- invoke('js_log', { level: 'error', message }).catch(() => {});
- }
- window.addEventListener('error', (event) => reportError(event.error || event.message));
- window.addEventListener('unhandledrejection', (event) => reportError(event.reason));
- function snapshot(extra) {
- const state = window.__luatos?.state || {};
- return {
- api: typeof window.api?.getInfo === 'function',
- cliStatus: document.querySelector('#cli-status')?.textContent,
- fwPath: document.querySelector('#fw-path')?.textContent,
- fwInfo: document.querySelector('#fw-info')?.innerText,
- fwError: document.querySelector('#fw-error')?.textContent,
- bootTip: document.querySelector('#boot-tip')?.innerText,
- stage: document.querySelector('#stage')?.textContent,
- percent: document.querySelector('#percent')?.textContent,
- message: document.querySelector('#message')?.textContent,
- flashDisabled: document.querySelector('#btn-flash')?.disabled,
- flashing: state.isFlashing,
- port: state.port,
- socPath: state.socPath,
- cliOk: state.cliOk,
- log: document.querySelector('#log')?.innerText.slice(-1500),
- ...extra,
- };
- }
- (async () => {
- let config = null;
- try {
- config = await invoke('selftest_config');
- } catch (error) {
- reportError(error);
- return;
- }
- if (!config || !config.soc) return;
- try {
- await wait(600);
- await window.__luatos.loadSoc(config.soc);
- await wait(1200);
- let timedOut = false;
- if (config.flashPort) {
- window.__luatos.state.port = config.flashPort;
- window.__luatos.updateFlashButton();
- const timeout = wait(20000).then(() => {
- timedOut = true;
- });
- await Promise.race([window.__luatos.startFlash(), timeout]);
- await wait(500);
- }
- await invoke('selftest_report', { payload: snapshot({ timedOut }) });
- } catch (error) {
- await invoke('selftest_report', { payload: snapshot({ error: String(error && error.stack ? error.stack : error) }) }).catch(reportError);
- }
- })();
- })();
|