utils.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. 'use strict';
  2. const { Controller } = require('ee-core');
  3. const { shell } = require('electron');
  4. const Addon = require('ee-core/addon');
  5. const { dialog } = require('electron');
  6. const fs = require('fs');
  7. const path = require('path');
  8. const CoreWindow = require('ee-core/electron/window');
  9. const { BrowserWindow, Menu,app } = require('electron');
  10. const { spawn } = require('child_process');
  11. const Log = require('ee-core/log');
  12. const { readConfigFile } = require('../utils/config');
  13. const configDeault = readConfigFile();
  14. const errData = {
  15. msg :'请求失败,请联系管理员',
  16. code:999
  17. }
  18. const sharp = require('sharp'); // 确保安装:npm install sharp
  19. /**
  20. * example
  21. * @class
  22. */
  23. class UtilsController extends Controller {
  24. constructor(ctx) {
  25. super(ctx);
  26. }
  27. /**
  28. * 运行外部工具(如exe)
  29. * @param {{exeName?: string, exePath?: string, args?: string[]}} params
  30. */
  31. async runExternalTool (params = {}) {
  32. try {
  33. const { exeName, exePath, args = [] } = params;
  34. const targetName = exePath || exeName;
  35. if (!targetName) {
  36. throw new Error('缺少可执行文件名称');
  37. }
  38. const isPackaged = app.isPackaged;
  39. const execDir = isPackaged ? path.dirname(app.getPath('exe')) : path.join(app.getAppPath(), '.');
  40. const resourcesDir = process.resourcesPath;
  41. const candidates = [];
  42. const pushCandidate = (candidatePath, isAbsolute = false) => {
  43. if (!candidatePath) return;
  44. const normalized = isAbsolute || path.isAbsolute(candidatePath)
  45. ? candidatePath
  46. : path.join(execDir, candidatePath);
  47. if (!candidates.includes(normalized)) {
  48. candidates.push(normalized);
  49. }
  50. };
  51. // 允许前端显式传入候选路径数组
  52. if (Array.isArray(params.candidatePaths)) {
  53. params.candidatePaths.forEach((p) => pushCandidate(p));
  54. }
  55. if (path.isAbsolute(targetName)) {
  56. pushCandidate(targetName, true);
  57. } else {
  58. if (isPackaged) {
  59. pushCandidate(path.join(execDir, targetName), true);
  60. pushCandidate(path.join(resourcesDir, targetName), true);
  61. pushCandidate(path.join(resourcesDir, 'extraResources', targetName), true);
  62. } else {
  63. pushCandidate(targetName);
  64. pushCandidate(path.join('build', 'extraResources', targetName));
  65. pushCandidate(path.join('extraResources', targetName));
  66. }
  67. }
  68. console.log('=======');
  69. console.log(candidates);
  70. const resolvedPath = candidates.find((filePath) => filePath && fs.existsSync(filePath));
  71. if (!resolvedPath) {
  72. throw new Error(`未找到工具:${targetName}`);
  73. }
  74. // 如果已经有正在运行的子进程,则先关闭旧进程,再重新启动新的(保证始终只有一个进程,同时刷新页面参数)
  75. if (this.app.externalToolProcess && !this.app.externalToolProcess.killed) {
  76. try {
  77. this.app.externalToolProcess.kill();
  78. } catch (e) {
  79. console.warn('关闭旧 externalTool 进程失败(忽略继续启动新进程):', e);
  80. }
  81. this.app.externalToolProcess = null;
  82. }
  83. const child = spawn(resolvedPath, args, {
  84. cwd: path.dirname(resolvedPath),
  85. detached: true,
  86. stdio: 'ignore',
  87. windowsHide: false
  88. });
  89. // 记录子进程,方便后续复用/判断是否已退出
  90. this.app.externalToolProcess = child;
  91. child.on('exit', () => {
  92. if (this.app.externalToolProcess === child) {
  93. this.app.externalToolProcess = null;
  94. }
  95. });
  96. child.unref();
  97. return {
  98. code: 0,
  99. data: {
  100. path: resolvedPath,
  101. reused: false
  102. }
  103. };
  104. } catch (error) {
  105. console.error('runExternalTool error:', error);
  106. return {
  107. code: 1,
  108. msg: error.message || '运行外部工具失败'
  109. };
  110. }
  111. }
  112. /**
  113. * 所有方法接收两个参数
  114. * @param args 前端传的参数
  115. * @param event - ipc通信时才有值。详情见:控制器文档
  116. */
  117. /**
  118. * upload
  119. */
  120. async shellFun (params) {
  121. // 如果是打开路径操作,确保路径存在
  122. if (params.action === 'openMkPath') {
  123. try {
  124. // 确保目录存在,如果不存在就创建
  125. if (!fs.existsSync(params.params)) {
  126. fs.mkdirSync(params.params, { recursive: true });
  127. }
  128. shell.openPath(params.params)
  129. return;
  130. } catch (err) {
  131. console.error('创建目录失败:', err);
  132. // 即使创建目录失败,也尝试打开路径(可能已经存在)
  133. }
  134. }
  135. shell[params.action](params.params)
  136. }
  137. async openMain (config) {
  138. const { id, url } = config;
  139. if (this.app.electron[id]) {
  140. const win = this.app.electron[id];
  141. // 切换到指定的 URL
  142. await win.loadURL(url);
  143. win.focus();
  144. win.show();
  145. return;
  146. }
  147. const win = new BrowserWindow({
  148. ...config,
  149. webPreferences: {
  150. webSecurity: false,
  151. contextIsolation: false, // false -> 可在渲染进程中使用electron的api,true->需要bridge.js(contextBridge)
  152. nodeIntegration: true,
  153. // preload: path.join('../preload/preload.js','../preload/bridge.js'),
  154. },
  155. });
  156. await win.loadURL(config.url); // 设置窗口的 URL
  157. // 监听窗口关闭事件
  158. if(configDeault.debug) win.webContents.openDevTools()
  159. //
  160. win.on('close', () => {
  161. delete this.app.electron[config.id]; // 删除窗口引用
  162. });
  163. this.app.electron[config.id] = win ;
  164. }
  165. setWindowClosable(payload = {}) {
  166. const id = payload.id
  167. const closable = payload.closable !== false
  168. const win = id && this.app.electron ? this.app.electron[id] : null
  169. if (!win || win.isDestroyed()) return { code: 1, msg: '窗口不存在' }
  170. try {
  171. win.setClosable(closable)
  172. return { code: 0 }
  173. } catch (error) {
  174. Log.error('设置窗口关闭状态失败:', error)
  175. return { code: 1, msg: error.message }
  176. }
  177. }
  178. async openDirectory(optiops={
  179. title:"选择文件夹"
  180. }){
  181. const filePaths = dialog.showOpenDialogSync({
  182. title:optiops.title || '选择文件夹',
  183. properties: ['openDirectory']
  184. })
  185. if(filePaths[0]) return filePaths[0];
  186. return filePaths
  187. }
  188. /**
  189. * 关闭所有子窗口
  190. */
  191. closeAllWindows() {
  192. try {
  193. // 获取所有窗口
  194. const windows = this.app.electron;
  195. // 关闭除主窗口外的所有窗口
  196. for (const [id, window] of Object.entries(windows)) {
  197. if (!['mainWindow','extra'].includes(id)) { // 保留主窗口
  198. try {
  199. window.close();
  200. delete this.app.electron[id];
  201. } catch (error) {
  202. console.error(`关闭窗口 ${id} 失败:`, error);
  203. }
  204. }
  205. }
  206. console.log('所有子窗口已关闭');
  207. return { success: true, message: '所有子窗口已关闭' };
  208. } catch (error) {
  209. console.error('关闭所有窗口失败:', error);
  210. return { success: false, message: '关闭所有窗口失败: ' + error.message };
  211. }
  212. }
  213. async openImage(
  214. optiops= {
  215. title:"选择图片",
  216. filters:[
  217. { name: '支持JPG,png,gif', extensions: ['jpg','jpeg','png'] },
  218. ],
  219. }
  220. ){
  221. const filePaths = dialog.showOpenDialogSync({
  222. title:optiops.title || '选择图片',
  223. properties:['openFile'],
  224. filters:optiops.filters || [
  225. { name: '支持JPG,png,gif', extensions: ['jpg','jpeg','png'] },
  226. ]
  227. })
  228. const filePath = filePaths[0];
  229. const fileBuffer = fs.readFileSync(filePath);
  230. const base64Image = fileBuffer.toString('base64');
  231. // 获取文件扩展名
  232. const extension = path.extname(filePath).toLowerCase().replace('.', '');
  233. // 根据扩展名确定 MIME 类型
  234. let mimeType = '';
  235. switch (extension) {
  236. case 'jpg':
  237. case 'jpeg':
  238. mimeType = 'image/jpeg';
  239. break;
  240. case 'png':
  241. mimeType = 'image/png';
  242. break;
  243. case 'gif':
  244. mimeType = 'image/gif';
  245. break;
  246. default:
  247. mimeType = 'application/octet-stream'; // 默认 MIME 类型
  248. break;
  249. }
  250. // 构建 data URL
  251. const dataUrl = `data:${mimeType};base64,${base64Image}`;
  252. return {
  253. filePath:filePath,
  254. base64Image:dataUrl
  255. };
  256. }
  257. /**
  258. * 将前端生成的详情图数据写入 EXE 同级目录下的 output 文件夹。
  259. * @param {{ bundles: Array }} payload
  260. */
  261. async saveGeneratedImages (payload = {}) {
  262. try {
  263. const { app } = require('electron');
  264. const bundles = payload.bundles || [];
  265. if (!Array.isArray(bundles) || !bundles.length) {
  266. return { code: 1, msg: '无可保存的图片数据' };
  267. }
  268. // 运行目录:打包后为 EXE 所在目录,开发环境为项目根目录
  269. const isPackaged = app.isPackaged;
  270. const exeDir = isPackaged ? path.dirname(app.getPath('exe')) : process.cwd();
  271. const baseOutputDir = path.join(exeDir, 'output');
  272. if (!fs.existsSync(baseOutputDir)) {
  273. fs.mkdirSync(baseOutputDir, { recursive: true });
  274. }
  275. let fileCount = 0;
  276. const saveDataUrlToFile = (dataUrl, targetPath) => {
  277. if (!dataUrl || typeof dataUrl !== 'string') return;
  278. const match = dataUrl.match(/^data:image\/\w+;base64,(.+)$/);
  279. const base64Data = match ? match[1] : dataUrl;
  280. const buffer = Buffer.from(base64Data, 'base64');
  281. const dir = path.dirname(targetPath);
  282. if (!fs.existsSync(dir)) {
  283. fs.mkdirSync(dir, { recursive: true });
  284. }
  285. fs.writeFileSync(targetPath, buffer);
  286. fileCount += 1;
  287. };
  288. bundles.forEach(bundle => {
  289. if (!bundle) return;
  290. const styleNo = (bundle.styleNo || bundle.styleKey || 'UNKNOWN').toString().replace(/[\\\/:*?"<>|]/g, '_');
  291. const styleDir = path.join(baseOutputDir, styleNo);
  292. if (!fs.existsSync(styleDir)) {
  293. fs.mkdirSync(styleDir, { recursive: true });
  294. }
  295. // 单画布图片
  296. (bundle.images || []).forEach((img, idx) => {
  297. if (!img || typeof img.dataUrl !== 'string') return;
  298. if (img.dataUrl === 'model' || img.dataUrl === 'scene') return;
  299. if (!img.dataUrl.startsWith('data:image')) return;
  300. const fileName = `canvas_${img.canvasIndex || 0}_img_${idx}.jpg`;
  301. const targetPath = path.join(styleDir, fileName);
  302. saveDataUrlToFile(img.dataUrl, targetPath);
  303. });
  304. // 合成长图
  305. if (bundle.combined && bundle.combined.dataUrl) {
  306. const combinedPath = path.join(styleDir, 'all_canvases.jpg');
  307. saveDataUrlToFile(bundle.combined.dataUrl, combinedPath);
  308. }
  309. });
  310. return {
  311. code: 0,
  312. data: {
  313. outputDir: baseOutputDir,
  314. fileCount,
  315. },
  316. };
  317. } catch (error) {
  318. console.error('saveGeneratedImages error:', error);
  319. return {
  320. code: 1,
  321. msg: error.message || '保存生成图片失败',
  322. };
  323. }
  324. }
  325. async saveRemoteImage(payload = {}) {
  326. try {
  327. const url = payload.url
  328. if (!url) return { code: 1, msg: '没有可保存的图片' }
  329. const defaultName = payload.defaultName || `湛江场景图_${Date.now()}.png`
  330. const dest = dialog.showSaveDialogSync({
  331. title: '保存图片到本地',
  332. defaultPath: defaultName,
  333. filters: [
  334. { name: '图片', extensions: ['png', 'jpg', 'jpeg', 'webp'] },
  335. ],
  336. })
  337. if (!dest) return { code: 1, msg: '已取消保存' }
  338. await this._writeImageToFile(url, dest)
  339. return { code: 0, msg: '保存成功', path: dest }
  340. } catch (error) {
  341. Log.error('保存图片失败:', error)
  342. return { code: 1, msg: error.message || '保存图片失败' }
  343. }
  344. }
  345. async saveRemoteImages(payload = {}) {
  346. try {
  347. const items = payload.items || []
  348. if (!items.length) return { code: 1, msg: '没有可保存的图片' }
  349. const dir = dialog.showOpenDialogSync({
  350. title: '选择保存文件夹',
  351. properties: ['openDirectory', 'createDirectory'],
  352. })
  353. if (!dir || !dir[0]) return { code: 1, msg: '已取消保存' }
  354. const folder = dir[0]
  355. let count = 0
  356. for (let i = 0; i < items.length; i++) {
  357. const item = items[i]
  358. if (!item || !item.url) continue
  359. let ext = path.extname(String(item.url || '').split('?')[0] || '')
  360. if (!['.png', '.jpg', '.jpeg', '.webp'].includes(ext.toLowerCase())) ext = '.png'
  361. const dest = path.join(folder, this._safeFileName(item.name || `湛江场景图_${i + 1}`) + ext)
  362. await this._writeImageToFile(item.url, dest)
  363. count += 1
  364. }
  365. return { code: 0, msg: '保存成功', path: folder, count }
  366. } catch (error) {
  367. Log.error('批量保存图片失败:', error)
  368. return { code: 1, msg: error.message || '保存图片失败' }
  369. }
  370. }
  371. _safeFileName(name) {
  372. return String(name || '湛江场景图').replace(/[\\/:*?"<>|]/g, '_').slice(0, 80)
  373. }
  374. _writeImageToFile(url, dest) {
  375. const fsPromises = fs.promises
  376. if (typeof url === 'string' && url.startsWith('data:image')) {
  377. const match = url.match(/^data:image\/\w+;base64,(.+)$/)
  378. const base64Data = match ? match[1] : url
  379. return fsPromises.writeFile(dest, Buffer.from(base64Data, 'base64'))
  380. }
  381. if (typeof url === 'string' && !/^https?:\/\//i.test(url)) {
  382. const localPath = url.replace(/^file:\/\//i, '')
  383. return fsPromises.copyFile(localPath, dest)
  384. }
  385. const http = require('http')
  386. const https = require('https')
  387. return new Promise((resolve, reject) => {
  388. const fetchOnce = (target, hops = 0) => {
  389. if (hops > 5) {
  390. reject(new Error('下载跳转次数过多'))
  391. return
  392. }
  393. const client = target.startsWith('https') ? https : http
  394. const req = client.get(target, (res) => {
  395. if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
  396. fetchOnce(res.headers.location, hops + 1)
  397. return
  398. }
  399. if (res.statusCode !== 200) {
  400. reject(new Error('下载失败: ' + res.statusCode))
  401. return
  402. }
  403. const chunks = []
  404. res.on('data', (chunk) => chunks.push(chunk))
  405. res.on('end', () => {
  406. fs.writeFile(dest, Buffer.concat(chunks), (err) => err ? reject(err) : resolve())
  407. })
  408. })
  409. req.on('error', reject)
  410. }
  411. fetchOnce(url)
  412. })
  413. }
  414. async openFile(optiops= {
  415. title:"选择文件",
  416. filters:[
  417. { name: '支持JPG', extensions: ['jpg','jpeg'] },
  418. ],
  419. }){
  420. const filePaths = dialog.showOpenDialogSync({
  421. title:optiops.title || '选择文件',
  422. properties: ['openFile'],
  423. filters: optiops.filters || [
  424. { name: '选择文件' },
  425. ]
  426. })
  427. if(filePaths[0]) return filePaths[0];
  428. return filePaths
  429. }
  430. getAppConfig(){
  431. const config = readConfigFile()
  432. const appPath = path.join(app.getAppPath(), '../..');
  433. const pyPath = path.join(path.dirname(appPath), 'extraResources', 'py');
  434. return {
  435. ...config,
  436. userDataPath: app.getPath('userData'),
  437. appPath: appPath,
  438. pyPath:pyPath,
  439. }
  440. }
  441. // 字体管理相关方法
  442. async downloadFont(args, event) {
  443. try {
  444. console.log('🔤 IPC downloadFont called with args:', args, 'event:', event)
  445. const { url, fontName } = args;
  446. console.log('🔤 IPC downloadFont parsed:', { url, fontName })
  447. Log.info('downloadFontdownloadFontdownloadFontdownloadFont:', url, fontName)
  448. const https = require('https');
  449. const http = require('http');
  450. const fs = require('fs');
  451. const path = require('path');
  452. const crypto = require('crypto');
  453. // 获取字体缓存目录
  454. const userDataPath = app.getPath('userData');
  455. const fontCacheDir = path.join(userDataPath, 'fonts');
  456. // 确保字体缓存目录存在
  457. if (!fs.existsSync(fontCacheDir)) {
  458. fs.mkdirSync(fontCacheDir, { recursive: true });
  459. }
  460. // 生成字体文件名(使用URL的哈希值避免文件名冲突)
  461. const urlHash = crypto.createHash('md5').update(url).digest('hex').substring(0, 8);
  462. const fontFileName = `${fontName.replace(/[^a-zA-Z0-9]/g, '_')}_${urlHash}.ttf`;
  463. const localFontPath = path.join(fontCacheDir, fontFileName);
  464. // 检查本地是否已有字体文件
  465. if (fs.existsSync(localFontPath)) {
  466. console.log('字体已存在:', localFontPath);
  467. return { success: true, path: localFontPath };
  468. }
  469. console.log('开始下载字体:', fontName, '到:', localFontPath);
  470. // 下载字体文件
  471. const protocol = url.startsWith('https:') ? https : http;
  472. return new Promise((resolve, reject) => {
  473. const request = protocol.get(url, (response) => {
  474. if (response.statusCode !== 200) {
  475. reject(new Error(`Failed to download font: ${response.statusCode}`));
  476. return;
  477. }
  478. const fileStream = fs.createWriteStream(localFontPath);
  479. response.pipe(fileStream);
  480. fileStream.on('finish', () => {
  481. fileStream.close();
  482. console.log('字体下载完成:', localFontPath);
  483. resolve({ success: true, path: localFontPath });
  484. });
  485. fileStream.on('error', (error) => {
  486. fs.unlinkSync(localFontPath); // 删除失败的文件
  487. reject(error);
  488. });
  489. });
  490. request.on('error', (error) => {
  491. reject(error);
  492. });
  493. // 设置超时
  494. request.setTimeout(30000, () => {
  495. request.abort();
  496. reject(new Error('Font download timeout'));
  497. });
  498. });
  499. } catch (error) {
  500. Log.info('downloadFont Error:', error);
  501. return { success: false, error: error.message };
  502. }
  503. }
  504. async loadFontFromCache(args, event) {
  505. try {
  506. const { fontName, fontUrl } = args;
  507. const fs = require('fs');
  508. const path = require('path');
  509. const crypto = require('crypto');
  510. // 获取字体缓存目录
  511. const userDataPath = app.getPath('userData');
  512. const fontCacheDir = path.join(userDataPath, 'fonts');
  513. // 生成字体文件名
  514. const urlHash = crypto.createHash('md5').update(fontUrl).digest('hex').substring(0, 8);
  515. const fontFileName = `${fontName.replace(/[^a-zA-Z0-9]/g, '_')}_${urlHash}.ttf`;
  516. const localFontPath = path.join(fontCacheDir, fontFileName);
  517. // 检查本地是否已有字体文件
  518. if (fs.existsSync(localFontPath)) {
  519. // 读取字体文件内容并转换为base64
  520. const fontData = fs.readFileSync(localFontPath);
  521. const base64Data = fontData.toString('base64');
  522. const dataUrl = `data:font/ttf;base64,${base64Data}`;
  523. return { success: true, dataUrl, path: localFontPath };
  524. }
  525. return { success: false, message: 'Font not found in cache' };
  526. } catch (error) {
  527. console.error('从缓存加载字体失败:', error);
  528. return { success: false, error: error.message };
  529. }
  530. }
  531. getFontCachePath(args, event) {
  532. const path = require('path');
  533. const userDataPath = app.getPath('userData');
  534. return path.join(userDataPath, 'fonts');
  535. }
  536. // 测试方法
  537. async testIPC(args, event) {
  538. console.log('🧪 IPC test method called:', args)
  539. return { success: true, message: 'IPC is working', args }
  540. }
  541. async readFileImageForPath(filePath,maxWidth=1500){
  542. const getMimeType = (fileName)=>{
  543. const extension = path.extname(fileName).toLowerCase().replace('.', '');
  544. let mimeType = '';
  545. switch (extension) {
  546. case 'jpg':
  547. case 'jpeg':
  548. mimeType = 'image/jpeg';
  549. break;
  550. case 'png':
  551. mimeType = 'image/png';
  552. break;
  553. case 'gif':
  554. mimeType = 'image/gif';
  555. break;
  556. case 'webp':
  557. mimeType = 'image/webp';
  558. break;
  559. case 'avif':
  560. mimeType = 'image/avif';
  561. break;
  562. default:
  563. mimeType = 'application/octet-stream';
  564. break;
  565. }
  566. return mimeType;
  567. }
  568. try {
  569. const fileName = path.basename(filePath);
  570. const image = sharp(filePath);
  571. const metadata = await image.metadata();
  572. let mimeType = getMimeType(fileName); // 调用下面定义的私有方法获取 MIME 类型
  573. let fileBuffer;
  574. if (metadata.width > maxWidth) {
  575. // 如果宽度大于 1500px,压缩至 1500px 宽度,保持比例
  576. fileBuffer = await image.resize(maxWidth).toBuffer();
  577. } else {
  578. // 否则直接读取原图
  579. fileBuffer = fs.readFileSync(filePath);
  580. }
  581. return {
  582. fileBuffer,
  583. fileName,
  584. mimeType
  585. };
  586. } catch (error) {
  587. console.error('Error processing image:', error);
  588. throw error;
  589. }
  590. }
  591. }
  592. UtilsController.toString = () => '[class ExampleController]';
  593. module.exports = UtilsController;