first pass at standardizing; suite still passing!

This commit is contained in:
Zeke Sikelianos 2016-03-24 13:15:04 -07:00 committed by Kevin Sawicki
parent f25c3d33b6
commit 4794385fac
30 changed files with 1454 additions and 1462 deletions

View file

@ -1,23 +1,23 @@
const electron = require('electron'); const electron = require('electron')
const app = electron.app; const app = electron.app
const BrowserWindow = electron.BrowserWindow; const BrowserWindow = electron.BrowserWindow
var mainWindow = null; var mainWindow = null
// Quit when all windows are closed. // Quit when all windows are closed.
app.on('window-all-closed', function() { app.on('window-all-closed', function () {
app.quit(); app.quit()
}); })
exports.load = function(appUrl) { exports.load = function (appUrl) {
app.on('ready', function() { app.on('ready', function () {
mainWindow = new BrowserWindow({ mainWindow = new BrowserWindow({
width: 800, width: 800,
height: 600, height: 600,
autoHideMenuBar: true, autoHideMenuBar: true,
useContentSize: true, useContentSize: true,
}); })
mainWindow.loadURL(appUrl); mainWindow.loadURL(appUrl)
mainWindow.focus(); mainWindow.focus()
}); })
}; }

View file

@ -1,52 +1,52 @@
const electron = require('electron'); const electron = require('electron')
const app = electron.app; const app = electron.app
const dialog = electron.dialog; const dialog = electron.dialog
const shell = electron.shell; const shell = electron.shell
const Menu = electron.Menu; const Menu = electron.Menu
const fs = require('fs'); const fs = require('fs')
const path = require('path'); const path = require('path')
const repl = require('repl'); const repl = require('repl')
const url = require('url'); const url = require('url')
// Parse command line options. // Parse command line options.
var argv = process.argv.slice(1); var argv = process.argv.slice(1)
var option = { file: null, help: null, version: null, webdriver: null, modules: [] }; var option = { file: null, help: null, version: null, webdriver: null, modules: [] }
for (var i = 0; i < argv.length; i++) { for (var i = 0; i < argv.length; i++) {
if (argv[i] == '--version' || argv[i] == '-v') { if (argv[i] == '--version' || argv[i] == '-v') {
option.version = true; option.version = true
break; break
} else if (argv[i].match(/^--app=/)) { } else if (argv[i].match(/^--app=/)) {
option.file = argv[i].split('=')[1]; option.file = argv[i].split('=')[1]
break; break
} else if (argv[i] == '--help' || argv[i] == '-h') { } else if (argv[i] == '--help' || argv[i] == '-h') {
option.help = true; option.help = true
break; break
} else if (argv[i] == '--interactive' || argv[i] == '-i') { } else if (argv[i] == '--interactive' || argv[i] == '-i') {
option.interactive = true; option.interactive = true
} else if (argv[i] == '--test-type=webdriver') { } else if (argv[i] == '--test-type=webdriver') {
option.webdriver = true; option.webdriver = true
} else if (argv[i] == '--require' || argv[i] == '-r') { } else if (argv[i] == '--require' || argv[i] == '-r') {
option.modules.push(argv[++i]); option.modules.push(argv[++i])
continue; continue
} else if (argv[i][0] == '-') { } else if (argv[i][0] == '-') {
continue; continue
} else { } else {
option.file = argv[i]; option.file = argv[i]
break; break
} }
} }
// Quit when all windows are closed and no other one is listening to this. // Quit when all windows are closed and no other one is listening to this.
app.on('window-all-closed', function() { app.on('window-all-closed', function () {
if (app.listeners('window-all-closed').length == 1 && !option.interactive) if (app.listeners('window-all-closed').length == 1 && !option.interactive)
app.quit(); app.quit()
}); })
// Create default menu. // Create default menu.
app.once('ready', function() { app.once('ready', function () {
if (Menu.getApplicationMenu()) if (Menu.getApplicationMenu())
return; return
var template = [ var template = [
{ {
@ -93,35 +93,35 @@ app.once('ready', function() {
{ {
label: 'Reload', label: 'Reload',
accelerator: 'CmdOrCtrl+R', accelerator: 'CmdOrCtrl+R',
click: function(item, focusedWindow) { click: function (item, focusedWindow) {
if (focusedWindow) if (focusedWindow)
focusedWindow.reload(); focusedWindow.reload()
} }
}, },
{ {
label: 'Toggle Full Screen', label: 'Toggle Full Screen',
accelerator: (function() { accelerator: (function () {
if (process.platform == 'darwin') if (process.platform == 'darwin')
return 'Ctrl+Command+F'; return 'Ctrl+Command+F'
else else
return 'F11'; return 'F11'
})(), })(),
click: function(item, focusedWindow) { click: function (item, focusedWindow) {
if (focusedWindow) if (focusedWindow)
focusedWindow.setFullScreen(!focusedWindow.isFullScreen()); focusedWindow.setFullScreen(!focusedWindow.isFullScreen())
} }
}, },
{ {
label: 'Toggle Developer Tools', label: 'Toggle Developer Tools',
accelerator: (function() { accelerator: (function () {
if (process.platform == 'darwin') if (process.platform == 'darwin')
return 'Alt+Command+I'; return 'Alt+Command+I'
else else
return 'Ctrl+Shift+I'; return 'Ctrl+Shift+I'
})(), })(),
click: function(item, focusedWindow) { click: function (item, focusedWindow) {
if (focusedWindow) if (focusedWindow)
focusedWindow.toggleDevTools(); focusedWindow.toggleDevTools()
} }
}, },
] ]
@ -148,33 +148,33 @@ app.once('ready', function() {
submenu: [ submenu: [
{ {
label: 'Learn More', label: 'Learn More',
click: function() { click: function () {
shell.openExternal('http://electron.atom.io'); shell.openExternal('http://electron.atom.io')
} }
}, },
{ {
label: 'Documentation', label: 'Documentation',
click: function() { click: function () {
shell.openExternal( shell.openExternal(
`https://github.com/atom/electron/tree/v${process.versions.electron}/docs#readme` `https://github.com/atom/electron/tree/v${process.versions.electron}/docs#readme`
); )
} }
}, },
{ {
label: 'Community Discussions', label: 'Community Discussions',
click: function() { click: function () {
shell.openExternal('https://discuss.atom.io/c/electron'); shell.openExternal('https://discuss.atom.io/c/electron')
} }
}, },
{ {
label: 'Search Issues', label: 'Search Issues',
click: function() { click: function () {
shell.openExternal('https://github.com/atom/electron/issues'); shell.openExternal('https://github.com/atom/electron/issues')
} }
} }
] ]
}, },
]; ]
if (process.platform == 'darwin') { if (process.platform == 'darwin') {
template.unshift({ template.unshift({
@ -215,10 +215,10 @@ app.once('ready', function() {
{ {
label: 'Quit', label: 'Quit',
accelerator: 'Command+Q', accelerator: 'Command+Q',
click: function() { app.quit(); } click: function () { app.quit(); }
}, },
] ]
}); })
template[3].submenu.push( template[3].submenu.push(
{ {
type: 'separator' type: 'separator'
@ -227,98 +227,104 @@ app.once('ready', function() {
label: 'Bring All to Front', label: 'Bring All to Front',
role: 'front' role: 'front'
} }
); )
} }
var menu = Menu.buildFromTemplate(template); var menu = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(menu); Menu.setApplicationMenu(menu)
}); })
if (option.modules.length > 0) { if (option.modules.length > 0) {
require('module')._preloadModules(option.modules); require('module')._preloadModules(option.modules)
} }
function loadApplicationPackage(packagePath) { function loadApplicationPackage (packagePath) {
try { try {
// Override app name and version. // Override app name and version.
packagePath = path.resolve(packagePath); packagePath = path.resolve(packagePath)
var packageJsonPath = path.join(packagePath, 'package.json'); var packageJsonPath = path.join(packagePath, 'package.json')
if (fs.existsSync(packageJsonPath)) { if (fs.existsSync(packageJsonPath)) {
var packageJson = JSON.parse(fs.readFileSync(packageJsonPath)); var packageJson = JSON.parse(fs.readFileSync(packageJsonPath))
if (packageJson.version) if (packageJson.version)
app.setVersion(packageJson.version); app.setVersion(packageJson.version)
if (packageJson.productName) if (packageJson.productName)
app.setName(packageJson.productName); app.setName(packageJson.productName)
else if (packageJson.name) else if (packageJson.name)
app.setName(packageJson.name); app.setName(packageJson.name)
app.setPath('userData', path.join(app.getPath('appData'), app.getName())); app.setPath('userData', path.join(app.getPath('appData'), app.getName()))
app.setPath('userCache', path.join(app.getPath('cache'), app.getName())); app.setPath('userCache', path.join(app.getPath('cache'), app.getName()))
app.setAppPath(packagePath); app.setAppPath(packagePath)
} }
// Run the app. // Run the app.
require('module')._load(packagePath, module, true); require('module')._load(packagePath, module, true)
} catch(e) { } catch(e) {
if (e.code == 'MODULE_NOT_FOUND') { if (e.code == 'MODULE_NOT_FOUND') {
app.focus(); app.focus()
dialog.showErrorBox( dialog.showErrorBox(
'Error opening app', 'Error opening app',
'The app provided is not a valid Electron app, please read the docs on how to write one:\n' + 'The app provided is not a valid Electron app, please read the docs on how to write one:\n' +
`https://github.com/atom/electron/tree/v${process.versions.electron}/docs\n\n${e.toString()}` `https://github.com/atom/electron/tree/v${process.versions.electron}/docs
);
process.exit(1); ${e.toString()}`
)
process.exit(1)
} else { } else {
console.error('App threw an error when running', e); console.error('App threw an error when running', e)
throw e; throw e
} }
} }
} }
function loadApplicationByUrl(appUrl) { function loadApplicationByUrl (appUrl) {
require('./default_app').load(appUrl); require('./default_app').load(appUrl)
} }
function startRepl() { function startRepl () {
repl.start('> ').on('exit', function() { repl.start('> ').on('exit', function () {
process.exit(0); process.exit(0)
}); })
} }
// Start the specified app if there is one specified in command line, otherwise // Start the specified app if there is one specified in command line, otherwise
// start the default app. // start the default app.
if (option.file && !option.webdriver) { if (option.file && !option.webdriver) {
var file = option.file; var file = option.file
var protocol = url.parse(file).protocol; var protocol = url.parse(file).protocol
var extension = path.extname(file); var extension = path.extname(file)
if (protocol === 'http:' || protocol === 'https:' || protocol === 'file:') { if (protocol === 'http:' || protocol === 'https:' || protocol === 'file:') {
loadApplicationByUrl(file); loadApplicationByUrl(file)
} else if (extension === '.html' || extension === '.htm') { } else if (extension === '.html' || extension === '.htm') {
loadApplicationByUrl('file://' + path.resolve(file)); loadApplicationByUrl('file://' + path.resolve(file))
} else { } else {
loadApplicationPackage(file); loadApplicationPackage(file)
} }
} else if (option.version) { } else if (option.version) {
console.log('v' + process.versions.electron); console.log('v' + process.versions.electron)
process.exit(0); process.exit(0)
} else if (option.help) { } else if (option.help) {
var helpMessage = "Electron v" + process.versions.electron + " - Cross Platform Desktop Application Shell\n\n"; var helpMessage = `Electron v${process.versions.electron} - Cross Platform Desktop Application Shell
helpMessage += "Usage: electron [options] [path]\n\n";
helpMessage += "A path to an Electron application may be specified.\n"; Usage: electron [options] [path]
helpMessage += "The path must be one of the following:\n\n";
helpMessage += " - index.js file.\n"; A path to an Electron application may be specified.
helpMessage += " - Folder containing a package.json file.\n"; The path must be one of the following:
helpMessage += " - Folder containing an index.js file.\n";
helpMessage += " - .html/.htm file.\n"; - index.js file.
helpMessage += " - http://, https://, or file:// URL.\n"; - Folder containing a package.json file.
helpMessage += "\nOptions:\n"; - Folder containing an index.js file.
helpMessage += " -h, --help Print this usage message.\n"; - .html/.htm file.
helpMessage += " -i, --interactive Open a REPL to the main process.\n"; - http://, https://, or file:// URL.
helpMessage += " -r, --require Module to preload (option can be repeated)\n";
helpMessage += " -v, --version Print the version."; Options:
console.log(helpMessage); -h, --help Print this usage message.
process.exit(0); -i, --interactive Open a REPL to the main process.
-r, --require Module to preload (option can be repeated)
-v, --version Print the version.`
console.log(helpMessage)
process.exit(0)
} else if (option.interactive) { } else if (option.interactive) {
startRepl(); startRepl()
} else { } else {
loadApplicationByUrl('file://' + __dirname + '/index.html'); loadApplicationByUrl('file://' + __dirname + '/index.html')
} }

View file

@ -1,36 +1,36 @@
'use strict'; 'use strict'
const deprecate = require('electron').deprecate; const deprecate = require('electron').deprecate
const session = require('electron').session; const session = require('electron').session
const Menu = require('electron').Menu; const Menu = require('electron').Menu
const EventEmitter = require('events').EventEmitter; const EventEmitter = require('events').EventEmitter
const bindings = process.atomBinding('app'); const bindings = process.atomBinding('app')
const downloadItemBindings = process.atomBinding('download_item'); const downloadItemBindings = process.atomBinding('download_item')
const app = bindings.app; const app = bindings.app
app.__proto__ = EventEmitter.prototype; app.__proto__ = EventEmitter.prototype
app.setApplicationMenu = function(menu) { app.setApplicationMenu = function (menu) {
return Menu.setApplicationMenu(menu); return Menu.setApplicationMenu(menu)
}; }
app.getApplicationMenu = function() { app.getApplicationMenu = function () {
return Menu.getApplicationMenu(); return Menu.getApplicationMenu()
}; }
app.commandLine = { app.commandLine = {
appendSwitch: bindings.appendSwitch, appendSwitch: bindings.appendSwitch,
appendArgument: bindings.appendArgument appendArgument: bindings.appendArgument
}; }
if (process.platform === 'darwin') { if (process.platform === 'darwin') {
app.dock = { app.dock = {
bounce: function(type) { bounce: function (type) {
if (type == null) { if (type == null) {
type = 'informational'; type = 'informational'
} }
return bindings.dockBounce(type); return bindings.dockBounce(type)
}, },
cancelBounce: bindings.dockCancelBounce, cancelBounce: bindings.dockCancelBounce,
setBadge: bindings.dockSetBadgeText, setBadge: bindings.dockSetBadgeText,
@ -39,81 +39,79 @@ if (process.platform === 'darwin') {
show: bindings.dockShow, show: bindings.dockShow,
setMenu: bindings.dockSetMenu, setMenu: bindings.dockSetMenu,
setIcon: bindings.dockSetIcon setIcon: bindings.dockSetIcon
}; }
} }
var appPath = null; var appPath = null
app.setAppPath = function(path) { app.setAppPath = function (path) {
return appPath = path; return appPath = path
}; }
app.getAppPath = function() { app.getAppPath = function () {
return appPath; return appPath
}; }
// Routes the events to webContents. // Routes the events to webContents.
var ref1 = ['login', 'certificate-error', 'select-client-certificate']; var ref1 = ['login', 'certificate-error', 'select-client-certificate']
var fn = function(name) { var fn = function (name) {
return app.on(name, function(event, webContents, ...args) { return app.on(name, function (event, webContents, ...args) {
return webContents.emit.apply(webContents, [name, event].concat(args)); return webContents.emit.apply(webContents, [name, event].concat(args))
}); })
}; }
var i, len; var i, len
for (i = 0, len = ref1.length; i < len; i++) { for (i = 0, len = ref1.length; i < len; i++) {
fn(ref1[i]); fn(ref1[i])
} }
// Deprecated. // Deprecated.
app.getHomeDir = deprecate('app.getHomeDir', 'app.getPath', function() { app.getHomeDir = deprecate('app.getHomeDir', 'app.getPath', function () {
return this.getPath('home'); return this.getPath('home')
}); })
app.getDataPath = deprecate('app.getDataPath', 'app.getPath', function() { app.getDataPath = deprecate('app.getDataPath', 'app.getPath', function () {
return this.getPath('userData'); return this.getPath('userData')
}); })
app.setDataPath = deprecate('app.setDataPath', 'app.setPath', function(path) { app.setDataPath = deprecate('app.setDataPath', 'app.setPath', function (path) {
return this.setPath('userData', path); return this.setPath('userData', path)
}); })
app.resolveProxy = deprecate('app.resolveProxy', 'session.defaultSession.resolveProxy', function(url, callback) { app.resolveProxy = deprecate('app.resolveProxy', 'session.defaultSession.resolveProxy', function (url, callback) {
return session.defaultSession.resolveProxy(url, callback); return session.defaultSession.resolveProxy(url, callback)
}); })
deprecate.rename(app, 'terminate', 'quit'); deprecate.rename(app, 'terminate', 'quit')
deprecate.event(app, 'finish-launching', 'ready', function() {
deprecate.event(app, 'finish-launching', 'ready', function () {
// give default app a chance to setup default menu. // give default app a chance to setup default menu.
setImmediate(() => { setImmediate(() => {
this.emit('finish-launching'); this.emit('finish-launching')
}); })
}); })
deprecate.event(app, 'activate-with-no-open-windows', 'activate', function(event, hasVisibleWindows) { deprecate.event(app, 'activate-with-no-open-windows', 'activate', function (event, hasVisibleWindows) {
if (!hasVisibleWindows) { if (!hasVisibleWindows) {
return this.emit('activate-with-no-open-windows', event); return this.emit('activate-with-no-open-windows', event)
} }
}); })
deprecate.event(app, 'select-certificate', 'select-client-certificate'); deprecate.event(app, 'select-certificate', 'select-client-certificate')
// Wrappers for native classes. // Wrappers for native classes.
var wrapDownloadItem = function(downloadItem) { var wrapDownloadItem = function (downloadItem) {
// downloadItem is an EventEmitter. // downloadItem is an EventEmitter.
downloadItem.__proto__ = EventEmitter.prototype; downloadItem.__proto__ = EventEmitter.prototype
// Deprecated. // Deprecated.
deprecate.property(downloadItem, 'url', 'getURL'); deprecate.property(downloadItem, 'url', 'getURL')
deprecate.property(downloadItem, 'filename', 'getFilename'); deprecate.property(downloadItem, 'filename', 'getFilename')
deprecate.property(downloadItem, 'mimeType', 'getMimeType'); deprecate.property(downloadItem, 'mimeType', 'getMimeType')
return deprecate.rename(downloadItem, 'getUrl', 'getURL'); return deprecate.rename(downloadItem, 'getUrl', 'getURL')
}; }
downloadItemBindings._setWrapDownloadItem(wrapDownloadItem); downloadItemBindings._setWrapDownloadItem(wrapDownloadItem)
// Only one App object pemitted. // Only one App object pemitted.
module.exports = app; module.exports = app

View file

@ -1,7 +1,7 @@
const deprecate = require('electron').deprecate; const deprecate = require('electron').deprecate
const autoUpdater = process.platform === 'win32' ? require('./auto-updater/auto-updater-win') : require('./auto-updater/auto-updater-native'); const autoUpdater = process.platform === 'win32' ? require('./auto-updater/auto-updater-win') : require('./auto-updater/auto-updater-native')
// Deprecated. // Deprecated.
deprecate.rename(autoUpdater, 'setFeedUrl', 'setFeedURL'); deprecate.rename(autoUpdater, 'setFeedUrl', 'setFeedURL')
module.exports = autoUpdater; module.exports = autoUpdater

View file

@ -1,6 +1,6 @@
const EventEmitter = require('events').EventEmitter; const EventEmitter = require('events').EventEmitter
const autoUpdater = process.atomBinding('auto_updater').autoUpdater; const autoUpdater = process.atomBinding('auto_updater').autoUpdater
autoUpdater.__proto__ = EventEmitter.prototype; autoUpdater.__proto__ = EventEmitter.prototype
module.exports = autoUpdater; module.exports = autoUpdater

View file

@ -1,61 +1,62 @@
'use strict'; 'use strict'
const app = require('electron').app; const app = require('electron').app
const EventEmitter = require('events').EventEmitter; const EventEmitter = require('events').EventEmitter
const squirrelUpdate = require('./squirrel-update-win'); const squirrelUpdate = require('./squirrel-update-win')
const util = require('util'); const util = require('util')
function AutoUpdater() { function AutoUpdater () {
EventEmitter.call(this); EventEmitter.call(this)
} }
util.inherits(AutoUpdater, EventEmitter); util.inherits(AutoUpdater, EventEmitter)
AutoUpdater.prototype.quitAndInstall = function() { AutoUpdater.prototype.quitAndInstall = function () {
squirrelUpdate.processStart(); squirrelUpdate.processStart()
return app.quit(); return app.quit()
}; }
AutoUpdater.prototype.setFeedURL = function(updateURL) { AutoUpdater.prototype.setFeedURL = function (updateURL) {
return this.updateURL = updateURL; this.updateURL = updateURL
}; }
AutoUpdater.prototype.checkForUpdates = function() { AutoUpdater.prototype.checkForUpdates = function () {
if (!this.updateURL) { if (!this.updateURL) {
return this.emitError('Update URL is not set'); return this.emitError('Update URL is not set')
} }
if (!squirrelUpdate.supported()) { if (!squirrelUpdate.supported()) {
return this.emitError('Can not find Squirrel'); return this.emitError('Can not find Squirrel')
} }
this.emit('checking-for-update'); this.emit('checking-for-update')
squirrelUpdate.download(this.updateURL, (error, update) => { squirrelUpdate.download(this.updateURL, (error, update) => {
if (error != null) { if (error != null) {
return this.emitError(error); return this.emitError(error)
} }
if (update == null) { if (update == null) {
return this.emit('update-not-available'); return this.emit('update-not-available')
} }
this.emit('update-available'); this.emit('update-available')
squirrelUpdate.update(this.updateURL, (error) => { squirrelUpdate.update(this.updateURL, (error) => {
var date, releaseNotes, version; var date, releaseNotes, version
if (error != null) { if (error != null) {
return this.emitError(error); return this.emitError(error)
} }
releaseNotes = update.releaseNotes, version = update.version; releaseNotes = update.releaseNotes
version = update.version
// Following information is not available on Windows, so fake them. // Following information is not available on Windows, so fake them.
date = new Date; date = new Date()
this.emit('update-downloaded', {}, releaseNotes, version, date, this.updateURL, () => { this.emit('update-downloaded', {}, releaseNotes, version, date, this.updateURL, () => {
this.quitAndInstall(); this.quitAndInstall()
}); })
}); })
}); })
}; }
// Private: Emit both error object and message, this is to keep compatibility // Private: Emit both error object and message, this is to keep compatibility
// with Old APIs. // with Old APIs.
AutoUpdater.prototype.emitError = function(message) { AutoUpdater.prototype.emitError = function (message) {
return this.emit('error', new Error(message), message); return this.emit('error', new Error(message), message)
}; }
module.exports = new AutoUpdater; module.exports = new AutoUpdater()

View file

@ -1,98 +1,95 @@
const fs = require('fs'); const fs = require('fs')
const path = require('path'); const path = require('path')
const spawn = require('child_process').spawn; const spawn = require('child_process').spawn
// i.e. my-app/app-0.1.13/ // i.e. my-app/app-0.1.13/
const appFolder = path.dirname(process.execPath); const appFolder = path.dirname(process.execPath)
// i.e. my-app/Update.exe // i.e. my-app/Update.exe
const updateExe = path.resolve(appFolder, '..', 'Update.exe'); const updateExe = path.resolve(appFolder, '..', 'Update.exe')
const exeName = path.basename(process.execPath); const exeName = path.basename(process.execPath)
// Spawn a command and invoke the callback when it completes with an error // Spawn a command and invoke the callback when it completes with an error
// and the output from standard out. // and the output from standard out.
var spawnUpdate = function(args, detached, callback) { var spawnUpdate = function (args, detached, callback) {
var error, errorEmitted, spawnedProcess, stderr, stdout; var error, errorEmitted, spawnedProcess, stderr, stdout
try { try {
spawnedProcess = spawn(updateExe, args, { spawnedProcess = spawn(updateExe, args, {
detached: detached detached: detached
}); })
} catch (error1) { } catch (error1) {
error = error1; error = error1
// Shouldn't happen, but still guard it. // Shouldn't happen, but still guard it.
process.nextTick(function() { process.nextTick(function () {
return callback(error); return callback(error)
}); })
return; return
} }
stdout = ''; stdout = ''
stderr = ''; stderr = ''
spawnedProcess.stdout.on('data', function(data) { spawnedProcess.stdout.on('data', function (data) {
return stdout += data; return stdout += data
}); })
spawnedProcess.stderr.on('data', function(data) { spawnedProcess.stderr.on('data', function (data) {
return stderr += data; return stderr += data
}); })
errorEmitted = false; errorEmitted = false
spawnedProcess.on('error', function(error) { spawnedProcess.on('error', function (error) {
errorEmitted = true; errorEmitted = true
return callback(error); return callback(error)
}); })
return spawnedProcess.on('exit', function(code, signal) { return spawnedProcess.on('exit', function (code, signal) {
// We may have already emitted an error. // We may have already emitted an error.
if (errorEmitted) { if (errorEmitted) {
return; return
} }
// Process terminated with error. // Process terminated with error.
if (code !== 0) { if (code !== 0) {
return callback("Command failed: " + (signal != null ? signal : code) + "\n" + stderr); return callback('Command failed: ' + (signal != null ? signal : code) + '\n' + stderr)
} }
// Success. // Success.
return callback(null, stdout); return callback(null, stdout)
}); })
}; }
// Start an instance of the installed app. // Start an instance of the installed app.
exports.processStart = function() { exports.processStart = function () {
return spawnUpdate(['--processStart', exeName], true, function() {}); return spawnUpdate(['--processStart', exeName], true, function () {})
}; }
// Download the releases specified by the URL and write new results to stdout. // Download the releases specified by the URL and write new results to stdout.
exports.download = function(updateURL, callback) { exports.download = function (updateURL, callback) {
return spawnUpdate(['--download', updateURL], false, function(error, stdout) { return spawnUpdate(['--download', updateURL], false, function (error, stdout) {
var json, ref, ref1, update; var json, ref, ref1, update
if (error != null) { if (error != null) {
return callback(error); return callback(error)
} }
try { try {
// Last line of output is the JSON details about the releases // Last line of output is the JSON details about the releases
json = stdout.trim().split('\n').pop(); json = stdout.trim().split('\n').pop()
update = (ref = JSON.parse(json)) != null ? (ref1 = ref.releasesToApply) != null ? typeof ref1.pop === "function" ? ref1.pop() : void 0 : void 0 : void 0; update = (ref = JSON.parse(json)) != null ? (ref1 = ref.releasesToApply) != null ? typeof ref1.pop === 'function' ? ref1.pop() : void 0 : void 0 : void 0
} catch (jsonError) { } catch (jsonError) {
return callback("Invalid result:\n" + stdout); return callback('Invalid result:\n' + stdout)
} }
return callback(null, update); return callback(null, update)
}); })
}; }
// Update the application to the latest remote version specified by URL. // Update the application to the latest remote version specified by URL.
exports.update = function(updateURL, callback) { exports.update = function (updateURL, callback) {
return spawnUpdate(['--update', updateURL], false, callback); return spawnUpdate(['--update', updateURL], false, callback)
}; }
// Is the Update.exe installed with the current application? // Is the Update.exe installed with the current application?
exports.supported = function() { exports.supported = function () {
try { try {
fs.accessSync(updateExe, fs.R_OK); fs.accessSync(updateExe, fs.R_OK)
return true; return true
} catch (error) { } catch (error) {
return false; return false
} }
}; }

View file

@ -1,65 +1,65 @@
'use strict'; 'use strict'
const ipcMain = require('electron').ipcMain; const ipcMain = require('electron').ipcMain
const deprecate = require('electron').deprecate; const deprecate = require('electron').deprecate
const EventEmitter = require('events').EventEmitter; const EventEmitter = require('events').EventEmitter
const {BrowserWindow, _setDeprecatedOptionsCheck} = process.atomBinding('window'); const {BrowserWindow, _setDeprecatedOptionsCheck} = process.atomBinding('window')
BrowserWindow.prototype.__proto__ = EventEmitter.prototype; BrowserWindow.prototype.__proto__ = EventEmitter.prototype
BrowserWindow.prototype._init = function() { BrowserWindow.prototype._init = function () {
// avoid recursive require. // avoid recursive require.
var app, menu; var app, menu
app = require('electron').app; app = require('electron').app
// Simulate the application menu on platforms other than OS X. // Simulate the application menu on platforms other than OS X.
if (process.platform !== 'darwin') { if (process.platform !== 'darwin') {
menu = app.getApplicationMenu(); menu = app.getApplicationMenu()
if (menu != null) { if (menu != null) {
this.setMenu(menu); this.setMenu(menu)
} }
} }
// Make new windows requested by links behave like "window.open" // Make new windows requested by links behave like "window.open"
this.webContents.on('-new-window', (event, url, frameName) => { this.webContents.on('-new-window', (event, url, frameName) => {
var options; var options
options = { options = {
show: true, show: true,
width: 800, width: 800,
height: 600 height: 600
}; }
return ipcMain.emit('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPEN', event, url, frameName, options); return ipcMain.emit('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPEN', event, url, frameName, options)
}); })
// window.resizeTo(...) // window.resizeTo(...)
// window.moveTo(...) // window.moveTo(...)
this.webContents.on('move', (event, size) => { this.webContents.on('move', (event, size) => {
this.setBounds(size); this.setBounds(size)
}); })
// Hide the auto-hide menu when webContents is focused. // Hide the auto-hide menu when webContents is focused.
this.webContents.on('activate', () => { this.webContents.on('activate', () => {
if (process.platform !== 'darwin' && this.isMenuBarAutoHide() && this.isMenuBarVisible()) { if (process.platform !== 'darwin' && this.isMenuBarAutoHide() && this.isMenuBarVisible()) {
this.setMenuBarVisibility(false); this.setMenuBarVisibility(false)
} }
}); })
// Forward the crashed event. // Forward the crashed event.
this.webContents.on('crashed', () => { this.webContents.on('crashed', () => {
this.emit('crashed'); this.emit('crashed')
}); })
// Change window title to page title. // Change window title to page title.
this.webContents.on('page-title-updated', (event, title) => { this.webContents.on('page-title-updated', (event, title) => {
// The page-title-updated event is not emitted immediately (see #3645), so // The page-title-updated event is not emitted immediately (see #3645), so
// when the callback is called the BrowserWindow might have been closed. // when the callback is called the BrowserWindow might have been closed.
if (this.isDestroyed()) if (this.isDestroyed())
return; return
// Route the event to BrowserWindow. // Route the event to BrowserWindow.
this.emit('page-title-updated', event, title); this.emit('page-title-updated', event, title)
if (!event.defaultPrevented) if (!event.defaultPrevented)
this.setTitle(title); this.setTitle(title)
}); })
// Sometimes the webContents doesn't get focus when window is shown, so we have // Sometimes the webContents doesn't get focus when window is shown, so we have
// to force focusing on webContents in this case. The safest way is to focus it // to force focusing on webContents in this case. The safest way is to focus it
@ -67,228 +67,228 @@ BrowserWindow.prototype._init = function() {
// if we do it later we might move focus in the page. // if we do it later we might move focus in the page.
// Though this hack is only needed on OS X when the app is launched from // Though this hack is only needed on OS X when the app is launched from
// Finder, we still do it on all platforms in case of other bugs we don't know. // Finder, we still do it on all platforms in case of other bugs we don't know.
this.webContents.once('load-url', function() { this.webContents.once('load-url', function () {
this.focus(); this.focus()
}); })
// Redirect focus/blur event to app instance too. // Redirect focus/blur event to app instance too.
this.on('blur', (event) => { this.on('blur', (event) => {
app.emit('browser-window-blur', event, this); app.emit('browser-window-blur', event, this)
}); })
this.on('focus', (event) => { this.on('focus', (event) => {
app.emit('browser-window-focus', event, this); app.emit('browser-window-focus', event, this)
}); })
// Evented visibilityState changes // Evented visibilityState changes
this.on('show', () => { this.on('show', () => {
this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), this.isMinimized()); this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), this.isMinimized())
}); })
this.on('hide', () => { this.on('hide', () => {
this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), this.isMinimized()); this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), this.isMinimized())
}); })
this.on('minimize', () => { this.on('minimize', () => {
this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), this.isMinimized()); this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), this.isMinimized())
}); })
this.on('restore', () => { this.on('restore', () => {
this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), this.isMinimized()); this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), this.isMinimized())
}); })
// Notify the creation of the window. // Notify the creation of the window.
app.emit('browser-window-created', {}, this); app.emit('browser-window-created', {}, this)
// Be compatible with old APIs. // Be compatible with old APIs.
this.webContents.on('devtools-focused', () => { this.webContents.on('devtools-focused', () => {
this.emit('devtools-focused'); this.emit('devtools-focused')
}); })
this.webContents.on('devtools-opened', () => { this.webContents.on('devtools-opened', () => {
this.emit('devtools-opened'); this.emit('devtools-opened')
}); })
this.webContents.on('devtools-closed', () => { this.webContents.on('devtools-closed', () => {
this.emit('devtools-closed'); this.emit('devtools-closed')
}); })
Object.defineProperty(this, 'devToolsWebContents', { Object.defineProperty(this, 'devToolsWebContents', {
enumerable: true, enumerable: true,
configurable: false, configurable: false,
get: function() { get: function () {
return this.webContents.devToolsWebContents; return this.webContents.devToolsWebContents
} }
}); })
}; }
BrowserWindow.getFocusedWindow = function() { BrowserWindow.getFocusedWindow = function () {
var i, len, window, windows; var i, len, window, windows
windows = BrowserWindow.getAllWindows(); windows = BrowserWindow.getAllWindows()
for (i = 0, len = windows.length; i < len; i++) { for (i = 0, len = windows.length; i < len; i++) {
window = windows[i]; window = windows[i]
if (window.isFocused()) { if (window.isFocused()) {
return window; return window
} }
} }
return null; return null
}; }
BrowserWindow.fromWebContents = function(webContents) { BrowserWindow.fromWebContents = function (webContents) {
var i, len, ref1, window, windows; var i, len, ref1, window, windows
windows = BrowserWindow.getAllWindows(); windows = BrowserWindow.getAllWindows()
for (i = 0, len = windows.length; i < len; i++) { for (i = 0, len = windows.length; i < len; i++) {
window = windows[i]; window = windows[i]
if ((ref1 = window.webContents) != null ? ref1.equal(webContents) : void 0) { if ((ref1 = window.webContents) != null ? ref1.equal(webContents) : void 0) {
return window; return window
} }
} }
}; }
BrowserWindow.fromDevToolsWebContents = function(webContents) { BrowserWindow.fromDevToolsWebContents = function (webContents) {
var i, len, ref1, window, windows; var i, len, ref1, window, windows
windows = BrowserWindow.getAllWindows(); windows = BrowserWindow.getAllWindows()
for (i = 0, len = windows.length; i < len; i++) { for (i = 0, len = windows.length; i < len; i++) {
window = windows[i]; window = windows[i]
if ((ref1 = window.devToolsWebContents) != null ? ref1.equal(webContents) : void 0) { if ((ref1 = window.devToolsWebContents) != null ? ref1.equal(webContents) : void 0) {
return window; return window
} }
} }
}; }
// Helpers. // Helpers.
BrowserWindow.prototype.loadURL = function() { BrowserWindow.prototype.loadURL = function () {
return this.webContents.loadURL.apply(this.webContents, arguments); return this.webContents.loadURL.apply(this.webContents, arguments)
}; }
BrowserWindow.prototype.getURL = function() { BrowserWindow.prototype.getURL = function () {
return this.webContents.getURL(); return this.webContents.getURL()
}; }
BrowserWindow.prototype.reload = function() { BrowserWindow.prototype.reload = function () {
return this.webContents.reload.apply(this.webContents, arguments); return this.webContents.reload.apply(this.webContents, arguments)
}; }
BrowserWindow.prototype.send = function() { BrowserWindow.prototype.send = function () {
return this.webContents.send.apply(this.webContents, arguments); return this.webContents.send.apply(this.webContents, arguments)
}; }
BrowserWindow.prototype.openDevTools = function() { BrowserWindow.prototype.openDevTools = function () {
return this.webContents.openDevTools.apply(this.webContents, arguments); return this.webContents.openDevTools.apply(this.webContents, arguments)
}; }
BrowserWindow.prototype.closeDevTools = function() { BrowserWindow.prototype.closeDevTools = function () {
return this.webContents.closeDevTools(); return this.webContents.closeDevTools()
}; }
BrowserWindow.prototype.isDevToolsOpened = function() { BrowserWindow.prototype.isDevToolsOpened = function () {
return this.webContents.isDevToolsOpened(); return this.webContents.isDevToolsOpened()
}; }
BrowserWindow.prototype.isDevToolsFocused = function() { BrowserWindow.prototype.isDevToolsFocused = function () {
return this.webContents.isDevToolsFocused(); return this.webContents.isDevToolsFocused()
}; }
BrowserWindow.prototype.toggleDevTools = function() { BrowserWindow.prototype.toggleDevTools = function () {
return this.webContents.toggleDevTools(); return this.webContents.toggleDevTools()
}; }
BrowserWindow.prototype.inspectElement = function() { BrowserWindow.prototype.inspectElement = function () {
return this.webContents.inspectElement.apply(this.webContents, arguments); return this.webContents.inspectElement.apply(this.webContents, arguments)
}; }
BrowserWindow.prototype.inspectServiceWorker = function() { BrowserWindow.prototype.inspectServiceWorker = function () {
return this.webContents.inspectServiceWorker(); return this.webContents.inspectServiceWorker()
}; }
// Deprecated. // Deprecated.
deprecate.member(BrowserWindow, 'undo', 'webContents'); deprecate.member(BrowserWindow, 'undo', 'webContents')
deprecate.member(BrowserWindow, 'redo', 'webContents'); deprecate.member(BrowserWindow, 'redo', 'webContents')
deprecate.member(BrowserWindow, 'cut', 'webContents'); deprecate.member(BrowserWindow, 'cut', 'webContents')
deprecate.member(BrowserWindow, 'copy', 'webContents'); deprecate.member(BrowserWindow, 'copy', 'webContents')
deprecate.member(BrowserWindow, 'paste', 'webContents'); deprecate.member(BrowserWindow, 'paste', 'webContents')
deprecate.member(BrowserWindow, 'selectAll', 'webContents'); deprecate.member(BrowserWindow, 'selectAll', 'webContents')
deprecate.member(BrowserWindow, 'reloadIgnoringCache', 'webContents'); deprecate.member(BrowserWindow, 'reloadIgnoringCache', 'webContents')
deprecate.member(BrowserWindow, 'isLoading', 'webContents'); deprecate.member(BrowserWindow, 'isLoading', 'webContents')
deprecate.member(BrowserWindow, 'isWaitingForResponse', 'webContents'); deprecate.member(BrowserWindow, 'isWaitingForResponse', 'webContents')
deprecate.member(BrowserWindow, 'stop', 'webContents'); deprecate.member(BrowserWindow, 'stop', 'webContents')
deprecate.member(BrowserWindow, 'isCrashed', 'webContents'); deprecate.member(BrowserWindow, 'isCrashed', 'webContents')
deprecate.member(BrowserWindow, 'print', 'webContents'); deprecate.member(BrowserWindow, 'print', 'webContents')
deprecate.member(BrowserWindow, 'printToPDF', 'webContents'); deprecate.member(BrowserWindow, 'printToPDF', 'webContents')
deprecate.rename(BrowserWindow, 'restart', 'reload'); deprecate.rename(BrowserWindow, 'restart', 'reload')
deprecate.rename(BrowserWindow, 'loadUrl', 'loadURL'); deprecate.rename(BrowserWindow, 'loadUrl', 'loadURL')
deprecate.rename(BrowserWindow, 'getUrl', 'getURL'); deprecate.rename(BrowserWindow, 'getUrl', 'getURL')
BrowserWindow.prototype.executeJavaScriptInDevTools = deprecate('executeJavaScriptInDevTools', 'devToolsWebContents.executeJavaScript', function(code) { BrowserWindow.prototype.executeJavaScriptInDevTools = deprecate('executeJavaScriptInDevTools', 'devToolsWebContents.executeJavaScript', function (code) {
var ref1; var ref1
return (ref1 = this.devToolsWebContents) != null ? ref1.executeJavaScript(code) : void 0; return (ref1 = this.devToolsWebContents) != null ? ref1.executeJavaScript(code) : void 0
}); })
BrowserWindow.prototype.getPageTitle = deprecate('getPageTitle', 'webContents.getTitle', function() { BrowserWindow.prototype.getPageTitle = deprecate('getPageTitle', 'webContents.getTitle', function () {
var ref1; var ref1
return (ref1 = this.webContents) != null ? ref1.getTitle() : void 0; return (ref1 = this.webContents) != null ? ref1.getTitle() : void 0
}); })
const isDeprecatedKey = function(key) { const isDeprecatedKey = function (key) {
return key.indexOf('-') >= 0; return key.indexOf('-') >= 0
}; }
// Map deprecated key with hyphens to camel case key // Map deprecated key with hyphens to camel case key
const getNonDeprecatedKey = function(deprecatedKey) { const getNonDeprecatedKey = function (deprecatedKey) {
return deprecatedKey.replace(/-./g, function(match) { return deprecatedKey.replace(/-./g, function (match) {
return match[1].toUpperCase(); return match[1].toUpperCase()
}); })
}; }
// TODO Remove for 1.0 // TODO Remove for 1.0
const checkForDeprecatedOptions = function(options) { const checkForDeprecatedOptions = function (options) {
if (!options) return ''; if (!options) return ''
let keysToCheck = Object.keys(options); let keysToCheck = Object.keys(options)
if (options.webPreferences) { if (options.webPreferences) {
keysToCheck = keysToCheck.concat(Object.keys(options.webPreferences)); keysToCheck = keysToCheck.concat(Object.keys(options.webPreferences))
} }
// Check options for keys with hyphens in them // Check options for keys with hyphens in them
let deprecatedKey = keysToCheck.filter(isDeprecatedKey)[0]; let deprecatedKey = keysToCheck.filter(isDeprecatedKey)[0]
if (deprecatedKey) { if (deprecatedKey) {
try { try {
deprecate.warn(deprecatedKey, getNonDeprecatedKey(deprecatedKey)); deprecate.warn(deprecatedKey, getNonDeprecatedKey(deprecatedKey))
} catch (error) { } catch (error) {
// Return error message so it can be rethrown via C++ // Return error message so it can be rethrown via C++
return error.message; return error.message
} }
} }
let webPreferenceOption; let webPreferenceOption
if (options.hasOwnProperty('nodeIntegration')) { if (options.hasOwnProperty('nodeIntegration')) {
webPreferenceOption = 'nodeIntegration'; webPreferenceOption = 'nodeIntegration'
} else if (options.hasOwnProperty('preload')) { } else if (options.hasOwnProperty('preload')) {
webPreferenceOption = 'preload'; webPreferenceOption = 'preload'
} else if (options.hasOwnProperty('zoomFactor')) { } else if (options.hasOwnProperty('zoomFactor')) {
webPreferenceOption = 'zoomFactor'; webPreferenceOption = 'zoomFactor'
} }
if (webPreferenceOption) { if (webPreferenceOption) {
try { try {
deprecate.warn(`options.${webPreferenceOption}`, `options.webPreferences.${webPreferenceOption}`); deprecate.warn(`options.${webPreferenceOption}`, `options.webPreferences.${webPreferenceOption}`)
} catch (error) { } catch (error) {
// Return error message so it can be rethrown via C++ // Return error message so it can be rethrown via C++
return error.message; return error.message
} }
} }
return ''; return ''
}; }
_setDeprecatedOptionsCheck(checkForDeprecatedOptions); _setDeprecatedOptionsCheck(checkForDeprecatedOptions)
module.exports = BrowserWindow; module.exports = BrowserWindow

