tidy electron files, they were starting to annoy me

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>
This commit is contained in:
Michael Telatynski 2017-05-22 19:21:52 +01:00
parent 73ec3e1f4d
commit 911c3bcf6e
4 changed files with 107 additions and 176 deletions

View File

@ -20,15 +20,14 @@ limitations under the License.
// Squirrel on windows starts the app with various flags // Squirrel on windows starts the app with various flags
// as hooks to tell us when we've been installed/uninstalled // as hooks to tell us when we've been installed/uninstalled
// etc. // etc.
const check_squirrel_hooks = require('./squirrelhooks'); const checkSquirrelHooks = require('./squirrelhooks');
if (check_squirrel_hooks()) return; if (checkSquirrelHooks()) return;
const electron = require('electron'); const electron = require('electron');
const url = require('url'); const url = require('url');
const tray = require('./tray'); const tray = require('./tray');
const vectorMenu = require('./vectormenu');
const VectorMenu = require('./vectormenu');
const windowStateKeeper = require('electron-window-state'); const windowStateKeeper = require('electron-window-state');
@ -59,13 +58,13 @@ function safeOpenURL(target) {
// so put fairly stringent limits on what can be opened // so put fairly stringent limits on what can be opened
// (for instance, open /bin/sh does indeed open a terminal // (for instance, open /bin/sh does indeed open a terminal
// with a shell, albeit with no arguments) // with a shell, albeit with no arguments)
const parsed_url = url.parse(target); const parsedUrl = url.parse(target);
if (PERMITTED_URL_SCHEMES.indexOf(parsed_url.protocol) > -1) { if (PERMITTED_URL_SCHEMES.indexOf(parsedUrl.protocol) > -1) {
// explicitly use the URL re-assembled by the url library, // explicitly use the URL re-assembled by the url library,
// so we know the url parser has understood all the parts // so we know the url parser has understood all the parts
// of the input string // of the input string
const new_target = url.format(parsed_url); const newTarget = url.format(parsedUrl);
electron.shell.openExternal(new_target); electron.shell.openExternal(newTarget);
} }
} }
@ -79,20 +78,19 @@ function onWindowOrNavigate(ev, target) {
} }
function onLinkContextMenu(ev, params) { function onLinkContextMenu(ev, params) {
const popup_menu = new electron.Menu(); const popupMenu = new electron.Menu();
popup_menu.append(new electron.MenuItem({
popupMenu.append(new electron.MenuItem({
label: params.linkURL, label: params.linkURL,
click() { click() { safeOpenURL(params.linkURL); },
safeOpenURL(params.linkURL);
},
})); }));
popup_menu.append(new electron.MenuItem({
popupMenu.append(new electron.MenuItem({
label: 'Copy Link Address', label: 'Copy Link Address',
click() { click() { electron.clipboard.writeText(params.linkURL); },
electron.clipboard.writeText(params.linkURL);
},
})); }));
popup_menu.popup();
popupMenu.popup();
ev.preventDefault(); ev.preventDefault();
} }
@ -107,13 +105,13 @@ function pollForUpdates() {
try { try {
electron.autoUpdater.checkForUpdates(); electron.autoUpdater.checkForUpdates();
} catch (e) { } catch (e) {
console.log("Couldn't check for update", e); console.log('Couldn\'t check for update', e);
} }
} }
function startAutoUpdate(update_base_url) { function startAutoUpdate(updateBaseUrl) {
if (update_base_url.slice(-1) !== '/') { if (updateBaseUrl.slice(-1) !== '/') {
update_base_url = update_base_url + '/'; updateBaseUrl = updateBaseUrl + '/';
} }
try { try {
// For reasons best known to Squirrel, the way it checks for updates // For reasons best known to Squirrel, the way it checks for updates
@ -121,7 +119,7 @@ function startAutoUpdate(update_base_url) {
// hits a URL that either gives it a 200 with some json or // hits a URL that either gives it a 200 with some json or
// 204 No Content. On windows it takes a base path and looks for // 204 No Content. On windows it takes a base path and looks for
// files under that path. // files under that path.
if (process.platform == 'darwin') { if (process.platform === 'darwin') {
// include the current version in the URL we hit. Electron doesn't add // include the current version in the URL we hit. Electron doesn't add
// it anywhere (apart from the User-Agent) so it's up to us. We could // it anywhere (apart from the User-Agent) so it's up to us. We could
// (and previously did) just use the User-Agent, but this doesn't // (and previously did) just use the User-Agent, but this doesn't
@ -129,16 +127,15 @@ function startAutoUpdate(update_base_url) {
// and also acts as a convenient cache-buster to ensure that when the // and also acts as a convenient cache-buster to ensure that when the
// app updates it always gets a fresh value to avoid update-looping. // app updates it always gets a fresh value to avoid update-looping.
electron.autoUpdater.setFeedURL( electron.autoUpdater.setFeedURL(
update_base_url + `${updateBaseUrl}macos/?localVersion=${encodeURIComponent(electron.app.getVersion())}`);
'macos/?localVersion=' + encodeURIComponent(electron.app.getVersion())
); } else if (process.platform === 'win32') {
} else if (process.platform == 'win32') { electron.autoUpdater.setFeedURL(updateBaseUrl + 'win32/' + process.arch + '/');
electron.autoUpdater.setFeedURL(update_base_url + 'win32/' + process.arch + '/');
} else { } else {
// Squirrel / electron only supports auto-update on these two platforms. // Squirrel / electron only supports auto-update on these two platforms.
// I'm not even going to try to guess which feed style they'd use if they // I'm not even going to try to guess which feed style they'd use if they
// implemented it on Linux, or if it would be different again. // implemented it on Linux, or if it would be different again.
console.log("Auto update not supported on this platform"); console.log('Auto update not supported on this platform');
} }
// We check for updates ourselves rather than using 'updater' because we need to // We check for updates ourselves rather than using 'updater' because we need to
// do it in the main process (and we don't really need to check every 10 minutes: // do it in the main process (and we don't really need to check every 10 minutes:
@ -151,7 +148,7 @@ function startAutoUpdate(update_base_url) {
setInterval(pollForUpdates, UPDATE_POLL_INTERVAL_MS); setInterval(pollForUpdates, UPDATE_POLL_INTERVAL_MS);
} catch (err) { } catch (err) {
// will fail if running in debug mode // will fail if running in debug mode
console.log("Couldn't enable update checking", err); console.log('Couldn\'t enable update checking', err);
} }
} }
@ -162,13 +159,13 @@ function startAutoUpdate(update_base_url) {
// Assuming we generally run from the console when developing, // Assuming we generally run from the console when developing,
// this is far preferable. // this is far preferable.
process.on('uncaughtException', function(error) { process.on('uncaughtException', function(error) {
console.log("Unhandled exception", error); console.log('Unhandled exception', error);
}); });
electron.ipcMain.on('install_update', installUpdate); electron.ipcMain.on('install_update', installUpdate);
let focusHandlerAttached = false; let focusHandlerAttached = false;
electron.ipcMain.on('setBadgeCount', function(ev, count) { electron.ipcMain.on('setBadgeCount', function(ev, count: number) {
electron.app.setBadgeCount(count); electron.app.setBadgeCount(count);
if (process.platform === 'win32' && mainWindow && !mainWindow.isFocused()) { if (process.platform === 'win32' && mainWindow && !mainWindow.isFocused()) {
if (count > 0) { if (count > 0) {
@ -198,30 +195,28 @@ const shouldQuit = electron.app.makeSingleInstance((commandLine, workingDirector
}); });
if (shouldQuit) { if (shouldQuit) {
console.log("Other instance detected: exiting"); console.log('Other instance detected: exiting');
electron.app.quit() electron.app.quit();
} }
electron.app.on('ready', () => { electron.app.on('ready', () => {
if (vectorConfig.update_base_url) { if (vectorConfig.update_base_url) {
console.log("Starting auto update with base URL: " + vectorConfig.update_base_url); console.log(`Starting auto update with base URL: ${vectorConfig.update_base_url}`);
startAutoUpdate(vectorConfig.update_base_url); startAutoUpdate(vectorConfig.update_base_url);
} else { } else {
console.log("No update_base_url is defined: auto update is disabled"); console.log('No update_base_url is defined: auto update is disabled');
} }
const icon_path = `${__dirname}/../img/riot.` + ( const iconPath = `${__dirname}/../img/riot.${process.platform === 'win32' ? 'ico' : 'png'}`;
process.platform == 'win32' ? 'ico' : 'png'
);
// Load the previous window state with fallback to defaults // Load the previous window state with fallback to defaults
let mainWindowState = windowStateKeeper({ const mainWindowState = windowStateKeeper({
defaultWidth: 1024, defaultWidth: 1024,
defaultHeight: 768, defaultHeight: 768,
}); });
mainWindow = new electron.BrowserWindow({ mainWindow = new electron.BrowserWindow({
icon: icon_path, icon: iconPath,
show: false, show: false,
autoHideMenuBar: true, autoHideMenuBar: true,
@ -231,12 +226,12 @@ electron.app.on('ready', () => {
height: mainWindowState.height, height: mainWindowState.height,
}); });
mainWindow.loadURL(`file://${__dirname}/../../webapp/index.html`); mainWindow.loadURL(`file://${__dirname}/../../webapp/index.html`);
electron.Menu.setApplicationMenu(VectorMenu); electron.Menu.setApplicationMenu(vectorMenu);
// Create trayIcon icon // Create trayIcon icon
tray.create(mainWindow, { tray.create(mainWindow, {
icon_path: icon_path, icon_path: iconPath,
brand: vectorConfig.brand || 'Riot' brand: vectorConfig.brand || 'Riot',
}); });
if (!process.argv.includes('--hidden')) { if (!process.argv.includes('--hidden')) {
@ -249,7 +244,7 @@ electron.app.on('ready', () => {
mainWindow = null; mainWindow = null;
}); });
mainWindow.on('close', (e) => { mainWindow.on('close', (e) => {
if (!appQuitting && (tray.hasTray() || process.platform == 'darwin')) { if (!appQuitting && (tray.hasTray() || process.platform === 'darwin')) {
// On Mac, closing the window just hides it // On Mac, closing the window just hides it
// (this is generally how single-window Mac apps // (this is generally how single-window Mac apps
// behave, eg. Mail.app) // behave, eg. Mail.app)

View File

@ -16,30 +16,30 @@ limitations under the License.
const path = require('path'); const path = require('path');
const spawn = require('child_process').spawn; const spawn = require('child_process').spawn;
const app = require('electron').app; const {app} = require('electron');
function run_update_exe(args, done) { function runUpdateExe(args, done) {
// Invokes Squirrel's Update.exe which will do things for us like create shortcuts // Invokes Squirrel's Update.exe which will do things for us like create shortcuts
// Note that there's an Update.exe in the app-x.x.x directory and one in the parent // Note that there's an Update.exe in the app-x.x.x directory and one in the parent
// directory: we need to run the one in the parent directory, because it discovers // directory: we need to run the one in the parent directory, because it discovers
// information about the app by inspecting the directory it's run from. // information about the app by inspecting the directory it's run from.
const updateExe = path.resolve(path.dirname(process.execPath), '..', 'Update.exe'); const updateExe = path.resolve(path.dirname(process.execPath), '..', 'Update.exe');
console.log('Spawning `%s` with args `%s`', updateExe, args); console.log(`Spawning '${updateExe}' with args '${args}'`);
spawn(updateExe, args, { spawn(updateExe, args, {
detached: true detached: true,
}).on('close', done); }).on('close', done);
}; }
function check_squirrel_hooks() { function checkSquirrelHooks() {
if (process.platform != 'win32') return false; if (process.platform !== 'win32') return false;
const cmd = process.argv[1]; const cmd = process.argv[1];
const target = path.basename(process.execPath); const target = path.basename(process.execPath);
if (cmd === '--squirrel-install' || cmd === '--squirrel-updated') { if (cmd === '--squirrel-install' || cmd === '--squirrel-updated') {
run_update_exe(['--createShortcut=' + target + ''], app.quit); runUpdateExe(['--createShortcut=' + target + ''], app.quit);
return true; return true;
} else if (cmd === '--squirrel-uninstall') { } else if (cmd === '--squirrel-uninstall') {
run_update_exe(['--removeShortcut=' + target + ''], app.quit); runUpdateExe(['--removeShortcut=' + target + ''], app.quit);
return true; return true;
} else if (cmd === '--squirrel-obsolete') { } else if (cmd === '--squirrel-obsolete') {
app.quit(); app.quit();
@ -48,4 +48,4 @@ function check_squirrel_hooks() {
return false; return false;
} }
module.exports = check_squirrel_hooks; module.exports = checkSquirrelHooks;

View File

@ -25,9 +25,7 @@ exports.hasTray = function hasTray() {
exports.create = function(win, config) { exports.create = function(win, config) {
// no trays on darwin // no trays on darwin
if (process.platform === 'darwin' || trayIcon) { if (process.platform === 'darwin' || trayIcon) return;
return;
}
const toggleWin = function() { const toggleWin = function() {
if (win.isVisible() && !win.isMinimized()) { if (win.isVisible() && !win.isMinimized()) {
@ -41,12 +39,10 @@ exports.create = function(win, config) {
const contextMenu = Menu.buildFromTemplate([ const contextMenu = Menu.buildFromTemplate([
{ {
label: 'Show/Hide ' + config.brand, label: `Show/Hide ${config.brand}`,
click: toggleWin, click: toggleWin,
}, },
{ { type: 'separator' },
type: 'separator',
},
{ {
label: 'Quit', label: 'Quit',
click: function() { click: function() {

View File

@ -14,170 +14,112 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
const electron = require('electron'); const {app, shell, Menu} = require('electron');
// Menu template from http://electron.atom.io/docs/api/menu/, edited // Menu template from http://electron.atom.io/docs/api/menu/, edited
const template = [ const template = [
{ {
label: 'Edit', label: 'Edit',
submenu: [ submenu: [
{ { role: 'undo' },
role: 'undo' { role: 'redo' },
}, { type: 'separator' },
{ { role: 'cut' },
role: 'redo' { role: 'copy' },
}, { role: 'paste' },
{ { role: 'pasteandmatchstyle' },
type: 'separator' { role: 'delete' },
}, { role: 'selectall' },
{ ],
role: 'cut'
},
{
role: 'copy'
},
{
role: 'paste'
},
{
role: 'pasteandmatchstyle'
},
{
role: 'delete'
},
{
role: 'selectall'
}
]
}, },
{ {
label: 'View', label: 'View',
submenu: [ submenu: [
{ { type: 'separator' },
type: 'separator' { role: 'resetzoom' },
}, { role: 'zoomin' },
{ { role: 'zoomout' },
role: 'resetzoom' { type: 'separator' },
}, { role: 'togglefullscreen' },
{ { role: 'toggledevtools' },
role: 'zoomin' ],
},
{
role: 'zoomout'
},
{
type: 'separator'
},
{
role: 'togglefullscreen'
},
{
role: 'toggledevtools'
}
]
}, },
{ {
role: 'window', role: 'window',
submenu: [ submenu: [
{ { role: 'minimize' },
role: 'minimize' { role: 'close' },
}, ],
{
role: 'close'
}
]
}, },
{ {
role: 'help', role: 'help',
submenu: [ submenu: [
{ {
label: 'riot.im', label: 'riot.im',
click () { electron.shell.openExternal('https://riot.im/') } click() { shell.openExternal('https://riot.im/'); },
} },
] ],
} },
]; ];
// macOS has specific menu conventions... // macOS has specific menu conventions...
if (process.platform === 'darwin') { if (process.platform === 'darwin') {
// first macOS menu is the name of the app // first macOS menu is the name of the app
const name = electron.app.getName() const name = app.getName();
template.unshift({ template.unshift({
label: name, label: name,
submenu: [ submenu: [
{ { role: 'about' },
role: 'about' { type: 'separator' },
},
{
type: 'separator'
},
{ {
role: 'services', role: 'services',
submenu: [] submenu: [],
}, },
{ { type: 'separator' },
type: 'separator' { role: 'hide' },
}, { role: 'hideothers' },
{ { role: 'unhide' },
role: 'hide' { type: 'separator' },
}, { role: 'quit' },
{ ],
role: 'hideothers' });
},
{
role: 'unhide'
},
{
type: 'separator'
},
{
role: 'quit'
}
]
})
// Edit menu. // Edit menu.
// This has a 'speech' section on macOS // This has a 'speech' section on macOS
template[1].submenu.push( template[1].submenu.push(
{ { type: 'separator' },
type: 'separator'
},
{ {
label: 'Speech', label: 'Speech',
submenu: [ submenu: [
{ { role: 'startspeaking' },
role: 'startspeaking' { role: 'stopspeaking' },
}, ],
{ },
role: 'stopspeaking' );
}
]
}
)
// Window menu. // Window menu.
// This also has specific functionality on macOS // This also has specific functionality on macOS
template[3].submenu = [ template[3].submenu = [
{ {
label: 'Close', label: 'Close',
accelerator: 'CmdOrCtrl+W', accelerator: 'CmdOrCtrl+W',
role: 'close' role: 'close',
}, },
{ {
label: 'Minimize', label: 'Minimize',
accelerator: 'CmdOrCtrl+M', accelerator: 'CmdOrCtrl+M',
role: 'minimize' role: 'minimize',
}, },
{ {
label: 'Zoom', label: 'Zoom',
role: 'zoom' role: 'zoom',
}, },
{ {
type: 'separator' type: 'separator',
}, },
{ {
label: 'Bring All to Front', label: 'Bring All to Front',
role: 'front' role: 'front',
} },
] ];
} else { } else {
template.unshift({ template.unshift({
label: 'File', label: 'File',
@ -186,12 +128,10 @@ if (process.platform === 'darwin') {
/*{ /*{
role: 'about' role: 'about'
},*/ },*/
{ { role: 'quit' },
role: 'quit' ],
}
]
}); });
} }
module.exports = electron.Menu.buildFromTemplate(template) module.exports = Menu.buildFromTemplate(template);