keeweb/desktop/app.js

644 lines
21 KiB
JavaScript
Raw Normal View History

2017-01-31 07:50:28 +01:00
const electron = require('electron');
const path = require('path');
const fs = require('fs');
2015-10-21 22:32:02 +02:00
2020-03-29 10:59:40 +02:00
let perfTimestamps = global.perfTimestamps;
perfTimestamps.push({ name: 'loading app requires', ts: process.hrtime() });
const app = electron.app;
2017-01-31 07:50:28 +01:00
let mainWindow = null;
let appIcon = null;
let ready = false;
let appReady = false;
let restartPending = false;
let mainWindowPosition = {};
let updateMainWindowPositionTimeout = null;
2019-01-06 14:45:50 +01:00
const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
app.quit();
}
perfTimestamps?.push({ name: 'single instance lock', ts: process.hrtime() });
2020-03-29 10:59:40 +02:00
2019-01-06 14:45:50 +01:00
let openFile = process.argv.filter(arg => /\.kdbx$/i.test(arg))[0];
const userDataDir =
process.env.KEEWEB_PORTABLE_EXECUTABLE_DIR ||
app.getPath('userData').replace(/[\\/]temp[\\/]\d+\.\d+[\\/]?$/, '');
2017-06-05 13:33:12 +02:00
const windowPositionFileName = path.join(userDataDir, 'window-position.json');
const appSettingsFileName = path.join(userDataDir, 'app-settings.json');
const tempUserDataPath = path.join(userDataDir, 'temp');
const tempUserDataPathRand = Date.now().toString() + Math.random().toString();
2015-10-25 20:26:33 +01:00
const isDev = !__dirname.endsWith('.asar');
const htmlPath =
(isDev && process.env.KEEWEB_HTML_PATH) || 'file://' + path.join(__dirname, 'index.html');
2020-04-15 19:37:03 +02:00
const showDevToolsOnStart =
process.argv.some(arg => arg.startsWith('--devtools')) ||
process.env.KEEWEB_OPEN_DEVTOOLS === '1';
2015-10-21 22:32:02 +02:00
const startMinimized = process.argv.some(arg => arg.startsWith('--minimized'));
2019-09-28 13:43:30 +02:00
const themeBgColors = {
db: '#342f2e',
fb: '#282c34',
wh: '#fafafa',
te: '#222',
hc: '#fafafa',
sd: '#002b36',
sl: '#fdf6e3',
macdark: '#1f1f20'
};
const defaultBgColor = '#282C34';
perfTimestamps?.push({ name: 'defining args', ts: process.hrtime() });
2017-12-02 20:38:13 +01:00
2020-05-10 09:49:09 +02:00
setDevAppIcon();
setEnv();
2019-01-06 23:33:09 +01:00
restorePreferences();
2017-06-05 13:33:12 +02:00
const appSettings = readAppSettings() || {};
2016-07-17 13:30:38 +02:00
app.on('window-all-closed', () => {
2016-07-16 18:39:52 +02:00
if (restartPending) {
app.relaunch();
app.exit(0);
2016-07-16 18:39:52 +02:00
} else {
2016-04-16 22:34:16 +02:00
if (process.platform !== 'darwin') {
2016-07-16 18:39:52 +02:00
app.quit();
2016-04-16 22:34:16 +02:00
}
2016-07-16 18:39:52 +02:00
}
});
2016-07-17 13:30:38 +02:00
app.on('ready', () => {
perfTimestamps?.push({ name: 'app on ready', ts: process.hrtime() });
appReady = true;
setAppOptions();
2019-09-07 19:16:09 +02:00
setSystemAppearance();
createMainWindow();
setGlobalShortcuts(appSettings);
subscribePowerEvents();
deleteOldTempFiles();
hookRequestHeaders();
2016-07-16 18:39:52 +02:00
});
2016-07-17 13:30:38 +02:00
app.on('open-file', (e, path) => {
2016-07-16 18:39:52 +02:00
e.preventDefault();
openFile = path;
notifyOpenFile();
});
2016-07-17 13:30:38 +02:00
app.on('activate', () => {
2016-07-16 18:39:52 +02:00
if (process.platform === 'darwin') {
2016-12-26 10:51:59 +01:00
if (appReady && !mainWindow) {
2016-07-16 18:39:52 +02:00
createMainWindow();
}
}
});
2016-07-17 13:30:38 +02:00
app.on('will-quit', () => {
2016-07-16 18:39:52 +02:00
electron.globalShortcut.unregisterAll();
});
app.on('second-instance', () => {
if (mainWindow) {
restoreMainWindow();
}
});
2020-04-17 21:50:53 +02:00
app.on('web-contents-created', (event, contents) => {
contents.on('new-window', async (e, url) => {
e.preventDefault();
emitRemoteEvent('log', { message: `Prevented new window: ${url}` });
});
2020-04-17 21:54:34 +02:00
contents.on('will-navigate', (e, url) => {
if (!url.startsWith('https://beta.keeweb.info/') && !url.startsWith(htmlPath)) {
e.preventDefault();
emitRemoteEvent('log', { message: `Prevented navigation: ${url}` });
}
});
2020-04-17 21:50:53 +02:00
});
2019-08-16 23:05:39 +02:00
app.restartApp = function() {
2016-07-16 18:39:52 +02:00
restartPending = true;
mainWindow.close();
2016-07-17 13:30:38 +02:00
setTimeout(() => {
2016-07-16 18:39:52 +02:00
restartPending = false;
}, 1000);
};
2019-10-05 08:37:10 +02:00
app.minimizeApp = function(menuItemLabels) {
2017-12-04 22:33:40 +01:00
let imagePath;
tray-min-auto-type-select-fix The fix for alt-tab behavior when KeeWeb is minimized to the tray in 3dae878 left a problem when auto-type raises a selection list: the taskbar button shows, and after a selection is made KeeWeb minimizes to the taskbar but leaves a tray icon present. The same thing happens if auto-type is canceled by clicking either the minimize button or the close button at the top right of the selection window. From this state, various scenarios lead to having duplicate tray icons. This commit restores the behavior of 1.6.3 when auto-type raises a selection list while KeeWeb is minimized to the tray: the selection window shows, the tray icon stays, and no taskbar button shows. We used to minimize the window after selection regardless of its previous state; this worked because we hid the taskbar button and minimized the window when minimizing to the tray, but that's what caused the alt-tab problem. Since we now hide when minimizing to the tray, we have to know whether to minimize or hide after selection. The simplest way to do that is to keep the old behavior of leaving the tray icon present when auto-type raises a selection window while KeeWeb is minimized to the tray. Instead of calling minimize on the main window, launcher-electron.js now calls app.minimizeThenHideIfInTray which is defined in desktop/app.js. That routine minimizes KeeWeb (which returns focus to the previously active window) and then hides the main window if and only if a tray icon is present. Because we don't want a tray icon and a taskbar button present at the same time, app.minimizeApp is also changed to restore the call to mainWindow.setSkipTaskbar(true) in the non-Darwin path; thus, when auto-type raises a selection window, there won't be a taskbar button if KeeWeb was minimized to the tray. If auto-type is canceled by clicking the top right close button while a selection list is displayed and there is a tray icon, the KeeWeb window is hidden and the tray icon stays, just as one would expect. This is the most likely way someone using "Minimize app instead of close" would choose to dismiss the auto-type selection list. If auto-type is canceled when a selection list is displayed while there is a tray icon by clicking the top right minimize button, by using alt-tab, or by clicking outside the selection window, the KeeWeb window reverts to its normal display and shows in the alt-tab list, but the tray icon remains and no taskbar button is shown. This is not ideal; it could be addressed in another commit if it seems worth doing. This commit mitigates these scenarios by adding a check to app.minimizeApp to assure that we never create a second tray icon if one is already present. This can do no harm and might catch other "corner cases" that are difficult to foresee. The next time the tray icon is clicked or the app is minimized to the tray by clicking the top right close button normal behavior is fully restored. If I've made no mistakes, the only change to the Darwin path is that it, too, is subject to the check that a new tray icon is not created if one already exists. I'm guessing that's OK, but I have no way to test Darwin.
2018-09-05 05:29:45 +02:00
mainWindow.hide();
2017-12-04 22:33:40 +01:00
if (process.platform === 'darwin') {
app.dock.hide();
imagePath = 'mac-menubar-icon.png';
} else {
imagePath = 'icon.png';
2016-07-16 18:39:52 +02:00
}
tray-min-auto-type-select-fix The fix for alt-tab behavior when KeeWeb is minimized to the tray in 3dae878 left a problem when auto-type raises a selection list: the taskbar button shows, and after a selection is made KeeWeb minimizes to the taskbar but leaves a tray icon present. The same thing happens if auto-type is canceled by clicking either the minimize button or the close button at the top right of the selection window. From this state, various scenarios lead to having duplicate tray icons. This commit restores the behavior of 1.6.3 when auto-type raises a selection list while KeeWeb is minimized to the tray: the selection window shows, the tray icon stays, and no taskbar button shows. We used to minimize the window after selection regardless of its previous state; this worked because we hid the taskbar button and minimized the window when minimizing to the tray, but that's what caused the alt-tab problem. Since we now hide when minimizing to the tray, we have to know whether to minimize or hide after selection. The simplest way to do that is to keep the old behavior of leaving the tray icon present when auto-type raises a selection window while KeeWeb is minimized to the tray. Instead of calling minimize on the main window, launcher-electron.js now calls app.minimizeThenHideIfInTray which is defined in desktop/app.js. That routine minimizes KeeWeb (which returns focus to the previously active window) and then hides the main window if and only if a tray icon is present. Because we don't want a tray icon and a taskbar button present at the same time, app.minimizeApp is also changed to restore the call to mainWindow.setSkipTaskbar(true) in the non-Darwin path; thus, when auto-type raises a selection window, there won't be a taskbar button if KeeWeb was minimized to the tray. If auto-type is canceled by clicking the top right close button while a selection list is displayed and there is a tray icon, the KeeWeb window is hidden and the tray icon stays, just as one would expect. This is the most likely way someone using "Minimize app instead of close" would choose to dismiss the auto-type selection list. If auto-type is canceled when a selection list is displayed while there is a tray icon by clicking the top right minimize button, by using alt-tab, or by clicking outside the selection window, the KeeWeb window reverts to its normal display and shows in the alt-tab list, but the tray icon remains and no taskbar button is shown. This is not ideal; it could be addressed in another commit if it seems worth doing. This commit mitigates these scenarios by adding a check to app.minimizeApp to assure that we never create a second tray icon if one is already present. This can do no harm and might catch other "corner cases" that are difficult to foresee. The next time the tray icon is clicked or the app is minimized to the tray by clicking the top right close button normal behavior is fully restored. If I've made no mistakes, the only change to the Darwin path is that it, too, is subject to the check that a new tray icon is not created if one already exists. I'm guessing that's OK, but I have no way to test Darwin.
2018-09-05 05:29:45 +02:00
mainWindow.setSkipTaskbar(true);
if (!appIcon) {
const image = electron.nativeImage.createFromPath(path.join(__dirname, imagePath));
appIcon = new electron.Tray(image);
appIcon.on('click', restoreMainWindow);
const contextMenu = electron.Menu.buildFromTemplate([
2019-10-05 08:37:10 +02:00
{ label: menuItemLabels.restore, click: restoreMainWindow },
{ label: menuItemLabels.quit, click: closeMainWindow }
tray-min-auto-type-select-fix The fix for alt-tab behavior when KeeWeb is minimized to the tray in 3dae878 left a problem when auto-type raises a selection list: the taskbar button shows, and after a selection is made KeeWeb minimizes to the taskbar but leaves a tray icon present. The same thing happens if auto-type is canceled by clicking either the minimize button or the close button at the top right of the selection window. From this state, various scenarios lead to having duplicate tray icons. This commit restores the behavior of 1.6.3 when auto-type raises a selection list while KeeWeb is minimized to the tray: the selection window shows, the tray icon stays, and no taskbar button shows. We used to minimize the window after selection regardless of its previous state; this worked because we hid the taskbar button and minimized the window when minimizing to the tray, but that's what caused the alt-tab problem. Since we now hide when minimizing to the tray, we have to know whether to minimize or hide after selection. The simplest way to do that is to keep the old behavior of leaving the tray icon present when auto-type raises a selection window while KeeWeb is minimized to the tray. Instead of calling minimize on the main window, launcher-electron.js now calls app.minimizeThenHideIfInTray which is defined in desktop/app.js. That routine minimizes KeeWeb (which returns focus to the previously active window) and then hides the main window if and only if a tray icon is present. Because we don't want a tray icon and a taskbar button present at the same time, app.minimizeApp is also changed to restore the call to mainWindow.setSkipTaskbar(true) in the non-Darwin path; thus, when auto-type raises a selection window, there won't be a taskbar button if KeeWeb was minimized to the tray. If auto-type is canceled by clicking the top right close button while a selection list is displayed and there is a tray icon, the KeeWeb window is hidden and the tray icon stays, just as one would expect. This is the most likely way someone using "Minimize app instead of close" would choose to dismiss the auto-type selection list. If auto-type is canceled when a selection list is displayed while there is a tray icon by clicking the top right minimize button, by using alt-tab, or by clicking outside the selection window, the KeeWeb window reverts to its normal display and shows in the alt-tab list, but the tray icon remains and no taskbar button is shown. This is not ideal; it could be addressed in another commit if it seems worth doing. This commit mitigates these scenarios by adding a check to app.minimizeApp to assure that we never create a second tray icon if one is already present. This can do no harm and might catch other "corner cases" that are difficult to foresee. The next time the tray icon is clicked or the app is minimized to the tray by clicking the top right close button normal behavior is fully restored. If I've made no mistakes, the only change to the Darwin path is that it, too, is subject to the check that a new tray icon is not created if one already exists. I'm guessing that's OK, but I have no way to test Darwin.
2018-09-05 05:29:45 +02:00
]);
appIcon.setContextMenu(contextMenu);
appIcon.setToolTip('KeeWeb');
}
};
2019-08-16 23:05:39 +02:00
app.minimizeThenHideIfInTray = function() {
tray-min-auto-type-select-fix The fix for alt-tab behavior when KeeWeb is minimized to the tray in 3dae878 left a problem when auto-type raises a selection list: the taskbar button shows, and after a selection is made KeeWeb minimizes to the taskbar but leaves a tray icon present. The same thing happens if auto-type is canceled by clicking either the minimize button or the close button at the top right of the selection window. From this state, various scenarios lead to having duplicate tray icons. This commit restores the behavior of 1.6.3 when auto-type raises a selection list while KeeWeb is minimized to the tray: the selection window shows, the tray icon stays, and no taskbar button shows. We used to minimize the window after selection regardless of its previous state; this worked because we hid the taskbar button and minimized the window when minimizing to the tray, but that's what caused the alt-tab problem. Since we now hide when minimizing to the tray, we have to know whether to minimize or hide after selection. The simplest way to do that is to keep the old behavior of leaving the tray icon present when auto-type raises a selection window while KeeWeb is minimized to the tray. Instead of calling minimize on the main window, launcher-electron.js now calls app.minimizeThenHideIfInTray which is defined in desktop/app.js. That routine minimizes KeeWeb (which returns focus to the previously active window) and then hides the main window if and only if a tray icon is present. Because we don't want a tray icon and a taskbar button present at the same time, app.minimizeApp is also changed to restore the call to mainWindow.setSkipTaskbar(true) in the non-Darwin path; thus, when auto-type raises a selection window, there won't be a taskbar button if KeeWeb was minimized to the tray. If auto-type is canceled by clicking the top right close button while a selection list is displayed and there is a tray icon, the KeeWeb window is hidden and the tray icon stays, just as one would expect. This is the most likely way someone using "Minimize app instead of close" would choose to dismiss the auto-type selection list. If auto-type is canceled when a selection list is displayed while there is a tray icon by clicking the top right minimize button, by using alt-tab, or by clicking outside the selection window, the KeeWeb window reverts to its normal display and shows in the alt-tab list, but the tray icon remains and no taskbar button is shown. This is not ideal; it could be addressed in another commit if it seems worth doing. This commit mitigates these scenarios by adding a check to app.minimizeApp to assure that we never create a second tray icon if one is already present. This can do no harm and might catch other "corner cases" that are difficult to foresee. The next time the tray icon is clicked or the app is minimized to the tray by clicking the top right close button normal behavior is fully restored. If I've made no mistakes, the only change to the Darwin path is that it, too, is subject to the check that a new tray icon is not created if one already exists. I'm guessing that's OK, but I have no way to test Darwin.
2018-09-05 05:29:45 +02:00
// This function is called when auto-type has displayed a selection list and a selection was made.
// To ensure focus returns to the previous window we must minimize first even if we're going to hide.
mainWindow.minimize();
if (appIcon) mainWindow.hide();
2016-07-16 18:39:52 +02:00
};
2019-08-16 23:05:39 +02:00
app.getMainWindow = function() {
2016-07-16 18:39:52 +02:00
return mainWindow;
};
app.setGlobalShortcuts = setGlobalShortcuts;
2015-10-24 21:06:44 +02:00
2016-04-10 09:37:55 +02:00
function setAppOptions() {
app.commandLine.appendSwitch('disable-background-timer-throttling');
perfTimestamps?.push({ name: 'setting app options', ts: process.hrtime() });
2016-04-10 09:37:55 +02:00
}
function readAppSettings() {
2017-03-28 18:19:39 +02:00
try {
return JSON.parse(fs.readFileSync(appSettingsFileName, 'utf8'));
2017-03-28 18:19:39 +02:00
} catch (e) {
return null;
2020-03-29 10:59:40 +02:00
} finally {
perfTimestamps?.push({ name: 'reading app settings', ts: process.hrtime() });
2017-03-28 18:19:39 +02:00
}
}
2019-09-07 19:16:09 +02:00
function setSystemAppearance() {
if (process.platform === 'darwin') {
2019-10-26 22:58:48 +02:00
if (electron.nativeTheme.shouldUseDarkColors) {
electron.systemPreferences.appLevelAppearance = 'dark';
2019-09-07 19:16:09 +02:00
}
}
perfTimestamps?.push({ name: 'setting system appearance', ts: process.hrtime() });
2019-09-07 19:16:09 +02:00
}
function createMainWindow() {
const windowOptions = {
show: false,
2019-08-16 23:05:39 +02:00
width: 1000,
height: 700,
minWidth: 700,
minHeight: 400,
titleBarStyle: appSettings.titlebarStyle,
2019-09-28 13:43:30 +02:00
backgroundColor: themeBgColors[appSettings.theme] || defaultBgColor,
2016-07-24 22:58:21 +02:00
webPreferences: {
2019-08-17 15:20:00 +02:00
backgroundThrottling: false,
nodeIntegration: true,
nodeIntegrationInWorker: true
2016-07-24 22:58:21 +02:00
}
};
if (process.platform !== 'win32') {
windowOptions.icon = path.join(__dirname, 'icon.png');
}
mainWindow = new electron.BrowserWindow(windowOptions);
perfTimestamps?.push({ name: 'creating main window', ts: process.hrtime() });
2020-03-29 10:59:40 +02:00
setMenu();
perfTimestamps?.push({ name: 'setting menu', ts: process.hrtime() });
2020-03-29 10:59:40 +02:00
2016-08-13 16:28:06 +02:00
mainWindow.loadURL(htmlPath);
2017-12-03 01:04:16 +01:00
if (showDevToolsOnStart) {
2019-01-07 20:43:14 +01:00
mainWindow.openDevTools({ mode: 'bottom' });
2017-12-03 01:04:16 +01:00
}
2017-12-03 09:02:27 +01:00
mainWindow.once('ready-to-show', () => {
perfTimestamps?.push({ name: 'main window ready', ts: process.hrtime() });
if (startMinimized) {
emitRemoteEvent('launcher-started-minimized');
} else {
mainWindow.show();
}
2017-12-03 09:03:56 +01:00
ready = true;
notifyOpenFile();
perfTimestamps?.push({ name: 'main window shown', ts: process.hrtime() });
2020-03-29 10:59:40 +02:00
reportStartProfile();
});
mainWindow.webContents.on('context-menu', onContextMenu);
mainWindow.on('resize', delaySaveMainWindowPosition);
mainWindow.on('move', delaySaveMainWindowPosition);
mainWindow.on('restore', coerceMainWindowPositionToConnectedDisplay);
mainWindow.on('close', updateMainWindowPositionIfPending);
2019-02-09 12:11:32 +01:00
mainWindow.on('focus', mainWindowFocus);
2016-07-24 23:10:03 +02:00
mainWindow.on('blur', mainWindowBlur);
2016-07-17 13:30:38 +02:00
mainWindow.on('closed', () => {
mainWindow = null;
saveMainWindowPosition();
});
2016-07-17 13:30:38 +02:00
mainWindow.on('minimize', () => {
2019-09-20 20:31:19 +02:00
emitRemoteEvent('launcher-minimize');
});
mainWindow.on('leave-full-screen', () => {
2019-09-20 20:31:19 +02:00
emitRemoteEvent('leave-full-screen');
});
mainWindow.on('enter-full-screen', () => {
2019-09-20 20:31:19 +02:00
emitRemoteEvent('enter-full-screen');
});
2017-06-02 20:04:57 +02:00
mainWindow.on('session-end', () => {
2019-09-20 20:31:19 +02:00
emitRemoteEvent('os-lock');
2017-06-02 20:04:57 +02:00
});
perfTimestamps?.push({ name: 'configuring main window', ts: process.hrtime() });
2020-03-29 10:59:40 +02:00
restoreMainWindowPosition();
perfTimestamps?.push({ name: 'restoring main window position', ts: process.hrtime() });
}
function restoreMainWindow() {
2017-12-04 22:33:40 +01:00
// if (process.platform === 'darwin') {
// app.dock.show();
// mainWindow.show();
// }
if (mainWindow.isMinimized()) {
mainWindow.restore();
}
mainWindow.setSkipTaskbar(false);
mainWindow.show();
coerceMainWindowPositionToConnectedDisplay();
2017-06-05 14:15:22 +02:00
setTimeout(destroyAppIcon, 0);
}
function closeMainWindow() {
2019-09-20 20:31:19 +02:00
emitRemoteEvent('launcher-exit-request');
2017-06-05 17:14:41 +02:00
setTimeout(destroyAppIcon, 0);
}
function destroyAppIcon() {
if (appIcon) {
appIcon.destroy();
appIcon = null;
}
}
function delaySaveMainWindowPosition() {
if (updateMainWindowPositionTimeout) {
clearTimeout(updateMainWindowPositionTimeout);
}
updateMainWindowPositionTimeout = setTimeout(updateMainWindowPosition, 500);
}
function updateMainWindowPositionIfPending() {
if (updateMainWindowPositionTimeout) {
clearTimeout(updateMainWindowPositionTimeout);
updateMainWindowPosition();
}
}
function updateMainWindowPosition() {
if (!mainWindow) {
return;
}
updateMainWindowPositionTimeout = null;
2017-01-31 07:50:28 +01:00
const bounds = mainWindow.getBounds();
if (!mainWindow.isMaximized() && !mainWindow.isMinimized() && !mainWindow.isFullScreen()) {
mainWindowPosition.x = bounds.x;
mainWindowPosition.y = bounds.y;
mainWindowPosition.width = bounds.width;
mainWindowPosition.height = bounds.height;
}
mainWindowPosition.maximized = mainWindow.isMaximized();
mainWindowPosition.fullScreen = mainWindow.isFullScreen();
mainWindowPosition.changed = true;
}
function saveMainWindowPosition() {
if (!mainWindowPosition.changed) {
return;
}
delete mainWindowPosition.changed;
try {
fs.writeFileSync(windowPositionFileName, JSON.stringify(mainWindowPosition), 'utf8');
} catch (e) {}
}
function restoreMainWindowPosition() {
2016-07-17 13:30:38 +02:00
fs.readFile(windowPositionFileName, 'utf8', (e, data) => {
if (data) {
mainWindowPosition = JSON.parse(data);
2016-02-14 14:24:49 +01:00
if (mainWindow && mainWindowPosition) {
if (mainWindowPosition.width && mainWindowPosition.height) {
mainWindow.setBounds(mainWindowPosition);
coerceMainWindowPositionToConnectedDisplay();
}
2019-08-16 23:05:39 +02:00
if (mainWindowPosition.maximized) {
mainWindow.maximize();
}
if (mainWindowPosition.fullScreen) {
mainWindow.setFullScreen(true);
}
}
}
});
}
2016-07-24 23:10:03 +02:00
function mainWindowBlur() {
2019-09-20 20:31:19 +02:00
emitRemoteEvent('main-window-blur');
2016-07-24 23:10:03 +02:00
}
2019-02-09 12:11:32 +01:00
function mainWindowFocus() {
2019-09-20 20:31:19 +02:00
emitRemoteEvent('main-window-focus');
2019-02-09 12:11:32 +01:00
}
2019-09-20 20:31:19 +02:00
function emitRemoteEvent(e, arg) {
if (mainWindow && mainWindow.webContents) {
app.emit('remote-app-event', {
name: e,
data: arg
});
}
}
2015-11-02 18:35:56 +01:00
function setMenu() {
if (process.platform === 'darwin') {
2019-10-26 22:58:48 +02:00
const name = require('electron').app.name;
2017-01-31 07:50:28 +01:00
const template = [
2015-11-02 18:35:56 +01:00
{
label: name,
submenu: [
{ role: 'about' },
2015-11-02 18:35:56 +01:00
{ type: 'separator' },
{ role: 'services', submenu: [] },
2015-11-02 18:35:56 +01:00
{ type: 'separator' },
{ accelerator: 'Command+H', role: 'hide' },
{ accelerator: 'Command+Shift+H', role: 'hideothers' },
{ role: 'unhide' },
2015-11-02 18:35:56 +01:00
{ type: 'separator' },
{ role: 'quit', accelerator: 'Command+Q' }
2015-11-02 18:35:56 +01:00
]
},
{
label: 'Edit',
submenu: [
{ accelerator: 'CmdOrCtrl+Z', role: 'undo' },
{ accelerator: 'Shift+CmdOrCtrl+Z', role: 'redo' },
2015-11-02 18:35:56 +01:00
{ type: 'separator' },
{ accelerator: 'CmdOrCtrl+X', role: 'cut' },
{ accelerator: 'CmdOrCtrl+C', role: 'copy' },
{ accelerator: 'CmdOrCtrl+V', role: 'paste' },
{ accelerator: 'CmdOrCtrl+A', role: 'selectall' }
2015-11-02 18:35:56 +01:00
]
2017-01-29 11:29:21 +01:00
},
{
label: 'Window',
2019-08-18 08:05:38 +02:00
submenu: [
{ accelerator: 'CmdOrCtrl+M', role: 'minimize' },
{ accelerator: 'Command+W', role: 'close' }
]
2015-11-02 18:35:56 +01:00
}
];
2017-01-31 07:50:28 +01:00
const menu = electron.Menu.buildFromTemplate(template);
2016-05-13 14:07:46 +02:00
electron.Menu.setApplicationMenu(menu);
} else {
mainWindow.setMenuBarVisibility(false);
mainWindow.setMenu(null);
electron.Menu.setApplicationMenu(null);
2015-11-02 18:35:56 +01:00
}
}
function onContextMenu(e, props) {
if (props.inputFieldType !== 'plainText' || !props.isEditable) {
return;
}
const Menu = electron.Menu;
const inputMenu = Menu.buildFromTemplate([
2019-08-16 23:05:39 +02:00
{ role: 'undo' },
{ role: 'redo' },
{ type: 'separator' },
{ role: 'cut' },
{ role: 'copy' },
{ role: 'paste' },
{ type: 'separator' },
{ role: 'selectall' }
]);
inputMenu.popup(mainWindow);
}
2015-10-24 21:06:44 +02:00
function notifyOpenFile() {
if (ready && openFile && mainWindow) {
2019-08-16 23:05:39 +02:00
const openKeyfile = process.argv
.filter(arg => arg.startsWith('--keyfile='))
.map(arg => arg.replace('--keyfile=', ''))[0];
const fileInfo = JSON.stringify({ data: openFile, key: openKeyfile });
2019-08-16 23:05:39 +02:00
mainWindow.webContents.executeJavaScript(
'if (window.launcherOpen) { window.launcherOpen(' +
fileInfo +
'); } ' +
' else { window.launcherOpenedFile=' +
fileInfo +
'; }'
);
2015-10-25 08:53:05 +01:00
openFile = null;
2015-10-24 21:06:44 +02:00
}
}
function setGlobalShortcuts(appSettings) {
const defaultShortcutModifiers = process.platform === 'darwin' ? 'Ctrl+Alt+' : 'Shift+Alt+';
const defaultShortcuts = {
AutoType: { shortcut: defaultShortcutModifiers + 'T', event: 'auto-type' },
CopyPassword: { shortcut: defaultShortcutModifiers + 'C', event: 'copy-password' },
CopyUser: { shortcut: defaultShortcutModifiers + 'B', event: 'copy-user' },
CopyUrl: { shortcut: defaultShortcutModifiers + 'U', event: 'copy-url' },
CopyOtp: { event: 'copy-otp' },
RestoreApp: { action: restoreMainWindow }
};
electron.globalShortcut.unregisterAll();
for (const [key, shortcutDef] of Object.entries(defaultShortcuts)) {
const fromSettings = appSettings[`globalShortcut${key}`];
const shortcut = fromSettings || shortcutDef.shortcut;
if (shortcut) {
try {
electron.globalShortcut.register(shortcut, () => {
if (shortcutDef.event) {
emitRemoteEvent(shortcutDef.event);
}
if (shortcutDef.action) {
shortcutDef.action();
}
});
} catch (e) {}
}
}
perfTimestamps?.push({ name: 'setting global shortcuts', ts: process.hrtime() });
}
2016-08-20 09:04:30 +02:00
function subscribePowerEvents() {
electron.powerMonitor.on('suspend', () => {
2019-09-20 20:31:19 +02:00
emitRemoteEvent('power-monitor-suspend');
2016-08-20 09:04:30 +02:00
});
electron.powerMonitor.on('resume', () => {
2019-09-20 20:31:19 +02:00
emitRemoteEvent('power-monitor-resume');
2016-08-20 09:04:30 +02:00
});
electron.powerMonitor.on('lock-screen', () => {
emitRemoteEvent('os-lock');
});
perfTimestamps?.push({ name: 'subscribing to power events', ts: process.hrtime() });
2016-08-20 09:04:30 +02:00
}
2017-06-05 13:33:12 +02:00
function setEnv() {
2020-03-29 10:59:40 +02:00
app.setPath('userData', path.join(tempUserDataPath, tempUserDataPathRand));
2019-08-18 08:05:38 +02:00
if (
process.platform === 'linux' &&
['Pantheon', 'Unity:Unity7'].indexOf(process.env.XDG_CURRENT_DESKTOP) !== -1
) {
// https://github.com/electron/electron/issues/9046
process.env.XDG_CURRENT_DESKTOP = 'Unity';
}
perfTimestamps?.push({ name: 'setting env', ts: process.hrtime() });
}
2019-01-06 23:33:09 +01:00
function restorePreferences() {
const profileConfigPath = path.join(userDataDir, 'profile.json');
const newProfile = { dir: tempUserDataPathRand };
let oldProfile;
try {
oldProfile = JSON.parse(fs.readFileSync(profileConfigPath, 'utf8'));
2019-08-16 23:05:39 +02:00
} catch (e) {}
2019-01-06 23:33:09 +01:00
fs.writeFileSync(profileConfigPath, JSON.stringify(newProfile));
if (oldProfile && oldProfile.dir && /^[\d.]+$/.test(oldProfile.dir)) {
const oldProfilePath = path.join(tempUserDataPath, oldProfile.dir);
const newProfilePath = path.join(tempUserDataPath, newProfile.dir);
if (fs.existsSync(path.join(oldProfilePath, 'Cookies'))) {
if (!fs.existsSync(newProfilePath)) {
fs.mkdirSync(newProfilePath);
}
const cookiesFileSrc = path.join(oldProfilePath, 'Cookies');
const cookiesFileDest = path.join(newProfilePath, 'Cookies');
try {
fs.renameSync(cookiesFileSrc, cookiesFileDest);
} catch (e) {
try {
fs.copyFileSync(cookiesFileSrc, cookiesFileDest);
2019-08-16 23:05:39 +02:00
} catch (e) {}
}
2019-01-06 23:33:09 +01:00
}
}
2020-03-29 10:59:40 +02:00
perfTimestamps?.push({ name: 'restoring preferences', ts: process.hrtime() });
2019-01-06 23:33:09 +01:00
}
2017-06-05 13:33:12 +02:00
function deleteOldTempFiles() {
2017-12-02 20:38:13 +01:00
if (app.oldTempFilesDeleted) {
return;
}
2017-06-05 13:33:12 +02:00
setTimeout(() => {
for (const dir of fs.readdirSync(tempUserDataPath)) {
if (dir !== tempUserDataPathRand) {
try {
deleteRecursive(path.join(tempUserDataPath, dir));
} catch (e) {}
}
}
2017-12-02 20:38:13 +01:00
app.oldTempFilesDeleted = true; // this is added to prevent file deletion on restart
2017-06-05 13:33:12 +02:00
}, 1000);
perfTimestamps?.push({ name: 'deleting old temp files', ts: process.hrtime() });
2017-06-05 13:33:12 +02:00
}
function deleteRecursive(dir) {
for (const file of fs.readdirSync(dir)) {
const filePath = path.join(dir, file);
if (fs.lstatSync(filePath).isDirectory()) {
deleteRecursive(filePath);
} else {
fs.unlinkSync(filePath);
}
}
fs.rmdirSync(dir);
}
2020-05-10 09:49:09 +02:00
function setDevAppIcon() {
if (isDev && htmlPath) {
const icon = electron.nativeImage.createFromPath(
path.join(__dirname, '../graphics/512x512.png')
);
app.dock.setIcon(icon);
}
}
// When sending a PUT XMLHttpRequest Chromium includes the header "Origin: file://".
// This confuses some WebDAV clients, notably OwnCloud.
// The header is invalid, so removing it everywhere it occurs should do no harm.
function hookRequestHeaders() {
electron.session.defaultSession.webRequest.onBeforeSendHeaders((details, callback) => {
2019-01-07 20:38:58 +01:00
if (!details.url.startsWith('ws:')) {
2019-09-08 09:39:30 +02:00
delete details.requestHeaders.Origin;
2019-01-07 20:38:58 +01:00
}
2020-03-17 07:52:34 +01:00
callback({ requestHeaders: details.requestHeaders });
});
perfTimestamps?.push({ name: 'setting request handlers', ts: process.hrtime() });
}
// If a display is disconnected while KeeWeb is minimized, Electron does not
// ensure that the restored window appears on a display that is still connected.
// This checks to be sure the title bar is somewhere the user can grab it,
// without making it impossible to minimize and restore a window keeping it
// partially off-screen or straddling two displays if the user desires that.
function coerceMainWindowPositionToConnectedDisplay() {
2019-01-07 22:04:39 +01:00
const eScreen = electron.screen;
const displays = eScreen.getAllDisplays();
if (!displays || !displays.length) return;
const windowBounds = mainWindow.getBounds();
const contentBounds = mainWindow.getContentBounds();
const tbLeft = windowBounds.x;
const tbRight = windowBounds.x + windowBounds.width;
const tbTop = windowBounds.y;
const tbBottom = contentBounds.y;
// 160px width and 2/3s the title bar height should be enough that the user can grab it
for (let i = 0; i < displays.length; ++i) {
const workArea = displays[i].workArea;
2019-08-18 08:05:38 +02:00
const overlapWidth =
Math.min(tbRight, workArea.x + workArea.width) - Math.max(tbLeft, workArea.x);
const overlapHeight =
Math.min(tbBottom, workArea.y + workArea.height) - Math.max(tbTop, workArea.y);
if (overlapWidth >= 160 && 3 * overlapHeight >= 2 * (tbBottom - tbTop)) return;
}
// If we get here, no display contains a big enough strip of the title bar
// that we can be confident the user can drag it into visibility. Rather than
// attempt to guess what the user wants, just center it on the primary display.
// Try to keep the previous height and width, but clamp each to 90% of the workarea.
const workArea = eScreen.getPrimaryDisplay().workArea;
const newWidth = Math.min(windowBounds.width, Math.floor(0.9 * workArea.width));
const newHeight = Math.min(windowBounds.height, Math.floor(0.9 * workArea.height));
mainWindow.setBounds({
'x': workArea.x + Math.floor((workArea.width - newWidth) / 2),
'y': workArea.y + Math.floor((workArea.height - newHeight) / 2),
'width': newWidth,
'height': newHeight
});
updateMainWindowPosition();
}
2020-03-29 10:59:40 +02:00
function reportStartProfile() {
if (!perfTimestamps) {
return;
}
2020-03-29 10:59:40 +02:00
const processCreationTime = process.getCreationTime();
const totalTime = Math.round(Date.now() - processCreationTime);
let lastTs = 0;
const timings = perfTimestamps
.map(milestone => {
const ts = milestone.ts;
const elapsed = lastTs
? Math.round((ts[0] - lastTs[0]) * 1e3 + (ts[1] - lastTs[1]) / 1e6)
: 0;
lastTs = ts;
return {
name: milestone.name,
elapsed
};
})
.slice(1);
perfTimestamps = global.perfTimestamps = undefined;
const startProfile = { totalTime, timings };
emitRemoteEvent('start-profile', startProfile);
}