View file

@ -1 +1 @@
module.exports = process.atomBinding('content_tracing'); module.exports = process.atomBinding('content_tracing')

View file

@ -1,183 +1,183 @@
'use strict'; 'use strict'
const app = require('electron').app; const app = require('electron').app
const BrowserWindow = require('electron').BrowserWindow; const BrowserWindow = require('electron').BrowserWindow
const binding = process.atomBinding('dialog'); const binding = process.atomBinding('dialog')
const v8Util = process.atomBinding('v8_util'); const v8Util = process.atomBinding('v8_util')
var includes = [].includes; var includes = [].includes
var fileDialogProperties = { var fileDialogProperties = {
openFile: 1 << 0, openFile: 1 << 0,
openDirectory: 1 << 1, openDirectory: 1 << 1,
multiSelections: 1 << 2, multiSelections: 1 << 2,
createDirectory: 1 << 3 createDirectory: 1 << 3
}; }
var messageBoxTypes = ['none', 'info', 'warning', 'error', 'question']; var messageBoxTypes = ['none', 'info', 'warning', 'error', 'question']
var messageBoxOptions = { var messageBoxOptions = {
noLink: 1 << 0 noLink: 1 << 0
}; }
var parseArgs = function(window, options, callback) { var parseArgs = function (window, options, callback) {
if (!(window === null || (window != null ? window.constructor : void 0) === BrowserWindow)) { if (!(window === null || (window != null ? window.constructor : void 0) === BrowserWindow)) {
// Shift. // Shift.
callback = options; callback = options
options = window; options = window
window = null; window = null
} }
if ((callback == null) && typeof options === 'function') { if ((callback == null) && typeof options === 'function') {
// Shift. // Shift.
callback = options; callback = options
options = null; options = null
} }
return [window, options, callback]; return [window, options, callback]
}; }
var checkAppInitialized = function() { var checkAppInitialized = function () {
if (!app.isReady()) { if (!app.isReady()) {
throw new Error('dialog module can only be used after app is ready'); throw new Error('dialog module can only be used after app is ready')
} }
}; }
module.exports = { module.exports = {
showOpenDialog: function(...args) { showOpenDialog: function (...args) {
var prop, properties, value, wrappedCallback; var prop, properties, value, wrappedCallback
checkAppInitialized(); checkAppInitialized()
let [window, options, callback] = parseArgs.apply(null, args); let [window, options, callback] = parseArgs.apply(null, args)
if (options == null) { if (options == null) {
options = { options = {
title: 'Open', title: 'Open',
properties: ['openFile'] properties: ['openFile']
}; }
} }
if (options.properties == null) { if (options.properties == null) {
options.properties = ['openFile']; options.properties = ['openFile']
} }
if (!Array.isArray(options.properties)) { if (!Array.isArray(options.properties)) {
throw new TypeError('Properties must be an array'); throw new TypeError('Properties must be an array')
} }
properties = 0; properties = 0
for (prop in fileDialogProperties) { for (prop in fileDialogProperties) {
value = fileDialogProperties[prop]; value = fileDialogProperties[prop]
if (includes.call(options.properties, prop)) { if (includes.call(options.properties, prop)) {
properties |= value; properties |= value
} }
} }
if (options.title == null) { if (options.title == null) {
options.title = ''; options.title = ''
} else if (typeof options.title !== 'string') { } else if (typeof options.title !== 'string') {
throw new TypeError('Title must be a string'); throw new TypeError('Title must be a string')
} }
if (options.defaultPath == null) { if (options.defaultPath == null) {
options.defaultPath = ''; options.defaultPath = ''
} else if (typeof options.defaultPath !== 'string') { } else if (typeof options.defaultPath !== 'string') {
throw new TypeError('Default path must be a string'); throw new TypeError('Default path must be a string')
} }
if (options.filters == null) { if (options.filters == null) {
options.filters = []; options.filters = []
} }
wrappedCallback = typeof callback === 'function' ? function(success, result) { wrappedCallback = typeof callback === 'function' ? function (success, result) {
return callback(success ? result : void 0); return callback(success ? result : void 0)
} : null; } : null
return binding.showOpenDialog(String(options.title), String(options.defaultPath), options.filters, properties, window, wrappedCallback); return binding.showOpenDialog(String(options.title), String(options.defaultPath), options.filters, properties, window, wrappedCallback)
}, },
showSaveDialog: function(...args) { showSaveDialog: function (...args) {
var wrappedCallback; var wrappedCallback
checkAppInitialized(); checkAppInitialized()
let [window, options, callback] = parseArgs.apply(null, args); let [window, options, callback] = parseArgs.apply(null, args)
if (options == null) { if (options == null) {
options = { options = {
title: 'Save' title: 'Save'
}; }
} }
if (options.title == null) { if (options.title == null) {
options.title = ''; options.title = ''
} else if (typeof options.title !== 'string') { } else if (typeof options.title !== 'string') {
throw new TypeError('Title must be a string'); throw new TypeError('Title must be a string')
} }
if (options.defaultPath == null) { if (options.defaultPath == null) {
options.defaultPath = ''; options.defaultPath = ''
} else if (typeof options.defaultPath !== 'string') { } else if (typeof options.defaultPath !== 'string') {
throw new TypeError('Default path must be a string'); throw new TypeError('Default path must be a string')
} }
if (options.filters == null) { if (options.filters == null) {
options.filters = []; options.filters = []
} }
wrappedCallback = typeof callback === 'function' ? function(success, result) { wrappedCallback = typeof callback === 'function' ? function (success, result) {
return callback(success ? result : void 0); return callback(success ? result : void 0)
} : null; } : null
return binding.showSaveDialog(String(options.title), String(options.defaultPath), options.filters, window, wrappedCallback); return binding.showSaveDialog(String(options.title), String(options.defaultPath), options.filters, window, wrappedCallback)
}, },
showMessageBox: function(...args) { showMessageBox: function (...args) {
var flags, i, j, len, messageBoxType, ref2, ref3, text; var flags, i, j, len, messageBoxType, ref2, ref3, text
checkAppInitialized(); checkAppInitialized()
let [window, options, callback] = parseArgs.apply(null, args); let [window, options, callback] = parseArgs.apply(null, args)
if (options == null) { if (options == null) {
options = { options = {
type: 'none' type: 'none'
}; }
} }
if (options.type == null) { if (options.type == null) {
options.type = 'none'; options.type = 'none'
} }
messageBoxType = messageBoxTypes.indexOf(options.type); messageBoxType = messageBoxTypes.indexOf(options.type)
if (!(messageBoxType > -1)) { if (!(messageBoxType > -1)) {
throw new TypeError('Invalid message box type'); throw new TypeError('Invalid message box type')
} }
if (!Array.isArray(options.buttons)) { if (!Array.isArray(options.buttons)) {
throw new TypeError('Buttons must be an array'); throw new TypeError('Buttons must be an array')
} }
if (options.title == null) { if (options.title == null) {
options.title = ''; options.title = ''
} else if (typeof options.title !== 'string') { } else if (typeof options.title !== 'string') {
throw new TypeError('Title must be a string'); throw new TypeError('Title must be a string')
} }
if (options.message == null) { if (options.message == null) {
options.message = ''; options.message = ''
} else if (typeof options.message !== 'string') { } else if (typeof options.message !== 'string') {
throw new TypeError('Message must be a string'); throw new TypeError('Message must be a string')
} }
if (options.detail == null) { if (options.detail == null) {
options.detail = ''; options.detail = ''
} else if (typeof options.detail !== 'string') { } else if (typeof options.detail !== 'string') {
throw new TypeError('Detail must be a string'); throw new TypeError('Detail must be a string')
} }
if (options.icon == null) { if (options.icon == null) {
options.icon = null; options.icon = null
} }
if (options.defaultId == null) { if (options.defaultId == null) {
options.defaultId = -1; options.defaultId = -1
} }
// Choose a default button to get selected when dialog is cancelled. // Choose a default button to get selected when dialog is cancelled.
if (options.cancelId == null) { if (options.cancelId == null) {
options.cancelId = 0; options.cancelId = 0
ref2 = options.buttons; ref2 = options.buttons
for (i = j = 0, len = ref2.length; j < len; i = ++j) { for (i = j = 0, len = ref2.length; j < len; i = ++j) {
text = ref2[i]; text = ref2[i]
if ((ref3 = text.toLowerCase()) === 'cancel' || ref3 === 'no') { if ((ref3 = text.toLowerCase()) === 'cancel' || ref3 === 'no') {
options.cancelId = i; options.cancelId = i
break; break
} }
} }
} }
flags = options.noLink ? messageBoxOptions.noLink : 0; flags = options.noLink ? messageBoxOptions.noLink : 0
return binding.showMessageBox(messageBoxType, options.buttons, options.defaultId, options.cancelId, flags, options.title, options.message, options.detail, options.icon, window, callback); return binding.showMessageBox(messageBoxType, options.buttons, options.defaultId, options.cancelId, flags, options.title, options.message, options.detail, options.icon, window, callback)
}, },
showErrorBox: function(...args) { showErrorBox: function (...args) {
return binding.showErrorBox.apply(binding, args); return binding.showErrorBox.apply(binding, args)
} }
}; }
// Mark standard asynchronous functions. // Mark standard asynchronous functions.
var ref1 = ['showMessageBox', 'showOpenDialog', 'showSaveDialog']; var ref1 = ['showMessageBox', 'showOpenDialog', 'showSaveDialog']
var j, len, api; var j, len, api
for (j = 0, len = ref1.length; j < len; j++) { for (j = 0, len = ref1.length; j < len; j++) {
api = ref1[j]; api = ref1[j]
v8Util.setHiddenValue(module.exports[api], 'asynchronous', true); v8Util.setHiddenValue(module.exports[api], 'asynchronous', true)
} }

