Merge pull request #4106 from atom/clean-up-comments

Clean up comments from CoffeeScript migration
This commit is contained in:
Kevin Sawicki 2016-01-14 14:10:26 -08:00
commit f31289c735
43 changed files with 475 additions and 869 deletions

View file

@ -53,9 +53,7 @@ app.getAppPath = function() {
return appPath; return appPath;
}; };
// Routes the events to webContents.
/* Routes the events to webContents. */
ref1 = ['login', 'certificate-error', 'select-client-certificate']; ref1 = ['login', 'certificate-error', 'select-client-certificate'];
fn = function(name) { fn = function(name) {
return app.on(name, function() { return app.on(name, function() {
@ -69,8 +67,7 @@ for (i = 0, len = ref1.length; i < len; i++) {
fn(name); fn(name);
} }
// 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');
@ -92,7 +89,7 @@ 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.
return setImmediate((function(_this) { return setImmediate((function(_this) {
return function() { return function() {
return _this.emit('finish-launching'); return _this.emit('finish-launching');
@ -108,15 +105,13 @@ deprecate.event(app, 'activate-with-no-open-windows', 'activate', function(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. */
wrapDownloadItem = function(downloadItem) { 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');
@ -125,7 +120,5 @@ wrapDownloadItem = function(downloadItem) {
downloadItemBindings._setWrapDownloadItem(wrapDownloadItem); downloadItemBindings._setWrapDownloadItem(wrapDownloadItem);
// Only one App object pemitted.
/* Only one App object pemitted. */
module.exports = app; module.exports = app;

View file

@ -4,11 +4,7 @@ deprecate = require('electron').deprecate;
autoUpdater = process.platform === 'win32' ? require('./auto-updater/auto-updater-win') : require('./auto-updater/auto-updater-native'); 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

@ -50,7 +50,7 @@ AutoUpdater = (function(superClass) {
} }
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;
url = _this.updateURL; url = _this.updateURL;
return _this.emit('update-downloaded', {}, releaseNotes, version, date, url, function() { return _this.emit('update-downloaded', {}, releaseNotes, version, date, url, function() {
@ -62,11 +62,8 @@ AutoUpdater = (function(superClass) {
}; };
/* // 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);
}; };

View file

@ -6,24 +6,16 @@ path = require('path');
spawn = require('child_process').spawn; spawn = require('child_process').spawn;
// i.e. my-app/app-0.1.13/
/* i.e. my-app/app-0.1.13/ */
appFolder = path.dirname(process.execPath); appFolder = path.dirname(process.execPath);
// i.e. my-app/Update.exe
/* i.e. my-app/Update.exe */
updateExe = path.resolve(appFolder, '..', 'Update.exe'); updateExe = path.resolve(appFolder, '..', 'Update.exe');
exeName = path.basename(process.execPath); exeName = path.basename(process.execPath);
// Spawn a command and invoke the callback when it completes with an error
/* // and the output from standard out.
Spawn a command and invoke the callback when it completes with an error
and the output from standard out.
*/
spawnUpdate = function(args, detached, callback) { spawnUpdate = function(args, detached, callback) {
var error, error1, errorEmitted, spawnedProcess, stderr, stdout; var error, error1, errorEmitted, spawnedProcess, stderr, stdout;
try { try {
@ -33,7 +25,7 @@ spawnUpdate = function(args, detached, callback) {
} 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);
}); });
@ -54,31 +46,27 @@ spawnUpdate = function(args, detached, callback) {
}); });
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(callback) { exports.processStart = function(callback) {
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 error1, json, ref, ref1, update; var error1, json, ref, ref1, update;
@ -87,7 +75,7 @@ exports.download = function(updateURL, callback) {
} }
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 (error1) { } catch (error1) {
@ -98,15 +86,13 @@ exports.download = function(updateURL, callback) {
}; };
/* 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() {
var error1; var error1;
try { try {

View file

@ -10,11 +10,11 @@ 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) {
@ -22,7 +22,7 @@ BrowserWindow.prototype._init = function() {
} }
} }
/* 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', function(event, url, frameName) { this.webContents.on('-new-window', function(event, url, frameName) {
var options; var options;
options = { options = {
@ -33,17 +33,15 @@ BrowserWindow.prototype._init = function() {
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', (function(_this) { this.webContents.on('move', (function(_this) {
return function(event, size) { return function(event, size) {
return _this.setBounds(size); return _this.setBounds(size);
}; };
})(this)); })(this));
/* Hide the auto-hide menu when webContents is focused. */ // Hide the auto-hide menu when webContents is focused.
this.webContents.on('activate', (function(_this) { this.webContents.on('activate', (function(_this) {
return function() { return function() {
if (process.platform !== 'darwin' && _this.isMenuBarAutoHide() && _this.isMenuBarVisible()) { if (process.platform !== 'darwin' && _this.isMenuBarAutoHide() && _this.isMenuBarVisible()) {
@ -52,14 +50,14 @@ BrowserWindow.prototype._init = function() {
}; };
})(this)); })(this));
/* Forward the crashed event. */ // Forward the crashed event.
this.webContents.on('crashed', (function(_this) { this.webContents.on('crashed', (function(_this) {
return function() { return function() {
return _this.emit('crashed'); return _this.emit('crashed');
}; };
})(this)); })(this));
/* Change window title to page title. */ // Change window title to page title.
this.webContents.on('page-title-updated', (function(_this) { this.webContents.on('page-title-updated', (function(_this) {
return function(event, title, explicitSet) { return function(event, title, explicitSet) {
_this.emit('page-title-updated', event, title); _this.emit('page-title-updated', event, title);
@ -69,19 +67,17 @@ BrowserWindow.prototype._init = function() {
}; };
})(this)); })(this));
/* // 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 // when we first start to load URL, if we do it earlier it won't have effect,
when we first start to load URL, if we do it earlier it won't have effect, // 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() {
return this.focus(); return this.focus();
}); });
/* Redirect focus/blur event to app instance too. */ // Redirect focus/blur event to app instance too.
this.on('blur', (function(_this) { this.on('blur', (function(_this) {
return function(event) { return function(event) {
return app.emit('browser-window-blur', event, _this); return app.emit('browser-window-blur', event, _this);
@ -93,10 +89,10 @@ BrowserWindow.prototype._init = function() {
}; };
})(this)); })(this));
/* 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', (function(_this) { this.webContents.on('devtools-focused', (function(_this) {
return function() { return function() {
return _this.emit('devtools-focused'); return _this.emit('devtools-focused');
@ -155,8 +151,7 @@ BrowserWindow.fromDevToolsWebContents = function(webContents) {
} }
}; };
// 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);
@ -202,8 +197,7 @@ BrowserWindow.prototype.inspectServiceWorker = function() {
return this.webContents.inspectServiceWorker(); return this.webContents.inspectServiceWorker();
}; };
// Deprecated.
/* Deprecated. */
deprecate.member(BrowserWindow, 'undo', 'webContents'); deprecate.member(BrowserWindow, 'undo', 'webContents');

View file

@ -23,15 +23,13 @@ messageBoxOptions = {
parseArgs = function(window, options, callback) { 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;
} }
@ -143,7 +141,7 @@ module.exports = {
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;
@ -165,9 +163,7 @@ module.exports = {
} }
}; };
// Mark standard asynchronous functions.
/* Mark standard asynchronous functions. */
ref1 = ['showMessageBox', 'showOpenDialog', 'showSaveDialog']; ref1 = ['showMessageBox', 'showOpenDialog', 'showSaveDialog'];
for (j = 0, len = ref1.length; j < len; j++) { for (j = 0, len = ref1.length; j < len; j++) {
api = ref1[j]; api = ref1[j];

View file

@ -3,13 +3,12 @@ var common;
common = require('../../../../common/api/lib/exports/electron'); common = require('../../../../common/api/lib/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() {
@ -101,7 +100,7 @@ Object.defineProperties(exports, {
} }
}, },
/* 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');

View file

@ -2,9 +2,7 @@ var deprecate, ipcMain, ref;
ref = require('electron'), deprecate = ref.deprecate, ipcMain = ref.ipcMain; ref = require('electron'), deprecate = ref.deprecate, ipcMain = ref.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

@ -4,9 +4,7 @@ v8Util = process.atomBinding('v8_util');
nextCommandId = 0; nextCommandId = 0;
// Maps role to methods of webContents
/* Maps role to methods of webContents */
rolesMap = { rolesMap = {
undo: 'undo', undo: 'undo',
redo: 'redo', redo: 'redo',
@ -18,9 +16,7 @@ rolesMap = {
close: 'close' close: 'close'
}; };
// 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
@ -59,7 +55,7 @@ MenuItem = (function() {
this.click = (function(_this) { this.click = (function(_this) {
return function(focusedWindow) { return function(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;

View file

@ -8,17 +8,11 @@ v8Util = process.atomBinding('v8_util');
bindings = process.atomBinding('menu'); bindings = process.atomBinding('menu');
// Automatically generated radio menu item's group id.
/* Automatically generated radio menu item's group id. */
nextGroupId = 0; nextGroupId = 0;
// Search between seperators to find a radio menu item and return its group id,
/* Search between seperators to find a radio menu item and return its group id, */ // otherwise generate a group id.
/* otherwise generate a group id. */
generateGroupId = function(items, pos) { 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) {
@ -45,9 +39,7 @@ generateGroupId = function(items, pos) {
return ++nextGroupId; return ++nextGroupId;
}; };
// Returns the index of item according to |id|.
/* Returns the index of item according to |id|. */
indexOfItemById = function(items, id) { 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) {
@ -59,9 +51,7 @@ indexOfItemById = function(items, id) {
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|. */
indexToInsertByPosition = function(items, position) { indexToInsertByPosition = function(items, position) {
var id, insertIndex, query, ref1; var id, insertIndex, query, ref1;
if (!position) { if (!position) {
@ -79,7 +69,7 @@ indexToInsertByPosition = function(items, position) {
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|.
if (insertIndex === -1) { if (insertIndex === -1) {
items.push({ items.push({
id: id, id: id,
@ -88,7 +78,7 @@ indexToInsertByPosition = function(items, position) {
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++;
@ -145,7 +135,7 @@ Menu.prototype._init = function() {
menuWillShow: (function(_this) { menuWillShow: (function(_this) {
return function() { return function() {
/* 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, results; var checked, group, id, j, len, radioItem, ref1, results;
ref1 = _this.groupsMap; ref1 = _this.groupsMap;
results = []; results = [];
@ -174,8 +164,7 @@ Menu.prototype._init = function() {
Menu.prototype.popup = function(window, x, y) { Menu.prototype.popup = function(window, x, y) {
if ((window != null ? window.constructor : void 0) !== BrowserWindow) { if ((window != null ? window.constructor : void 0) !== BrowserWindow) {
// Shift.
/* Shift. */
y = x; y = x;
x = window; x = window;
window = BrowserWindow.getFocusedWindow(); window = BrowserWindow.getFocusedWindow();
@ -210,15 +199,14 @@ Menu.prototype.insert = function(pos, item) {
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,
@ -251,17 +239,16 @@ Menu.prototype.insert = function(pos, item) {
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() {
var item, j, len, ref1, ref2, results; var item, j, len, ref1, ref2, results;
if ((ref1 = this.delegate) != null) { if ((ref1 = this.delegate) != null) {
@ -286,7 +273,7 @@ Menu.setApplicationMenu = function(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) {
@ -323,8 +310,7 @@ Menu.buildFromTemplate = function(template) {
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);

View file

@ -3,9 +3,7 @@ var NavigationController, ipcMain,
ipcMain = require('electron').ipcMain; 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() { ipcMain.on('ATOM_SHELL_NAVIGATION_CONTROLLER', function() {
var args, event, method, ref; var args, event, method, ref;
event = arguments[0], method = arguments[1], args = 3 <= arguments.length ? slice.call(arguments, 2) : []; event = arguments[0], method = arguments[1], args = 3 <= arguments.length ? slice.call(arguments, 2) : [];
@ -18,21 +16,17 @@ ipcMain.on('ATOM_SHELL_SYNC_NAVIGATION_CONTROLLER', function() {
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.
/* // Instead of relying on Chromium for history control, we compeletely do history
JavaScript implementation of Chromium's NavigationController. // control on user land, and only rely on WebContents.loadURL for navigation.
Instead of relying on Chromium for history control, we compeletely do history // This helps us avoid Chromium's various optimizations so we can ensure renderer
control on user land, and only rely on WebContents.loadURL for navigation. // process is restarted everytime.
This helps us avoid Chromium's various optimizations so we can ensure renderer
process is restarted everytime.
*/
NavigationController = (function() { 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());
@ -42,26 +36,26 @@ NavigationController = (function() {
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) {

View file

@ -8,9 +8,7 @@ if (!app.isReady()) {
protocol = process.atomBinding('protocol').protocol; protocol = process.atomBinding('protocol').protocol;
// Warn about removed APIs.
/* Warn about removed APIs. */
logAndThrow = function(callback, message) { logAndThrow = function(callback, message) {
console.error(message); console.error(message);
if (callback) { if (callback) {

View file

@ -6,9 +6,7 @@ bindings = process.atomBinding('session');
PERSIST_PERFIX = 'persist:'; PERSIST_PERFIX = '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 = '';
@ -23,9 +21,7 @@ exports.fromPartition = function(partition) {
} }
}; };
// Returns the default session.
/* Returns the default session. */
Object.defineProperty(exports, 'defaultSession', { Object.defineProperty(exports, 'defaultSession', {
enumerable: true, enumerable: true,
get: function() { get: function() {
@ -34,8 +30,7 @@ Object.defineProperty(exports, 'defaultSession', {
}); });
wrapSession = function(session) { wrapSession = function(session) {
// session is an EventEmitter.
/* session is an EventEmitter. */
return session.__proto__ = EventEmitter.prototype; return session.__proto__ = EventEmitter.prototype;
}; };

View file

@ -9,8 +9,7 @@ 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');
@ -21,7 +20,7 @@ Tray.prototype._init = function() {
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;
}; };

View file

@ -65,19 +65,18 @@ const webFrameMethods = [
]; ];
wrapWebContents = function(webContents) { 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;
/* WebContents::send(channel, args..) */ // WebContents::send(channel, args..)
webContents.send = function() { webContents.send = function() {
var args, channel; var args, channel;
channel = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : []; channel = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
return this._send(channel, slice.call(args)); return this._send(channel, slice.call(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) {
@ -109,7 +108,7 @@ wrapWebContents = function(webContents) {
return this.once('did-finish-load', executeJavaScript.bind(this, code, hasUserGesture)); return this.once('did-finish-load', executeJavaScript.bind(this, code, hasUserGesture));
}; };
/* Dispatch IPC messages to the ipc module. */ // Dispatch IPC messages to the ipc module.
webContents.on('ipc-message', function(event, packed) { webContents.on('ipc-message', function(event, packed) {
var args, channel; var args, channel;
channel = packed[0], args = 2 <= packed.length ? slice.call(packed, 1) : []; channel = packed[0], args = 2 <= packed.length ? slice.call(packed, 1) : [];
@ -126,22 +125,20 @@ wrapWebContents = function(webContents) {
return ipcMain.emit.apply(ipcMain, [channel, event].concat(slice.call(args))); return ipcMain.emit.apply(ipcMain, [channel, event].concat(slice.call(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() { webContents.on('did-fail-provisional-load', function() {
var args; var args;
args = 1 <= arguments.length ? slice.call(arguments, 0) : []; args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
/* // 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.
*/
return setImmediate((function(_this) { return setImmediate((function(_this) {
return function() { return function() {
return _this.emit.apply(_this, ['did-fail-load'].concat(slice.call(args))); return _this.emit.apply(_this, ['did-fail-load'].concat(slice.call(args)));
@ -149,7 +146,7 @@ wrapWebContents = function(webContents) {
})(this)); })(this));
}); });
/* Delays the page-title-updated event to next tick. */ // Delays the page-title-updated event to next tick.
webContents.on('-page-title-updated', function() { webContents.on('-page-title-updated', function() {
var args; var args;
args = 1 <= arguments.length ? slice.call(arguments, 0) : []; args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
@ -160,7 +157,7 @@ wrapWebContents = function(webContents) {
})(this)); })(this));
}); });
/* 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() { deprecate.event(webContents, 'page-title-set', 'page-title-updated', function() {

View file

@ -8,9 +8,7 @@ path = require('path');
url = require('url'); url = require('url');
// Mapping between hostname and file path.
/* Mapping between hostname and file path. */
hostPathMap = {}; hostPathMap = {};
hostPathMapNextKey = 0; hostPathMapNextKey = 0;
@ -26,9 +24,7 @@ getPathForHost = function(host) {
return hostPathMap[host]; return hostPathMap[host];
}; };
// Cache extensionInfo.
/* Cache extensionInfo. */
extensionInfoMap = {}; extensionInfoMap = {};
getExtensionInfoFromPath = function(srcDirectory) { getExtensionInfoFromPath = function(srcDirectory) {
@ -36,10 +32,8 @@ getExtensionInfoFromPath = function(srcDirectory) {
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({
protocol: 'chrome-extension', protocol: 'chrome-extension',
slashes: true, slashes: true,
@ -56,16 +50,11 @@ getExtensionInfoFromPath = function(srcDirectory) {
} }
}; };
// The loaded extensions cache and its persistent path.
/* The loaded extensions cache and its persistent path. */
loadedExtensions = null; loadedExtensions = null;
loadedExtensionsPath = null; loadedExtensionsPath = null;
// Persistent loaded extensions.
/* Persistent loaded extensions. */
app = electron.app; app = electron.app;
app.on('will-quit', function() { app.on('will-quit', function() {
@ -85,14 +74,12 @@ app.on('will-quit', function() {
} }
}); });
// 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, e, error1, i, init, len, protocol, srcDirectory; var BrowserWindow, chromeExtensionHandler, e, error1, i, init, len, protocol, srcDirectory;
protocol = electron.protocol, BrowserWindow = electron.BrowserWindow; protocol = electron.protocol, BrowserWindow = electron.BrowserWindow;
/* Load persistented extensions. */ // Load persistented 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));
@ -100,7 +87,7 @@ app.once('ready', function() {
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);
@ -109,7 +96,7 @@ app.once('ready', function() {
e = error1; e = error1;
} }
/* 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);
@ -150,7 +137,7 @@ app.once('ready', function() {
return delete extensionInfoMap[name]; return delete extensionInfoMap[name];
}; };
/* Load persistented extensions when devtools is opened. */ // Load persistented 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);

View file

@ -8,9 +8,7 @@ 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. */
requestsQueue = []; 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) {
@ -29,18 +27,15 @@ ipcMain.on('ATOM_BROWSER_DESKTOP_CAPTURER_GET_SOURCES', function(event, captureW
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 captureScreen, captureWindow, handledRequest, i, len, ref, ref1, ref2, request, result, source, thumbnailSize, unhandledRequestsQueue; var captureScreen, captureWindow, handledRequest, i, len, ref, ref1, ref2, request, result, source, thumbnailSize, unhandledRequestsQueue;
handledRequest = requestsQueue.shift(0); handledRequest = requestsQueue.shift(0);
result = (function() { result = (function() {
@ -60,10 +55,8 @@ desktopCapturer.emit = function(event, name, sources) {
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];
@ -77,7 +70,7 @@ desktopCapturer.emit = function(event, name, sources) {
} }
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) {
ref2 = requestsQueue[0].options, captureWindow = ref2.captureWindow, captureScreen = ref2.captureScreen, thumbnailSize = ref2.thumbnailSize; ref2 = requestsQueue[0].options, captureWindow = ref2.captureWindow, captureScreen = ref2.captureScreen, thumbnailSize = ref2.thumbnailSize;
return desktopCapturer.startHandling(captureWindow, captureScreen, thumbnailSize); return desktopCapturer.startHandling(captureWindow, captureScreen, thumbnailSize);

View file

@ -3,9 +3,7 @@ var attachGuest, createGuest, destroyGuest, embedderElementsMap, getNextInstance
ref = require('electron'), ipcMain = ref.ipcMain, webContents = ref.webContents; ref = require('electron'), ipcMain = ref.ipcMain, webContents = ref.webContents;
// Doesn't exist in early initialization.
/* Doesn't exist in early initialization. */
webViewManager = null; webViewManager = null;
supportedWebViewEvents = ['load-commit', 'did-finish-load', 'did-fail-load', 'did-frame-finish-load', 'did-start-loading', 'did-stop-loading', 'did-get-response-details', 'did-get-redirect-request', 'dom-ready', 'console-message', 'devtools-opened', 'devtools-closed', 'devtools-focused', 'new-window', 'will-navigate', 'did-navigate', 'did-navigate-in-page', 'close', 'crashed', 'gpu-crashed', 'plugin-crashed', 'destroyed', 'page-title-updated', 'page-favicon-updated', 'enter-html-full-screen', 'leave-html-full-screen', 'media-started-playing', 'media-paused', 'found-in-page', 'did-change-theme-color']; supportedWebViewEvents = ['load-commit', 'did-finish-load', 'did-fail-load', 'did-frame-finish-load', 'did-start-loading', 'did-stop-loading', 'did-get-response-details', 'did-get-redirect-request', 'dom-ready', 'console-message', 'devtools-opened', 'devtools-closed', 'devtools-focused', 'new-window', 'will-navigate', 'did-navigate', 'did-navigate-in-page', 'close', 'crashed', 'gpu-crashed', 'plugin-crashed', 'destroyed', 'page-title-updated', 'page-favicon-updated', 'enter-html-full-screen', 'leave-html-full-screen', 'media-started-playing', 'media-paused', 'found-in-page', 'did-change-theme-color'];
@ -18,23 +16,17 @@ embedderElementsMap = {};
reverseEmbedderElementsMap = {}; reverseEmbedderElementsMap = {};
// Moves the last element of array to the first one.
/* Moves the last element of array to the first one. */
moveLastToFirst = function(list) { moveLastToFirst = function(list) {
return list.unshift(list.pop()); return list.unshift(list.pop());
}; };
// Generate guestInstanceId.
/* Generate guestInstanceId. */
getNextInstanceId = function(webContents) { getNextInstanceId = function(webContents) {
return ++nextInstanceId; return ++nextInstanceId;
}; };
// Create a new guest instance.
/* Create a new guest instance. */
createGuest = function(embedder, params) { 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) {
@ -51,7 +43,7 @@ createGuest = function(embedder, params) {
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) {
@ -62,11 +54,9 @@ createGuest = function(embedder, params) {
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);
@ -82,7 +72,7 @@ createGuest = function(embedder, params) {
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;
@ -119,7 +109,7 @@ createGuest = function(embedder, params) {
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() { return guest.on(event, function() {
var _, args; var _, args;
@ -132,14 +122,14 @@ createGuest = function(embedder, params) {
fn(event); fn(event);
} }
/* Dispatch guest's IPC messages to embedder. */ // Dispatch guest's IPC messages to embedder.
guest.on('ipc-message-host', function(_, packed) { guest.on('ipc-message-host', function(_, packed) {
var args, channel; var args, channel;
channel = packed[0], args = 2 <= packed.length ? slice.call(packed, 1) : []; channel = packed[0], args = 2 <= packed.length ? slice.call(packed, 1) : [];
return embedder.send.apply(embedder, ["ATOM_SHELL_GUEST_VIEW_INTERNAL_IPC_MESSAGE-" + guest.viewInstanceId, channel].concat(slice.call(args))); return embedder.send.apply(embedder, ["ATOM_SHELL_GUEST_VIEW_INTERNAL_IPC_MESSAGE-" + guest.viewInstanceId, channel].concat(slice.call(args)));
}); });
/* Autosize. */ // Autosize.
guest.on('size-changed', function() { guest.on('size-changed', function() {
var _, args; var _, args;
_ = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : []; _ = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
@ -148,19 +138,17 @@ createGuest = function(embedder, params) {
return id; return id;
}; };
// Attach the guest to an element of embedder.
/* Attach the guest to an element of embedder. */
attachGuest = function(embedder, elementInstanceId, guestInstanceId, params) { 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;
} }
@ -184,9 +172,7 @@ attachGuest = function(embedder, elementInstanceId, guestInstanceId, params) {
return reverseEmbedderElementsMap[guestInstanceId] = key; return reverseEmbedderElementsMap[guestInstanceId] = key;
}; };
// Destroy an existing guest instance.
/* Destroy an existing guest instance. */
destroyGuest = function(embedder, id) { destroyGuest = function(embedder, id) {
var key; var key;
webViewManager.removeGuest(embedder, id); webViewManager.removeGuest(embedder, id);
@ -221,17 +207,13 @@ ipcMain.on('ATOM_SHELL_GUEST_VIEW_MANAGER_SET_ALLOW_TRANSPARENCY', function(even
return (ref1 = guestInstances[id]) != null ? ref1.guest.setAllowTransparency(allowtransparency) : void 0; return (ref1 = guestInstances[id]) != null ? ref1.guest.setAllowTransparency(allowtransparency) : 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

@ -8,9 +8,7 @@ v8Util = process.atomBinding('v8_util');
frameToGuest = {}; 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|. */
mergeOptions = function(child, parent) { mergeOptions = function(child, parent) {
var key, value; var key, value;
for (key in parent) { for (key in parent) {
@ -27,17 +25,15 @@ mergeOptions = function(child, parent) {
return child; return child;
}; };
// Merge |options| with the |embedder|'s window's options.
/* Merge |options| with the |embedder|'s window's options. */
mergeBrowserWindowOptions = function(embedder, options) { 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 = {};
} }
@ -46,9 +42,7 @@ mergeBrowserWindowOptions = function(embedder, options) {
return options; return options;
}; };
// Create a new guest created by |embedder| with |options|.
/* Create a new guest created by |embedder| with |options|. */
createGuest = function(embedder, url, frameName, options) { createGuest = function(embedder, url, frameName, options) {
var closedByEmbedder, closedByUser, guest, guestId, ref1; var closedByEmbedder, closedByUser, guest, guestId, ref1;
guest = frameToGuest[frameName]; guest = frameToGuest[frameName];
@ -57,7 +51,7 @@ createGuest = function(embedder, url, frameName, options) {
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 = {};
} }
@ -65,11 +59,9 @@ createGuest = function(embedder, url, frameName, options) {
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);
@ -91,9 +83,7 @@ createGuest = function(embedder, url, frameName, options) {
return guest.id; return guest.id;
}; };
// Routed window.open messages.
/* Routed window.open messages. */
ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPEN', function() { ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPEN', function() {
var args, event, frameName, options, url; var args, event, frameName, options, url;
event = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : []; event = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];

View file

@ -9,22 +9,14 @@ util = require('util');
Module = require('module'); Module = require('module');
// 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(path.resolve(__dirname, '..', '..', 'common', 'lib', 'reset-search-paths')); require(path.resolve(__dirname, '..', '..', 'common', 'lib', 'reset-search-paths'));
// Import common settings.
/* Import common settings. */
require(path.resolve(__dirname, '..', '..', 'common', 'lib', 'init')); require(path.resolve(__dirname, '..', '..', 'common', 'lib', 'init'));
globalPaths = Module.globalPaths; globalPaths = Module.globalPaths;
@ -33,17 +25,12 @@ if (!process.env.ELECTRON_HIDE_INTERNAL_MODULES) {
globalPaths.push(path.resolve(__dirname, '..', 'api', 'lib')); globalPaths.push(path.resolve(__dirname, '..', 'api', 'lib'));
} }
// Expose public APIs.
/* Expose public APIs. */
globalPaths.push(path.resolve(__dirname, '..', 'api', 'lib', 'exports')); globalPaths.push(path.resolve(__dirname, '..', 'api', 'lib', 'exports'));
if (process.platform === 'win32') { if (process.platform === 'win32') {
// Redirect node's console to use our own implementations, since node can not
/* // handle console output when running as GUI program.
Redirect node's console to use our own implementations, since node can not
handle console output when running as GUI program.
*/
consoleLog = function() { consoleLog = function() {
var args; var args;
args = 1 <= arguments.length ? slice.call(arguments, 0) : []; args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
@ -62,7 +49,7 @@ if (process.platform === 'win32') {
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.
Readable = require('stream').Readable; Readable = require('stream').Readable;
stdin = new Readable; stdin = new Readable;
stdin.push(null); stdin.push(null);
@ -71,53 +58,42 @@ if (process.platform === 'win32') {
}); });
} }
// 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. */
app = require('electron').app; 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);
}); });
// 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.
packageJson = null; packageJson = null;
searchPaths = ['app', 'app.asar', 'default_app']; searchPaths = ['app', 'app.asar', 'default_app'];
@ -141,61 +117,43 @@ if (packageJson == null) {
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");
} }
// 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. */
mainStartupScript = packageJson.main || 'index.js'; 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

@ -13,30 +13,22 @@ ObjectsRegistry = (function(superClass) {
this.setMaxListeners(Number.MAX_VALUE); this.setMaxListeners(Number.MAX_VALUE);
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) => (count)}
(webContentsId) => {(id) => (count)}
*/
this.owners = {}; this.owners = {};
} }
// Register a new object, the object would be kept referenced until you release
/* // it explicitly.
Register a new object, the object would be kept referenced until you release
it explicitly.
*/
ObjectsRegistry.prototype.add = function(webContentsId, obj) { ObjectsRegistry.prototype.add = function(webContentsId, obj) {
var base, base1, id; var base, base1, id;
id = this.saveToStorage(obj); id = this.saveToStorage(obj);
/* Remember the owner. */ // Remember the owner.
if ((base = this.owners)[webContentsId] == null) { if ((base = this.owners)[webContentsId] == null) {
base[webContentsId] = {}; base[webContentsId] = {};
} }
@ -45,26 +37,24 @@ ObjectsRegistry = (function(superClass) {
} }
this.owners[webContentsId][id]++; this.owners[webContentsId][id]++;
/* Returns object's id */ // Returns object's id
return id; return id;
}; };
/* Get an object according to its ID. */ // Get an object according to its ID.
ObjectsRegistry.prototype.get = function(id) { ObjectsRegistry.prototype.get = function(id) {
var ref; var ref;
return (ref = this.storage[id]) != null ? ref.object : void 0; return (ref = this.storage[id]) != null ? ref.object : void 0;
}; };
/* Dereference an object according to its ID. */ // Dereference an object according to its ID.
ObjectsRegistry.prototype.remove = function(webContentsId, id) { ObjectsRegistry.prototype.remove = function(webContentsId, id) {
var pointer; var pointer;
this.dereference(id, 1); this.dereference(id, 1);
/* Also reduce the count in owner. */ // Also reduce the count in owner.
pointer = this.owners[webContentsId]; pointer = this.owners[webContentsId];
if (pointer == null) { if (pointer == null) {
return; return;
@ -75,9 +65,7 @@ ObjectsRegistry = (function(superClass) {
} }
}; };
// Clear all references to objects refrenced by the WebContents.
/* Clear all references to objects refrenced by the WebContents. */
ObjectsRegistry.prototype.clear = function(webContentsId) { ObjectsRegistry.prototype.clear = function(webContentsId) {
var count, id, ref; var count, id, ref;
this.emit("clear-" + webContentsId); this.emit("clear-" + webContentsId);
@ -92,9 +80,7 @@ ObjectsRegistry = (function(superClass) {
return delete this.owners[webContentsId]; return 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. */
ObjectsRegistry.prototype.saveToStorage = function(object) { ObjectsRegistry.prototype.saveToStorage = function(object) {
var id; var id;
id = v8Util.getHiddenValue(object, 'atomId'); id = v8Util.getHiddenValue(object, 'atomId');
@ -110,9 +96,7 @@ ObjectsRegistry = (function(superClass) {
return id; return id;
}; };
// Private: Dereference the object from store.
/* Private: Dereference the object from store. */
ObjectsRegistry.prototype.dereference = function(id, count) { ObjectsRegistry.prototype.dereference = function(id, count) {
var pointer; var pointer;
pointer = this.storage[id]; pointer = this.storage[id];

View file

@ -13,9 +13,7 @@ v8Util = process.atomBinding('v8_util');
IDWeakMap = process.atomBinding('id_weak_map').IDWeakMap; IDWeakMap = process.atomBinding('id_weak_map').IDWeakMap;
// Convert a real value into meta data.
/* Convert a real value into meta data. */
valueToMeta = function(sender, value, optimizeSimpleObject) { valueToMeta = function(sender, value, optimizeSimpleObject) {
var el, field, i, len, meta, name; var el, field, i, len, meta, name;
if (optimizeSimpleObject == null) { if (optimizeSimpleObject == null) {
@ -43,12 +41,12 @@ valueToMeta = function(sender, value, optimizeSimpleObject) {
meta.type = 'promise'; meta.type = 'promise';
} }
/* Treat simple objects as value. */ // Treat simple objects as value.
if (optimizeSimpleObject && meta.type === 'object' && v8Util.getHiddenValue(value, 'simple')) { if (optimizeSimpleObject && meta.type === 'object' && v8Util.getHiddenValue(value, 'simple')) {
meta.type = 'value'; meta.type = 'value';
} }
/* Treat the arguments object as array. */ // Treat the arguments object as array.
if (meta.type === 'object' && (value.callee != null) && (value.length != null)) { if (meta.type === 'object' && (value.callee != null) && (value.length != null)) {
meta.type = 'array'; meta.type = 'array';
} }
@ -61,11 +59,9 @@ valueToMeta = function(sender, value, optimizeSimpleObject) {
} else if (meta.type === 'object' || meta.type === 'function') { } else if (meta.type === 'object' || meta.type === 'function') {
meta.name = value.constructor.name; meta.name = value.constructor.name;
/* // Reference the original value if it's an object, because when it's
Reference the original value if it's an object, because when it's // passed to renderer we would assume the renderer keeps a reference of
passed to renderer we would assume the renderer keeps a reference of // it.
it.
*/
meta.id = objectsRegistry.add(sender.getId(), value); meta.id = objectsRegistry.add(sender.getId(), value);
meta.members = (function() { meta.members = (function() {
var results; var results;
@ -86,7 +82,7 @@ valueToMeta = function(sender, value, optimizeSimpleObject) {
} else if (meta.type === 'error') { } else if (meta.type === 'error') {
meta.members = plainObjectToMeta(value); meta.members = plainObjectToMeta(value);
/* Error.name is not part of own properties. */ // Error.name is not part of own properties.
meta.members.push({ meta.members.push({
name: 'name', name: 'name',
value: value.name value: value.name
@ -100,9 +96,7 @@ valueToMeta = function(sender, value, optimizeSimpleObject) {
return meta; return meta;
}; };
// Convert object to meta by value.
/* Convert object to meta by value. */
plainObjectToMeta = function(obj) { plainObjectToMeta = function(obj) {
return Object.getOwnPropertyNames(obj).map(function(name) { return Object.getOwnPropertyNames(obj).map(function(name) {
return { return {
@ -112,9 +106,7 @@ plainObjectToMeta = function(obj) {
}); });
}; };
// Convert Error into meta data.
/* Convert Error into meta data. */
exceptionToMeta = function(error) { exceptionToMeta = function(error) {
return { return {
type: 'exception', type: 'exception',
@ -123,9 +115,7 @@ exceptionToMeta = function(error) {
}; };
}; };
// Convert array of meta data from renderer into array of real values.
/* Convert array of meta data from renderer into array of real values. */
unwrapArgs = function(sender, args) { unwrapArgs = function(sender, args) {
var metaToValue; var metaToValue;
metaToValue = function(meta) { metaToValue = function(meta) {
@ -159,8 +149,7 @@ unwrapArgs = function(sender, args) {
return returnValue; return returnValue;
}; };
case 'function': case 'function':
// Cache the callbacks in renderer.
/* Cache the callbacks in renderer. */
if (!sender.callbacks) { if (!sender.callbacks) {
sender.callbacks = new IDWeakMap; sender.callbacks = new IDWeakMap;
sender.on('render-view-deleted', function() { sender.on('render-view-deleted', function() {
@ -196,12 +185,8 @@ unwrapArgs = function(sender, args) {
return args.map(metaToValue); return args.map(metaToValue);
}; };
// Call a function and send reply asynchronously if it's a an asynchronous
/* // style function and the caller didn't pass a callback.
Call a function and send reply asynchronously if it's a an asynchronous
style function and the caller didn't pass a callback.
*/
callFunction = function(event, func, caller, args) { callFunction = function(event, func, caller, args) {
var e, error1, funcMarkedAsync, funcName, funcPassedCallback, ref, ret; var e, error1, funcMarkedAsync, funcName, funcPassedCallback, ref, ret;
funcMarkedAsync = v8Util.getHiddenValue(func, 'asynchronous'); funcMarkedAsync = v8Util.getHiddenValue(func, 'asynchronous');
@ -219,19 +204,15 @@ callFunction = function(event, func, caller, args) {
} catch (error1) { } catch (error1) {
e = error1; e = error1;
/* // Catch functions thrown further down in function invocation and wrap
Catch functions thrown further down in function invocation and wrap // them with the function name so it's easier to trace things like
them with the function name so it's easier to trace things like // `Error processing argument -1.`
`Error processing argument -1.`
*/
funcName = (ref = func.name) != null ? ref : "anonymous"; funcName = (ref = func.name) != null ? ref : "anonymous";
throw new Error("Could not call remote function `" + funcName + "`. Check that the function signature is correct. Underlying error: " + e.message); throw new Error("Could not call remote function `" + funcName + "`. Check that the function signature is correct. Underlying error: " + e.message);
} }
}; };
// Send by BrowserWindow when its render view is deleted.
/* Send by BrowserWindow when its render view is deleted. */
process.on('ATOM_BROWSER_RELEASE_RENDER_VIEW', function(id) { process.on('ATOM_BROWSER_RELEASE_RENDER_VIEW', function(id) {
return objectsRegistry.clear(id); return objectsRegistry.clear(id);
}); });
@ -286,10 +267,8 @@ ipcMain.on('ATOM_BROWSER_CONSTRUCTOR', function(event, id, args) {
args = unwrapArgs(event.sender, args); args = unwrapArgs(event.sender, args);
constructor = objectsRegistry.get(id); constructor = objectsRegistry.get(id);
/* // Call new with array of arguments.
Call new with array of arguments. // http://stackoverflow.com/questions/1606797/use-of-apply-with-new-operator-is-this-possible
http://stackoverflow.com/questions/1606797/use-of-apply-with-new-operator-is-this-possible
*/
obj = new (Function.prototype.bind.apply(constructor, [null].concat(args))); obj = new (Function.prototype.bind.apply(constructor, [null].concat(args)));
return event.returnValue = valueToMeta(event.sender, obj); return event.returnValue = valueToMeta(event.sender, obj);
} catch (error1) { } catch (error1) {
@ -316,7 +295,7 @@ ipcMain.on('ATOM_BROWSER_MEMBER_CONSTRUCTOR', function(event, id, method, args)
args = unwrapArgs(event.sender, args); args = unwrapArgs(event.sender, args);
constructor = objectsRegistry.get(id)[method]; constructor = objectsRegistry.get(id)[method];
/* Call new with array of arguments. */ // Call new with array of arguments.
obj = new (Function.prototype.bind.apply(constructor, [null].concat(args))); obj = new (Function.prototype.bind.apply(constructor, [null].concat(args)));
return event.returnValue = valueToMeta(event.sender, obj); return event.returnValue = valueToMeta(event.sender, obj);
} catch (error1) { } catch (error1) {

View file

@ -10,8 +10,7 @@ module.exports = CallbacksRegistry = (function() {
} }
CallbacksRegistry.prototype.add = function(callback) { CallbacksRegistry.prototype.add = function(callback) {
// The callback is already added.
/* The callback is already added. */
var filenameAndLine, id, location, match, ref, regexp, stackString, x; var filenameAndLine, id, location, match, ref, regexp, stackString, x;
id = v8Util.getHiddenValue(callback, 'callbackId'); id = v8Util.getHiddenValue(callback, 'callbackId');
if (id != null) { if (id != null) {
@ -19,10 +18,8 @@ module.exports = CallbacksRegistry = (function() {
} }
id = ++this.nextId; id = ++this.nextId;
/* // Capture the location of the function and put it in the ID string,
Capture the location of the function and put it in the ID string, // so that release errors can be tracked down easily.
so that release errors can be tracked down easily.
*/
regexp = /at (.*)/gi; regexp = /at (.*)/gi;
stackString = (new Error).stack; stackString = (new Error).stack;
while ((match = regexp.exec(stackString)) !== null) { while ((match = regexp.exec(stackString)) !== null) {

View file

@ -1,6 +1,5 @@
if (process.platform === 'linux' && process.type === 'renderer') { if (process.platform === 'linux' && process.type === 'renderer') {
// On Linux we could not access clipboard in renderer process.
/* On Linux we could not access clipboard in renderer process. */
module.exports = require('electron').remote.clipboard; module.exports = require('electron').remote.clipboard;
} else { } else {
module.exports = process.atomBinding('clipboard'); module.exports = process.atomBinding('clipboard');

View file

@ -22,7 +22,7 @@ CrashReporter = (function() {
} }
this.productName = options.productName, companyName = options.companyName, submitURL = options.submitURL, autoSubmit = options.autoSubmit, ignoreSystemCrashHandler = options.ignoreSystemCrashHandler, extra = options.extra; this.productName = options.productName, companyName = options.companyName, submitURL = options.submitURL, autoSubmit = options.autoSubmit, ignoreSystemCrashHandler = options.ignoreSystemCrashHandler, extra = options.extra;
/* Deprecated. */ // Deprecated.
deprecate = electron.deprecate; deprecate = electron.deprecate;
if (options.submitUrl) { if (options.submitUrl) {
if (submitURL == null) { if (submitURL == null) {

View file

@ -1,5 +1,4 @@
// Deprecate a method.
/* Deprecate a method. */
var deprecate, var deprecate,
slice = [].slice; slice = [].slice;
@ -15,9 +14,7 @@ deprecate = function(oldName, newName, fn) {
}; };
}; };
// The method is renamed.
/* The method is renamed. */
deprecate.rename = function(object, oldName, newName) { deprecate.rename = function(object, oldName, newName) {
var newMethod, warned; var newMethod, warned;
warned = false; warned = false;
@ -35,9 +32,7 @@ deprecate.rename = function(object, oldName, newName) {
} }
}; };
// Forward the method to member.
/* Forward the method to member. */
deprecate.member = function(object, method, member) { deprecate.member = function(object, method, member) {
var warned; var warned;
warned = false; warned = false;
@ -50,9 +45,7 @@ deprecate.member = function(object, method, member) {
}; };
}; };
// Deprecate a property.
/* Deprecate a property. */
deprecate.property = function(object, property, method) { deprecate.property = function(object, property, method) {
return Object.defineProperty(object, property, { return Object.defineProperty(object, property, {
get: function() { get: function() {
@ -67,9 +60,7 @@ deprecate.property = function(object, property, method) {
}); });
}; };
// Deprecate an event.
/* Deprecate an event. */
deprecate.event = function(emitter, oldName, newName, fn) { deprecate.event = function(emitter, oldName, newName, fn) {
var warned; var warned;
warned = false; warned = false;
@ -77,7 +68,7 @@ deprecate.event = function(emitter, oldName, newName, fn) {
var args; var args;
args = 1 <= arguments.length ? slice.call(arguments, 0) : []; args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
/* there is listeners for old API. */ // there is listeners for old API.
if (this.listenerCount(oldName) > 0) { if (this.listenerCount(oldName) > 0) {
if (!(warned || process.noDeprecation)) { if (!(warned || process.noDeprecation)) {
warned = true; warned = true;
@ -92,16 +83,12 @@ deprecate.event = function(emitter, oldName, newName, fn) {
}); });
}; };
// Print deprecation warning.
/* Print deprecation warning. */
deprecate.warn = function(oldName, newName) { deprecate.warn = function(oldName, newName) {
return deprecate.log(oldName + " is deprecated. Use " + newName + " instead."); return deprecate.log(oldName + " is deprecated. Use " + newName + " instead.");
}; };
// Print deprecation message.
/* Print deprecation message. */
deprecate.log = function(message) { deprecate.log = function(message) {
if (process.throwDeprecation) { if (process.throwDeprecation) {
throw new Error(message); throw new Error(message);

View file

@ -1,25 +1,22 @@
// Do not expose the internal modules to `require`.
/* Do not expose the internal modules to `require`. */
exports.hideInternalModules = function() { exports.hideInternalModules = function() {
var globalPaths; var globalPaths;
globalPaths = require('module').globalPaths; globalPaths = require('module').globalPaths;
if (globalPaths.length === 3) { if (globalPaths.length === 3) {
/* Remove the "common/api/lib" and "browser-or-renderer/api/lib". */ // Remove the "common/api/lib" and "browser-or-renderer/api/lib".
return globalPaths.splice(0, 2); return globalPaths.splice(0, 2);
} }
}; };
// Attaches properties to |exports|.
/* Attaches properties to |exports|. */
exports.defineProperties = function(exports) { exports.defineProperties = function(exports) {
return Object.defineProperties(exports, { return Object.defineProperties(exports, {
/* Common modules, please sort with alphabet order. */ // Common modules, please sort with alphabet order.
clipboard: { clipboard: {
/* Must be enumerable, otherwise it woulde be invisible to remote module. */ // Must be enumerable, otherwise it woulde be invisible to remote module.
enumerable: true, enumerable: true,
get: function() { get: function() {
return require('../clipboard'); return require('../clipboard');
@ -44,7 +41,7 @@ exports.defineProperties = function(exports) {
} }
}, },
/* The internal modules, invisible unless you know their names. */ // The internal modules, invisible unless you know their names.
CallbacksRegistry: { CallbacksRegistry: {
get: function() { get: function() {
return require('../callbacks-registry'); return require('../callbacks-registry');

View file

@ -4,9 +4,7 @@ deprecate = require('electron').deprecate;
nativeImage = process.atomBinding('native_image'); nativeImage = process.atomBinding('native_image');
// Deprecated.
/* Deprecated. */
deprecate.rename(nativeImage, 'createFromDataUrl', 'createFromDataURL'); deprecate.rename(nativeImage, 'createFromDataUrl', 'createFromDataURL');
module.exports = nativeImage; module.exports = nativeImage;

View file

@ -10,9 +10,7 @@ path = require('path');
util = require('util'); util = require('util');
// Cache asar archive objects.
/* Cache asar archive objects. */
cachedArchives = {}; cachedArchives = {};
getOrCreateArchive = function(p) { getOrCreateArchive = function(p) {
@ -28,9 +26,7 @@ getOrCreateArchive = function(p) {
return cachedArchives[p] = archive; return cachedArchives[p] = archive;
}; };
// Clean cache on quit.
/* Clean cache on quit. */
process.on('exit', function() { process.on('exit', function() {
var archive, p, results; var archive, p, results;
results = []; results = [];
@ -42,12 +38,10 @@ process.on('exit', function() {
return results; return results;
}); });
// Separate asar package's path from full path.
/* Separate asar package's path from full path. */
splitPath = function(p) { splitPath = function(p) {
/* shortcut to disable asar. */ // shortcut to disable asar.
var index; var index;
if (process.noAsar) { if (process.noAsar) {
return [false]; return [false];
@ -66,9 +60,7 @@ splitPath = function(p) {
return [true, p.substr(0, index + 5), p.substr(index + 6)]; return [true, p.substr(0, index + 5), p.substr(index + 6)];
}; };
// Convert asar archive's Stats object to fs's Stats object.
/* Convert asar archive's Stats object to fs's Stats object. */
nextInode = 0; nextInode = 0;
uid = process.getuid != null ? process.getuid() : 0; uid = process.getuid != null ? process.getuid() : 0;
@ -115,9 +107,7 @@ asarStatsToFsStats = function(stats) {
}; };
}; };
// Create a ENOENT error.
/* Create a ENOENT error. */
notFoundError = function(asarPath, filePath, callback) { notFoundError = function(asarPath, filePath, callback) {
var error; var error;
error = new Error("ENOENT, " + filePath + " not found in " + asarPath); error = new Error("ENOENT, " + filePath + " not found in " + asarPath);
@ -131,9 +121,7 @@ notFoundError = function(asarPath, filePath, callback) {
}); });
}; };
// Create a ENOTDIR error.
/* Create a ENOTDIR error. */
notDirError = function(callback) { notDirError = function(callback) {
var error; var error;
error = new Error('ENOTDIR, not a directory'); error = new Error('ENOTDIR, not a directory');
@ -147,9 +135,7 @@ notDirError = function(callback) {
}); });
}; };
// Create invalid archive error.
/* Create invalid archive error. */
invalidArchiveError = function(asarPath, callback) { invalidArchiveError = function(asarPath, callback) {
var error; var error;
error = new Error("Invalid package " + asarPath); error = new Error("Invalid package " + asarPath);
@ -161,9 +147,7 @@ invalidArchiveError = function(asarPath, callback) {
}); });
}; };
// Override APIs that rely on passing file path instead of content to C++.
/* Override APIs that rely on passing file path instead of content to C++. */
overrideAPISync = function(module, name, arg) { overrideAPISync = function(module, name, arg) {
var old; var old;
if (arg == null) { if (arg == null) {
@ -220,9 +204,7 @@ overrideAPI = function(module, name, arg) {
}; };
}; };
// Override fs APIs.
/* Override fs APIs. */
exports.wrapFsWithAsar = function(fs) { exports.wrapFsWithAsar = function(fs) {
var exists, existsSync, internalModuleReadFile, internalModuleStat, lstat, lstatSync, mkdir, mkdirSync, open, openSync, readFile, readFileSync, readdir, readdirSync, realpath, realpathSync, stat, statSync, statSyncNoException; var exists, existsSync, internalModuleReadFile, internalModuleStat, lstat, lstatSync, mkdir, mkdirSync, open, openSync, readFile, readFileSync, readdir, readdirSync, realpath, realpathSync, stat, statSync, statSyncNoException;
lstatSync = fs.lstatSync; lstatSync = fs.lstatSync;
@ -269,7 +251,7 @@ exports.wrapFsWithAsar = function(fs) {
return statSync(p); return statSync(p);
} }
/* Do not distinguish links for now. */ // Do not distinguish links for now.
return fs.lstatSync(p); return fs.lstatSync(p);
}; };
stat = fs.stat; stat = fs.stat;
@ -280,7 +262,7 @@ exports.wrapFsWithAsar = function(fs) {
return stat(p, callback); return stat(p, callback);
} }
/* Do not distinguish links for now. */ // Do not distinguish links for now.
return process.nextTick(function() { return process.nextTick(function() {
return fs.lstat(p, callback); return fs.lstat(p, callback);
}); });
@ -427,7 +409,7 @@ exports.wrapFsWithAsar = function(fs) {
readFileSync = fs.readFileSync; readFileSync = fs.readFileSync;
fs.readFileSync = function(p, opts) { fs.readFileSync = function(p, opts) {
/* this allows v8 to optimize this function */ // this allows v8 to optimize this function
var archive, asarPath, buffer, encoding, fd, filePath, info, isAsar, options, realPath, ref; var archive, asarPath, buffer, encoding, fd, filePath, info, isAsar, options, realPath, ref;
options = opts; options = opts;
ref = splitPath(p), isAsar = ref[0], asarPath = ref[1], filePath = ref[2]; ref = splitPath(p), isAsar = ref[0], asarPath = ref[1], filePath = ref[2];
@ -554,13 +536,13 @@ exports.wrapFsWithAsar = function(fs) {
} }
archive = getOrCreateArchive(asarPath); archive = getOrCreateArchive(asarPath);
/* -ENOENT */ // -ENOENT
if (!archive) { if (!archive) {
return -34; return -34;
} }
stats = archive.stat(filePath); stats = archive.stat(filePath);
/* -ENOENT */ // -ENOENT
if (!stats) { if (!stats) {
return -34; return -34;
} }
@ -571,12 +553,10 @@ exports.wrapFsWithAsar = function(fs) {
} }
}; };
/* // Calling mkdir for directory inside asar archive should throw ENOTDIR
Calling mkdir for directory inside asar archive should throw ENOTDIR // error, but on Windows it throws ENOENT.
error, but on Windows it throws ENOENT. // This is to work around the recursive looping bug of mkdirp since it is
This is to work around the recursive looping bug of mkdirp since it is // widely used.
widely used.
*/
if (process.platform === 'win32') { if (process.platform === 'win32') {
mkdir = fs.mkdir; mkdir = fs.mkdir;
fs.mkdir = function(p, mode, callback) { fs.mkdir = function(p, mode, callback) {

View file

@ -3,13 +3,13 @@ return function(process, require, asarSource) {
var createArchive, source; var createArchive, source;
createArchive = process.binding('atom_common_asar').createArchive; createArchive = process.binding('atom_common_asar').createArchive;
/* Make asar.coffee accessible via "require". */ // Make asar.coffee accessible via "require".
process.binding('natives').ATOM_SHELL_ASAR = asarSource; process.binding('natives').ATOM_SHELL_ASAR = asarSource;
/* Monkey-patch the fs module. */ // Monkey-patch the fs module.
require('ATOM_SHELL_ASAR').wrapFsWithAsar(require('fs')); require('ATOM_SHELL_ASAR').wrapFsWithAsar(require('fs'));
/* Make graceful-fs work with asar. */ // Make graceful-fs work with asar.
source = process.binding('natives'); source = process.binding('natives');
source['original-fs'] = source.fs; source['original-fs'] = source.fs;
return source['fs'] = "var src = '(function (exports, require, module, __filename, __dirname) { ' +\n process.binding('natives')['original-fs'] +\n ' });';\nvar vm = require('vm');\nvar fn = vm.runInThisContext(src, { filename: 'fs.js' });\nfn(exports, require, module);\nvar asar = require('ATOM_SHELL_ASAR');\nasar.wrapFsWithAsar(exports);"; return source['fs'] = "var src = '(function (exports, require, module, __filename, __dirname) { ' +\n process.binding('natives')['original-fs'] +\n ' });';\nvar vm = require('vm');\nvar fn = vm.runInThisContext(src, { filename: 'fs.js' });\nfn(exports, require, module);\nvar asar = require('ATOM_SHELL_ASAR');\nasar.wrapFsWithAsar(exports);";

View file

@ -21,21 +21,17 @@ process.atomBinding = function(name) {
}; };
if (!process.env.ELECTRON_HIDE_INTERNAL_MODULES) { if (!process.env.ELECTRON_HIDE_INTERNAL_MODULES) {
// Add common/api/lib to module search paths.
/* Add common/api/lib to module search paths. */
Module.globalPaths.push(path.resolve(__dirname, '..', 'api', 'lib')); Module.globalPaths.push(path.resolve(__dirname, '..', 'api', 'lib'));
} }
/* // setImmediate and process.nextTick makes use of uv_check and uv_prepare to
setImmediate and process.nextTick makes use of uv_check and uv_prepare to // run the callbacks, however since we only run uv loop on requests, the
run the callbacks, however since we only run uv loop on requests, the // callbacks wouldn't be called until something else activated the uv loop,
callbacks wouldn't be called until something else activated the uv loop, // which would delay the callbacks for arbitrary long time. So we should
which would delay the callbacks for arbitrary long time. So we should // initiatively activate the uv loop once setImmediate and process.nextTick is
initiatively activate the uv loop once setImmediate and process.nextTick is // called.
called.
*/
wrapWithActivateUvLoop = function(func) { wrapWithActivateUvLoop = function(func) {
return function() { return function() {
process.activateUvLoop(); process.activateUvLoop();
@ -50,13 +46,10 @@ global.setImmediate = wrapWithActivateUvLoop(timers.setImmediate);
global.clearImmediate = timers.clearImmediate; global.clearImmediate = timers.clearImmediate;
if (process.type === 'browser') { if (process.type === 'browser') {
// setTimeout needs to update the polling timeout of the event loop, when
/* // called under Chromium's event loop the node's event loop won't get a chance
setTimeout needs to update the polling timeout of the event loop, when // to update the timeout, so we have to force the node's event loop to
called under Chromium's event loop the node's event loop won't get a chance // recalculate the timeout in browser process.
to update the timeout, so we have to force the node's event loop to
recalculate the timeout in browser process.
*/
global.setTimeout = wrapWithActivateUvLoop(timers.setTimeout); global.setTimeout = wrapWithActivateUvLoop(timers.setTimeout);
global.setInterval = wrapWithActivateUvLoop(timers.setInterval); global.setInterval = wrapWithActivateUvLoop(timers.setInterval);
} }

View file

@ -4,29 +4,23 @@ path = require('path');
Module = require('module'); Module = require('module');
// Clear Node's global search paths.
/* Clear Node's global search paths. */
Module.globalPaths.length = 0; Module.globalPaths.length = 0;
// Clear current and parent(init.coffee)'s search paths.
/* Clear current and parent(init.coffee)'s search paths. */
module.paths = []; module.paths = [];
module.parent.paths = []; module.parent.paths = [];
// Prevent Node from adding paths outside this app to search paths.
/* Prevent Node from adding paths outside this app to search paths. */
Module._nodeModulePaths = function(from) { Module._nodeModulePaths = function(from) {
var dir, i, part, parts, paths, skipOutsidePaths, splitRe, tip; var dir, i, part, parts, paths, skipOutsidePaths, splitRe, tip;
from = path.resolve(from); from = path.resolve(from);
/* If "from" is outside the app then we do nothing. */ // If "from" is outside the app then we do nothing.
skipOutsidePaths = from.startsWith(process.resourcesPath); skipOutsidePaths = from.startsWith(process.resourcesPath);
/* Following logoic is copied from module.js. */ // Following logoic is copied from module.js.
splitRe = process.platform === 'win32' ? /[\/\\]/ : /\//; splitRe = process.platform === 'win32' ? /[\/\\]/ : /\//;
paths = []; paths = [];
parts = from.split(splitRe); parts = from.split(splitRe);

View file

@ -9,9 +9,7 @@ getNextId = function() {
return ++nextId; return ++nextId;
}; };
// |options.type| can not be empty and has to include 'window' or 'screen'.
/* |options.type| can not be empty and has to include 'window' or 'screen'. */
isValid = function(options) { isValid = function(options) {
return ((options != null ? options.types : void 0) != null) && Array.isArray(options.types); return ((options != null ? options.types : void 0) != null) && Array.isArray(options.types);
}; };

View file

@ -2,14 +2,11 @@ var common;
common = require('../../../../common/api/lib/exports/electron'); common = require('../../../../common/api/lib/exports/electron');
// Import common modules.
/* Import common modules. */
common.defineProperties(exports); common.defineProperties(exports);
Object.defineProperties(exports, { Object.defineProperties(exports, {
// Renderer side modules, please sort with alphabet order.
/* Renderer side modules, please sort with alphabet order. */
desktopCapturer: { desktopCapturer: {
enumerable: true, enumerable: true,
get: function() { get: function() {

View file

@ -7,9 +7,7 @@ binding = process.atomBinding('ipc');
v8Util = process.atomBinding('v8_util'); v8Util = process.atomBinding('v8_util');
// Created by init.coffee.
/* Created by init.coffee. */
ipcRenderer = v8Util.getHiddenValue(global, 'ipc'); ipcRenderer = v8Util.getHiddenValue(global, 'ipc');
ipcRenderer.send = function() { ipcRenderer.send = function() {

View file

@ -5,14 +5,10 @@ ref = require('electron'), ipcRenderer = ref.ipcRenderer, deprecate = ref.deprec
EventEmitter = require('events').EventEmitter; EventEmitter = require('events').EventEmitter;
// This module is deprecated, we mirror everything from ipcRenderer.
/* This module is deprecated, we mirror everything from ipcRenderer. */
deprecate.warn('ipc module', 'require("electron").ipcRenderer'); deprecate.warn('ipc module', 'require("electron").ipcRenderer');
// Routes events of ipcRenderer.
/* Routes events of ipcRenderer. */
ipc = new EventEmitter; ipc = new EventEmitter;
ipcRenderer.emit = function() { ipcRenderer.emit = function() {
@ -22,9 +18,7 @@ ipcRenderer.emit = function() {
return EventEmitter.prototype.emit.apply(ipcRenderer, arguments); return EventEmitter.prototype.emit.apply(ipcRenderer, arguments);
}; };
// Deprecated.
/* Deprecated. */
for (method in ipcRenderer) { for (method in ipcRenderer) {
if (method.startsWith('send')) { if (method.startsWith('send')) {
ipc[method] = ipcRenderer[method]; ipc[method] = ipcRenderer[method];

View file

@ -7,9 +7,7 @@ v8Util = process.atomBinding('v8_util');
callbacksRegistry = new CallbacksRegistry; callbacksRegistry = new CallbacksRegistry;
// Check for circular reference.
/* Check for circular reference. */
isCircular = function(field, visited) { isCircular = function(field, visited) {
if (typeof field === 'object') { if (typeof field === 'object') {
if (indexOf.call(visited, field) >= 0) { if (indexOf.call(visited, field) >= 0) {
@ -20,9 +18,7 @@ isCircular = function(field, visited) {
return false; return false;
}; };
// Convert the arguments object into an array of meta data.
/* Convert the arguments object into an array of meta data. */
wrapArgs = function(args, visited) { wrapArgs = function(args, visited) {
var valueToMeta; var valueToMeta;
if (visited == null) { if (visited == null) {
@ -90,9 +86,7 @@ wrapArgs = function(args, visited) {
return Array.prototype.slice.call(args).map(valueToMeta); return Array.prototype.slice.call(args).map(valueToMeta);
}; };
// Convert meta data from browser into real value.
/* Convert meta data from browser into real value. */
metaToValue = function(meta) { metaToValue = function(meta) {
var RemoteFunction, el, i, j, len, len1, member, ref1, ref2, results, ret; var RemoteFunction, el, i, j, len, len1, member, ref1, ref2, results, ret;
switch (meta.type) { switch (meta.type) {
@ -121,14 +115,13 @@ metaToValue = function(meta) {
break; break;
default: default:
if (meta.type === 'function') { if (meta.type === 'function') {
// A shadow class to represent the remote function object.
/* A shadow class to represent the remote function object. */
ret = RemoteFunction = (function() { ret = RemoteFunction = (function() {
function RemoteFunction() { function RemoteFunction() {
var obj; var obj;
if (this.constructor === RemoteFunction) { if (this.constructor === RemoteFunction) {
/* Constructor call. */ // Constructor call.
obj = ipcRenderer.sendSync('ATOM_BROWSER_CONSTRUCTOR', meta.id, wrapArgs(arguments)); obj = ipcRenderer.sendSync('ATOM_BROWSER_CONSTRUCTOR', meta.id, wrapArgs(arguments));
/* /*
@ -139,7 +132,7 @@ metaToValue = function(meta) {
return metaToValue(obj); return metaToValue(obj);
} else { } else {
/* Function call. */ // Function call.
obj = ipcRenderer.sendSync('ATOM_BROWSER_FUNCTION_CALL', meta.id, wrapArgs(arguments)); obj = ipcRenderer.sendSync('ATOM_BROWSER_FUNCTION_CALL', meta.id, wrapArgs(arguments));
return metaToValue(obj); return metaToValue(obj);
} }
@ -152,7 +145,7 @@ metaToValue = function(meta) {
ret = v8Util.createObjectWithName(meta.name); ret = v8Util.createObjectWithName(meta.name);
} }
/* Polulate delegate members. */ // Polulate delegate members.
ref2 = meta.members; ref2 = meta.members;
for (j = 0, len1 = ref2.length; j < len1; j++) { for (j = 0, len1 = ref2.length; j < len1; j++) {
member = ref2[j]; member = ref2[j];
@ -163,23 +156,19 @@ metaToValue = function(meta) {
} }
} }
/* // Track delegate object's life time, and tell the browser to clean up
Track delegate object's life time, and tell the browser to clean up // when the object is GCed.
when the object is GCed.
*/
v8Util.setDestructor(ret, function() { v8Util.setDestructor(ret, function() {
return ipcRenderer.send('ATOM_BROWSER_DEREFERENCE', meta.id); return ipcRenderer.send('ATOM_BROWSER_DEREFERENCE', meta.id);
}); });
/* Remember object's id. */ // Remember object's id.
v8Util.setHiddenValue(ret, 'atomId', meta.id); v8Util.setHiddenValue(ret, 'atomId', meta.id);
return ret; return ret;
} }
}; };
// Construct a plain object from the meta.
/* Construct a plain object from the meta. */
metaToPlainObject = function(meta) { metaToPlainObject = function(meta) {
var i, len, name, obj, ref1, ref2, value; var i, len, name, obj, ref1, ref2, value;
obj = (function() { obj = (function() {
@ -198,13 +187,9 @@ metaToPlainObject = function(meta) {
return obj; return obj;
}; };
// Create a RemoteMemberFunction instance.
/* // This function's content should not be inlined into metaToValue, otherwise V8
Create a RemoteMemberFunction instance. // may consider it circular reference.
This function's content should not be inlined into metaToValue, otherwise V8
may consider it circular reference.
*/
createRemoteMemberFunction = function(metaId, name) { createRemoteMemberFunction = function(metaId, name) {
var RemoteMemberFunction; var RemoteMemberFunction;
return RemoteMemberFunction = (function() { return RemoteMemberFunction = (function() {
@ -212,12 +197,12 @@ createRemoteMemberFunction = function(metaId, name) {
var ret; var ret;
if (this.constructor === RemoteMemberFunction) { if (this.constructor === RemoteMemberFunction) {
/* Constructor call. */ // Constructor call.
ret = ipcRenderer.sendSync('ATOM_BROWSER_MEMBER_CONSTRUCTOR', metaId, name, wrapArgs(arguments)); ret = ipcRenderer.sendSync('ATOM_BROWSER_MEMBER_CONSTRUCTOR', metaId, name, wrapArgs(arguments));
return metaToValue(ret); return metaToValue(ret);
} else { } else {
/* Call member function. */ // Call member function.
ret = ipcRenderer.sendSync('ATOM_BROWSER_MEMBER_CALL', metaId, name, wrapArgs(arguments)); ret = ipcRenderer.sendSync('ATOM_BROWSER_MEMBER_CALL', metaId, name, wrapArgs(arguments));
return metaToValue(ret); return metaToValue(ret);
} }
@ -228,53 +213,41 @@ createRemoteMemberFunction = function(metaId, name) {
})(); })();
}; };
// Create configuration for defineProperty.
/* // This function's content should not be inlined into metaToValue, otherwise V8
Create configuration for defineProperty. // may consider it circular reference.
This function's content should not be inlined into metaToValue, otherwise V8
may consider it circular reference.
*/
createRemoteMemberProperty = function(metaId, name) { createRemoteMemberProperty = function(metaId, name) {
return { return {
enumerable: true, enumerable: true,
configurable: false, configurable: false,
set: function(value) { set: function(value) {
/* Set member data. */ // Set member data.
ipcRenderer.sendSync('ATOM_BROWSER_MEMBER_SET', metaId, name, value); ipcRenderer.sendSync('ATOM_BROWSER_MEMBER_SET', metaId, name, value);
return value; return value;
}, },
get: function() { get: function() {
/* Get member data. */ // Get member data.
return metaToValue(ipcRenderer.sendSync('ATOM_BROWSER_MEMBER_GET', metaId, name)); return metaToValue(ipcRenderer.sendSync('ATOM_BROWSER_MEMBER_GET', metaId, name));
} }
}; };
}; };
// Browser calls a callback in renderer.
/* Browser calls a callback in renderer. */
ipcRenderer.on('ATOM_RENDERER_CALLBACK', function(event, id, args) { ipcRenderer.on('ATOM_RENDERER_CALLBACK', function(event, id, args) {
return callbacksRegistry.apply(id, metaToValue(args)); return callbacksRegistry.apply(id, metaToValue(args));
}); });
// A callback in browser is released.
/* A callback in browser is released. */
ipcRenderer.on('ATOM_RENDERER_RELEASE_CALLBACK', function(event, id) { ipcRenderer.on('ATOM_RENDERER_RELEASE_CALLBACK', function(event, id) {
return callbacksRegistry.remove(id); return callbacksRegistry.remove(id);
}); });
// List all built-in modules in browser process.
/* List all built-in modules in browser process. */
browserModules = require('../../../browser/api/lib/exports/electron'); browserModules = require('../../../browser/api/lib/exports/electron');
// And add a helper receiver for each one.
/* And add a helper receiver for each one. */
fn = function(name) { fn = function(name) {
return Object.defineProperty(exports, name, { return Object.defineProperty(exports, name, {
get: function() { get: function() {
@ -287,12 +260,9 @@ for (name in browserModules) {
} }
/* // Get remote module.
Get remote module. // (Just like node's require, the modules are cached permanently, note that this
(Just like node's require, the modules are cached permanently, note that this // is safe leak since the object is not expected to get freed in browser)
is safe leak since the object is not expected to get freed in browser)
*/
moduleCache = {}; moduleCache = {};
exports.require = function(module) { exports.require = function(module) {
@ -305,13 +275,11 @@ exports.require = function(module) {
}; };
/* Optimize require('electron'). */ // Optimize require('electron').
moduleCache.electron = exports; moduleCache.electron = exports;
/* Alias to remote.require('electron').xxx. */ // Alias to remote.require('electron').xxx.
builtinCache = {}; builtinCache = {};
exports.getBuiltin = function(module) { exports.getBuiltin = function(module) {
@ -323,9 +291,7 @@ exports.getBuiltin = function(module) {
return builtinCache[module] = metaToValue(meta); return builtinCache[module] = metaToValue(meta);
}; };
// Get current BrowserWindow object.
/* Get current BrowserWindow object. */
windowCache = null; windowCache = null;
exports.getCurrentWindow = function() { exports.getCurrentWindow = function() {
@ -337,9 +303,7 @@ exports.getCurrentWindow = function() {
return windowCache = metaToValue(meta); return windowCache = metaToValue(meta);
}; };
// Get current WebContents object.
/* Get current WebContents object. */
webContentsCache = null; webContentsCache = null;
exports.getCurrentWebContents = function() { exports.getCurrentWebContents = function() {
@ -351,18 +315,14 @@ exports.getCurrentWebContents = function() {
return webContentsCache = metaToValue(meta); return webContentsCache = metaToValue(meta);
}; };
// Get a global object in browser.
/* Get a global object in browser. */
exports.getGlobal = function(name) { exports.getGlobal = function(name) {
var meta; var meta;
meta = ipcRenderer.sendSync('ATOM_BROWSER_GLOBAL', name); meta = ipcRenderer.sendSync('ATOM_BROWSER_GLOBAL', name);
return metaToValue(meta); return metaToValue(meta);
}; };
// Get the process object in browser.
/* Get the process object in browser. */
processCache = null; processCache = null;
exports.__defineGetter__('process', function() { exports.__defineGetter__('process', function() {
@ -372,9 +332,7 @@ exports.__defineGetter__('process', function() {
return processCache; return processCache;
}); });
// Create a funtion that will return the specifed value when called in browser.
/* Create a funtion that will return the specifed value when called in browser. */
exports.createFunctionWithReturnValue = function(returnValue) { exports.createFunctionWithReturnValue = function(returnValue) {
var func; var func;
func = function() { func = function() {
@ -384,9 +342,7 @@ exports.createFunctionWithReturnValue = function(returnValue) {
return func; return func;
}; };
// Get the guest WebContents from guestInstanceId.
/* Get the guest WebContents from guestInstanceId. */
exports.getGuestWebContents = function(guestInstanceId) { exports.getGuestWebContents = function(guestInstanceId) {
var meta; var meta;
meta = ipcRenderer.sendSync('ATOM_BROWSER_GUEST_WEB_CONTENTS', guestInstanceId); meta = ipcRenderer.sendSync('ATOM_BROWSER_GUEST_WEB_CONTENTS', guestInstanceId);

View file

@ -11,21 +11,16 @@ url = require('url');
Module = require('module'); Module = require('module');
/* // We modified the original process.argv to let node.js load the
We modified the original process.argv to let node.js load the // atom-renderer.js, we need to restore it here.
atom-renderer.js, we need to restore it here.
*/
process.argv.splice(1, 1); process.argv.splice(1, 1);
/* Clear search paths. */ // Clear search paths.
require(path.resolve(__dirname, '..', '..', 'common', 'lib', 'reset-search-paths')); require(path.resolve(__dirname, '..', '..', 'common', 'lib', 'reset-search-paths'));
/* Import common settings. */ // Import common settings.
require(path.resolve(__dirname, '..', '..', 'common', 'lib', 'init')); require(path.resolve(__dirname, '..', '..', 'common', 'lib', 'init'));
globalPaths = Module.globalPaths; globalPaths = Module.globalPaths;
@ -34,14 +29,10 @@ if (!process.env.ELECTRON_HIDE_INTERNAL_MODULES) {
globalPaths.push(path.resolve(__dirname, '..', 'api', 'lib')); globalPaths.push(path.resolve(__dirname, '..', 'api', 'lib'));
} }
// Expose public APIs.
/* Expose public APIs. */
globalPaths.push(path.resolve(__dirname, '..', 'api', 'lib', 'exports')); globalPaths.push(path.resolve(__dirname, '..', 'api', 'lib', 'exports'));
// The global variable will be used by ipc for event dispatching
/* The global variable will be used by ipc for event dispatching */
v8Util = process.atomBinding('v8_util'); v8Util = process.atomBinding('v8_util');
v8Util.setHiddenValue(global, 'ipc', new events.EventEmitter); v8Util.setHiddenValue(global, 'ipc', new events.EventEmitter);
@ -54,20 +45,17 @@ electron.ipcRenderer.on('ELECTRON_INTERNAL_RENDERER_WEB_FRAME_METHOD', (event, m
electron.webFrame[method].apply(electron.webFrame, args); electron.webFrame[method].apply(electron.webFrame, args);
}); });
/* Process command line arguments. */ // Process command line arguments.
nodeIntegration = 'false'; nodeIntegration = 'false';
ref = process.argv; ref = process.argv;
for (i = 0, len = ref.length; i < len; i++) { for (i = 0, len = ref.length; i < len; i++) {
arg = ref[i]; arg = ref[i];
if (arg.indexOf('--guest-instance-id=') === 0) { if (arg.indexOf('--guest-instance-id=') === 0) {
// This is a guest web view.
/* This is a guest web view. */
process.guestInstanceId = parseInt(arg.substr(arg.indexOf('=') + 1)); process.guestInstanceId = parseInt(arg.substr(arg.indexOf('=') + 1));
} else if (arg.indexOf('--opener-id=') === 0) { } else if (arg.indexOf('--opener-id=') === 0) {
// This is a guest BrowserWindow.
/* This is a guest BrowserWindow. */
process.openerId = parseInt(arg.substr(arg.indexOf('=') + 1)); process.openerId = parseInt(arg.substr(arg.indexOf('=') + 1));
} else if (arg.indexOf('--node-integration=') === 0) { } else if (arg.indexOf('--node-integration=') === 0) {
nodeIntegration = arg.substr(arg.indexOf('=') + 1); nodeIntegration = arg.substr(arg.indexOf('=') + 1);
@ -77,21 +65,18 @@ for (i = 0, len = ref.length; i < len; i++) {
} }
if (location.protocol === 'chrome-devtools:') { if (location.protocol === 'chrome-devtools:') {
// Override some inspector APIs.
/* Override some inspector APIs. */
require('./inspector'); require('./inspector');
nodeIntegration = 'true'; nodeIntegration = 'true';
} else if (location.protocol === 'chrome-extension:') { } else if (location.protocol === 'chrome-extension:') {
// Add implementations of chrome API.
/* Add implementations of chrome API. */
require('./chrome-api'); require('./chrome-api');
nodeIntegration = 'true'; nodeIntegration = 'true';
} else { } else {
// Override default web functions.
/* Override default web functions. */
require('./override'); require('./override');
/* Load webview tag implementation. */ // Load webview tag implementation.
if (process.guestInstanceId == null) { if (process.guestInstanceId == null) {
require('./web-view/web-view'); require('./web-view/web-view');
require('./web-view/web-view-attributes'); require('./web-view/web-view-attributes');
@ -99,28 +84,27 @@ if (location.protocol === 'chrome-devtools:') {
} }
if (nodeIntegration === 'true' || nodeIntegration === 'all' || nodeIntegration === 'except-iframe' || nodeIntegration === 'manual-enable-iframe') { if (nodeIntegration === 'true' || nodeIntegration === 'all' || nodeIntegration === 'except-iframe' || nodeIntegration === 'manual-enable-iframe') {
// Export node bindings to global.
/* Export node bindings to global. */
global.require = require; global.require = require;
global.module = module; global.module = module;
/* Set the __filename to the path of html file if it is file: protocol. */ // Set the __filename to the path of html file if it is file: protocol.
if (window.location.protocol === 'file:') { if (window.location.protocol === 'file:') {
pathname = process.platform === 'win32' && window.location.pathname[0] === '/' ? window.location.pathname.substr(1) : window.location.pathname; pathname = process.platform === 'win32' && window.location.pathname[0] === '/' ? window.location.pathname.substr(1) : window.location.pathname;
global.__filename = path.normalize(decodeURIComponent(pathname)); global.__filename = path.normalize(decodeURIComponent(pathname));
global.__dirname = path.dirname(global.__filename); global.__dirname = path.dirname(global.__filename);
/* Set module's filename so relative require can work as expected. */ // Set module's filename so relative require can work as expected.
module.filename = global.__filename; module.filename = global.__filename;
/* Also search for module under the html file. */ // Also search for module under the html file.
module.paths = module.paths.concat(Module._nodeModulePaths(global.__dirname)); module.paths = module.paths.concat(Module._nodeModulePaths(global.__dirname));
} else { } else {
global.__filename = __filename; global.__filename = __filename;
global.__dirname = __dirname; global.__dirname = __dirname;
} }
/* Redirect window.onerror to uncaughtException. */ // Redirect window.onerror to uncaughtException.
window.onerror = function(message, filename, lineno, colno, error) { window.onerror = function(message, filename, lineno, colno, error) {
if (global.process.listeners('uncaughtException').length > 0) { if (global.process.listeners('uncaughtException').length > 0) {
global.process.emit('uncaughtException', error); global.process.emit('uncaughtException', error);
@ -130,13 +114,12 @@ if (nodeIntegration === 'true' || nodeIntegration === 'all' || nodeIntegration =
} }
}; };
/* Emit the 'exit' event when page is unloading. */ // Emit the 'exit' event when page is unloading.
window.addEventListener('unload', function() { window.addEventListener('unload', function() {
return process.emit('exit'); return process.emit('exit');
}); });
} else { } else {
// Delete Node's symbols after the Environment has been loaded.
/* Delete Node's symbols after the Environment has been loaded. */
process.once('loaded', function() { process.once('loaded', function() {
delete global.process; delete global.process;
delete global.setImmediate; delete global.setImmediate;
@ -145,9 +128,7 @@ if (nodeIntegration === 'true' || nodeIntegration === 'all' || nodeIntegration =
}); });
} }
// Load the script specfied by the "preload" attribute.
/* Load the script specfied by the "preload" attribute. */
if (preloadScript) { if (preloadScript) {
try { try {
require(preloadScript); require(preloadScript);

View file

@ -1,11 +1,10 @@
var convertToMenuTemplate, createFileSelectorElement, createMenu, pathToHtml5FileObject, showFileChooserDialog; var convertToMenuTemplate, createFileSelectorElement, createMenu, pathToHtml5FileObject, showFileChooserDialog;
window.onload = function() { window.onload = function() {
// Use menu API to show context menu.
/* Use menu API to show context menu. */
InspectorFrontendHost.showContextMenuAtPoint = createMenu; InspectorFrontendHost.showContextMenuAtPoint = createMenu;
/* Use dialog API to override file chooser dialog. */ // Use dialog API to override file chooser dialog.
return WebInspector.createFileSelectorElement = createFileSelectorElement; return WebInspector.createFileSelectorElement = createFileSelectorElement;
}; };
@ -52,7 +51,7 @@ createMenu = function(x, y, items, document) {
Menu = remote.Menu; Menu = remote.Menu;
menu = Menu.buildFromTemplate(convertToMenuTemplate(items)); menu = Menu.buildFromTemplate(convertToMenuTemplate(items));
/* The menu is expected to show asynchronously. */ // The menu is expected to show asynchronously.
return setTimeout(function() { return setTimeout(function() {
return menu.popup(remote.getCurrentWindow()); return menu.popup(remote.getCurrentWindow());
}); });

View file

@ -3,9 +3,7 @@ var BrowserWindowProxy, a, getHistoryOperation, ipcRenderer, ref, remote, resolv
ref = require('electron'), ipcRenderer = ref.ipcRenderer, remote = ref.remote; ref = require('electron'), ipcRenderer = ref.ipcRenderer, remote = ref.remote;
// Helper function to resolve relative url.
/* Helper function to resolve relative url. */
a = window.top.document.createElement('a'); a = window.top.document.createElement('a');
resolveURL = function(url) { resolveURL = function(url) {
@ -13,9 +11,7 @@ resolveURL = function(url) {
return a.href; return a.href;
}; };
// Window object returned by "window.open".
/* Window object returned by "window.open". */
BrowserWindowProxy = (function() { BrowserWindowProxy = (function() {
BrowserWindowProxy.proxies = {}; BrowserWindowProxy.proxies = {};
@ -69,16 +65,13 @@ BrowserWindowProxy = (function() {
})(); })();
if (process.guestInstanceId == null) { if (process.guestInstanceId == null) {
// Override default window.close.
/* Override default window.close. */
window.close = function() { window.close = function() {
return remote.getCurrentWindow().close(); return remote.getCurrentWindow().close();
}; };
} }
// Make the browser window or guest view emit "new-window" event.
/* Make the browser window or guest view emit "new-window" event. */
window.open = function(url, frameName, features) { window.open = function(url, frameName, features) {
var feature, guestId, i, ints, j, len, len1, name, options, ref1, ref2, value; var feature, guestId, i, ints, j, len, len1, name, options, ref1, ref2, value;
if (frameName == null) { if (frameName == null) {
@ -90,7 +83,7 @@ window.open = function(url, frameName, features) {
options = {}; options = {};
ints = ['x', 'y', 'width', 'height', 'min-width', 'max-width', 'min-height', 'max-height', 'zoom-factor']; ints = ['x', 'y', 'width', 'height', 'min-width', 'max-width', 'min-height', 'max-height', 'zoom-factor'];
/* Make sure to get rid of excessive whitespace in the property name */ // Make sure to get rid of excessive whitespace in the property name
ref1 = features.split(/,\s*/); ref1 = features.split(/,\s*/);
for (i = 0, len = ref1.length; i < len; i++) { for (i = 0, len = ref1.length; i < len; i++) {
feature = ref1[i]; feature = ref1[i];
@ -117,7 +110,7 @@ window.open = function(url, frameName, features) {
options.height = 600; options.height = 600;
} }
/* Resolve relative urls. */ // Resolve relative urls.
url = resolveURL(url); url = resolveURL(url);
for (j = 0, len1 = ints.length; j < len1; j++) { for (j = 0, len1 = ints.length; j < len1; j++) {
name = ints[j]; name = ints[j];
@ -133,9 +126,7 @@ window.open = function(url, frameName, features) {
} }
}; };
// Use the dialog API to implement alert().
/* Use the dialog API to implement alert(). */
window.alert = function(message, title) { window.alert = function(message, title) {
var buttons; var buttons;
if (title == null) { if (title == null) {
@ -149,12 +140,10 @@ window.alert = function(message, title) {
buttons: buttons buttons: buttons
}); });
/* Alert should always return undefined. */ // Alert should always return undefined.
}; };
// And the confirm().
/* And the confirm(). */
window.confirm = function(message, title) { window.confirm = function(message, title) {
var buttons, cancelId; var buttons, cancelId;
if (title == null) { if (title == null) {
@ -170,9 +159,7 @@ window.confirm = function(message, title) {
}); });
}; };
// But we do not support prompt().
/* But we do not support prompt(). */
window.prompt = function() { window.prompt = function() {
throw new Error('prompt() is and will not be supported.'); throw new Error('prompt() is and will not be supported.');
}; };
@ -182,10 +169,8 @@ if (process.openerId != null) {
} }
ipcRenderer.on('ATOM_SHELL_GUEST_WINDOW_POSTMESSAGE', function(event, sourceId, message, sourceOrigin) { ipcRenderer.on('ATOM_SHELL_GUEST_WINDOW_POSTMESSAGE', function(event, sourceId, message, sourceOrigin) {
// Manually dispatch event instead of using postMessage because we also need to
/* Manually dispatch event instead of using postMessage because we also need to */ // set event.source.
/* set event.source. */
event = document.createEvent('Event'); event = document.createEvent('Event');
event.initEvent('message', false, false); event.initEvent('message', false, false);
event.data = message; event.data = message;
@ -194,9 +179,7 @@ ipcRenderer.on('ATOM_SHELL_GUEST_WINDOW_POSTMESSAGE', function(event, sourceId,
return window.dispatchEvent(event); return window.dispatchEvent(event);
}); });
// Forward history operations to browser.
/* Forward history operations to browser. */
sendHistoryOperation = function() { sendHistoryOperation = function() {
var args; var args;
args = 1 <= arguments.length ? slice.call(arguments, 0) : []; args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
@ -227,9 +210,7 @@ Object.defineProperty(window.history, 'length', {
} }
}); });
// Make document.hidden and document.visibilityState return the correct value.
/* Make document.hidden and document.visibilityState return the correct value. */
Object.defineProperty(document, 'hidden', { Object.defineProperty(document, 'hidden', {
get: function() { get: function() {
var currentWindow; var currentWindow;

View file

@ -10,9 +10,7 @@ webViewConstants = require('./web-view-constants');
remote = require('electron').remote; remote = require('electron').remote;
// Helper function to resolve url set in attribute.
/* Helper function to resolve url set in attribute. */
a = document.createElement('a'); a = document.createElement('a');
resolveURL = function(url) { resolveURL = function(url) {
@ -20,12 +18,8 @@ resolveURL = function(url) {
return a.href; return a.href;
}; };
// Attribute objects.
/* // Default implementation of a WebView attribute.
Attribute objects.
Default implementation of a WebView attribute.
*/
WebViewAttribute = (function() { WebViewAttribute = (function() {
function WebViewAttribute(name, webViewImpl) { function WebViewAttribute(name, webViewImpl) {
this.name = name; this.name = name;
@ -35,32 +29,24 @@ WebViewAttribute = (function() {
this.defineProperty(); this.defineProperty();
} }
// Retrieves and returns the attribute's value.
/* Retrieves and returns the attribute's value. */
WebViewAttribute.prototype.getValue = function() { WebViewAttribute.prototype.getValue = function() {
return this.webViewImpl.webviewNode.getAttribute(this.name) || this.value; return this.webViewImpl.webviewNode.getAttribute(this.name) || this.value;
}; };
// Sets the attribute's value.
/* Sets the attribute's value. */
WebViewAttribute.prototype.setValue = function(value) { WebViewAttribute.prototype.setValue = function(value) {
return this.webViewImpl.webviewNode.setAttribute(this.name, value || ''); return this.webViewImpl.webviewNode.setAttribute(this.name, value || '');
}; };
// Changes the attribute's value without triggering its mutation handler.
/* Changes the attribute's value without triggering its mutation handler. */
WebViewAttribute.prototype.setValueIgnoreMutation = function(value) { WebViewAttribute.prototype.setValueIgnoreMutation = function(value) {
this.ignoreMutation = true; this.ignoreMutation = true;
this.setValue(value); this.setValue(value);
return this.ignoreMutation = false; return this.ignoreMutation = false;
}; };
// Defines this attribute as a property on the webview node.
/* Defines this attribute as a property on the webview node. */
WebViewAttribute.prototype.defineProperty = function() { WebViewAttribute.prototype.defineProperty = function() {
return Object.defineProperty(this.webViewImpl.webviewNode, this.name, { return Object.defineProperty(this.webViewImpl.webviewNode, this.name, {
get: (function(_this) { get: (function(_this) {
@ -77,18 +63,14 @@ WebViewAttribute = (function() {
}); });
}; };
// Called when the attribute's value changes.
/* Called when the attribute's value changes. */
WebViewAttribute.prototype.handleMutation = function() {}; WebViewAttribute.prototype.handleMutation = function() {};
return WebViewAttribute; return WebViewAttribute;
})(); })();
// An attribute that is treated as a Boolean.
/* An attribute that is treated as a Boolean. */
BooleanAttribute = (function(superClass) { BooleanAttribute = (function(superClass) {
extend(BooleanAttribute, superClass); extend(BooleanAttribute, superClass);
@ -112,9 +94,7 @@ BooleanAttribute = (function(superClass) {
})(WebViewAttribute); })(WebViewAttribute);
// Attribute that specifies whether transparency is allowed in the webview.
/* Attribute that specifies whether transparency is allowed in the webview. */
AllowTransparencyAttribute = (function(superClass) { AllowTransparencyAttribute = (function(superClass) {
extend(AllowTransparencyAttribute, superClass); extend(AllowTransparencyAttribute, superClass);
@ -133,9 +113,7 @@ AllowTransparencyAttribute = (function(superClass) {
})(BooleanAttribute); })(BooleanAttribute);
// Attribute used to define the demension limits of autosizing.
/* Attribute used to define the demension limits of autosizing. */
AutosizeDimensionAttribute = (function(superClass) { AutosizeDimensionAttribute = (function(superClass) {
extend(AutosizeDimensionAttribute, superClass); extend(AutosizeDimensionAttribute, superClass);
@ -168,9 +146,7 @@ AutosizeDimensionAttribute = (function(superClass) {
})(WebViewAttribute); })(WebViewAttribute);
// Attribute that specifies whether the webview should be autosized.
/* Attribute that specifies whether the webview should be autosized. */
AutosizeAttribute = (function(superClass) { AutosizeAttribute = (function(superClass) {
extend(AutosizeAttribute, superClass); extend(AutosizeAttribute, superClass);
@ -184,9 +160,7 @@ AutosizeAttribute = (function(superClass) {
})(BooleanAttribute); })(BooleanAttribute);
// Attribute representing the state of the storage partition.
/* Attribute representing the state of the storage partition. */
PartitionAttribute = (function(superClass) { PartitionAttribute = (function(superClass) {
extend(PartitionAttribute, superClass); extend(PartitionAttribute, superClass);
@ -198,7 +172,7 @@ PartitionAttribute = (function(superClass) {
PartitionAttribute.prototype.handleMutation = function(oldValue, newValue) { PartitionAttribute.prototype.handleMutation = function(oldValue, newValue) {
newValue = newValue || ''; newValue = newValue || '';
/* The partition cannot change if the webview has already navigated. */ // The partition cannot change if the webview has already navigated.
if (!this.webViewImpl.beforeFirstNavigation) { if (!this.webViewImpl.beforeFirstNavigation) {
window.console.error(webViewConstants.ERROR_MSG_ALREADY_NAVIGATED); window.console.error(webViewConstants.ERROR_MSG_ALREADY_NAVIGATED);
this.setValueIgnoreMutation(oldValue); this.setValueIgnoreMutation(oldValue);
@ -214,9 +188,7 @@ PartitionAttribute = (function(superClass) {
})(WebViewAttribute); })(WebViewAttribute);
// Attribute that handles the location and navigation of the webview.
/* Attribute that handles the location and navigation of the webview. */
SrcAttribute = (function(superClass) { SrcAttribute = (function(superClass) {
extend(SrcAttribute, superClass); extend(SrcAttribute, superClass);
@ -236,29 +208,23 @@ SrcAttribute = (function(superClass) {
SrcAttribute.prototype.setValueIgnoreMutation = function(value) { SrcAttribute.prototype.setValueIgnoreMutation = function(value) {
WebViewAttribute.prototype.setValueIgnoreMutation.call(this, value); WebViewAttribute.prototype.setValueIgnoreMutation.call(this, value);
/* // takeRecords() is needed to clear queued up src mutations. Without it, it
takeRecords() is needed to clear queued up src mutations. Without it, it // is possible for this change to get picked up asyncronously by src's
is possible for this change to get picked up asyncronously by src's // mutation observer |observer|, and then get handled even though we do not
mutation observer |observer|, and then get handled even though we do not // want to handle this mutation.
want to handle this mutation.
*/
return this.observer.takeRecords(); return this.observer.takeRecords();
}; };
SrcAttribute.prototype.handleMutation = function(oldValue, newValue) { SrcAttribute.prototype.handleMutation = function(oldValue, newValue) {
/* // Once we have navigated, we don't allow clearing the src attribute.
Once we have navigated, we don't allow clearing the src attribute. // Once <webview> enters a navigated state, it cannot return to a
Once <webview> enters a navigated state, it cannot return to a // placeholder state.
placeholder state.
*/
if (!newValue && oldValue) { if (!newValue && oldValue) {
/* // src attribute changes normally initiate a navigation. We suppress
src attribute changes normally initiate a navigation. We suppress // the next src attribute handler call to avoid reloading the page
the next src attribute handler call to avoid reloading the page // on every guest-initiated navigation.
on every guest-initiated navigation.
*/
this.setValueIgnoreMutation(oldValue); this.setValueIgnoreMutation(oldValue);
return; return;
} }
@ -266,13 +232,10 @@ SrcAttribute = (function(superClass) {
}; };
/* // The purpose of this mutation observer is to catch assignment to the src
The purpose of this mutation observer is to catch assignment to the src // attribute without any changes to its value. This is useful in the case
attribute without any changes to its value. This is useful in the case // where the webview guest has crashed and navigating to the same address
where the webview guest has crashed and navigating to the same address // spawns off a new process.
spawns off a new process.
*/
SrcAttribute.prototype.setupMutationObserver = function() { SrcAttribute.prototype.setupMutationObserver = function() {
var params; var params;
this.observer = new MutationObserver((function(_this) { this.observer = new MutationObserver((function(_this) {
@ -310,7 +273,7 @@ SrcAttribute = (function(superClass) {
return; return;
} }
/* Navigate to |this.src|. */ // Navigate to |this.src|.
opts = {}; opts = {};
httpreferrer = this.webViewImpl.attributes[webViewConstants.ATTRIBUTE_HTTPREFERRER].getValue(); httpreferrer = this.webViewImpl.attributes[webViewConstants.ATTRIBUTE_HTTPREFERRER].getValue();
if (httpreferrer) { if (httpreferrer) {
@ -328,9 +291,7 @@ SrcAttribute = (function(superClass) {
})(WebViewAttribute); })(WebViewAttribute);
// Attribute specifies HTTP referrer.
/* Attribute specifies HTTP referrer. */
HttpReferrerAttribute = (function(superClass) { HttpReferrerAttribute = (function(superClass) {
extend(HttpReferrerAttribute, superClass); extend(HttpReferrerAttribute, superClass);
@ -342,9 +303,7 @@ HttpReferrerAttribute = (function(superClass) {
})(WebViewAttribute); })(WebViewAttribute);
// Attribute specifies user agent
/* Attribute specifies user agent */
UserAgentAttribute = (function(superClass) { UserAgentAttribute = (function(superClass) {
extend(UserAgentAttribute, superClass); extend(UserAgentAttribute, superClass);
@ -356,9 +315,7 @@ UserAgentAttribute = (function(superClass) {
})(WebViewAttribute); })(WebViewAttribute);
// Attribute that set preload script.
/* Attribute that set preload script. */
PreloadAttribute = (function(superClass) { PreloadAttribute = (function(superClass) {
extend(PreloadAttribute, superClass); extend(PreloadAttribute, superClass);
@ -384,9 +341,7 @@ PreloadAttribute = (function(superClass) {
})(WebViewAttribute); })(WebViewAttribute);
// Sets up all of the webview attributes.
/* Sets up all of the webview attributes. */
WebViewImpl.prototype.setupWebViewAttributes = function() { WebViewImpl.prototype.setupWebViewAttributes = function() {
var attribute, autosizeAttributes, i, len, results; var attribute, autosizeAttributes, i, len, results;
this.attributes = {}; this.attributes = {};

View file

@ -1,6 +1,5 @@
module.exports = { module.exports = {
// Attributes.
/* Attributes. */
ATTRIBUTE_ALLOWTRANSPARENCY: 'allowtransparency', ATTRIBUTE_ALLOWTRANSPARENCY: 'allowtransparency',
ATTRIBUTE_AUTOSIZE: 'autosize', ATTRIBUTE_AUTOSIZE: 'autosize',
ATTRIBUTE_MAXHEIGHT: 'maxheight', ATTRIBUTE_MAXHEIGHT: 'maxheight',
@ -18,10 +17,10 @@ module.exports = {
ATTRIBUTE_PRELOAD: 'preload', ATTRIBUTE_PRELOAD: 'preload',
ATTRIBUTE_USERAGENT: 'useragent', ATTRIBUTE_USERAGENT: 'useragent',
/* Internal attribute. */ // Internal attribute.
ATTRIBUTE_INTERNALINSTANCEID: 'internalinstanceid', ATTRIBUTE_INTERNALINSTANCEID: 'internalinstanceid',
/* Error messages. */ // Error messages.
ERROR_MSG_ALREADY_NAVIGATED: 'The object has already navigated, so its partition cannot be changed.', ERROR_MSG_ALREADY_NAVIGATED: 'The object has already navigated, so its partition cannot be changed.',
ERROR_MSG_CANNOT_INJECT_SCRIPT: '<webview>: ' + 'Script cannot be injected into content until the page has loaded.', ERROR_MSG_CANNOT_INJECT_SCRIPT: '<webview>: ' + 'Script cannot be injected into content until the page has loaded.',
ERROR_MSG_INVALID_PARTITION_ATTRIBUTE: 'Invalid partition attribute.', ERROR_MSG_INVALID_PARTITION_ATTRIBUTE: 'Invalid partition attribute.',

View file

@ -12,18 +12,14 @@ guestViewInternal = require('./guest-view-internal');
webViewConstants = require('./web-view-constants'); webViewConstants = require('./web-view-constants');
// ID generator.
/* ID generator. */
nextId = 0; nextId = 0;
getNextId = function() { getNextId = function() {
return ++nextId; return ++nextId;
}; };
// Represents the internal state of the WebView node.
/* Represents the internal state of the WebView node. */
WebViewImpl = (function() { WebViewImpl = (function() {
function WebViewImpl(webviewNode) { function WebViewImpl(webviewNode) {
var shadowRoot; var shadowRoot;
@ -33,7 +29,7 @@ WebViewImpl = (function() {
this.elementAttached = false; this.elementAttached = false;
this.beforeFirstNavigation = true; this.beforeFirstNavigation = true;
/* on* Event handlers. */ // on* Event handlers.
this.on = {}; this.on = {};
this.browserPluginNode = this.createBrowserPluginNode(); this.browserPluginNode = this.createBrowserPluginNode();
shadowRoot = this.webviewNode.createShadowRoot(); shadowRoot = this.webviewNode.createShadowRoot();
@ -50,32 +46,25 @@ WebViewImpl = (function() {
} }
WebViewImpl.prototype.createBrowserPluginNode = function() { WebViewImpl.prototype.createBrowserPluginNode = function() {
// We create BrowserPlugin as a custom element in order to observe changes
/* // to attributes synchronously.
We create BrowserPlugin as a custom element in order to observe changes
to attributes synchronously.
*/
var browserPluginNode; var browserPluginNode;
browserPluginNode = new WebViewImpl.BrowserPlugin(); browserPluginNode = new WebViewImpl.BrowserPlugin();
v8Util.setHiddenValue(browserPluginNode, 'internal', this); v8Util.setHiddenValue(browserPluginNode, 'internal', this);
return browserPluginNode; return browserPluginNode;
}; };
// Resets some state upon reattaching <webview> element to the DOM.
/* Resets some state upon reattaching <webview> element to the DOM. */
WebViewImpl.prototype.reset = function() { WebViewImpl.prototype.reset = function() {
// Unlisten the zoom-level-changed event. // Unlisten the zoom-level-changed event.
webFrame.removeListener('zoom-level-changed', this.onZoomLevelChanged); webFrame.removeListener('zoom-level-changed', this.onZoomLevelChanged);
/* // If guestInstanceId is defined then the <webview> has navigated and has
If guestInstanceId is defined then the <webview> has navigated and has // already picked up a partition ID. Thus, we need to reset the initialization
already picked up a partition ID. Thus, we need to reset the initialization // state. However, it may be the case that beforeFirstNavigation is false BUT
state. However, it may be the case that beforeFirstNavigation is false BUT // guestInstanceId has yet to be initialized. This means that we have not
guestInstanceId has yet to be initialized. This means that we have not // heard back from createGuest yet. We will not reset the flag in this case so
heard back from createGuest yet. We will not reset the flag in this case so // that we don't end up allocating a second guest.
that we don't end up allocating a second guest.
*/
if (this.guestInstanceId) { if (this.guestInstanceId) {
guestViewInternal.destroyGuest(this.guestInstanceId); guestViewInternal.destroyGuest(this.guestInstanceId);
this.webContents = null; this.webContents = null;
@ -86,9 +75,7 @@ WebViewImpl = (function() {
return this.internalInstanceId = 0; return this.internalInstanceId = 0;
}; };
// Sets the <webview>.request property.
/* Sets the <webview>.request property. */
WebViewImpl.prototype.setRequestPropertyOnWebViewNode = function(request) { WebViewImpl.prototype.setRequestPropertyOnWebViewNode = function(request) {
return Object.defineProperty(this.webviewNode, 'request', { return Object.defineProperty(this.webviewNode, 'request', {
value: request, value: request,
@ -99,45 +86,40 @@ WebViewImpl = (function() {
WebViewImpl.prototype.setupFocusPropagation = function() { WebViewImpl.prototype.setupFocusPropagation = function() {
if (!this.webviewNode.hasAttribute('tabIndex')) { if (!this.webviewNode.hasAttribute('tabIndex')) {
/* // <webview> needs a tabIndex in order to be focusable.
<webview> needs a tabIndex in order to be focusable. // TODO(fsamuel): It would be nice to avoid exposing a tabIndex attribute
TODO(fsamuel): It would be nice to avoid exposing a tabIndex attribute // to allow <webview> to be focusable.
to allow <webview> to be focusable. // See http://crbug.com/231664.
See http://crbug.com/231664.
*/
this.webviewNode.setAttribute('tabIndex', -1); this.webviewNode.setAttribute('tabIndex', -1);
} }
this.webviewNode.addEventListener('focus', (function(_this) { this.webviewNode.addEventListener('focus', (function(_this) {
return function(e) { return function(e) {
/* Focus the BrowserPlugin when the <webview> takes focus. */ // Focus the BrowserPlugin when the <webview> takes focus.
return _this.browserPluginNode.focus(); return _this.browserPluginNode.focus();
}; };
})(this)); })(this));
return this.webviewNode.addEventListener('blur', (function(_this) { return this.webviewNode.addEventListener('blur', (function(_this) {
return function(e) { return function(e) {
/* Blur the BrowserPlugin when the <webview> loses focus. */ // Blur the BrowserPlugin when the <webview> loses focus.
return _this.browserPluginNode.blur(); return _this.browserPluginNode.blur();
}; };
})(this)); })(this));
}; };
/* // This observer monitors mutations to attributes of the <webview> and
This observer monitors mutations to attributes of the <webview> and // updates the BrowserPlugin properties accordingly. In turn, updating
updates the BrowserPlugin properties accordingly. In turn, updating // a BrowserPlugin property will update the corresponding BrowserPlugin
a BrowserPlugin property will update the corresponding BrowserPlugin // attribute, if necessary. See BrowserPlugin::UpdateDOMAttribute for more
attribute, if necessary. See BrowserPlugin::UpdateDOMAttribute for more // details.
details.
*/
WebViewImpl.prototype.handleWebviewAttributeMutation = function(attributeName, oldValue, newValue) { WebViewImpl.prototype.handleWebviewAttributeMutation = function(attributeName, oldValue, newValue) {
if (!this.attributes[attributeName] || this.attributes[attributeName].ignoreMutation) { if (!this.attributes[attributeName] || this.attributes[attributeName].ignoreMutation) {
return; return;
} }
/* Let the changed attribute handle its own mutation; */ // Let the changed attribute handle its own mutation;
return this.attributes[attributeName].handleMutation(oldValue, newValue); return this.attributes[attributeName].handleMutation(oldValue, newValue);
}; };
@ -146,7 +128,7 @@ WebViewImpl = (function() {
this.browserPluginNode.removeAttribute(webViewConstants.ATTRIBUTE_INTERNALINSTANCEID); this.browserPluginNode.removeAttribute(webViewConstants.ATTRIBUTE_INTERNALINSTANCEID);
this.internalInstanceId = parseInt(newValue); this.internalInstanceId = parseInt(newValue);
/* Track when the element resizes using the element resize callback. */ // Track when the element resizes using the element resize callback.
webFrame.registerElementResizeCallback(this.internalInstanceId, this.onElementResize.bind(this)); webFrame.registerElementResizeCallback(this.internalInstanceId, this.onElementResize.bind(this));
if (!this.guestInstanceId) { if (!this.guestInstanceId) {
return; return;
@ -163,9 +145,8 @@ WebViewImpl = (function() {
width = node.offsetWidth; width = node.offsetWidth;
height = node.offsetHeight; height = node.offsetHeight;
/* Check the current bounds to make sure we do not resize <webview> */ // Check the current bounds to make sure we do not resize <webview>
// outside of current constraints.
/* outside of current constraints. */
maxWidth = this.attributes[webViewConstants.ATTRIBUTE_MAXWIDTH].getValue() | width; maxWidth = this.attributes[webViewConstants.ATTRIBUTE_MAXWIDTH].getValue() | width;
maxHeight = this.attributes[webViewConstants.ATTRIBUTE_MAXHEIGHT].getValue() | width; maxHeight = this.attributes[webViewConstants.ATTRIBUTE_MAXHEIGHT].getValue() | width;
minWidth = this.attributes[webViewConstants.ATTRIBUTE_MINWIDTH].getValue() | width; minWidth = this.attributes[webViewConstants.ATTRIBUTE_MINWIDTH].getValue() | width;
@ -176,17 +157,14 @@ WebViewImpl = (function() {
node.style.width = newWidth + 'px'; node.style.width = newWidth + 'px';
node.style.height = newHeight + 'px'; node.style.height = newHeight + 'px';
/* // Only fire the DOM event if the size of the <webview> has actually
Only fire the DOM event if the size of the <webview> has actually // changed.
changed.
*/
return this.dispatchEvent(webViewEvent); return this.dispatchEvent(webViewEvent);
} }
}; };
WebViewImpl.prototype.onElementResize = function(newSize) { WebViewImpl.prototype.onElementResize = function(newSize) {
// Dispatch the 'resize' event.
/* Dispatch the 'resize' event. */
var resizeEvent; var resizeEvent;
resizeEvent = new Event('resize', { resizeEvent = new Event('resize', {
bubbles: true bubbles: true
@ -213,12 +191,8 @@ WebViewImpl = (function() {
return this.webviewNode.dispatchEvent(webViewEvent); return this.webviewNode.dispatchEvent(webViewEvent);
}; };
// Adds an 'on<event>' property on the webview, which can be used to set/unset
/* Adds an 'on<event>' property on the webview, which can be used to set/unset */ // an event handler.
/* an event handler. */
WebViewImpl.prototype.setupEventProperty = function(eventName) { WebViewImpl.prototype.setupEventProperty = function(eventName) {
var propertyName; var propertyName;
propertyName = 'on' + eventName.toLowerCase(); propertyName = 'on' + eventName.toLowerCase();
@ -243,20 +217,16 @@ WebViewImpl = (function() {
}); });
}; };
// Updates state upon loadcommit.
/* Updates state upon loadcommit. */
WebViewImpl.prototype.onLoadCommit = function(webViewEvent) { WebViewImpl.prototype.onLoadCommit = function(webViewEvent) {
var newValue, oldValue; var newValue, oldValue;
oldValue = this.webviewNode.getAttribute(webViewConstants.ATTRIBUTE_SRC); oldValue = this.webviewNode.getAttribute(webViewConstants.ATTRIBUTE_SRC);
newValue = webViewEvent.url; newValue = webViewEvent.url;
if (webViewEvent.isMainFrame && (oldValue !== newValue)) { if (webViewEvent.isMainFrame && (oldValue !== newValue)) {
/* // Touching the src attribute triggers a navigation. To avoid
Touching the src attribute triggers a navigation. To avoid // triggering a page reload on every guest-initiated navigation,
triggering a page reload on every guest-initiated navigation, // we do not handle this mutation.
we do not handle this mutation.
*/
return this.attributes[webViewConstants.ATTRIBUTE_SRC].setValueIgnoreMutation(newValue); return this.attributes[webViewConstants.ATTRIBUTE_SRC].setValueIgnoreMutation(newValue);
} }
}; };
@ -278,13 +248,11 @@ WebViewImpl = (function() {
params[attributeName] = attribute.getValue(); params[attributeName] = attribute.getValue();
} }
/* // When the WebView is not participating in layout (display:none)
When the WebView is not participating in layout (display:none) // then getBoundingClientRect() would report a width and height of 0.
then getBoundingClientRect() would report a width and height of 0. // However, in the case where the WebView has a fixed size we can
However, in the case where the WebView has a fixed size we can // use that value to initially size the guest so as to avoid a relayout of
use that value to initially size the guest so as to avoid a relayout of // the on display:block.
the on display:block.
*/
css = window.getComputedStyle(this.webviewNode, null); css = window.getComputedStyle(this.webviewNode, null);
elementRect = this.webviewNode.getBoundingClientRect(); elementRect = this.webviewNode.getBoundingClientRect();
params.elementWidth = parseInt(elementRect.width) || parseInt(css.getPropertyValue('width')); params.elementWidth = parseInt(elementRect.width) || parseInt(css.getPropertyValue('width'));
@ -305,9 +273,7 @@ WebViewImpl = (function() {
})(); })();
// Registers browser plugin <object> custom element.
/* Registers browser plugin <object> custom element. */
registerBrowserPluginElement = function() { registerBrowserPluginElement = function() {
var proto; var proto;
proto = Object.create(HTMLObjectElement.prototype); proto = Object.create(HTMLObjectElement.prototype);
@ -315,7 +281,7 @@ registerBrowserPluginElement = function() {
this.setAttribute('type', 'application/browser-plugin'); this.setAttribute('type', 'application/browser-plugin');
this.setAttribute('id', 'browser-plugin-' + getNextId()); this.setAttribute('id', 'browser-plugin-' + getNextId());
/* The <object> node fills in the <webview> container. */ // The <object> node fills in the <webview> container.
this.style.display = 'block'; this.style.display = 'block';
this.style.width = '100%'; this.style.width = '100%';
return this.style.height = '100%'; return this.style.height = '100%';
@ -329,8 +295,7 @@ registerBrowserPluginElement = function() {
return internal.handleBrowserPluginAttributeMutation(name, oldValue, newValue); return internal.handleBrowserPluginAttributeMutation(name, oldValue, newValue);
}; };
proto.attachedCallback = function() { proto.attachedCallback = function() {
// Load the plugin immediately.
/* Load the plugin immediately. */
var unused; var unused;
return unused = this.nonExistentAttribute; return unused = this.nonExistentAttribute;
}; };
@ -344,9 +309,7 @@ registerBrowserPluginElement = function() {
return delete proto.attributeChangedCallback; return delete proto.attributeChangedCallback;
}; };
// Registers <webview> custom element.
/* Registers <webview> custom element. */
registerWebViewElement = function() { registerWebViewElement = function() {
var createBlockHandler, createNonBlockHandler, i, j, len, len1, m, methods, nonblockMethods, proto; var createBlockHandler, createNonBlockHandler, i, j, len, len1, m, methods, nonblockMethods, proto;
proto = Object.create(HTMLObjectElement.prototype); proto = Object.create(HTMLObjectElement.prototype);
@ -384,8 +347,52 @@ registerWebViewElement = function() {
} }
}; };
/* Public-facing API methods. */ // Public-facing API methods.
methods = ['getURL', 'getTitle', 'isLoading', 'isWaitingForResponse', 'stop', 'reload', 'reloadIgnoringCache', 'canGoBack', 'canGoForward', 'canGoToOffset', 'clearHistory', 'goBack', 'goForward', 'goToIndex', 'goToOffset', 'isCrashed', 'setUserAgent', 'getUserAgent', 'openDevTools', 'closeDevTools', 'isDevToolsOpened', 'isDevToolsFocused', 'inspectElement', 'setAudioMuted', 'isAudioMuted', 'undo', 'redo', 'cut', 'copy', 'paste', 'pasteAndMatchStyle', 'delete', 'selectAll', 'unselect', 'replace', 'replaceMisspelling', 'findInPage', 'stopFindInPage', 'getId', 'downloadURL', 'inspectServiceWorker', 'print', 'printToPDF']; methods = [
'getURL',
'getTitle',
'isLoading',
'isWaitingForResponse',
'stop',
'reload',
'reloadIgnoringCache',
'canGoBack',
'canGoForward',
'canGoToOffset',
'clearHistory',
'goBack',
'goForward',
'goToIndex',
'goToOffset',
'isCrashed',
'setUserAgent',
'getUserAgent',
'openDevTools',
'closeDevTools',
'isDevToolsOpened',
'isDevToolsFocused',
'inspectElement',
'setAudioMuted',
'isAudioMuted',
'undo',
'redo',
'cut',
'copy',
'paste',
'pasteAndMatchStyle',
'delete',
'selectAll',
'unselect',
'replace',
'replaceMisspelling',
'findInPage',
'stopFindInPage',
'getId',
'downloadURL',
'inspectServiceWorker',
'print',
'printToPDF'
];
nonblockMethods = [ nonblockMethods = [
'executeJavaScript', 'executeJavaScript',
'insertCSS', 'insertCSS',
@ -397,7 +404,7 @@ registerWebViewElement = function() {
'setZoomLevelLimits', 'setZoomLevelLimits',
]; ];
/* Forward proto.foo* method calls to WebViewImpl.foo*. */ // Forward proto.foo* method calls to WebViewImpl.foo*.
createBlockHandler = function(m) { createBlockHandler = function(m) {
return function() { return function() {
var args, internal, ref1; var args, internal, ref1;
@ -423,15 +430,14 @@ registerWebViewElement = function() {
proto[m] = createNonBlockHandler(m); proto[m] = createNonBlockHandler(m);
} }
/* Deprecated. */ // Deprecated.
deprecate.rename(proto, 'getUrl', 'getURL'); deprecate.rename(proto, 'getUrl', 'getURL');
window.WebView = webFrame.registerEmbedderCustomElement('webview', { window.WebView = webFrame.registerEmbedderCustomElement('webview', {
prototype: proto prototype: proto
}); });
/* Delete the callbacks so developers cannot call them and produce unexpected */ // Delete the callbacks so developers cannot call them and produce unexpected
// behavior.
/* behavior. */
delete proto.createdCallback; delete proto.createdCallback;
delete proto.attachedCallback; delete proto.attachedCallback;
delete proto.detachedCallback; delete proto.detachedCallback;