lifecycle.ts 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { app as electronApp, screen } from 'electron';
  2. import { logger } from 'ee-core/log';
  3. import { getConfig } from 'ee-core/config';
  4. import { getMainWindow } from 'ee-core/electron';
  5. import { disposeCodex } from '../service/codex';
  6. import { locateCodexBinary } from '../service/codex/codexLocator';
  7. class Lifecycle {
  8. /**
  9. * core app have been loaded
  10. */
  11. async ready(): Promise<void> {
  12. logger.info('[lifecycle] ready');
  13. try {
  14. // 只解析路径、不 spawn:打包后 asar / asar.unpacked 的定位问题一眼可见
  15. logger.info('[lifecycle] codex 二进制:', await locateCodexBinary());
  16. } catch (error) {
  17. logger.error('[lifecycle] codex 二进制不可用:', error instanceof Error ? error.message : String(error));
  18. }
  19. }
  20. /**
  21. * electron app ready
  22. */
  23. async electronAppReady(): Promise<void> {
  24. logger.info('[lifecycle] electron-app-ready');
  25. // When double clicking the icon, display the opened window
  26. electronApp.on('second-instance', () => {
  27. const win = getMainWindow();
  28. if (win.isMinimized()) {
  29. win.restore();
  30. }
  31. win.show();
  32. win.focus();
  33. });
  34. }
  35. /**
  36. * main window have been loaded
  37. */
  38. async windowReady(): Promise<void> {
  39. logger.info('[lifecycle] window-ready');
  40. const win = getMainWindow();
  41. // The window is centered and scaled proportionally
  42. // Obtain the size information of the main screen, calculate the width and height of the window as a percentage of the screen,
  43. // and calculate the coordinates of the upper left corner when the window is centered
  44. const mainScreen = screen.getPrimaryDisplay();
  45. const { width, height } = mainScreen.workAreaSize;
  46. const windowWidth = Math.floor(width * 0.6);
  47. const windowHeight = Math.floor(height * 0.7);
  48. const x = Math.floor((width - windowWidth) / 2);
  49. const y = Math.floor((height - windowHeight) / 2);
  50. win.setBounds({ x, y, width: windowWidth, height: windowHeight })
  51. // Delayed loading, no white screen
  52. const { windowsOption } = getConfig();
  53. if (windowsOption.show == false) {
  54. win.once('ready-to-show', () => {
  55. win.show();
  56. win.focus();
  57. })
  58. }
  59. }
  60. /**
  61. * before app close
  62. */
  63. async beforeClose(): Promise<void> {
  64. logger.info('[lifecycle] before-close');
  65. try {
  66. // 回收 codex app-server 子进程,避免退出后留下孤儿进程
  67. await disposeCodex();
  68. } catch (error) {
  69. logger.error('[lifecycle] dispose codex failed:', error instanceof Error ? error.message : String(error));
  70. }
  71. }
  72. }
  73. export {
  74. Lifecycle
  75. };