main.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. const {app, BrowserWindow, Menu, shell} = require('electron')
  2. const path = require('path')
  3. const eggLauncher = require('./electron/lanucher')
  4. const setup = require('./electron/setup')
  5. const electronConfig = require('./electron/config')
  6. const storage = require('./electron/storage')
  7. const autoUpdater = require('./electron/autoUpdater')
  8. // main window
  9. global.MAIN_WINDOW = null
  10. // Initialize
  11. setup()
  12. // return
  13. // argv
  14. const eggConfig = electronConfig.get('egg')
  15. for (let i = 0; i < process.argv.length; i++) {
  16. const tmpArgv = process.argv[i]
  17. if (tmpArgv.indexOf('--env=') !== -1) {
  18. eggConfig.env = tmpArgv.substr(6)
  19. }
  20. }
  21. if (process.mas) app.setName('electron-egg')
  22. // Open url with the default browser
  23. app.on('web-contents-created', (e, webContents) => {
  24. webContents.on('new-window', (event, url) => {
  25. event.preventDefault()
  26. shell.openExternal(url)
  27. });
  28. });
  29. async function initialize () {
  30. app.whenReady().then(() => {
  31. createWindow()
  32. app.on('activate', function () {
  33. if (BrowserWindow.getAllWindows().length === 0) {
  34. createWindow()
  35. }
  36. })
  37. })
  38. app.on('window-all-closed', function () {
  39. if (process.platform !== 'darwin') {
  40. console.log('window-all-closed quit')
  41. app.quit()
  42. }
  43. })
  44. }
  45. async function createWindow () {
  46. MAIN_WINDOW = new BrowserWindow(electronConfig.get('windowsOption'))
  47. // if (process.platform === 'linux') {
  48. // windowOptions.icon = path.join(__dirname, '/assets/app-icon/png/512.png')
  49. // }
  50. if (eggConfig.env === 'prod') {
  51. // hidden menu
  52. Menu.setApplicationMenu(null)
  53. // dynamic port
  54. await storage.setDynamicPort()
  55. eggConfig.port = electronConfig.get('egg').port
  56. }
  57. // loding page
  58. MAIN_WINDOW.loadURL(path.join('file://', __dirname, '/app/public/loading.html'))
  59. // egg server
  60. setTimeout(function(){
  61. startServer(eggConfig)
  62. }, 100)
  63. // check update
  64. const updateConfig = electronConfig.get('autoUpdate')
  65. if (updateConfig.enable) {
  66. autoUpdater.checkUpdate()
  67. }
  68. return MAIN_WINDOW
  69. }
  70. async function startServer (options) {
  71. let startRes = null
  72. ELog.info('[main] [startServer] options', options)
  73. startRes = await eggLauncher.start(options).then((res) => res, (err) => err)
  74. ELog.info('[main] [startServer] startRes:', startRes)
  75. if (startRes === 'success') {
  76. let url = 'http://localhost:' + options.port
  77. MAIN_WINDOW.loadURL(url)
  78. return true
  79. }
  80. app.relaunch()
  81. }
  82. initialize()