View file

@ -1,112 +1,110 @@
const common = require('../../../common/api/exports/electron'); const common = require('../../../common/api/exports/electron')
// Import common modules. // Import common modules.
common.defineProperties(exports); common.defineProperties(exports)
Object.defineProperties(exports, { Object.defineProperties(exports, {
// Browser side modules, please sort with alphabet order. // Browser side modules, please sort with alphabet order.
app: { app: {
enumerable: true, enumerable: true,
get: function() { get: function () {
return require('../app'); return require('../app')
} }
}, },
autoUpdater: { autoUpdater: {
enumerable: true, enumerable: true,
get: function() { get: function () {
return require('../auto-updater'); return require('../auto-updater')
} }
}, },
BrowserWindow: { BrowserWindow: {
enumerable: true, enumerable: true,
get: function() { get: function () {
return require('../browser-window'); return require('../browser-window')
} }
}, },
contentTracing: { contentTracing: {
enumerable: true, enumerable: true,
get: function() { get: function () {
return require('../content-tracing'); return require('../content-tracing')
} }
}, },
dialog: { dialog: {
enumerable: true, enumerable: true,
get: function() { get: function () {
return require('../dialog'); return require('../dialog')
} }
}, },
ipcMain: { ipcMain: {
enumerable: true, enumerable: true,
get: function() { get: function () {
return require('../ipc-main'); return require('../ipc-main')
} }
}, },
globalShortcut: { globalShortcut: {
enumerable: true, enumerable: true,
get: function() { get: function () {
return require('../global-shortcut'); return require('../global-shortcut')
} }
}, },
Menu: { Menu: {
enumerable: true, enumerable: true,
get: function() { get: function () {
return require('../menu'); return require('../menu')
} }
}, },
MenuItem: { MenuItem: {
enumerable: true, enumerable: true,
get: function() { get: function () {
return require('../menu-item'); return require('../menu-item')
} }
}, },
powerMonitor: { powerMonitor: {
enumerable: true, enumerable: true,
get: function() { get: function () {
return require('../power-monitor'); return require('../power-monitor')
} }
}, },
powerSaveBlocker: { powerSaveBlocker: {
enumerable: true, enumerable: true,
get: function() { get: function () {
return require('../power-save-blocker'); return require('../power-save-blocker')
} }
}, },
protocol: { protocol: {
enumerable: true, enumerable: true,
get: function() { get: function () {
return require('../protocol'); return require('../protocol')
} }
}, },
screen: { screen: {
enumerable: true, enumerable: true,
get: function() { get: function () {
return require('../screen'); return require('../screen')
} }
}, },
session: { session: {
enumerable: true, enumerable: true,
get: function() { get: function () {
return require('../session'); return require('../session')
} }
}, },
Tray: { Tray: {
enumerable: true, enumerable: true,
get: function() { get: function () {
return require('../tray'); return require('../tray')
} }
}, },
// The internal modules, invisible unless you know their names. // The internal modules, invisible unless you know their names.
NavigationController: { NavigationController: {
get: function() { get: function () {
return require('../navigation-controller'); return require('../navigation-controller')
} }
}, },
webContents: { webContents: {
get: function() { get: function () {
return require('../web-contents'); return require('../web-contents')
} }
} }
}); })

View file

@ -1,5 +1,5 @@
var globalShortcut; var globalShortcut
globalShortcut = process.atomBinding('global_shortcut').globalShortcut; globalShortcut = process.atomBinding('global_shortcut').globalShortcut
module.exports = globalShortcut; module.exports = globalShortcut

View file

@ -1,3 +1,3 @@
const EventEmitter = require('events').EventEmitter; const EventEmitter = require('events').EventEmitter
module.exports = new EventEmitter; module.exports = new EventEmitter()

View file

@ -1,7 +1,7 @@
const deprecate = require('electron').deprecate; const deprecate = require('electron').deprecate
const ipcMain = require('electron').ipcMain; const ipcMain = require('electron').ipcMain
// This module is deprecated, we mirror everything from ipcMain. // This module is deprecated, we mirror everything from ipcMain.
deprecate.warn('ipc module', 'require("electron").ipcMain'); deprecate.warn('ipc module', 'require("electron").ipcMain')
module.exports = ipcMain; module.exports = ipcMain

View file

