electron.main.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. const { app, Tray, Menu, screen, BrowserWindow, ipcMain } = require('electron');
  2. const path = require('path');
  3. const Store = require('electron-store');
  4. // 初始化存储实例
  5. const store = new Store({
  6. username: {
  7. type: 'string',
  8. default: ''
  9. },
  10. password: {
  11. type: 'string',
  12. default: ''
  13. },
  14. token: {
  15. type: 'string',
  16. default: ''
  17. },
  18. // name: 'auth-data', // 存储文件名称(可选)
  19. // encryptionKey: 'your-encryption-key', // 可选加密(生产环境建议设置)
  20. });
  21. // store.set('username', '');
  22. // store.set('password', '');
  23. // if(store.get())
  24. if (store.get('token')) {
  25. store.delete('token');
  26. }
  27. // console.log(store.get('username'))
  28. let tray = null;
  29. let win = null;
  30. let floatingWindow = null;
  31. let tooltipWindow = null;
  32. let smart_win = null;
  33. let isFloatingWindowVisible = true; // 新增:跟踪悬浮球可见状态
  34. // 新增:记录登录状态
  35. let isLoggedIn = false;
  36. // 尝试获取单实例锁
  37. const gotTheLock = app.requestSingleInstanceLock();
  38. let iconPath;
  39. if (app.isPackaged) {
  40. iconPath = path.join(path.dirname(app.getPath('exe')), 'resources/tray-icon.png');
  41. } else {
  42. iconPath = path.join(__dirname, '/tray-icon.png');
  43. }
  44. function createWindow(w = 1200, h = 800) {
  45. win = new BrowserWindow({
  46. width: w,
  47. height: h,
  48. // frame: false,
  49. icon: iconPath, // 使用平台特定图标
  50. backgroundColor: '#fff',
  51. webPreferences: {
  52. preload: path.join(__dirname, 'preload.js'),
  53. nodeIntegration: true, //启用nodejs集成
  54. contextIsolation: true,
  55. contentSecurityPolicy:
  56. "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'"
  57. }
  58. });
  59. // 强刷
  60. win.webContents.reloadIgnoringCache()
  61. // 禁用默认菜单栏(保留窗口控制按钮)
  62. Menu.setApplicationMenu(null);
  63. // 初始设置为登录页模式(固定大小,禁止调整)
  64. setLoginWindowMode();
  65. const primaryDisplay = screen.getPrimaryDisplay();
  66. const { width, height } = primaryDisplay.workAreaSize;
  67. // win.setPosition(width - 660 - 900, 100);
  68. win.center();
  69. if (process.env.NODE_ENV === 'development') {
  70. win.loadURL(' http://localhost:5173/');
  71. } else {
  72. if (isLoggedIn) {
  73. win.loadURL('http://25.214.216.111:9000/pdwyzz/ai-znwd/dist/index.html#/conversation?id=znwd')
  74. } else {
  75. win.loadURL('http://25.214.216.111:9000/pdwyzz/ai-znwd/dist/index.html#/login')
  76. }
  77. // win.loadFile(path.join(__dirname, 'dist', 'index.html'));
  78. }
  79. // 设置窗口标题
  80. win.setTitle('智库问答助手');
  81. win.on('close', (e) => {
  82. if (!app.isQuitting) {
  83. e.preventDefault();
  84. win.hide();
  85. }
  86. return false;
  87. });
  88. win.on('closed', function () {
  89. win = null;
  90. });
  91. }
  92. // 设置登录窗口模式(固定大小,禁止调整)
  93. function setLoginWindowMode() {
  94. if (win && !win.isDestroyed()) {
  95. win.setResizable(false); // 禁止调整大小
  96. win.setMaximizable(false); // 禁用最大化按钮
  97. win.setMinimumSize(1080, 608); // 设置最小尺寸(可选)
  98. win.setSize(1080, 608); // 设置为固定尺寸
  99. win.center(); // 窗口居中
  100. win.setTitle('智库问答助手');
  101. isLoggedIn = false;
  102. }
  103. }
  104. // 设置主窗口模式(可调整大小,有最小限制)
  105. function setMainWindowMode() {
  106. if (win && !win.isDestroyed()) {
  107. win.setResizable(true); // 允许调整大小
  108. win.setMaximizable(true); // 启用最大化按钮
  109. win.setMinimumSize(1200, 800); // 设置最小尺寸
  110. win.setTitle('智库问答助手');
  111. isLoggedIn = true;
  112. }
  113. }
  114. // 创建快捷对话窗口
  115. function createSmartWindow() {
  116. smart_win = new BrowserWindow({
  117. width: 520,
  118. height: 110,
  119. // maxHeight: 500,
  120. frame: false,
  121. icon: iconPath, // 使用平台特定图标
  122. resizable: false, // 禁止调整窗口大小
  123. maximizable: false, // 禁止最大化
  124. webPreferences: {
  125. preload: path.join(__dirname, 'preload.js'),
  126. nodeIntegration: true,
  127. contextIsolation: true,
  128. contentSecurityPolicy:
  129. "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'"
  130. }
  131. });
  132. // 禁用默认菜单栏(保留窗口控制按钮)
  133. Menu.setApplicationMenu(null);
  134. const primaryDisplay = screen.getPrimaryDisplay();
  135. const { width, height } = primaryDisplay.workAreaSize;
  136. smart_win.setPosition(width - 660, 100);
  137. if (process.env.NODE_ENV === 'development') {
  138. smart_win.loadURL('http://localhost:5173/#/smart');
  139. } else {
  140. // smart_win.loadFile(path.join(__dirname, 'dist', 'index.html'), {
  141. // hash: '/smart'
  142. // });
  143. smart_win.loadURL('http://25.214.216.111:9000/pdwyzz/ai-znwd/dist/index.html#/smart')
  144. }
  145. }
  146. // 新增:设置悬浮窗事件监听
  147. function setupFloatingWindowEvents() {
  148. if (floatingWindow && !floatingWindow.isDestroyed()) {
  149. // 移除旧的事件监听器(如果存在)
  150. floatingWindow.removeAllListeners('closed');
  151. // 添加关闭事件处理
  152. floatingWindow.on('closed', () => {
  153. floatingWindow = null;
  154. });
  155. }
  156. }
  157. // 新增:切换悬浮球可见性
  158. function toggleFloatingWindow() {
  159. if (floatingWindow && !floatingWindow.isDestroyed()) {
  160. if (isFloatingWindowVisible) {
  161. smart_win?.close()
  162. // smart_win?.destroy()
  163. floatingWindow?.hide();
  164. hideTooltip(); // 隐藏可能显示的工具提示
  165. } else {
  166. floatingWindow?.show();
  167. // 重新设置悬浮窗事件监听
  168. setupFloatingWindowEvents();
  169. }
  170. isFloatingWindowVisible = !isFloatingWindowVisible;
  171. updateTrayMenu(); // 更新托盘菜单文本
  172. }
  173. }
  174. // 新增:更新托盘菜单
  175. function updateTrayMenu(show_float_item = true) {
  176. if (!tray) return;
  177. const menu_list = [
  178. {
  179. label: '打开',
  180. click: () => {
  181. if (win && !win.isDestroyed()) {
  182. if (win.isMinimized()) win.restore();
  183. win.show();
  184. win.focus();
  185. } else {
  186. createWindow();
  187. }
  188. }
  189. },
  190. // {
  191. // label: isFloatingWindowVisible ? '隐藏悬浮球' : '显示悬浮球',
  192. // click: toggleFloatingWindow
  193. // },
  194. {
  195. label: '退出',
  196. click: () => {
  197. app.isQuitting = true;
  198. if (floatingWindow) floatingWindow.destroy();
  199. app.quit();
  200. }
  201. }
  202. ]
  203. const float_item = {
  204. label: isFloatingWindowVisible ? '隐藏悬浮球' : '显示悬浮球',
  205. click: toggleFloatingWindow
  206. }
  207. if (show_float_item) {
  208. menu_list.splice(1, 0, float_item)
  209. }
  210. const contextMenu = Menu.buildFromTemplate(menu_list);
  211. tray.setContextMenu(contextMenu);
  212. }
  213. // 创建系统托盘
  214. function createTray() {
  215. let iconPath;
  216. if (app.isPackaged) {
  217. iconPath = path.join(path.dirname(app.getPath('exe')), 'resources/tray-icon.png');
  218. } else {
  219. iconPath = path.join(__dirname, '/tray-icon.png');
  220. }
  221. tray = new Tray(iconPath);
  222. updateTrayMenu(); // 使用函数设置菜单
  223. tray.setToolTip('智库问答助手');
  224. tray.on('click', () => {
  225. if (win && !win.isDestroyed()) {
  226. if (win.isMinimized()) win.restore();
  227. win.show();
  228. win.focus();
  229. } else {
  230. createWindow();
  231. }
  232. });
  233. }
  234. // 创建悬浮窗
  235. function createFloatingWindow() {
  236. floatingWindow = new BrowserWindow({
  237. width: 42,
  238. height: 42,
  239. frame: false,
  240. transparent: false,
  241. alwaysOnTop: true,
  242. skipTaskbar: true,
  243. resizable: false,
  244. backgroundColor: '#00000000', // 强制有颜色背景,否则 tooltip 不触发
  245. hasShadow: false,
  246. transparent: true,
  247. webPreferences: {
  248. preload: path.join(__dirname, 'preload.js'),
  249. nodeIntegration: true,
  250. contextIsolation: true
  251. },
  252. type: 'desktop'
  253. });
  254. floatingWindow.setAlwaysOnTop(true, 'screen-saver'); // 在macOS有效
  255. if (process.env.NODE_ENV === 'development') {
  256. floatingWindow.loadURL('http://localhost:5173/#/floating');
  257. } else {
  258. // floatingWindow.loadFile(path.join(__dirname, 'dist', 'index.html'), {
  259. // hash: '/floating'
  260. // });
  261. floatingWindow.loadURL('http://25.214.216.111:9000/pdwyzz/ai-znwd/dist/index.html#/floating')
  262. }
  263. const primaryDisplay = screen.getPrimaryDisplay();
  264. const { width, height } = primaryDisplay.workAreaSize;
  265. floatingWindow.setPosition(width - 50, height - 200);
  266. // 设置悬浮窗事件监听
  267. setupFloatingWindowEvents();
  268. }
  269. // 提示窗口
  270. function showTooltip(adsorbedPosition, x, y) {
  271. if (tooltipWindow) return;
  272. let tooltipX;
  273. if (adsorbedPosition === 0) {
  274. // 悬浮球吸附在左侧,tooltip 显示在右侧
  275. tooltipX = x + 50;
  276. } else {
  277. // 悬浮球吸附在右侧,tooltip 显示在左侧
  278. tooltipX = x - 125;
  279. }
  280. tooltipWindow = new BrowserWindow({
  281. width: 120,
  282. height: 40,
  283. x: tooltipX,
  284. y: y + 5,
  285. frame: false,
  286. alwaysOnTop: true,
  287. skipTaskbar: true,
  288. resizable: false,
  289. transparent: true,
  290. hasShadow: false,
  291. focusable: false,
  292. webPreferences: {
  293. nodeIntegration: true,
  294. contextIsolation: false
  295. }
  296. });
  297. if (process.env.NODE_ENV === 'development') {
  298. tooltipWindow.loadURL(' http://localhost:5173/#/tips');
  299. } else {
  300. // tooltipWindow.loadFile(path.join(__dirname, 'dist', 'index.html'), {
  301. // hash: '/tips'
  302. // });
  303. tooltipWindow.loadURL('http://25.214.216.111:9000/pdwyzz/ai-znwd/dist/index.html#/tips')
  304. }
  305. tooltipWindow.once('ready-to-show', () => {
  306. tooltipWindow?.showInactive();
  307. });
  308. }
  309. function hideTooltip() {
  310. if (tooltipWindow) {
  311. tooltipWindow.close();
  312. tooltipWindow = null;
  313. }
  314. }
  315. // 监听打开窗口事件
  316. ipcMain.on('open-window', () => {
  317. if (win && !win.isDestroyed()) {
  318. if (win.isMinimized()) win.restore();
  319. win.show();
  320. win.focus();
  321. } else {
  322. createWindow();
  323. }
  324. });
  325. // 监听窗口大小变化时间
  326. ipcMain.on('resize-main-window', (event, width, height) => {
  327. if (win && !win.isDestroyed()) {
  328. // 1. 先退出全屏状态(如果是全屏)
  329. if (win.isFullScreen()) {
  330. win.setFullScreen(false);
  331. // 等待全屏状态变更完成后再调整大小
  332. win.once('leave-full-screen', () => {
  333. adjustWindowSize(width, height);
  334. });
  335. }
  336. // 2. 再恢复窗口(如果是最大化)
  337. else if (win.isMaximized()) {
  338. win.unmaximize();
  339. // 等待窗口恢复后再调整大小
  340. win.once('unmaximize', () => {
  341. adjustWindowSize(width, height);
  342. });
  343. }
  344. // 3. 直接调整大小(普通状态)
  345. else {
  346. adjustWindowSize(width, height);
  347. }
  348. } else {
  349. createWindow(width, height);
  350. }
  351. });
  352. // 提取调整窗口大小的公共逻辑
  353. function adjustWindowSize(width, height) {
  354. win.setSize(width, height);
  355. win.center();
  356. }
  357. ipcMain.on('open-smart-window', () => {
  358. if (smart_win && !smart_win.isDestroyed()) {
  359. if (smart_win.isMinimized()) smart_win.restore();
  360. smart_win.show();
  361. smart_win.focus();
  362. } else {
  363. createSmartWindow();
  364. }
  365. });
  366. ipcMain.on('toggle-smart-window', () => {
  367. if (smart_win && !smart_win.isDestroyed()) {
  368. smart_win.hide();
  369. smart_win.close();
  370. smart_win.destroy()
  371. smart_win = null
  372. } else {
  373. createSmartWindow();
  374. smart_win.focus();
  375. }
  376. });
  377. ipcMain.on('close-smart-window', () => {
  378. if (smart_win && !smart_win.isDestroyed()) {
  379. smart_win.close();
  380. }
  381. });
  382. ipcMain.on('resize-smart-window', (event, height) => {
  383. if (smart_win && !smart_win.isDestroyed()) {
  384. // 获取当前窗口宽度
  385. const [width] = smart_win.getSize();
  386. // 设置新的窗口大小(保持宽度不变,修改高度)
  387. smart_win.setSize(width, height);
  388. }
  389. });
  390. ipcMain.on('set-float-window-position', (event, x, y) => {
  391. if (floatingWindow && !floatingWindow.isDestroyed()) {
  392. floatingWindow.setBounds({ x, y, width: 50, height: 50 });
  393. }
  394. });
  395. ipcMain.handle('get-float-window-position', () => {
  396. if (floatingWindow && !floatingWindow.isDestroyed()) {
  397. const [x, y] = floatingWindow.getPosition();
  398. return { x, y };
  399. }
  400. return { x: 0, y: 0 };
  401. });
  402. ipcMain.handle('get-smart-window-position', () => {
  403. if (smart_win && !smart_win.isDestroyed()) {
  404. const [x, y] = smart_win.getPosition();
  405. return { x, y };
  406. }
  407. return { x: 0, y: 0 };
  408. });
  409. ipcMain.on('set-smart-window-position', (event, x, y) => {
  410. if (smart_win && !smart_win.isDestroyed()) {
  411. smart_win.setBounds({ x, y });
  412. }
  413. });
  414. ipcMain.on('show-tooltip', (event, adsorbedPosition) => {
  415. if (!floatingWindow) return;
  416. const [x, y] = floatingWindow.getPosition();
  417. showTooltip(adsorbedPosition, x, y);
  418. });
  419. ipcMain.on('hide-tooltip', hideTooltip);
  420. ipcMain.on('hide-tray-float-window', (event) => {
  421. if (floatingWindow && !floatingWindow.isDestroyed()) {
  422. if (isFloatingWindowVisible) {
  423. if (smart_win) {
  424. smart_win?.close()
  425. // smart_win?.destroy()
  426. floatingWindow?.hide();
  427. hideTooltip(); // 隐藏可能显示的工具提示
  428. } else {
  429. floatingWindow?.close()
  430. }
  431. }
  432. updateTrayMenu(false); // 更新托盘菜单文本
  433. }
  434. })
  435. ipcMain.on('show-tray-float-window', (event) => {
  436. createFloatingWindow();
  437. floatingWindow.focus();
  438. isFloatingWindowVisible = true;
  439. updateTrayMenu(); // 更新托盘菜单文本
  440. })
  441. // 新增:监听登录状态变化
  442. ipcMain.on('set-login-state', (event, loggedIn) => {
  443. if (loggedIn) {
  444. setLoginWindowMode();
  445. } else {
  446. setMainWindowMode();
  447. }
  448. });
  449. // 封装存储操作
  450. // 保存认证信息
  451. ipcMain.handle('save-auth', (event, username, password, token) => {
  452. console.log('Saving auth:', username, password, token);
  453. try {
  454. console.log('Saving auth:', username, password, token);
  455. store.set('username', username);
  456. store.set('password', password);
  457. store.set('token', token);
  458. return { success: true, message: '认证信息保存成功' };
  459. } catch (error) {
  460. console.error('Failed to save auth:', error);
  461. return new Error('保存认证信息失败: ' + error.message);
  462. }
  463. });
  464. // 获取用户名
  465. ipcMain.handle('get-username', () => {
  466. return store.get('username') || '';
  467. });
  468. // 获取密码
  469. ipcMain.handle('get-password', () => {
  470. return store.get('password') || '';
  471. });
  472. // 获取 Token
  473. ipcMain.handle('get-token', () => {
  474. return store.get('token') || '';
  475. });
  476. // 删除认证信息
  477. ipcMain.handle('clear-auth', () => {
  478. // store.delete('username');n
  479. store.delete('token');
  480. // store.delete('password')
  481. });
  482. ipcMain.on('logout', () => {
  483. updateTrayMenu(false)
  484. if (smart_win && !smart_win.isDestroyed()) {
  485. smart_win.destroy();
  486. smart_win = null;
  487. }
  488. if (floatingWindow && !floatingWindow.isDestroyed()) {
  489. floatingWindow.destroy();
  490. floatingWindow = null;
  491. }
  492. });
  493. // 显示主窗口
  494. function showMainWindow() {
  495. if (win && !win.isDestroyed()) {
  496. if (win.isMinimized()) win.restore();
  497. win.show();
  498. win.focus();
  499. } else {
  500. createWindow();
  501. }
  502. }
  503. if (!gotTheLock) {
  504. // 如果没有获取到锁,说明已经有一个实例在运行,直接退出当前实例
  505. app.quit();
  506. } else {
  507. app.whenReady().then(() => {
  508. createWindow();
  509. createTray();
  510. createFloatingWindow();
  511. app.on('activate', function () {
  512. if (BrowserWindow.getAllWindows().length === 0) createWindow();
  513. });
  514. });
  515. app.on('window-all-closed', function () {
  516. if (process.platform !== 'darwin') app.quit();
  517. });
  518. // 再次启动时,如果有主窗口,则显示主窗口
  519. app.on('second-instance', showMainWindow);
  520. }