diff --git a/src/main.js b/src/main.js index 1ba8546f..15a765e2 100644 --- a/src/main.js +++ b/src/main.js @@ -219,6 +219,35 @@ function clearAppCache() { } } +function getValidWindowPosition(state) { + // Screen cannot be required before app is ready + const {screen} = require('electron'); + + // Check if the previous position is out of the viewable area + // (e.g. because the screen has been plugged off) + const displays = screen.getAllDisplays(); + let minX = 0; + let maxX = 0; + let minY = 0; + let maxY = 0; + for (let i = 0; i < displays.length; i++) { + const display = displays[i]; + maxX = Math.max(maxX, display.bounds.x + display.bounds.width); + maxY = Math.max(maxY, display.bounds.y + display.bounds.height); + minX = Math.min(minX, display.bounds.x); + minY = Math.min(minY, display.bounds.y); + } + + if (state.x > maxX || state.y > maxY || state.x < minX || state.y < minY) { + Reflect.deleteProperty(state, 'x'); + Reflect.deleteProperty(state, 'y'); + Reflect.deleteProperty(state, 'width'); + Reflect.deleteProperty(state, 'height'); + } + + return state; +} + // Quit when all windows are closed. app.on('window-all-closed', () => { // On OS X it is common for applications and their menu bar @@ -413,7 +442,7 @@ app.on('ready', () => { var boundsInfoPath = path.resolve(app.getPath('userData'), 'bounds-info.json'); var windowOptions; try { - windowOptions = JSON.parse(fs.readFileSync(boundsInfoPath, 'utf-8')); + windowOptions = getValidWindowPosition(JSON.parse(fs.readFileSync(boundsInfoPath, 'utf-8'))); } catch (e) { // follow Electron's defaults windowOptions = {};