@ -1,8 +1,8 @@
'use strict'; 'use strict'
var MenuItem, methodInBrowserWindow, nextCommandId, rolesMap; var MenuItem, methodInBrowserWindow, nextCommandId, rolesMap
nextCommandId = 0; nextCommandId = 0
// Maps role to methods of webContents // Maps role to methods of webContents
rolesMap = { rolesMap = {
@ -15,88 +15,87 @@ rolesMap = {
minimize: 'minimize', minimize: 'minimize',
close: 'close', close: 'close',
delete: 'delete' delete: 'delete'
}; }
// Maps methods that should be called directly on the BrowserWindow instance // Maps methods that should be called directly on the BrowserWindow instance
methodInBrowserWindow = { methodInBrowserWindow = {
minimize: true, minimize: true,
close: true close: true
}; }
MenuItem = (function() { MenuItem = (function () {
MenuItem.types = ['normal', 'separator', 'submenu', 'checkbox', 'radio']; MenuItem.types = ['normal', 'separator', 'submenu', 'checkbox', 'radio']
function MenuItem(options) { function MenuItem (options) {
var click, ref; var click, ref
const Menu = require('electron').Menu; const Menu = require('electron').Menu
click = options.click, this.selector = options.selector, this.type = options.type, this.role = options.role, this.label = options.label, this.sublabel = options.sublabel, this.accelerator = options.accelerator, this.icon = options.icon, this.enabled = options.enabled, this.visible = options.visible, this.checked = options.checked, this.submenu = options.submenu; click = options.click, this.selector = options.selector, this.type = options.type, this.role = options.role, this.label = options.label, this.sublabel = options.sublabel, this.accelerator = options.accelerator, this.icon = options.icon, this.enabled = options.enabled, this.visible = options.visible, this.checked = options.checked, this.submenu = options.submenu
if ((this.submenu != null) && this.submenu.constructor !== Menu) { if ((this.submenu != null) && this.submenu.constructor !== Menu) {
this.submenu = Menu.buildFromTemplate(this.submenu); this.submenu = Menu.buildFromTemplate(this.submenu)
} }
if ((this.type == null) && (this.submenu != null)) { if ((this.type == null) && (this.submenu != null)) {
this.type = 'submenu'; this.type = 'submenu'
} }
if (this.type === 'submenu' && ((ref = this.submenu) != null ? ref.constructor : void 0) !== Menu) { if (this.type === 'submenu' && ((ref = this.submenu) != null ? ref.constructor : void 0) !== Menu) {
throw new Error('Invalid submenu'); throw new Error('Invalid submenu')
} }
this.overrideReadOnlyProperty('type', 'normal'); this.overrideReadOnlyProperty('type', 'normal')
this.overrideReadOnlyProperty('role'); this.overrideReadOnlyProperty('role')
this.overrideReadOnlyProperty('accelerator'); this.overrideReadOnlyProperty('accelerator')
this.overrideReadOnlyProperty('icon'); this.overrideReadOnlyProperty('icon')
this.overrideReadOnlyProperty('submenu'); this.overrideReadOnlyProperty('submenu')
this.overrideProperty('label', ''); this.overrideProperty('label', '')
this.overrideProperty('sublabel', ''); this.overrideProperty('sublabel', '')
this.overrideProperty('enabled', true); this.overrideProperty('enabled', true)
this.overrideProperty('visible', true); this.overrideProperty('visible', true)
this.overrideProperty('checked', false); this.overrideProperty('checked', false)
if (MenuItem.types.indexOf(this.type) === -1) { if (MenuItem.types.indexOf(this.type) === -1) {
throw new Error("Unknown menu type " + this.type); throw new Error('Unknown menu type ' + this.type)
} }
this.commandId = ++nextCommandId; this.commandId = ++nextCommandId
this.click = (focusedWindow) => { this.click = (focusedWindow) => {
// Manually flip the checked flags when clicked. // Manually flip the checked flags when clicked.
var methodName, ref1, ref2; var methodName, ref1, ref2
if ((ref1 = this.type) === 'checkbox' || ref1 === 'radio') { if ((ref1 = this.type) === 'checkbox' || ref1 === 'radio') {
this.checked = !this.checked; this.checked = !this.checked
} }
if (this.role && rolesMap[this.role] && process.platform !== 'darwin' && (focusedWindow != null)) { if (this.role && rolesMap[this.role] && process.platform !== 'darwin' && (focusedWindow != null)) {
methodName = rolesMap[this.role]; methodName = rolesMap[this.role]
if (methodInBrowserWindow[methodName]) { if (methodInBrowserWindow[methodName]) {
return focusedWindow[methodName](); return focusedWindow[methodName]()
} else { } else {
return (ref2 = focusedWindow.webContents) != null ? ref2[methodName]() : void 0; return (ref2 = focusedWindow.webContents) != null ? ref2[methodName]() : void 0
} }
} else if (typeof click === 'function') { } else if (typeof click === 'function') {
return click(this, focusedWindow); return click(this, focusedWindow)
} else if (typeof this.selector === 'string' && process.platform === 'darwin') { } else if (typeof this.selector === 'string' && process.platform === 'darwin') {
return Menu.sendActionToFirstResponder(this.selector); return Menu.sendActionToFirstResponder(this.selector)
}
} }
};
} }
MenuItem.prototype.overrideProperty = function(name, defaultValue) { MenuItem.prototype.overrideProperty = function (name, defaultValue) {
if (defaultValue == null) { if (defaultValue == null) {
defaultValue = null; defaultValue = null
}
return this[name] != null ? this[name] : this[name] = defaultValue
} }
return this[name] != null ? this[name] : this[name] = defaultValue;
};
MenuItem.prototype.overrideReadOnlyProperty = function(name, defaultValue) { MenuItem.prototype.overrideReadOnlyProperty = function (name, defaultValue) {
if (defaultValue == null) { if (defaultValue == null) {
defaultValue = null; defaultValue = null
} }
if (this[name] == null) { if (this[name] == null) {
this[name] = defaultValue; this[name] = defaultValue
} }
return Object.defineProperty(this, name, { return Object.defineProperty(this, name, {
enumerable: true, enumerable: true,
writable: false, writable: false,
value: this[name] value: this[name]
}); })
}; }
return MenuItem; return MenuItem
})()
})(); module.exports = MenuItem
module.exports = MenuItem;

View file

@ -1,70 +1,70 @@
'use strict'; 'use strict'
const BrowserWindow = require('electron').BrowserWindow; const BrowserWindow = require('electron').BrowserWindow
const MenuItem = require('electron').MenuItem; const MenuItem = require('electron').MenuItem
const EventEmitter = require('events').EventEmitter; const EventEmitter = require('events').EventEmitter
const v8Util = process.atomBinding('v8_util'); const v8Util = process.atomBinding('v8_util')
const bindings = process.atomBinding('menu'); const bindings = process.atomBinding('menu')
// Automatically generated radio menu item's group id. // Automatically generated radio menu item's group id.
var nextGroupId = 0; var nextGroupId = 0
// Search between separators to find a radio menu item and return its group id, // Search between separators to find a radio menu item and return its group id,
// otherwise generate a group id. // otherwise generate a group id.
var generateGroupId = function(items, pos) { var generateGroupId = function (items, pos) {
var i, item, j, k, ref1, ref2, ref3; var i, item, j, k, ref1, ref2, ref3
if (pos > 0) { if (pos > 0) {
for (i = j = ref1 = pos - 1; ref1 <= 0 ? j <= 0 : j >= 0; i = ref1 <= 0 ? ++j : --j) { for (i = j = ref1 = pos - 1; ref1 <= 0 ? j <= 0 : j >= 0; i = ref1 <= 0 ? ++j : --j) {
item = items[i]; item = items[i]
if (item.type === 'radio') { if (item.type === 'radio') {
return item.groupId; return item.groupId
} }
if (item.type === 'separator') { if (item.type === 'separator') {
break; break
} }
} }
} else if (pos < items.length) { } else if (pos < items.length) {
for (i = k = ref2 = pos, ref3 = items.length - 1; ref2 <= ref3 ? k <= ref3 : k >= ref3; i = ref2 <= ref3 ? ++k : --k) { for (i = k = ref2 = pos, ref3 = items.length - 1; ref2 <= ref3 ? k <= ref3 : k >= ref3; i = ref2 <= ref3 ? ++k : --k) {
item = items[i]; item = items[i]
if (item.type === 'radio') { if (item.type === 'radio') {
return item.groupId; return item.groupId
} }
if (item.type === 'separator') { if (item.type === 'separator') {
break; break
} }
} }
} }
return ++nextGroupId; return ++nextGroupId
}; }
// Returns the index of item according to |id|. // Returns the index of item according to |id|.
var indexOfItemById = function(items, id) { var indexOfItemById = function (items, id) {
var i, item, j, len; var i, item, j, len
for (i = j = 0, len = items.length; j < len; i = ++j) { for (i = j = 0, len = items.length; j < len; i = ++j) {
item = items[i]; item = items[i]
if (item.id === id) { if (item.id === id) {
return i; return i
} }
} }
return -1; return -1
}; }
// Returns the index of where to insert the item according to |position|. // Returns the index of where to insert the item according to |position|.
var indexToInsertByPosition = function(items, position) { var indexToInsertByPosition = function (items, position) {
var insertIndex; var insertIndex
if (!position) { if (!position) {
return items.length; return items.length
} }
const [query, id] = position.split('='); const [query, id] = position.split('=')
insertIndex = indexOfItemById(items, id); insertIndex = indexOfItemById(items, id)
if (insertIndex === -1 && query !== 'endof') { if (insertIndex === -1 && query !== 'endof') {
console.warn("Item with id '" + id + "' is not found"); console.warn("Item with id '" + id + "' is not found")
return items.length; return items.length
} }
switch (query) { switch (query) {
case 'after': case 'after':
insertIndex++; insertIndex++
break; break
case 'endof': case 'endof':
// If the |id| doesn't exist, then create a new group with the |id|. // If the |id| doesn't exist, then create a new group with the |id|.
@ -72,235 +72,234 @@ var indexToInsertByPosition = function(items, position) {
items.push({ items.push({
id: id, id: id,
type: 'separator' type: 'separator'
}); })
insertIndex = items.length - 1; insertIndex = items.length - 1
} }
// Find the end of the group. // Find the end of the group.
insertIndex++; insertIndex++
while (insertIndex < items.length && items[insertIndex].type !== 'separator') { while (insertIndex < items.length && items[insertIndex].type !== 'separator') {
insertIndex++; insertIndex++
} }
} }
return insertIndex; return insertIndex
}; }
const Menu = bindings.Menu; const Menu = bindings.Menu
Menu.prototype.__proto__ = EventEmitter.prototype; Menu.prototype.__proto__ = EventEmitter.prototype
Menu.prototype._init = function() { Menu.prototype._init = function () {
this.commandsMap = {}; this.commandsMap = {}
this.groupsMap = {}; this.groupsMap = {}
this.items = []; this.items = []
return this.delegate = { return this.delegate = {
isCommandIdChecked: (commandId) => { isCommandIdChecked: (commandId) => {
var command = this.commandsMap[commandId]; var command = this.commandsMap[commandId]
return command != null ? command.checked : undefined; return command != null ? command.checked : undefined
}, },
isCommandIdEnabled: (commandId) => { isCommandIdEnabled: (commandId) => {
var command = this.commandsMap[commandId]; var command = this.commandsMap[commandId]
return command != null ? command.enabled : undefined; return command != null ? command.enabled : undefined
}, },
isCommandIdVisible: (commandId) => { isCommandIdVisible: (commandId) => {
var command = this.commandsMap[commandId]; var command = this.commandsMap[commandId]
return command != null ? command.visible : undefined; return command != null ? command.visible : undefined
}, },
getAcceleratorForCommandId: (commandId) => { getAcceleratorForCommandId: (commandId) => {
var command = this.commandsMap[commandId]; var command = this.commandsMap[commandId]
return command != null ? command.accelerator : undefined; return command != null ? command.accelerator : undefined
}, },
getIconForCommandId: (commandId) => { getIconForCommandId: (commandId) => {
var command = this.commandsMap[commandId]; var command = this.commandsMap[commandId]
return command != null ? command.icon : undefined; return command != null ? command.icon : undefined
}, },
executeCommand: (commandId) => { executeCommand: (commandId) => {
var command = this.commandsMap[commandId]; var command = this.commandsMap[commandId]
return command != null ? command.click(BrowserWindow.getFocusedWindow()) : undefined; return command != null ? command.click(BrowserWindow.getFocusedWindow()) : undefined
}, },
menuWillShow: () => { menuWillShow: () => {
// Make sure radio groups have at least one menu item seleted. // Make sure radio groups have at least one menu item seleted.
var checked, group, id, j, len, radioItem, ref1; var checked, group, id, j, len, radioItem, ref1
ref1 = this.groupsMap; ref1 = this.groupsMap
for (id in ref1) { for (id in ref1) {
group = ref1[id]; group = ref1[id]
checked = false; checked = false
for (j = 0, len = group.length; j < len; j++) { for (j = 0, len = group.length; j < len; j++) {
radioItem = group[j]; radioItem = group[j]
if (!radioItem.checked) { if (!radioItem.checked) {
continue; continue
} }
checked = true; checked = true
break; break
} }
if (!checked) { if (!checked) {
v8Util.setHiddenValue(group[0], 'checked', true); v8Util.setHiddenValue(group[0], 'checked', true)
} }
} }
} }
}; }
}; }
Menu.prototype.popup = function(window, x, y, positioningItem) { Menu.prototype.popup = function (window, x, y, positioningItem) {
if (typeof window != 'object' || window.constructor !== BrowserWindow) { if (typeof window != 'object' || window.constructor !== BrowserWindow) {
// Shift. // Shift.
positioningItem = y; positioningItem = y
y = x; y = x
x = window; x = window
window = BrowserWindow.getFocusedWindow(); window = BrowserWindow.getFocusedWindow()
} }
// Default parameters. // Default parameters.
if (typeof x !== 'number') x = -1; if (typeof x !== 'number') x = -1
if (typeof y !== 'number') y = -1; if (typeof y !== 'number') y = -1
if (typeof positioningItem !== 'number') positioningItem = 0; if (typeof positioningItem !== 'number') positioningItem = 0
this.popupAt(window, x, y, positioningItem); this.popupAt(window, x, y, positioningItem)
}; }
Menu.prototype.append = function(item) { Menu.prototype.append = function (item) {
return this.insert(this.getItemCount(), item); return this.insert(this.getItemCount(), item)
}; }
Menu.prototype.insert = function(pos, item) { Menu.prototype.insert = function (pos, item) {
var base, name; var base, name
if ((item != null ? item.constructor : void 0) !== MenuItem) { if ((item != null ? item.constructor : void 0) !== MenuItem) {
throw new TypeError('Invalid item'); throw new TypeError('Invalid item')
} }
switch (item.type) { switch (item.type) {
case 'normal': case 'normal':
this.insertItem(pos, item.commandId, item.label); this.insertItem(pos, item.commandId, item.label)
break; break
case 'checkbox': case 'checkbox':
this.insertCheckItem(pos, item.commandId, item.label); this.insertCheckItem(pos, item.commandId, item.label)
break; break
case 'separator': case 'separator':
this.insertSeparator(pos); this.insertSeparator(pos)
break; break
case 'submenu': case 'submenu':
this.insertSubMenu(pos, item.commandId, item.label, item.submenu); this.insertSubMenu(pos, item.commandId, item.label, item.submenu)
break; break
case 'radio': case 'radio':
// Grouping radio menu items. // Grouping radio menu items.
item.overrideReadOnlyProperty('groupId', generateGroupId(this.items, pos)); item.overrideReadOnlyProperty('groupId', generateGroupId(this.items, pos))
if ((base = this.groupsMap)[name = item.groupId] == null) { if ((base = this.groupsMap)[name = item.groupId] == null) {
base[name] = []; base[name] = []
} }
this.groupsMap[item.groupId].push(item); this.groupsMap[item.groupId].push(item)
// Setting a radio menu item should flip other items in the group. // Setting a radio menu item should flip other items in the group.
v8Util.setHiddenValue(item, 'checked', item.checked); v8Util.setHiddenValue(item, 'checked', item.checked)
Object.defineProperty(item, 'checked', { Object.defineProperty(item, 'checked', {
enumerable: true, enumerable: true,
get: function() { get: function () {
return v8Util.getHiddenValue(item, 'checked'); return v8Util.getHiddenValue(item, 'checked')
}, },
set: () => { set: () => {
var j, len, otherItem, ref1; var j, len, otherItem, ref1
ref1 = this.groupsMap[item.groupId]; ref1 = this.groupsMap[item.groupId]
for (j = 0, len = ref1.length; j < len; j++) { for (j = 0, len = ref1.length; j < len; j++) {
otherItem = ref1[j]; otherItem = ref1[j]
if (otherItem !== item) { if (otherItem !== item) {
v8Util.setHiddenValue(otherItem, 'checked', false); v8Util.setHiddenValue(otherItem, 'checked', false)
} }
} }
return v8Util.setHiddenValue(item, 'checked', true); return v8Util.setHiddenValue(item, 'checked', true)
} }
}); })
this.insertRadioItem(pos, item.commandId, item.label, item.groupId); this.insertRadioItem(pos, item.commandId, item.label, item.groupId)
} }
if (item.sublabel != null) { if (item.sublabel != null) {
this.setSublabel(pos, item.sublabel); this.setSublabel(pos, item.sublabel)
} }
if (item.icon != null) { if (item.icon != null) {
this.setIcon(pos, item.icon); this.setIcon(pos, item.icon)
} }
if (item.role != null) { if (item.role != null) {
this.setRole(pos, item.role); this.setRole(pos, item.role)
} }
// Make menu accessable to items. // Make menu accessable to items.
item.overrideReadOnlyProperty('menu', this); item.overrideReadOnlyProperty('menu', this)
// Remember the items. // Remember the items.
this.items.splice(pos, 0, item); this.items.splice(pos, 0, item)
return this.commandsMap[item.commandId] = item; return this.commandsMap[item.commandId] = item
}; }
// Force menuWillShow to be called // Force menuWillShow to be called
Menu.prototype._callMenuWillShow = function() { Menu.prototype._callMenuWillShow = function () {
if (this.delegate != null) { if (this.delegate != null) {
this.delegate.menuWillShow(); this.delegate.menuWillShow()
} }
this.items.forEach(function(item) { this.items.forEach(function (item) {
if (item.submenu != null) { if (item.submenu != null) {
item.submenu._callMenuWillShow(); item.submenu._callMenuWillShow()
} }
}); })
}; }
var applicationMenu = null; var applicationMenu = null
Menu.setApplicationMenu = function(menu) { Menu.setApplicationMenu = function (menu) {
if (!(menu === null || menu.constructor === Menu)) { if (!(menu === null || menu.constructor === Menu)) {
throw new TypeError('Invalid menu'); throw new TypeError('Invalid menu')
} }
// Keep a reference. // Keep a reference.
applicationMenu = menu; applicationMenu = menu
if (process.platform === 'darwin') { if (process.platform === 'darwin') {
if (menu === null) { if (menu === null) {
return; return
} }
menu._callMenuWillShow(); menu._callMenuWillShow()
bindings.setApplicationMenu(menu); bindings.setApplicationMenu(menu)
} else { } else {
BrowserWindow.getAllWindows().forEach(function(window) { BrowserWindow.getAllWindows().forEach(function (window) {
window.setMenu(menu); window.setMenu(menu)
}); })
} }
}; }
Menu.getApplicationMenu = function() { Menu.getApplicationMenu = function () {
return applicationMenu; return applicationMenu
}; }
Menu.sendActionToFirstResponder = bindings.sendActionToFirstResponder; Menu.sendActionToFirstResponder = bindings.sendActionToFirstResponder
Menu.buildFromTemplate = function(template) { Menu.buildFromTemplate = function (template) {
var insertIndex, item, j, k, key, len, len1, menu, menuItem, positionedTemplate; var insertIndex, item, j, k, key, len, len1, menu, menuItem, positionedTemplate
if (!Array.isArray(template)) { if (!Array.isArray(template)) {
throw new TypeError('Invalid template for Menu'); throw new TypeError('Invalid template for Menu')
} }
positionedTemplate = []; positionedTemplate = []
insertIndex = 0; insertIndex = 0
for (j = 0, len = template.length; j < len; j++) { for (j = 0, len = template.length; j < len; j++) {
item = template[j]; item = template[j]
if (item.position) { if (item.position) {
insertIndex = indexToInsertByPosition(positionedTemplate, item.position); insertIndex = indexToInsertByPosition(positionedTemplate, item.position)
} else { } else {
// If no |position| is specified, insert after last item. // If no |position| is specified, insert after last item.
insertIndex++; insertIndex++
} }
positionedTemplate.splice(insertIndex, 0, item); positionedTemplate.splice(insertIndex, 0, item)
} }
menu = new Menu; menu = new Menu
for (k = 0, len1 = positionedTemplate.length; k < len1; k++) { for (k = 0, len1 = positionedTemplate.length; k < len1; k++) {
item = positionedTemplate[k]; item = positionedTemplate[k]
if (typeof item !== 'object') { if (typeof item !== 'object') {
throw new TypeError('Invalid template for MenuItem'); throw new TypeError('Invalid template for MenuItem')
} }
menuItem = new MenuItem(item); menuItem = new MenuItem(item)
for (key in item) { for (key in item) {
// Preserve extra fields specified by user // Preserve extra fields specified by user
if (!menuItem.hasOwnProperty(key)) { if (!menuItem.hasOwnProperty(key)) {
menuItem[key] = item[key]; menuItem[key] = item[key]
} }
} }
menu.append(menuItem); menu.append(menuItem)
} }
return menu; return menu
}; }
module.exports = Menu; module.exports = Menu

