Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Electron Shutdown #392

Merged
merged 9 commits into from
Sep 26, 2023
142 changes: 59 additions & 83 deletions src/main/main.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import { app, BrowserWindow, dialog, shell } from 'electron';
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import { app, BrowserWindow, dialog, shell, globalShortcut } from 'electron';
import { is } from '@electron-toolkit/utils'

import paths from '../../paths.config.json'

import main from '@electron/remote/main';
main.initialize()

let showExitPrompt = true;
import path from 'path';
import { autoUpdater } from 'electron-updater';
import { ipcMain } from 'electron';
Expand All @@ -18,7 +17,6 @@ import fs from 'fs';
import axios from 'axios';

import './application-menu.js';
import './shortcuts.js';

import icon from '../renderer/assets/img/logo-guide-draft.png?asset'
import splashHTML from './splash-screen.html?asset'
Expand All @@ -44,7 +42,6 @@ const portRange = 100;

const isWindows = process.platform === 'win32'

let mainWindowReady = false
let readyQueue: Function[] = []

let globals: {
Expand All @@ -54,7 +51,6 @@ let globals: {
sent: boolean,
latestError: string
},
mainWindowReady: boolean
} = {

// mainWindow: undefined,
Expand All @@ -64,26 +60,14 @@ let globals: {
sent: false,
restart: false,
latestError: ''
},

// Reactive ready variable
get mainWindowReady() {
return mainWindowReady
},

set mainWindowReady(v) {
if (!globals.mainWindow) throw new Error('Main window cannot be ready. It does not exist...')
mainWindowReady = v
if (v) readyQueue.forEach(f => onWindowReady(f))
readyQueue = []
}
}

function send(this: BrowserWindow, ...args: any[]) {
return this.webContents.send(...args)
}

const onWindowReady = (f: (win: BrowserWindow) => any) => (globals.mainWindowReady) ? f(globals.mainWindow) : readyQueue.push(f)
const onWindowReady = (f: (win: BrowserWindow) => any) => (globals.mainWindow?.webContents) ? f(globals.mainWindow) : readyQueue.push(f)


// Pass all important log functions to the application
Expand Down Expand Up @@ -157,13 +141,14 @@ const createPyProc = async () => {

pyflaskProcess.stdout.on('data', (data: string) => {
const isRestarting = globals.python.restart
setTimeout(() => pythonIsOpen(isRestarting), 100); // Wait just a bit to give the server some time to come online
setTimeout(() => {
pythonIsOpen(isRestarting)
}, 100); // Wait just a bit to give the server some time to come online
console.log(`${data}`)
resolve(true)
});

pyflaskProcess.on('close', (code: number) => {
console.error(`exit code ${code}`)
pyflaskProcess.on('close', () => {
pythonIsClosed()
reject()
});
Expand Down Expand Up @@ -216,15 +201,12 @@ const killAllPreviousProcesses = async () => {
await Promise.allSettled(promisesArray);
};

let user_restart_confirmed = false;
let updatechecked = false;

let hasBeenOpened = false;

function initialize() {

if (globals.mainWindow) return // Do not re-initialize if the main window is already declared

makeSingleInstance();

function createWindow() {
Expand All @@ -239,35 +221,32 @@ function initialize() {
autoUpdater.checkForUpdatesAndNotify();
}
});

globals.mainWindow.once("close", async (e) => {

globals.mainWindowReady = false

if (!user_restart_confirmed) {
if (showExitPrompt) {
e.preventDefault(); // Prevents the window from closing
dialog
.showMessageBox(BrowserWindow.getFocusedWindow() as BrowserWindow, {
type: "question",
buttons: ["Yes", "No"],
title: "Confirm",
message: "Any running process will be stopped. Are you sure you want to quit?",
})
.then((responseObject) => {
let { response } = responseObject;
if (response === 0) app.quit();
else globals.mainWindowReady = true
});
}
} else {
app.quit();
}
});
}

function onAppReady () {

if (globals.mainWindow) return // Do not re-initialize if the main window is already declared

const windowOptions = {
minWidth: 1121,
minHeight: 735,
width: 1121,
height: 735,
center: true,
show: false,
icon,
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
contextIsolation: false,
sandbox: false,
// preload: path.join(__dirname, "preload.js"),
},
};

globals.mainWindow = new BrowserWindow(windowOptions);


// Only create one python process
if (!pyflaskProcess) {
const promise = createPyProc();
Expand All @@ -290,24 +269,6 @@ function initialize() {
})
}

const windowOptions = {
minWidth: 1121,
minHeight: 735,
width: 1121,
height: 735,
center: true,
show: false,
icon,
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
contextIsolation: false,
sandbox: false,
// preload: path.join(__dirname, "preload.js"),
},
};

globals.mainWindow = new BrowserWindow(windowOptions);
main.enable(globals.mainWindow.webContents);

// HMR for renderer base on electron-vite cli.
Expand Down Expand Up @@ -344,7 +305,9 @@ function initialize() {
autoUpdater.checkForUpdatesAndNotify();
updatechecked = true;

globals.mainWindowReady = true
// Clear ready queue
readyQueue.forEach(f => onWindowReady(f))
readyQueue = []

}, hasBeenOpened ? 100 : 1000);
});
Expand Down Expand Up @@ -383,7 +346,10 @@ function restoreWindow(){
function makeSingleInstance() {
if (process.mas) return;

if (!app.requestSingleInstanceLock()) app.quit();
if (!app.requestSingleInstanceLock()){
console.error('An instance of this application is already open...')
app.exit(); // Skip quit callbacks
}
else app.on("second-instance", () => restoreWindow());
}

Expand Down Expand Up @@ -420,25 +386,36 @@ function deleteFoldersWithoutPipelines() {
stubsToRemove.forEach(name => fs.rmSync(path.join(guidedStubFolderPath, name), { recursive: true }))
}

app.on("window-all-closed", () => {
if (process.platform != 'darwin') app.quit() // Exit the application not on Mac
})

app.on("before-quit", async (ev: Event) => {

ev.preventDefault()

console.log('AHH', globals.python.status)

const { response } = await dialog
.showMessageBox(BrowserWindow.getFocusedWindow() as BrowserWindow, {
type: "question",
buttons: ["Yes", "No"],
title: "Confirm",
message: "Any running process will be stopped. Are you sure you want to quit?",
})

if (response !== 0) return // Skip quitting

app.on('will-quit', async () => {
try {
globalShortcut.unregisterAll();
deleteFoldersWithoutPipelines()
await exitPyProc()
if (globals.mainWindow) {
globals.mainWindow.close();
if (!globals.mainWindow.closed) globals.mainWindow.destroy()
}
} catch (err) {
console.error(err);
} finally {
app.exit()
}
});

app.on("window-all-closed", async () => {
if (process.platform != 'darwin') app.quit();
});

// app.on("will-quit", () => app.quit());
})

app.on("open-file", onFileOpened)

Expand All @@ -464,7 +441,6 @@ autoUpdater.on("update-downloaded", () => {
});

ipcMain.on("restart_app", async () => {
user_restart_confirmed = true;
autoUpdater.quitAndInstall();
});

Expand Down
5 changes: 0 additions & 5 deletions src/main/shortcuts.js

This file was deleted.

2 changes: 1 addition & 1 deletion src/renderer/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ async function pythonServerClosed(message?: string) {
allowEscapeKey: false,
});

if (isElectron) app.quit();
if (isElectron) app.exit();
else location.reload()

Swal.close();
Expand Down
Loading