This repository has been archived by the owner on Feb 18, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 49
/
window.js
83 lines (70 loc) · 2.35 KB
/
window.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// This helper remembers the size and position of your windows (and restores
// them in that place after app relaunch).
// Can be used for more than one window, just construct many
// instances of it and give each different name.
import { app, BrowserWindow, screen } from 'electron';
import jetpack from 'fs-jetpack';
export default function (name, options) {
const userDataDir = jetpack.cwd(app.getPath('userData'));
const stateStoreFile = 'window-state-' + name +'.json';
var defaultSize = {
width: options.width,
height: options.height
};
let state = {};
let win;
var restore = function () {
let restoredState = {};
try {
restoredState = userDataDir.read(stateStoreFile, 'json');
} catch (err) {
// For some reason json can't be read (might be corrupted).
// No worries, we have defaults.
}
return Object.assign({}, defaultSize, restoredState);
};
const getCurrentPosition = function () {
const [x, y] = win.getPosition();
const [width, height] = win.getSize();
return {
x,
y,
width,
height,
};
};
const windowWithinBounds = function (windowState, bounds) {
return windowState.x >= bounds.x &&
windowState.y >= bounds.y &&
windowState.x + windowState.width <= bounds.x + bounds.width &&
windowState.y + windowState.height <= bounds.y + bounds.height;
};
var resetToDefaults = function () {
const { bounds } = screen.getPrimaryDisplay();
return Object.assign({}, defaultSize, {
x: (bounds.width - defaultSize.width) / 2,
y: (bounds.height - defaultSize.height) / 2
});
};
const ensureVisibleOnSomeDisplay = function (windowState) {
const visible = screen.getAllDisplays().some(function (display) {
return windowWithinBounds(windowState, display.bounds);
});
if (!visible) {
// Window is partially or fully not visible now.
// Reset it to safe defaults.
return resetToDefaults(windowState);
}
return windowState;
};
const saveState = function () {
if (!win.isMinimized()) {
Object.assign(state, getCurrentPosition());
}
userDataDir.write(stateStoreFile, state, { atomic: true });
};
state = ensureVisibleOnSomeDisplay(restore());
win = new BrowserWindow(Object.assign({}, options, state));
win.on('close', saveState);
return win;
}