View file

@ -1,179 +1,178 @@
'use strict'; 'use strict'
const ipcMain = require('electron').ipcMain; const ipcMain = require('electron').ipcMain
// The history operation in renderer is redirected to browser. // The history operation in renderer is redirected to browser.
ipcMain.on('ATOM_SHELL_NAVIGATION_CONTROLLER', function(event, method, ...args) { ipcMain.on('ATOM_SHELL_NAVIGATION_CONTROLLER', function (event, method, ...args) {
var ref; var ref
return (ref = event.sender)[method].apply(ref, args); return (ref = event.sender)[method].apply(ref, args)
}); })
ipcMain.on('ATOM_SHELL_SYNC_NAVIGATION_CONTROLLER', function(event, method, ...args) { ipcMain.on('ATOM_SHELL_SYNC_NAVIGATION_CONTROLLER', function (event, method, ...args) {
var ref; var ref
return event.returnValue = (ref = event.sender)[method].apply(ref, args); return event.returnValue = (ref = event.sender)[method].apply(ref, args)
}); })
// JavaScript implementation of Chromium's NavigationController. // JavaScript implementation of Chromium's NavigationController.
// Instead of relying on Chromium for history control, we compeletely do history // Instead of relying on Chromium for history control, we compeletely do history
// control on user land, and only rely on WebContents.loadURL for navigation. // control on user land, and only rely on WebContents.loadURL for navigation.
// This helps us avoid Chromium's various optimizations so we can ensure renderer // This helps us avoid Chromium's various optimizations so we can ensure renderer
// process is restarted everytime. // process is restarted everytime.
var NavigationController = (function() { var NavigationController = (function () {
function NavigationController(webContents) { function NavigationController (webContents) {
this.webContents = webContents; this.webContents = webContents
this.clearHistory(); this.clearHistory()
// webContents may have already navigated to a page. // webContents may have already navigated to a page.
if (this.webContents._getURL()) { if (this.webContents._getURL()) {
this.currentIndex++; this.currentIndex++
this.history.push(this.webContents._getURL()); this.history.push(this.webContents._getURL())
} }
this.webContents.on('navigation-entry-commited', (event, url, inPage, replaceEntry) => { this.webContents.on('navigation-entry-commited', (event, url, inPage, replaceEntry) => {
var currentEntry; var currentEntry
if (this.inPageIndex > -1 && !inPage) { if (this.inPageIndex > -1 && !inPage) {
// Navigated to a new page, clear in-page mark. // Navigated to a new page, clear in-page mark.
this.inPageIndex = -1; this.inPageIndex = -1
} else if (this.inPageIndex === -1 && inPage) { } else if (this.inPageIndex === -1 && inPage) {
// Started in-page navigations. // Started in-page navigations.
this.inPageIndex = this.currentIndex; this.inPageIndex = this.currentIndex
} }
if (this.pendingIndex >= 0) { if (this.pendingIndex >= 0) {
// Go to index. // Go to index.
this.currentIndex = this.pendingIndex; this.currentIndex = this.pendingIndex
this.pendingIndex = -1; this.pendingIndex = -1
return this.history[this.currentIndex] = url; return this.history[this.currentIndex] = url
} else if (replaceEntry) { } else if (replaceEntry) {
// Non-user initialized navigation. // Non-user initialized navigation.
return this.history[this.currentIndex] = url; return this.history[this.currentIndex] = url
} else { } else {
// Normal navigation. Clear history. // Normal navigation. Clear history.
this.history = this.history.slice(0, this.currentIndex + 1); this.history = this.history.slice(0, this.currentIndex + 1)
currentEntry = this.history[this.currentIndex]; currentEntry = this.history[this.currentIndex]
if ((currentEntry != null ? currentEntry.url : void 0) !== url) { if ((currentEntry != null ? currentEntry.url : void 0) !== url) {
this.currentIndex++; this.currentIndex++
return this.history.push(url); return this.history.push(url)
} }
} }
}); })
} }
NavigationController.prototype.loadURL = function(url, options) { NavigationController.prototype.loadURL = function (url, options) {
if (options == null) { if (options == null) {
options = {}; options = {}
}
this.pendingIndex = -1
this.webContents._loadURL(url, options)
return this.webContents.emit('load-url', url, options)
} }
this.pendingIndex = -1;
this.webContents._loadURL(url, options);
return this.webContents.emit('load-url', url, options);
};
NavigationController.prototype.getURL = function() { NavigationController.prototype.getURL = function () {
if (this.currentIndex === -1) { if (this.currentIndex === -1) {
return ''; return ''
} else { } else {
return this.history[this.currentIndex]; return this.history[this.currentIndex]
}
} }
};
NavigationController.prototype.stop = function() { NavigationController.prototype.stop = function () {
this.pendingIndex = -1; this.pendingIndex = -1
return this.webContents._stop(); return this.webContents._stop()
}; }
NavigationController.prototype.reload = function() { NavigationController.prototype.reload = function () {
this.pendingIndex = this.currentIndex; this.pendingIndex = this.currentIndex
return this.webContents._loadURL(this.getURL(), {}); return this.webContents._loadURL(this.getURL(), {})
}; }
NavigationController.prototype.reloadIgnoringCache = function() { NavigationController.prototype.reloadIgnoringCache = function () {
this.pendingIndex = this.currentIndex; this.pendingIndex = this.currentIndex
return this.webContents._loadURL(this.getURL(), { return this.webContents._loadURL(this.getURL(), {
extraHeaders: "pragma: no-cache\n" extraHeaders: 'pragma: no-cache\n'
}); })
}; }
NavigationController.prototype.canGoBack = function() { NavigationController.prototype.canGoBack = function () {
return this.getActiveIndex() > 0; return this.getActiveIndex() > 0
}; }
NavigationController.prototype.canGoForward = function() { NavigationController.prototype.canGoForward = function () {
return this.getActiveIndex() < this.history.length - 1; return this.getActiveIndex() < this.history.length - 1
}; }
NavigationController.prototype.canGoToIndex = function(index) { NavigationController.prototype.canGoToIndex = function (index) {
return index >= 0 && index < this.history.length; return index >= 0 && index < this.history.length
}; }
NavigationController.prototype.canGoToOffset = function(offset) { NavigationController.prototype.canGoToOffset = function (offset) {
return this.canGoToIndex(this.currentIndex + offset); return this.canGoToIndex(this.currentIndex + offset)
}; }
NavigationController.prototype.clearHistory = function() { NavigationController.prototype.clearHistory = function () {
this.history = []; this.history = []
this.currentIndex = -1; this.currentIndex = -1
this.pendingIndex = -1; this.pendingIndex = -1
return this.inPageIndex = -1; return this.inPageIndex = -1
}; }
NavigationController.prototype.goBack = function() { NavigationController.prototype.goBack = function () {
if (!this.canGoBack()) { if (!this.canGoBack()) {
return; return
} }
this.pendingIndex = this.getActiveIndex() - 1; this.pendingIndex = this.getActiveIndex() - 1
if (this.inPageIndex > -1 && this.pendingIndex >= this.inPageIndex) { if (this.inPageIndex > -1 && this.pendingIndex >= this.inPageIndex) {
return this.webContents._goBack(); return this.webContents._goBack()
} else { } else {
return this.webContents._loadURL(this.history[this.pendingIndex], {}); return this.webContents._loadURL(this.history[this.pendingIndex], {})
}
} }
};
NavigationController.prototype.goForward = function() { NavigationController.prototype.goForward = function () {
if (!this.canGoForward()) { if (!this.canGoForward()) {
return; return
} }
this.pendingIndex = this.getActiveIndex() + 1; this.pendingIndex = this.getActiveIndex() + 1
if (this.inPageIndex > -1 && this.pendingIndex >= this.inPageIndex) { if (this.inPageIndex > -1 && this.pendingIndex >= this.inPageIndex) {
return this.webContents._goForward(); return this.webContents._goForward()
} else { } else {
return this.webContents._loadURL(this.history[this.pendingIndex], {}); return this.webContents._loadURL(this.history[this.pendingIndex], {})
}
} }
};
NavigationController.prototype.goToIndex = function(index) { NavigationController.prototype.goToIndex = function (index) {
if (!this.canGoToIndex(index)) { if (!this.canGoToIndex(index)) {
return; return
}
this.pendingIndex = index
return this.webContents._loadURL(this.history[this.pendingIndex], {})
} }
this.pendingIndex = index;
return this.webContents._loadURL(this.history[this.pendingIndex], {});
};
NavigationController.prototype.goToOffset = function(offset) { NavigationController.prototype.goToOffset = function (offset) {
var pendingIndex; var pendingIndex
if (!this.canGoToOffset(offset)) { if (!this.canGoToOffset(offset)) {
return; return
} }
pendingIndex = this.currentIndex + offset; pendingIndex = this.currentIndex + offset
if (this.inPageIndex > -1 && pendingIndex >= this.inPageIndex) { if (this.inPageIndex > -1 && pendingIndex >= this.inPageIndex) {
this.pendingIndex = pendingIndex; this.pendingIndex = pendingIndex
return this.webContents._goToOffset(offset); return this.webContents._goToOffset(offset)
} else { } else {
return this.goToIndex(pendingIndex); return this.goToIndex(pendingIndex)
}
} }
};
NavigationController.prototype.getActiveIndex = function() { NavigationController.prototype.getActiveIndex = function () {
if (this.pendingIndex === -1) { if (this.pendingIndex === -1) {
return this.currentIndex; return this.currentIndex
} else { } else {
return this.pendingIndex; return this.pendingIndex
}
} }
};
NavigationController.prototype.length = function() { NavigationController.prototype.length = function () {
return this.history.length; return this.history.length
}; }
return NavigationController; return NavigationController
})()
})(); module.exports = NavigationController
module.exports = NavigationController;

View file

@ -1,6 +1,6 @@
const EventEmitter = require('events').EventEmitter; const EventEmitter = require('events').EventEmitter
const powerMonitor = process.atomBinding('power_monitor').powerMonitor; const powerMonitor = process.atomBinding('power_monitor').powerMonitor
powerMonitor.__proto__ = EventEmitter.prototype; powerMonitor.__proto__ = EventEmitter.prototype
module.exports = powerMonitor; module.exports = powerMonitor

View file

@ -1,5 +1,5 @@
var powerSaveBlocker; var powerSaveBlocker
powerSaveBlocker = process.atomBinding('power_save_blocker').powerSaveBlocker; powerSaveBlocker = process.atomBinding('power_save_blocker').powerSaveBlocker
module.exports = powerSaveBlocker; module.exports = powerSaveBlocker

View file

@ -1,31 +1,31 @@
const app = require('electron').app; const app = require('electron').app
if (!app.isReady()) { if (!app.isReady()) {
throw new Error('Can not initialize protocol module before app is ready'); throw new Error('Can not initialize protocol module before app is ready')
} }
const protocol = process.atomBinding('protocol').protocol; const protocol = process.atomBinding('protocol').protocol
// Warn about removed APIs. // Warn about removed APIs.
var logAndThrow = function(callback, message) { var logAndThrow = function (callback, message) {
console.error(message); console.error(message)
if (callback) { if (callback) {
return callback(new Error(message)); return callback(new Error(message))
} else { } else {
throw new Error(message); throw new Error(message)
} }
}; }
protocol.registerProtocol = function(scheme, handler, callback) { protocol.registerProtocol = function (scheme, handler, callback) {
return logAndThrow(callback, 'registerProtocol API has been replaced by the register[File/Http/Buffer/String]Protocol API family, please switch to the new APIs.'); return logAndThrow(callback, 'registerProtocol API has been replaced by the register[File/Http/Buffer/String]Protocol API family, please switch to the new APIs.')
}; }
protocol.isHandledProtocol = function(scheme, callback) { protocol.isHandledProtocol = function (scheme, callback) {
return logAndThrow(callback, 'isHandledProtocol API has been replaced by isProtocolHandled.'); return logAndThrow(callback, 'isHandledProtocol API has been replaced by isProtocolHandled.')
}; }
protocol.interceptProtocol = function(scheme, handler, callback) { protocol.interceptProtocol = function (scheme, handler, callback) {
return logAndThrow(callback, 'interceptProtocol API has been replaced by the intercept[File/Http/Buffer/String]Protocol API family, please switch to the new APIs.'); return logAndThrow(callback, 'interceptProtocol API has been replaced by the intercept[File/Http/Buffer/String]Protocol API family, please switch to the new APIs.')
}; }
module.exports = protocol; module.exports = protocol

View file

@ -1,6 +1,6 @@
const EventEmitter = require('events').EventEmitter; const EventEmitter = require('events').EventEmitter
const screen = process.atomBinding('screen').screen; const screen = process.atomBinding('screen').screen
screen.__proto__ = EventEmitter.prototype; screen.__proto__ = EventEmitter.prototype
module.exports = screen; module.exports = screen

View file

@ -1,33 +1,33 @@
const EventEmitter = require('events').EventEmitter; const EventEmitter = require('events').EventEmitter
const bindings = process.atomBinding('session'); const bindings = process.atomBinding('session')
const PERSIST_PREFIX = 'persist:'; const PERSIST_PREFIX = 'persist:'
// Returns the Session from |partition| string. // Returns the Session from |partition| string.
exports.fromPartition = function(partition) { exports.fromPartition = function (partition) {
if (partition == null) { if (partition == null) {
partition = ''; partition = ''
} }
if (partition === '') { if (partition === '') {
return exports.defaultSession; return exports.defaultSession
} }
if (partition.startsWith(PERSIST_PREFIX)) { if (partition.startsWith(PERSIST_PREFIX)) {
return bindings.fromPartition(partition.substr(PERSIST_PREFIX.length), false); return bindings.fromPartition(partition.substr(PERSIST_PREFIX.length), false)
} else { } else {
return bindings.fromPartition(partition, true); return bindings.fromPartition(partition, true)
} }
}; }
// Returns the default session. // Returns the default session.
Object.defineProperty(exports, 'defaultSession', { Object.defineProperty(exports, 'defaultSession', {
enumerable: true, enumerable: true,
get: function() { get: function () {
return bindings.fromPartition('', false); return bindings.fromPartition('', false)
} }
}); })
var wrapSession = function(session) { var wrapSession = function (session) {
// session is an EventEmitter. // session is an EventEmitter.
return session.__proto__ = EventEmitter.prototype; return session.__proto__ = EventEmitter.prototype
}; }
bindings._setWrapSession(wrapSession); bindings._setWrapSession(wrapSession)

View file

@ -1,23 +1,23 @@
const deprecate = require('electron').deprecate; const deprecate = require('electron').deprecate
const EventEmitter = require('events').EventEmitter; const EventEmitter = require('events').EventEmitter
const Tray = process.atomBinding('tray').Tray; const Tray = process.atomBinding('tray').Tray
Tray.prototype.__proto__ = EventEmitter.prototype; Tray.prototype.__proto__ = EventEmitter.prototype
Tray.prototype._init = function() { Tray.prototype._init = function () {
// Deprecated. // Deprecated.
deprecate.rename(this, 'popContextMenu', 'popUpContextMenu'); deprecate.rename(this, 'popContextMenu', 'popUpContextMenu')
deprecate.event(this, 'clicked', 'click'); deprecate.event(this, 'clicked', 'click')
deprecate.event(this, 'double-clicked', 'double-click'); deprecate.event(this, 'double-clicked', 'double-click')
deprecate.event(this, 'right-clicked', 'right-click'); deprecate.event(this, 'right-clicked', 'right-click')
return deprecate.event(this, 'balloon-clicked', 'balloon-click'); return deprecate.event(this, 'balloon-clicked', 'balloon-click')
}; }
Tray.prototype.setContextMenu = function(menu) { Tray.prototype.setContextMenu = function (menu) {
this._setContextMenu(menu); this._setContextMenu(menu)
// Keep a strong reference of menu. // Keep a strong reference of menu.
return this.menu = menu; return this.menu = menu
}; }
module.exports = Tray; module.exports = Tray

View file

@ -1,59 +1,59 @@
'use strict'; 'use strict'
const EventEmitter = require('events').EventEmitter; const EventEmitter = require('events').EventEmitter
const deprecate = require('electron').deprecate; const deprecate = require('electron').deprecate
const ipcMain = require('electron').ipcMain; const ipcMain = require('electron').ipcMain
const NavigationController = require('electron').NavigationController; const NavigationController = require('electron').NavigationController
const Menu = require('electron').Menu; const Menu = require('electron').Menu
const binding = process.atomBinding('web_contents'); const binding = process.atomBinding('web_contents')
const debuggerBinding = process.atomBinding('debugger'); const debuggerBinding = process.atomBinding('debugger')
let nextId = 0; let nextId = 0
let getNextId = function() { let getNextId = function () {
return ++nextId; return ++nextId
}; }
let PDFPageSize = { let PDFPageSize = {
A5: { A5: {
custom_display_name: "A5", custom_display_name: 'A5',
height_microns: 210000, height_microns: 210000,
name: "ISO_A5", name: 'ISO_A5',
width_microns: 148000 width_microns: 148000
}, },
A4: { A4: {
custom_display_name: "A4", custom_display_name: 'A4',
height_microns: 297000, height_microns: 297000,
name: "ISO_A4", name: 'ISO_A4',
is_default: "true", is_default: 'true',
width_microns: 210000 width_microns: 210000
}, },
A3: { A3: {
custom_display_name: "A3", custom_display_name: 'A3',
height_microns: 420000, height_microns: 420000,
name: "ISO_A3", name: 'ISO_A3',
width_microns: 297000 width_microns: 297000
}, },
Legal: { Legal: {
custom_display_name: "Legal", custom_display_name: 'Legal',
height_microns: 355600, height_microns: 355600,
name: "NA_LEGAL", name: 'NA_LEGAL',
width_microns: 215900 width_microns: 215900
}, },
Letter: { Letter: {
custom_display_name: "Letter", custom_display_name: 'Letter',
height_microns: 279400, height_microns: 279400,
name: "NA_LETTER", name: 'NA_LETTER',
width_microns: 215900 width_microns: 215900
}, },
Tabloid: { Tabloid: {
height_microns: 431800, height_microns: 431800,
name: "NA_LEDGER", name: 'NA_LEDGER',
width_microns: 279400, width_microns: 279400,
custom_display_name: "Tabloid" custom_display_name: 'Tabloid'
} }
}; }
// Following methods are mapped to webFrame. // Following methods are mapped to webFrame.
const webFrameMethods = [ const webFrameMethods = [
@ -61,112 +61,112 @@ const webFrameMethods = [
'setZoomFactor', 'setZoomFactor',
'setZoomLevel', 'setZoomLevel',
'setZoomLevelLimits' 'setZoomLevelLimits'
]; ]
let wrapWebContents = function(webContents) { let wrapWebContents = function (webContents) {
// webContents is an EventEmitter. // webContents is an EventEmitter.
var controller, method, name, ref1; var controller, method, name, ref1
webContents.__proto__ = EventEmitter.prototype; webContents.__proto__ = EventEmitter.prototype
// Every remote callback from renderer process would add a listenter to the // Every remote callback from renderer process would add a listenter to the
// render-view-deleted event, so ignore the listenters warning. // render-view-deleted event, so ignore the listenters warning.
webContents.setMaxListeners(0); webContents.setMaxListeners(0)
// WebContents::send(channel, args..) // WebContents::send(channel, args..)
webContents.send = function(channel, ...args) { webContents.send = function (channel, ...args) {
if (channel == null) { if (channel == null) {
throw new Error('Missing required channel argument'); throw new Error('Missing required channel argument')
}
return this._send(channel, args)
} }
return this._send(channel, args);
};
// The navigation controller. // The navigation controller.
controller = new NavigationController(webContents); controller = new NavigationController(webContents)
ref1 = NavigationController.prototype; ref1 = NavigationController.prototype
for (name in ref1) { for (name in ref1) {
method = ref1[name]; method = ref1[name]
if (method instanceof Function) { if (method instanceof Function) {
(function(name, method) { (function (name, method) {
return webContents[name] = function() { return webContents[name] = function () {
return method.apply(controller, arguments); return method.apply(controller, arguments)
}; }
})(name, method); })(name, method)
} }
} }
// Mapping webFrame methods. // Mapping webFrame methods.
for (let method of webFrameMethods) { for (let method of webFrameMethods) {
webContents[method] = function(...args) { webContents[method] = function (...args) {
this.send('ELECTRON_INTERNAL_RENDERER_WEB_FRAME_METHOD', method, args); this.send('ELECTRON_INTERNAL_RENDERER_WEB_FRAME_METHOD', method, args)
}; }
} }
const asyncWebFrameMethods = function(requestId, method, callback, ...args) { const asyncWebFrameMethods = function (requestId, method, callback, ...args) {
this.send('ELECTRON_INTERNAL_RENDERER_ASYNC_WEB_FRAME_METHOD', requestId, method, args); this.send('ELECTRON_INTERNAL_RENDERER_ASYNC_WEB_FRAME_METHOD', requestId, method, args)
ipcMain.once(`ELECTRON_INTERNAL_BROWSER_ASYNC_WEB_FRAME_RESPONSE_${requestId}`, function(event, result) { ipcMain.once(`ELECTRON_INTERNAL_BROWSER_ASYNC_WEB_FRAME_RESPONSE_${requestId}`, function (event, result) {
if (callback) if (callback)
callback(result); callback(result)
}); })
}; }
// Make sure webContents.executeJavaScript would run the code only when the // Make sure webContents.executeJavaScript would run the code only when the
// webContents has been loaded. // webContents has been loaded.
webContents.executeJavaScript = function(code, hasUserGesture, callback) { webContents.executeJavaScript = function (code, hasUserGesture, callback) {
let requestId = getNextId(); let requestId = getNextId()
if (typeof hasUserGesture === "function") { if (typeof hasUserGesture === 'function') {
callback = hasUserGesture; callback = hasUserGesture
hasUserGesture = false; hasUserGesture = false
} }
if (this.getURL() && !this.isLoading()) if (this.getURL() && !this.isLoading())
return asyncWebFrameMethods.call(this, requestId, "executeJavaScript", callback, code, hasUserGesture); return asyncWebFrameMethods.call(this, requestId, 'executeJavaScript', callback, code, hasUserGesture)
else else
return this.once('did-finish-load', asyncWebFrameMethods.bind(this, requestId, "executeJavaScript", callback, code, hasUserGesture)); return this.once('did-finish-load', asyncWebFrameMethods.bind(this, requestId, 'executeJavaScript', callback, code, hasUserGesture))
}; }
// Dispatch IPC messages to the ipc module. // Dispatch IPC messages to the ipc module.
webContents.on('ipc-message', function(event, [channel, ...args]) { webContents.on('ipc-message', function (event, [channel, ...args]) {
return ipcMain.emit.apply(ipcMain, [channel, event].concat(args)); return ipcMain.emit.apply(ipcMain, [channel, event].concat(args))
}); })
webContents.on('ipc-message-sync', function(event, [channel, ...args]) { webContents.on('ipc-message-sync', function (event, [channel, ...args]) {
Object.defineProperty(event, 'returnValue', { Object.defineProperty(event, 'returnValue', {
set: function(value) { set: function (value) {
return event.sendReply(JSON.stringify(value)); return event.sendReply(JSON.stringify(value))
} }
}); })
return ipcMain.emit.apply(ipcMain, [channel, event].concat(args)); return ipcMain.emit.apply(ipcMain, [channel, event].concat(args))
}); })
// Handle context menu action request from pepper plugin. // Handle context menu action request from pepper plugin.
webContents.on('pepper-context-menu', function(event, params) { webContents.on('pepper-context-menu', function (event, params) {
var menu; var menu
menu = Menu.buildFromTemplate(params.menu); menu = Menu.buildFromTemplate(params.menu)
return menu.popup(params.x, params.y); return menu.popup(params.x, params.y)
}); })
// This error occurs when host could not be found. // This error occurs when host could not be found.
webContents.on('did-fail-provisional-load', function(...args) { webContents.on('did-fail-provisional-load', function (...args) {
// Calling loadURL during this event might cause crash, so delay the event // Calling loadURL during this event might cause crash, so delay the event
// until next tick. // until next tick.
setImmediate(() => { setImmediate(() => {
this.emit.apply(this, ['did-fail-load'].concat(args)); this.emit.apply(this, ['did-fail-load'].concat(args))
}); })
}); })
// Delays the page-title-updated event to next tick. // Delays the page-title-updated event to next tick.
webContents.on('-page-title-updated', function(...args) { webContents.on('-page-title-updated', function (...args) {
setImmediate(() => { setImmediate(() => {
this.emit.apply(this, ['page-title-updated'].concat(args)); this.emit.apply(this, ['page-title-updated'].concat(args))
}); })
}); })
// Deprecated. // Deprecated.
deprecate.rename(webContents, 'loadUrl', 'loadURL'); deprecate.rename(webContents, 'loadUrl', 'loadURL')
deprecate.rename(webContents, 'getUrl', 'getURL'); deprecate.rename(webContents, 'getUrl', 'getURL')
deprecate.event(webContents, 'page-title-set', 'page-title-updated', function(...args) { deprecate.event(webContents, 'page-title-set', 'page-title-updated', function (...args) {
return this.emit.apply(this, ['page-title-set'].concat(args)); return this.emit.apply(this, ['page-title-set'].concat(args))
}); })
return webContents.printToPDF = function(options, callback) { return webContents.printToPDF = function (options, callback) {
var printingSetting; var printingSetting
printingSetting = { printingSetting = {
pageRage: [], pageRage: [],
mediaSize: {}, mediaSize: {},
@ -181,7 +181,7 @@ let wrapWebContents = function(webContents) {
printWithCloudPrint: false, printWithCloudPrint: false,
printWithPrivet: false, printWithPrivet: false,
printWithExtension: false, printWithExtension: false,
deviceName: "Save as PDF", deviceName: 'Save as PDF',
generateDraftData: true, generateDraftData: true,
fitToPageEnabled: false, fitToPageEnabled: false,
duplex: 0, duplex: 0,
@ -189,40 +189,40 @@ let wrapWebContents = function(webContents) {
collate: true, collate: true,
shouldPrintBackgrounds: false, shouldPrintBackgrounds: false,
shouldPrintSelectionOnly: false shouldPrintSelectionOnly: false
}; }
if (options.landscape) { if (options.landscape) {
printingSetting.landscape = options.landscape; printingSetting.landscape = options.landscape
} }
if (options.marginsType) { if (options.marginsType) {
printingSetting.marginsType = options.marginsType; printingSetting.marginsType = options.marginsType
} }
if (options.printSelectionOnly) { if (options.printSelectionOnly) {
printingSetting.shouldPrintSelectionOnly = options.printSelectionOnly; printingSetting.shouldPrintSelectionOnly = options.printSelectionOnly
} }
if (options.printBackground) { if (options.printBackground) {
printingSetting.shouldPrintBackgrounds = options.printBackground; printingSetting.shouldPrintBackgrounds = options.printBackground
} }
if (options.pageSize && PDFPageSize[options.pageSize]) { if (options.pageSize && PDFPageSize[options.pageSize]) {
printingSetting.mediaSize = PDFPageSize[options.pageSize]; printingSetting.mediaSize = PDFPageSize[options.pageSize]
} else { } else {
printingSetting.mediaSize = PDFPageSize['A4']; printingSetting.mediaSize = PDFPageSize['A4']
} }
return this._printToPDF(printingSetting, callback); return this._printToPDF(printingSetting, callback)
}; }
}; }
// Wrapper for native class. // Wrapper for native class.
let wrapDebugger = function(webContentsDebugger) { let wrapDebugger = function (webContentsDebugger) {
// debugger is an EventEmitter. // debugger is an EventEmitter.
webContentsDebugger.__proto__ = EventEmitter.prototype; webContentsDebugger.__proto__ = EventEmitter.prototype
}; }
binding._setWrapWebContents(wrapWebContents); binding._setWrapWebContents(wrapWebContents)
debuggerBinding._setWrapDebugger(wrapDebugger); debuggerBinding._setWrapDebugger(wrapDebugger)
module.exports.create = function(options) { module.exports.create = function (options) {
if (options == null) { if (options == null) {
options = {}; options = {}
} }
return binding.create(options); return binding.create(options)
}; }

View file

@ -1,32 +1,31 @@
const electron = require('electron'); const electron = require('electron')
const app = electron.app; const app = electron.app
const fs = require('fs'); const fs = require('fs')
const path = require('path'); const path = require('path')
const url = require('url'); const url = require('url')
// Mapping between hostname and file path. // Mapping between hostname and file path.
var hostPathMap = {}; var hostPathMap = {}
var hostPathMapNextKey = 0; var hostPathMapNextKey = 0
var getHostForPath = function(path) { var getHostForPath = function (path) {
var key; var key
key = "extension-" + (++hostPathMapNextKey); key = 'extension-' + (++hostPathMapNextKey)
hostPathMap[key] = path; hostPathMap[key] = path
return key; return key
}; }
var getPathForHost = function(host) { var getPathForHost = function (host) {
return hostPathMap[host]; return hostPathMap[host]
}; }
// Cache extensionInfo. // Cache extensionInfo.
var extensionInfoMap = {}; var extensionInfoMap = {}
var getExtensionInfoFromPath = function(srcDirectory) { var getExtensionInfoFromPath = function (srcDirectory) {
var manifest, page; var manifest, page
manifest = JSON.parse(fs.readFileSync(path.join(srcDirectory, 'manifest.json'))); manifest = JSON.parse(fs.readFileSync(path.join(srcDirectory, 'manifest.json')))
if (extensionInfoMap[manifest.name] == null) { if (extensionInfoMap[manifest.name] == null) {
// We can not use 'file://' directly because all resources in the extension // We can not use 'file://' directly because all resources in the extension
// will be treated as relative to the root in Chrome. // will be treated as relative to the root in Chrome.
page = url.format({ page = url.format({
@ -34,112 +33,112 @@ var getExtensionInfoFromPath = function(srcDirectory) {
slashes: true, slashes: true,
hostname: getHostForPath(srcDirectory), hostname: getHostForPath(srcDirectory),
pathname: manifest.devtools_page pathname: manifest.devtools_page
}); })
extensionInfoMap[manifest.name] = { extensionInfoMap[manifest.name] = {
startPage: page, startPage: page,
name: manifest.name, name: manifest.name,
srcDirectory: srcDirectory, srcDirectory: srcDirectory,
exposeExperimentalAPIs: true exposeExperimentalAPIs: true
};
return extensionInfoMap[manifest.name];
} }
}; return extensionInfoMap[manifest.name]
}
}
// The loaded extensions cache and its persistent path. // The loaded extensions cache and its persistent path.
var loadedExtensions = null; var loadedExtensions = null
var loadedExtensionsPath = null; var loadedExtensionsPath = null
app.on('will-quit', function() { app.on('will-quit', function () {
try { try {
loadedExtensions = Object.keys(extensionInfoMap).map(function(key) { loadedExtensions = Object.keys(extensionInfoMap).map(function (key) {
return extensionInfoMap[key].srcDirectory; return extensionInfoMap[key].srcDirectory
}); })
if (loadedExtensions.length > 0) { if (loadedExtensions.length > 0) {
try { try {
fs.mkdirSync(path.dirname(loadedExtensionsPath)); fs.mkdirSync(path.dirname(loadedExtensionsPath))
} catch (error) { } catch (error) {
// Ignore error // Ignore error
} }
fs.writeFileSync(loadedExtensionsPath, JSON.stringify(loadedExtensions)); fs.writeFileSync(loadedExtensionsPath, JSON.stringify(loadedExtensions))
} else { } else {
fs.unlinkSync(loadedExtensionsPath); fs.unlinkSync(loadedExtensionsPath)
} }
} catch (error) { } catch (error) {
// Ignore error // Ignore error
} }
}); })
// We can not use protocol or BrowserWindow until app is ready. // We can not use protocol or BrowserWindow until app is ready.
app.once('ready', function() { app.once('ready', function () {
var BrowserWindow, chromeExtensionHandler, i, init, len, protocol, srcDirectory; var BrowserWindow, chromeExtensionHandler, i, init, len, protocol, srcDirectory
protocol = electron.protocol, BrowserWindow = electron.BrowserWindow; protocol = electron.protocol, BrowserWindow = electron.BrowserWindow
// Load persisted extensions. // Load persisted extensions.
loadedExtensionsPath = path.join(app.getPath('userData'), 'DevTools Extensions'); loadedExtensionsPath = path.join(app.getPath('userData'), 'DevTools Extensions')
try { try {
loadedExtensions = JSON.parse(fs.readFileSync(loadedExtensionsPath)); loadedExtensions = JSON.parse(fs.readFileSync(loadedExtensionsPath))
if (!Array.isArray(loadedExtensions)) { if (!Array.isArray(loadedExtensions)) {
loadedExtensions = []; loadedExtensions = []
} }
// Preheat the extensionInfo cache. // Preheat the extensionInfo cache.
for (i = 0, len = loadedExtensions.length; i < len; i++) { for (i = 0, len = loadedExtensions.length; i < len; i++) {
srcDirectory = loadedExtensions[i]; srcDirectory = loadedExtensions[i]
getExtensionInfoFromPath(srcDirectory); getExtensionInfoFromPath(srcDirectory)
} }
} catch (error) { } catch (error) {
// Ignore error // Ignore error
} }
// The chrome-extension: can map a extension URL request to real file path. // The chrome-extension: can map a extension URL request to real file path.
chromeExtensionHandler = function(request, callback) { chromeExtensionHandler = function (request, callback) {
var directory, parsed; var directory, parsed
parsed = url.parse(request.url); parsed = url.parse(request.url)
if (!(parsed.hostname && (parsed.path != null))) { if (!(parsed.hostname && (parsed.path != null))) {
return callback(); return callback()
} }
if (!/extension-\d+/.test(parsed.hostname)) { if (!/extension-\d+/.test(parsed.hostname)) {
return callback(); return callback()
} }
directory = getPathForHost(parsed.hostname); directory = getPathForHost(parsed.hostname)
if (directory == null) { if (directory == null) {
return callback(); return callback()
} }
return callback(path.join(directory, parsed.path)); return callback(path.join(directory, parsed.path))
}; }
protocol.registerFileProtocol('chrome-extension', chromeExtensionHandler, function(error) { protocol.registerFileProtocol('chrome-extension', chromeExtensionHandler, function (error) {
if (error) { if (error) {
return console.error('Unable to register chrome-extension protocol'); return console.error('Unable to register chrome-extension protocol')
} }
}); })
BrowserWindow.prototype._loadDevToolsExtensions = function(extensionInfoArray) { BrowserWindow.prototype._loadDevToolsExtensions = function (extensionInfoArray) {
var ref; var ref
return (ref = this.devToolsWebContents) != null ? ref.executeJavaScript("DevToolsAPI.addExtensions(" + (JSON.stringify(extensionInfoArray)) + ");") : void 0; return (ref = this.devToolsWebContents) != null ? ref.executeJavaScript('DevToolsAPI.addExtensions(' + (JSON.stringify(extensionInfoArray)) + ');') : void 0
}; }
BrowserWindow.addDevToolsExtension = function(srcDirectory) { BrowserWindow.addDevToolsExtension = function (srcDirectory) {
var extensionInfo, j, len1, ref, window; var extensionInfo, j, len1, ref, window
extensionInfo = getExtensionInfoFromPath(srcDirectory); extensionInfo = getExtensionInfoFromPath(srcDirectory)
if (extensionInfo) { if (extensionInfo) {
ref = BrowserWindow.getAllWindows(); ref = BrowserWindow.getAllWindows()
for (j = 0, len1 = ref.length; j < len1; j++) { for (j = 0, len1 = ref.length; j < len1; j++) {
window = ref[j]; window = ref[j]
window._loadDevToolsExtensions([extensionInfo]); window._loadDevToolsExtensions([extensionInfo])
} }
return extensionInfo.name; return extensionInfo.name
}
}
BrowserWindow.removeDevToolsExtension = function (name) {
return delete extensionInfoMap[name]
} }
};
BrowserWindow.removeDevToolsExtension = function(name) {
return delete extensionInfoMap[name];
};
// Load persisted extensions when devtools is opened. // Load persisted extensions when devtools is opened.
init = BrowserWindow.prototype._init; init = BrowserWindow.prototype._init
return BrowserWindow.prototype._init = function() { return BrowserWindow.prototype._init = function () {
init.call(this); init.call(this)
return this.on('devtools-opened', function() { return this.on('devtools-opened', function () {
return this._loadDevToolsExtensions(Object.keys(extensionInfoMap).map(function(key) { return this._loadDevToolsExtensions(Object.keys(extensionInfoMap).map(function (key) {
return extensionInfoMap[key]; return extensionInfoMap[key]
})); }))
}); })
}; }
}); })

View file

@ -1,17 +1,17 @@
'use strict'; 'use strict'
const ipcMain = require('electron').ipcMain; const ipcMain = require('electron').ipcMain
const desktopCapturer = process.atomBinding('desktop_capturer').desktopCapturer; const desktopCapturer = process.atomBinding('desktop_capturer').desktopCapturer
var deepEqual = function(opt1, opt2) { var deepEqual = function (opt1, opt2) {
return JSON.stringify(opt1) === JSON.stringify(opt2); return JSON.stringify(opt1) === JSON.stringify(opt2)
}; }
// A queue for holding all requests from renderer process. // A queue for holding all requests from renderer process.
var requestsQueue = []; var requestsQueue = []
ipcMain.on('ATOM_BROWSER_DESKTOP_CAPTURER_GET_SOURCES', function(event, captureWindow, captureScreen, thumbnailSize, id) { ipcMain.on('ATOM_BROWSER_DESKTOP_CAPTURER_GET_SOURCES', function (event, captureWindow, captureScreen, thumbnailSize, id) {
var request; var request
request = { request = {
id: id, id: id,
options: { options: {
@ -20,58 +20,58 @@ ipcMain.on('ATOM_BROWSER_DESKTOP_CAPTURER_GET_SOURCES', function(event, captureW
thumbnailSize: thumbnailSize thumbnailSize: thumbnailSize
}, },
webContents: event.sender webContents: event.sender
}; }
requestsQueue.push(request); requestsQueue.push(request)
if (requestsQueue.length === 1) { if (requestsQueue.length === 1) {
desktopCapturer.startHandling(captureWindow, captureScreen, thumbnailSize); desktopCapturer.startHandling(captureWindow, captureScreen, thumbnailSize)
} }
// If the WebContents is destroyed before receiving result, just remove the // If the WebContents is destroyed before receiving result, just remove the
// reference from requestsQueue to make the module not send the result to it. // reference from requestsQueue to make the module not send the result to it.
return event.sender.once('destroyed', function() { return event.sender.once('destroyed', function () {
return request.webContents = null; return request.webContents = null
}); })
}); })
desktopCapturer.emit = function(event, name, sources) { desktopCapturer.emit = function (event, name, sources) {
// Receiving sources result from main process, now send them back to renderer. // Receiving sources result from main process, now send them back to renderer.
var handledRequest, i, len, ref, ref1, request, result, source, unhandledRequestsQueue; var handledRequest, i, len, ref, ref1, request, result, source, unhandledRequestsQueue
handledRequest = requestsQueue.shift(0); handledRequest = requestsQueue.shift(0)
result = (function() { result = (function () {
var i, len, results; var i, len, results
results = []; results = []
for (i = 0, len = sources.length; i < len; i++) { for (i = 0, len = sources.length; i < len; i++) {
source = sources[i]; source = sources[i]
results.push({ results.push({
id: source.id, id: source.id,
name: source.name, name: source.name,
thumbnail: source.thumbnail.toDataUrl() thumbnail: source.thumbnail.toDataUrl()
}); })
} }
return results; return results
})(); })()
if ((ref = handledRequest.webContents) != null) { if ((ref = handledRequest.webContents) != null) {
ref.send("ATOM_RENDERER_DESKTOP_CAPTURER_RESULT_" + handledRequest.id, result); ref.send('ATOM_RENDERER_DESKTOP_CAPTURER_RESULT_' + handledRequest.id, result)
} }
// Check the queue to see whether there is other same request. If has, handle // Check the queue to see whether there is other same request. If has, handle
// it for reducing redunplicated `desktopCaptuer.startHandling` calls. // it for reducing redunplicated `desktopCaptuer.startHandling` calls.
unhandledRequestsQueue = []; unhandledRequestsQueue = []
for (i = 0, len = requestsQueue.length; i < len; i++) { for (i = 0, len = requestsQueue.length; i < len; i++) {
request = requestsQueue[i]; request = requestsQueue[i]
if (deepEqual(handledRequest.options, request.options)) { if (deepEqual(handledRequest.options, request.options)) {
if ((ref1 = request.webContents) != null) { if ((ref1 = request.webContents) != null) {
ref1.send("ATOM_RENDERER_DESKTOP_CAPTURER_RESULT_" + request.id, result); ref1.send('ATOM_RENDERER_DESKTOP_CAPTURER_RESULT_' + request.id, result)
} }
} else { } else {
unhandledRequestsQueue.push(request); unhandledRequestsQueue.push(request)
} }
} }
requestsQueue = unhandledRequestsQueue; requestsQueue = unhandledRequestsQueue
// If the requestsQueue is not empty, start a new request handling. // If the requestsQueue is not empty, start a new request handling.
if (requestsQueue.length > 0) { if (requestsQueue.length > 0) {
const {captureWindow, captureScreen, thumbnailSize} = requestsQueue[0].options; const {captureWindow, captureScreen, thumbnailSize} = requestsQueue[0].options
return desktopCapturer.startHandling(captureWindow, captureScreen, thumbnailSize); return desktopCapturer.startHandling(captureWindow, captureScreen, thumbnailSize)
} }
}; }

View file

@ -1,10 +1,10 @@
'use strict'; 'use strict'
const ipcMain = require('electron').ipcMain; const ipcMain = require('electron').ipcMain
const webContents = require('electron').webContents; const webContents = require('electron').webContents
// Doesn't exist in early initialization. // Doesn't exist in early initialization.
var webViewManager = null; var webViewManager = null
var supportedWebViewEvents = [ var supportedWebViewEvents = [
'load-commit', 'load-commit',
@ -37,75 +37,75 @@ var supportedWebViewEvents = [
'media-paused', 'media-paused',
'found-in-page', 'found-in-page',
'did-change-theme-color' 'did-change-theme-color'
]; ]
var nextInstanceId = 0; var nextInstanceId = 0
var guestInstances = {}; var guestInstances = {}
var embedderElementsMap = {}; var embedderElementsMap = {}
var reverseEmbedderElementsMap = {}; var reverseEmbedderElementsMap = {}
// Moves the last element of array to the first one. // Moves the last element of array to the first one.
var moveLastToFirst = function(list) { var moveLastToFirst = function (list) {
return list.unshift(list.pop()); return list.unshift(list.pop())
}; }
// Generate guestInstanceId. // Generate guestInstanceId.
var getNextInstanceId = function() { var getNextInstanceId = function () {
return ++nextInstanceId; return ++nextInstanceId
}; }
// Create a new guest instance. // Create a new guest instance.
var createGuest = function(embedder, params) { var createGuest = function (embedder, params) {
var destroy, destroyEvents, event, fn, guest, i, id, j, len, len1, listeners; var destroy, destroyEvents, event, fn, guest, i, id, j, len, len1, listeners
if (webViewManager == null) { if (webViewManager == null) {
webViewManager = process.atomBinding('web_view_manager'); webViewManager = process.atomBinding('web_view_manager')
} }
id = getNextInstanceId(embedder); id = getNextInstanceId(embedder)
guest = webContents.create({ guest = webContents.create({
isGuest: true, isGuest: true,
partition: params.partition, partition: params.partition,
embedder: embedder embedder: embedder
}); })
guestInstances[id] = { guestInstances[id] = {
guest: guest, guest: guest,
embedder: embedder embedder: embedder
}; }
// Destroy guest when the embedder is gone or navigated. // Destroy guest when the embedder is gone or navigated.
destroyEvents = ['will-destroy', 'crashed', 'did-navigate']; destroyEvents = ['will-destroy', 'crashed', 'did-navigate']
destroy = function() { destroy = function () {
if (guestInstances[id] != null) { if (guestInstances[id] != null) {
return destroyGuest(embedder, id); return destroyGuest(embedder, id)
}
} }
};
for (i = 0, len = destroyEvents.length; i < len; i++) { for (i = 0, len = destroyEvents.length; i < len; i++) {
event = destroyEvents[i]; event = destroyEvents[i]
embedder.once(event, destroy); embedder.once(event, destroy)
// Users might also listen to the crashed event, so We must ensure the guest // Users might also listen to the crashed event, so We must ensure the guest
// is destroyed before users' listener gets called. It is done by moving our // is destroyed before users' listener gets called. It is done by moving our
// listener to the first one in queue. // listener to the first one in queue.
listeners = embedder._events[event]; listeners = embedder._events[event]
if (Array.isArray(listeners)) { if (Array.isArray(listeners)) {
moveLastToFirst(listeners); moveLastToFirst(listeners)
} }
} }
guest.once('destroyed', function() { guest.once('destroyed', function () {
var j, len1, results; var j, len1, results
results = []; results = []
for (j = 0, len1 = destroyEvents.length; j < len1; j++) { for (j = 0, len1 = destroyEvents.length; j < len1; j++) {
event = destroyEvents[j]; event = destroyEvents[j]
results.push(embedder.removeListener(event, destroy)); results.push(embedder.removeListener(event, destroy))
} }
return results; return results
}); })
// Init guest web view after attached. // Init guest web view after attached.
guest.once('did-attach', function() { guest.once('did-attach', function () {
var opts; var opts
params = this.attachParams; params = this.attachParams
delete this.attachParams; delete this.attachParams
this.viewInstanceId = params.instanceId; this.viewInstanceId = params.instanceId
this.setSize({ this.setSize({
normal: { normal: {
width: params.elementWidth, width: params.elementWidth,
@ -120,61 +120,60 @@ var createGuest = function(embedder, params) {
width: params.maxwidth, width: params.maxwidth,
height: params.maxheight height: params.maxheight
} }
}); })
if (params.src) { if (params.src) {
opts = {}; opts = {}
if (params.httpreferrer) { if (params.httpreferrer) {
opts.httpReferrer = params.httpreferrer; opts.httpReferrer = params.httpreferrer
} }
if (params.useragent) { if (params.useragent) {
opts.userAgent = params.useragent; opts.userAgent = params.useragent
} }
this.loadURL(params.src, opts); this.loadURL(params.src, opts)
} }
return guest.allowPopups = params.allowpopups; return guest.allowPopups = params.allowpopups
}); })
// Dispatch events to embedder. // Dispatch events to embedder.
fn = function(event) { fn = function (event) {
return guest.on(event, function(_, ...args) { return guest.on(event, function (_, ...args) {
return embedder.send.apply(embedder, ["ATOM_SHELL_GUEST_VIEW_INTERNAL_DISPATCH_EVENT-" + guest.viewInstanceId, event].concat(args)); return embedder.send.apply(embedder, ['ATOM_SHELL_GUEST_VIEW_INTERNAL_DISPATCH_EVENT-' + guest.viewInstanceId, event].concat(args))
}); })
}; }
for (j = 0, len1 = supportedWebViewEvents.length; j < len1; j++) { for (j = 0, len1 = supportedWebViewEvents.length; j < len1; j++) {
event = supportedWebViewEvents[j]; event = supportedWebViewEvents[j]
fn(event); fn(event)
} }
// Dispatch guest's IPC messages to embedder. // Dispatch guest's IPC messages to embedder.
guest.on('ipc-message-host', function(_, [channel, ...args]) { guest.on('ipc-message-host', function (_, [channel, ...args]) {
return embedder.send.apply(embedder, ["ATOM_SHELL_GUEST_VIEW_INTERNAL_IPC_MESSAGE-" + guest.viewInstanceId, channel].concat(args)); return embedder.send.apply(embedder, ['ATOM_SHELL_GUEST_VIEW_INTERNAL_IPC_MESSAGE-' + guest.viewInstanceId, channel].concat(args))
}); })
// Autosize. // Autosize.
guest.on('size-changed', function(_, ...args) { guest.on('size-changed', function (_, ...args) {
return embedder.send.apply(embedder, ["ATOM_SHELL_GUEST_VIEW_INTERNAL_SIZE_CHANGED-" + guest.viewInstanceId].concat(args)); return embedder.send.apply(embedder, ['ATOM_SHELL_GUEST_VIEW_INTERNAL_SIZE_CHANGED-' + guest.viewInstanceId].concat(args))
}); })
return id; return id
}; }
// Attach the guest to an element of embedder. // Attach the guest to an element of embedder.
var attachGuest = function(embedder, elementInstanceId, guestInstanceId, params) { var attachGuest = function (embedder, elementInstanceId, guestInstanceId, params) {
var guest, key, oldGuestInstanceId, ref1, webPreferences; var guest, key, oldGuestInstanceId, ref1, webPreferences
guest = guestInstances[guestInstanceId].guest; guest = guestInstances[guestInstanceId].guest
// Destroy the old guest when attaching. // Destroy the old guest when attaching.
key = (embedder.getId()) + "-" + elementInstanceId; key = (embedder.getId()) + '-' + elementInstanceId
oldGuestInstanceId = embedderElementsMap[key]; oldGuestInstanceId = embedderElementsMap[key]
if (oldGuestInstanceId != null) { if (oldGuestInstanceId != null) {
// Reattachment to the same guest is not currently supported. // Reattachment to the same guest is not currently supported.
if (oldGuestInstanceId === guestInstanceId) { if (oldGuestInstanceId === guestInstanceId) {
return; return
} }
if (guestInstances[oldGuestInstanceId] == null) { if (guestInstances[oldGuestInstanceId] == null) {
return; return
} }
destroyGuest(embedder, oldGuestInstanceId); destroyGuest(embedder, oldGuestInstanceId)
} }
webPreferences = { webPreferences = {
guestInstanceId: guestInstanceId, guestInstanceId: guestInstanceId,
@ -182,54 +181,54 @@ var attachGuest = function(embedder, elementInstanceId, guestInstanceId, params)
plugins: params.plugins, plugins: params.plugins,
webSecurity: !params.disablewebsecurity, webSecurity: !params.disablewebsecurity,
blinkFeatures: params.blinkfeatures blinkFeatures: params.blinkfeatures
};
if (params.preload) {
webPreferences.preloadURL = params.preload;
} }
webViewManager.addGuest(guestInstanceId, elementInstanceId, embedder, guest, webPreferences); if (params.preload) {
guest.attachParams = params; webPreferences.preloadURL = params.preload
embedderElementsMap[key] = guestInstanceId; }
return reverseEmbedderElementsMap[guestInstanceId] = key; webViewManager.addGuest(guestInstanceId, elementInstanceId, embedder, guest, webPreferences)
}; guest.attachParams = params
embedderElementsMap[key] = guestInstanceId
return reverseEmbedderElementsMap[guestInstanceId] = key
}
// Destroy an existing guest instance. // Destroy an existing guest instance.
var destroyGuest = function(embedder, id) { var destroyGuest = function (embedder, id) {
var key; var key
webViewManager.removeGuest(embedder, id); webViewManager.removeGuest(embedder, id)
guestInstances[id].guest.destroy(); guestInstances[id].guest.destroy()
delete guestInstances[id]; delete guestInstances[id]
key = reverseEmbedderElementsMap[id]; key = reverseEmbedderElementsMap[id]
if (key != null) { if (key != null) {
delete reverseEmbedderElementsMap[id]; delete reverseEmbedderElementsMap[id]
return delete embedderElementsMap[key]; return delete embedderElementsMap[key]
} }
}; }
ipcMain.on('ATOM_SHELL_GUEST_VIEW_MANAGER_CREATE_GUEST', function(event, params, requestId) { ipcMain.on('ATOM_SHELL_GUEST_VIEW_MANAGER_CREATE_GUEST', function (event, params, requestId) {
return event.sender.send("ATOM_SHELL_RESPONSE_" + requestId, createGuest(event.sender, params)); return event.sender.send('ATOM_SHELL_RESPONSE_' + requestId, createGuest(event.sender, params))
}); })
ipcMain.on('ATOM_SHELL_GUEST_VIEW_MANAGER_ATTACH_GUEST', function(event, elementInstanceId, guestInstanceId, params) { ipcMain.on('ATOM_SHELL_GUEST_VIEW_MANAGER_ATTACH_GUEST', function (event, elementInstanceId, guestInstanceId, params) {
return attachGuest(event.sender, elementInstanceId, guestInstanceId, params); return attachGuest(event.sender, elementInstanceId, guestInstanceId, params)
}); })
ipcMain.on('ATOM_SHELL_GUEST_VIEW_MANAGER_DESTROY_GUEST', function(event, id) { ipcMain.on('ATOM_SHELL_GUEST_VIEW_MANAGER_DESTROY_GUEST', function (event, id) {
return destroyGuest(event.sender, id); return destroyGuest(event.sender, id)
}); })
ipcMain.on('ATOM_SHELL_GUEST_VIEW_MANAGER_SET_SIZE', function(event, id, params) { ipcMain.on('ATOM_SHELL_GUEST_VIEW_MANAGER_SET_SIZE', function (event, id, params) {
var ref1; var ref1
return (ref1 = guestInstances[id]) != null ? ref1.guest.setSize(params) : void 0; return (ref1 = guestInstances[id]) != null ? ref1.guest.setSize(params) : void 0
}); })
// Returns WebContents from its guest id. // Returns WebContents from its guest id.
exports.getGuest = function(id) { exports.getGuest = function (id) {
var ref1; var ref1
return (ref1 = guestInstances[id]) != null ? ref1.guest : void 0; return (ref1 = guestInstances[id]) != null ? ref1.guest : void 0
}; }
// Returns the embedder of the guest. // Returns the embedder of the guest.
exports.getEmbedder = function(id) { exports.getEmbedder = function (id) {
var ref1; var ref1
return (ref1 = guestInstances[id]) != null ? ref1.embedder : void 0; return (ref1 = guestInstances[id]) != null ? ref1.embedder : void 0
}; }

View file

@ -1,120 +1,118 @@
'use strict'; 'use strict'
const ipcMain = require('electron').ipcMain; const ipcMain = require('electron').ipcMain
const BrowserWindow = require('electron').BrowserWindow; const BrowserWindow = require('electron').BrowserWindow
var hasProp = {}.hasOwnProperty; var hasProp = {}.hasOwnProperty
var frameToGuest = {}; var frameToGuest = {}
// Copy attribute of |parent| to |child| if it is not defined in |child|. // Copy attribute of |parent| to |child| if it is not defined in |child|.
var mergeOptions = function(child, parent) { var mergeOptions = function (child, parent) {
var key, value; var key, value
for (key in parent) { for (key in parent) {
if (!hasProp.call(parent, key)) continue; if (!hasProp.call(parent, key)) continue
value = parent[key]; value = parent[key]
if (!(key in child)) { if (!(key in child)) {
if (typeof value === 'object') { if (typeof value === 'object') {
child[key] = mergeOptions({}, value); child[key] = mergeOptions({}, value)
} else { } else {
child[key] = value; child[key] = value
} }
} }
} }
return child; return child
}; }
// Merge |options| with the |embedder|'s window's options. // Merge |options| with the |embedder|'s window's options.
var mergeBrowserWindowOptions = function(embedder, options) { var mergeBrowserWindowOptions = function (embedder, options) {
if (embedder.browserWindowOptions != null) { if (embedder.browserWindowOptions != null) {
// Inherit the original options if it is a BrowserWindow. // Inherit the original options if it is a BrowserWindow.
mergeOptions(options, embedder.browserWindowOptions); mergeOptions(options, embedder.browserWindowOptions)
} else { } else {
// Or only inherit web-preferences if it is a webview. // Or only inherit web-preferences if it is a webview.
if (options.webPreferences == null) { if (options.webPreferences == null) {
options.webPreferences = {}; options.webPreferences = {}
} }
mergeOptions(options.webPreferences, embedder.getWebPreferences()); mergeOptions(options.webPreferences, embedder.getWebPreferences())
} }
return options; return options
}; }
// Create a new guest created by |embedder| with |options|. // Create a new guest created by |embedder| with |options|.
var createGuest = function(embedder, url, frameName, options) { var createGuest = function (embedder, url, frameName, options) {
var closedByEmbedder, closedByUser, guest, guestId, ref1; var closedByEmbedder, closedByUser, guest, guestId, ref1
guest = frameToGuest[frameName]; guest = frameToGuest[frameName]
if (frameName && (guest != null)) { if (frameName && (guest != null)) {
guest.loadURL(url); guest.loadURL(url)
return guest.id; return guest.id
} }
// Remember the embedder window's id. // Remember the embedder window's id.
if (options.webPreferences == null) { if (options.webPreferences == null) {
options.webPreferences = {}; options.webPreferences = {}
} }
options.webPreferences.openerId = (ref1 = BrowserWindow.fromWebContents(embedder)) != null ? ref1.id : void 0; options.webPreferences.openerId = (ref1 = BrowserWindow.fromWebContents(embedder)) != null ? ref1.id : void 0
guest = new BrowserWindow(options); guest = new BrowserWindow(options)
guest.loadURL(url); guest.loadURL(url)
// When |embedder| is destroyed we should also destroy attached guest, and if // When |embedder| is destroyed we should also destroy attached guest, and if
// guest is closed by user then we should prevent |embedder| from double // guest is closed by user then we should prevent |embedder| from double
// closing guest. // closing guest.
guestId = guest.id; guestId = guest.id
closedByEmbedder = function() { closedByEmbedder = function () {
guest.removeListener('closed', closedByUser); guest.removeListener('closed', closedByUser)
return guest.destroy(); return guest.destroy()
};
closedByUser = function() {
embedder.send("ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_CLOSED_" + guestId);
return embedder.removeListener('render-view-deleted', closedByEmbedder);
};
embedder.once('render-view-deleted', closedByEmbedder);
guest.once('closed', closedByUser);
if (frameName) {
frameToGuest[frameName] = guest;
guest.frameName = frameName;
guest.once('closed', function() {
return delete frameToGuest[frameName];
});
} }
return guest.id; closedByUser = function () {
}; embedder.send('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_CLOSED_' + guestId)
return embedder.removeListener('render-view-deleted', closedByEmbedder)
}
embedder.once('render-view-deleted', closedByEmbedder)
guest.once('closed', closedByUser)
if (frameName) {
frameToGuest[frameName] = guest
guest.frameName = frameName
guest.once('closed', function () {
return delete frameToGuest[frameName]
})
}
return guest.id
}
// Routed window.open messages. // Routed window.open messages.
ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPEN', function(event, url, frameName, options) { ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPEN', function (event, url, frameName, options) {
options = mergeBrowserWindowOptions(event.sender, options); options = mergeBrowserWindowOptions(event.sender, options)
event.sender.emit('new-window', event, url, frameName, 'new-window', options); event.sender.emit('new-window', event, url, frameName, 'new-window', options)
if ((event.sender.isGuest() && !event.sender.allowPopups) || event.defaultPrevented) { if ((event.sender.isGuest() && !event.sender.allowPopups) || event.defaultPrevented) {
return event.returnValue = null; return event.returnValue = null
} else { } else {
return event.returnValue = createGuest(event.sender, url, frameName, options); return event.returnValue = createGuest(event.sender, url, frameName, options)
} }
}); })
ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_CLOSE', function(event, guestId) { ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_CLOSE', function (event, guestId) {
var ref1; var ref1
return (ref1 = BrowserWindow.fromId(guestId)) != null ? ref1.destroy() : void 0; return (ref1 = BrowserWindow.fromId(guestId)) != null ? ref1.destroy() : void 0
}); })
ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_METHOD', function(event, guestId, method, ...args) { ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_METHOD', function (event, guestId, method, ...args) {
var ref1; var ref1
return event.returnValue = (ref1 = BrowserWindow.fromId(guestId)) != null ? ref1[method].apply(ref1, args) : void 0; return event.returnValue = (ref1 = BrowserWindow.fromId(guestId)) != null ? ref1[method].apply(ref1, args) : void 0
}); })
ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_POSTMESSAGE', function(event, guestId, message, targetOrigin, sourceOrigin) { ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_POSTMESSAGE', function (event, guestId, message, targetOrigin, sourceOrigin) {
var guestContents, ref1, ref2, sourceId; var guestContents, ref1, ref2, sourceId
sourceId = (ref1 = BrowserWindow.fromWebContents(event.sender)) != null ? ref1.id : void 0; sourceId = (ref1 = BrowserWindow.fromWebContents(event.sender)) != null ? ref1.id : void 0
if (sourceId == null) { if (sourceId == null) {
return; return
} }
guestContents = (ref2 = BrowserWindow.fromId(guestId)) != null ? ref2.webContents : void 0; guestContents = (ref2 = BrowserWindow.fromId(guestId)) != null ? ref2.webContents : void 0
if ((guestContents != null ? guestContents.getURL().indexOf(targetOrigin) : void 0) === 0 || targetOrigin === '*') { if ((guestContents != null ? guestContents.getURL().indexOf(targetOrigin) : void 0) === 0 || targetOrigin === '*') {
return guestContents != null ? guestContents.send('ATOM_SHELL_GUEST_WINDOW_POSTMESSAGE', sourceId, message, sourceOrigin) : void 0; return guestContents != null ? guestContents.send('ATOM_SHELL_GUEST_WINDOW_POSTMESSAGE', sourceId, message, sourceOrigin) : void 0
} }
}); })
ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WEB_CONTENTS_METHOD', function(event, guestId, method, ...args) { ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WEB_CONTENTS_METHOD', function (event, guestId, method, ...args) {
var ref1, ref2; var ref1, ref2
return (ref1 = BrowserWindow.fromId(guestId)) != null ? (ref2 = ref1.webContents) != null ? ref2[method].apply(ref2, args) : void 0 : void 0; return (ref1 = BrowserWindow.fromId(guestId)) != null ? (ref2 = ref1.webContents) != null ? ref2[method].apply(ref2, args) : void 0 : void 0
}); })

View file

@ -1,80 +1,79 @@
'use strict'; 'use strict'
const fs = require('fs'); const fs = require('fs')
const path = require('path'); const path = require('path')
const util = require('util'); const util = require('util')
const Module = require('module'); const Module = require('module')
const v8 = require('v8'); const v8 = require('v8')
// We modified the original process.argv to let node.js load the atom.js, // We modified the original process.argv to let node.js load the atom.js,
// we need to restore it here. // we need to restore it here.
process.argv.splice(1, 1); process.argv.splice(1, 1)
// Clear search paths. // Clear search paths.
require('../common/reset-search-paths'); require('../common/reset-search-paths')
// Import common settings. // Import common settings.
require('../common/init'); require('../common/init')
var globalPaths = Module.globalPaths; var globalPaths = Module.globalPaths
if (!process.env.ELECTRON_HIDE_INTERNAL_MODULES) { if (!process.env.ELECTRON_HIDE_INTERNAL_MODULES) {
globalPaths.push(path.join(__dirname, 'api')); globalPaths.push(path.join(__dirname, 'api'))
} }
// Expose public APIs. // Expose public APIs.
globalPaths.push(path.join(__dirname, 'api', 'exports')); globalPaths.push(path.join(__dirname, 'api', 'exports'))
if (process.platform === 'win32') { if (process.platform === 'win32') {
// Redirect node's console to use our own implementations, since node can not // Redirect node's console to use our own implementations, since node can not
// handle console output when running as GUI program. // handle console output when running as GUI program.
var consoleLog = function(...args) { var consoleLog = function (...args) {
return process.log(util.format.apply(util, args) + "\n"); return process.log(util.format.apply(util, args) + '\n')
}; }
var streamWrite = function(chunk, encoding, callback) { var streamWrite = function (chunk, encoding, callback) {
if (Buffer.isBuffer(chunk)) { if (Buffer.isBuffer(chunk)) {
chunk = chunk.toString(encoding); chunk = chunk.toString(encoding)
} }
process.log(chunk); process.log(chunk)
if (callback) { if (callback) {
callback(); callback()
} }
return true; return true
}; }
console.log = console.error = console.warn = consoleLog; console.log = console.error = console.warn = consoleLog
process.stdout.write = process.stderr.write = streamWrite; process.stdout.write = process.stderr.write = streamWrite
// Always returns EOF for stdin stream. // Always returns EOF for stdin stream.
var Readable = require('stream').Readable; var Readable = require('stream').Readable
var stdin = new Readable; var stdin = new Readable
stdin.push(null); stdin.push(null)
process.__defineGetter__('stdin', function() { process.__defineGetter__('stdin', function () {
return stdin; return stdin
}); })
} }
// Don't quit on fatal error. // Don't quit on fatal error.
process.on('uncaughtException', function(error) { process.on('uncaughtException', function (error) {
// Do nothing if the user has a custom uncaught exception handler. // Do nothing if the user has a custom uncaught exception handler.
var dialog, message, ref, stack; var dialog, message, ref, stack
if (process.listeners('uncaughtException').length > 1) { if (process.listeners('uncaughtException').length > 1) {
return; return
} }
// Show error in GUI. // Show error in GUI.
dialog = require('electron').dialog; dialog = require('electron').dialog
stack = (ref = error.stack) != null ? ref : error.name + ": " + error.message; stack = (ref = error.stack) != null ? ref : error.name + ': ' + error.message
message = "Uncaught Exception:\n" + stack; message = 'Uncaught Exception:\n' + stack
return dialog.showErrorBox('A JavaScript error occurred in the main process', message); return dialog.showErrorBox('A JavaScript error occurred in the main process', message)
}); })
// Emit 'exit' event on quit. // Emit 'exit' event on quit.
var app = require('electron').app; var app = require('electron').app
app.on('quit', function(event, exitCode) { app.on('quit', function (event, exitCode) {
return process.emit('exit', exitCode); return process.emit('exit', exitCode)
}); })
if (process.platform === 'win32') { if (process.platform === 'win32') {
// If we are a Squirrel.Windows-installed app, set app user model ID // If we are a Squirrel.Windows-installed app, set app user model ID
@ -94,92 +93,92 @@ if (process.platform === 'win32') {
var updateDotExe = path.join( var updateDotExe = path.join(
path.dirname(process.execPath), path.dirname(process.execPath),
'..', '..',
'update.exe'); 'update.exe')
if (fs.statSyncNoException(updateDotExe)) { if (fs.statSyncNoException(updateDotExe)) {
var packageDir = path.dirname(path.resolve(updateDotExe)); var packageDir = path.dirname(path.resolve(updateDotExe))
var packageName = path.basename(packageDir); var packageName = path.basename(packageDir)
var exeName = path.basename(process.execPath).replace(/\.exe$/i, ''); var exeName = path.basename(process.execPath).replace(/\.exe$/i, '')
app.setAppUserModelId(`com.squirrel.${packageName}.${exeName}`); app.setAppUserModelId(`com.squirrel.${packageName}.${exeName}`)
} }
} }
// Map process.exit to app.exit, which quits gracefully. // Map process.exit to app.exit, which quits gracefully.
process.exit = app.exit; process.exit = app.exit
// Load the RPC server. // Load the RPC server.
require('./rpc-server'); require('./rpc-server')
// Load the guest view manager. // Load the guest view manager.
require('./guest-view-manager'); require('./guest-view-manager')
require('./guest-window-manager'); require('./guest-window-manager')
// Now we try to load app's package.json. // Now we try to load app's package.json.
var packageJson = null; var packageJson = null
var searchPaths = ['app', 'app.asar', 'default_app']; var searchPaths = ['app', 'app.asar', 'default_app']
var i, len, packagePath; var i, len, packagePath
for (i = 0, len = searchPaths.length; i < len; i++) { for (i = 0, len = searchPaths.length; i < len; i++) {
packagePath = searchPaths[i]; packagePath = searchPaths[i]
try { try {
packagePath = path.join(process.resourcesPath, packagePath); packagePath = path.join(process.resourcesPath, packagePath)
packageJson = JSON.parse(fs.readFileSync(path.join(packagePath, 'package.json'))); packageJson = JSON.parse(fs.readFileSync(path.join(packagePath, 'package.json')))
break; break
} catch (error) { } catch (error) {
continue; continue
} }
} }
if (packageJson == null) { if (packageJson == null) {
process.nextTick(function() { process.nextTick(function () {
return process.exit(1); return process.exit(1)
}); })
throw new Error("Unable to find a valid app"); throw new Error('Unable to find a valid app')
} }
// Set application's version. // Set application's version.
if (packageJson.version != null) { if (packageJson.version != null) {
app.setVersion(packageJson.version); app.setVersion(packageJson.version)
} }
// Set application's name. // Set application's name.
if (packageJson.productName != null) { if (packageJson.productName != null) {
app.setName(packageJson.productName); app.setName(packageJson.productName)
} else if (packageJson.name != null) { } else if (packageJson.name != null) {
app.setName(packageJson.name); app.setName(packageJson.name)
} }
// Set application's desktop name. // Set application's desktop name.
if (packageJson.desktopName != null) { if (packageJson.desktopName != null) {
app.setDesktopName(packageJson.desktopName); app.setDesktopName(packageJson.desktopName)
} else { } else {
app.setDesktopName((app.getName()) + ".desktop"); app.setDesktopName((app.getName()) + '.desktop')
} }
// Set v8 flags // Set v8 flags
if (packageJson.v8Flags != null) { if (packageJson.v8Flags != null) {
v8.setFlagsFromString(packageJson.v8Flags); v8.setFlagsFromString(packageJson.v8Flags)
} }
// Chrome 42 disables NPAPI plugins by default, reenable them here // Chrome 42 disables NPAPI plugins by default, reenable them here
app.commandLine.appendSwitch('enable-npapi'); app.commandLine.appendSwitch('enable-npapi')
// Set the user path according to application's name. // Set the user path according to application's name.
app.setPath('userData', path.join(app.getPath('appData'), app.getName())); app.setPath('userData', path.join(app.getPath('appData'), app.getName()))
app.setPath('userCache', path.join(app.getPath('cache'), app.getName())); app.setPath('userCache', path.join(app.getPath('cache'), app.getName()))
app.setAppPath(packagePath); app.setAppPath(packagePath)
// Load the chrome extension support. // Load the chrome extension support.
require('./chrome-extension'); require('./chrome-extension')
// Load internal desktop-capturer module. // Load internal desktop-capturer module.
require('./desktop-capturer'); require('./desktop-capturer')
// Set main startup script of the app. // Set main startup script of the app.
var mainStartupScript = packageJson.main || 'index.js'; var mainStartupScript = packageJson.main || 'index.js'
// Finally load app's main.js and transfer control to C++. // Finally load app's main.js and transfer control to C++.
Module._load(path.join(packagePath, mainStartupScript), Module, true); Module._load(path.join(packagePath, mainStartupScript), Module, true)

View file

@ -1,94 +1,94 @@
'use strict'; 'use strict'
const v8Util = process.atomBinding('v8_util'); const v8Util = process.atomBinding('v8_util')
class ObjectsRegistry { class ObjectsRegistry {
constructor() { constructor () {
this.nextId = 0; this.nextId = 0
// Stores all objects by ref-counting. // Stores all objects by ref-counting.
// (id) => {object, count} // (id) => {object, count}
this.storage = {}; this.storage = {}
// Stores the IDs of objects referenced by WebContents. // Stores the IDs of objects referenced by WebContents.
// (webContentsId) => [id] // (webContentsId) => [id]
this.owners = {}; this.owners = {}
} }
// Register a new object and return its assigned ID. If the object is already // Register a new object and return its assigned ID. If the object is already
// registered then the already assigned ID would be returned. // registered then the already assigned ID would be returned.
add(webContents, obj) { add (webContents, obj) {
// Get or assign an ID to the object. // Get or assign an ID to the object.
let id = this.saveToStorage(obj); let id = this.saveToStorage(obj)
// Add object to the set of referenced objects. // Add object to the set of referenced objects.
let webContentsId = webContents.getId(); let webContentsId = webContents.getId()
let owner = this.owners[webContentsId]; let owner = this.owners[webContentsId]
if (!owner) { if (!owner) {
owner = this.owners[webContentsId] = new Set(); owner = this.owners[webContentsId] = new Set()
// Clear the storage when webContents is reloaded/navigated. // Clear the storage when webContents is reloaded/navigated.
webContents.once('render-view-deleted', (event, id) => { webContents.once('render-view-deleted', (event, id) => {
this.clear(id); this.clear(id)
}); })
} }
if (!owner.has(id)) { if (!owner.has(id)) {
owner.add(id); owner.add(id)
// Increase reference count if not referenced before. // Increase reference count if not referenced before.
this.storage[id].count++; this.storage[id].count++
} }
return id; return id
} }
// Get an object according to its ID. // Get an object according to its ID.
get(id) { get (id) {
return this.storage[id].object; return this.storage[id].object
} }
// Dereference an object according to its ID. // Dereference an object according to its ID.
remove(webContentsId, id) { remove (webContentsId, id) {
// Dereference from the storage. // Dereference from the storage.
this.dereference(id); this.dereference(id)
// Also remove the reference in owner. // Also remove the reference in owner.
this.owners[webContentsId].delete(id); this.owners[webContentsId].delete(id)
} }
// Clear all references to objects refrenced by the WebContents. // Clear all references to objects refrenced by the WebContents.
clear(webContentsId) { clear (webContentsId) {
let owner = this.owners[webContentsId]; let owner = this.owners[webContentsId]
if (!owner) if (!owner) return
return;
for (let id of owner) for (let id of owner) this.dereference(id)
this.dereference(id);
delete this.owners[webContentsId]; delete this.owners[webContentsId]
} }
// Private: Saves the object into storage and assigns an ID for it. // Private: Saves the object into storage and assigns an ID for it.
saveToStorage(object) { saveToStorage (object) {
let id = v8Util.getHiddenValue(object, 'atomId'); let id = v8Util.getHiddenValue(object, 'atomId')
if (!id) { if (!id) {
id = ++this.nextId; id = ++this.nextId
this.storage[id] = { this.storage[id] = {
count: 0, count: 0,
object: object object: object
};
v8Util.setHiddenValue(object, 'atomId', id);
} }
return id; v8Util.setHiddenValue(object, 'atomId', id)
}
return id
} }
// Private: Dereference the object from store. // Private: Dereference the object from store.
dereference(id) { dereference (id) {
let pointer = this.storage[id]; let pointer = this.storage[id]
if (pointer == null) { if (pointer == null) {
return; return
} }
pointer.count -= 1; pointer.count -= 1
if (pointer.count === 0) { if (pointer.count === 0) {
v8Util.deleteHiddenValue(pointer.object, 'atomId'); v8Util.deleteHiddenValue(pointer.object, 'atomId')
return delete this.storage[id]; return delete this.storage[id]
} }
} }
} }
module.exports = new ObjectsRegistry; module.exports = new ObjectsRegistry()