manually standardize this tricky file

This commit is contained in:
Zeke Sikelianos 2016-03-24 13:34:36 -07:00 committed by Kevin Sawicki
parent 4794385fac
commit 4d4f479721

View file

@ -1,128 +1,127 @@
'use strict'; 'use strict'
const electron = require('electron'); const electron = require('electron')
const ipcMain = electron.ipcMain; const ipcMain = electron.ipcMain
const objectsRegistry = require('./objects-registry'); const objectsRegistry = require('./objects-registry')
const v8Util = process.atomBinding('v8_util'); const v8Util = process.atomBinding('v8_util')
const IDWeakMap = process.atomBinding('id_weak_map').IDWeakMap; const IDWeakMap = process.atomBinding('id_weak_map').IDWeakMap
// The internal properties of Function. // The internal properties of Function.
const FUNCTION_PROPERTIES = [ const FUNCTION_PROPERTIES = [
'length', 'name', 'arguments', 'caller', 'prototype', 'length', 'name', 'arguments', 'caller', 'prototype'
]; ]
// The remote functions in renderer processes. // The remote functions in renderer processes.
// (webContentsId) => {id: Function} // (webContentsId) => {id: Function}
let rendererFunctions = {}; let rendererFunctions = {}
// Return the description of object's members: // Return the description of object's members:
let getObjectMembers = function (object) { let getObjectMembers = function (object) {
let names = Object.getOwnPropertyNames(object); let names = Object.getOwnPropertyNames(object)
// For Function, we should not override following properties even though they // For Function, we should not override following properties even though they
// are "own" properties. // are "own" properties.
if (typeof object === 'function') { if (typeof object === 'function') {
names = names.filter((name) => { names = names.filter((name) => {
return !FUNCTION_PROPERTIES.includes(name); return !FUNCTION_PROPERTIES.includes(name)
}); })
} }
// Map properties to descriptors. // Map properties to descriptors.
return names.map((name) => { return names.map((name) => {
let descriptor = Object.getOwnPropertyDescriptor(object, name); let descriptor = Object.getOwnPropertyDescriptor(object, name)
let member = {name, enumerable: descriptor.enumerable, writable: false}; let member = {name, enumerable: descriptor.enumerable, writable: false}
if (descriptor.get === undefined && typeof object[name] === 'function') { if (descriptor.get === undefined && typeof object[name] === 'function') {
member.type = 'method'; member.type = 'method'
} else { } else {
if (descriptor.set || descriptor.writable) if (descriptor.set || descriptor.writable) member.writable = true
member.writable = true; member.type = 'get'
member.type = 'get'; }
return member
})
} }
return member;
});
};
// Return the description of object's prototype. // Return the description of object's prototype.
let getObjectPrototype = function (object) { let getObjectPrototype = function (object) {
let proto = Object.getPrototypeOf(object); let proto = Object.getPrototypeOf(object)
if (proto === null || proto === Object.prototype) if (proto === null || proto === Object.prototype) return null
return null;
return { return {
members: getObjectMembers(proto), members: getObjectMembers(proto),
proto: getObjectPrototype(proto), proto: getObjectPrototype(proto)
}; }
}; }
// Convert a real value into meta data. // Convert a real value into meta data.
var valueToMeta = function (sender, value, optimizeSimpleObject) { var valueToMeta = function (sender, value, optimizeSimpleObject) {
var el, i, len, meta; var el, i, len, meta
if (optimizeSimpleObject == null) { if (optimizeSimpleObject == null) {
optimizeSimpleObject = false; optimizeSimpleObject = false
} }
meta = { meta = {
type: typeof value type: typeof value
}; }
if (Buffer.isBuffer(value)) { if (Buffer.isBuffer(value)) {
meta.type = 'buffer'; meta.type = 'buffer'
} }
if (value === null) { if (value === null) {
meta.type = 'value'; meta.type = 'value'
} }
if (Array.isArray(value)) { if (Array.isArray(value)) {
meta.type = 'array'; meta.type = 'array'
} }
if (value instanceof Error) { if (value instanceof Error) {
meta.type = 'error'; meta.type = 'error'
} }
if (value instanceof Date) { if (value instanceof Date) {
meta.type = 'date'; meta.type = 'date'
} }
if ((value != null ? value.constructor.name : void 0) === 'Promise') { if ((value != null ? value.constructor.name : void 0) === 'Promise') {
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.hasOwnProperty('callee')) && (value.length != null)) { if (meta.type === 'object' && (value.hasOwnProperty('callee')) && (value.length != null)) {
meta.type = 'array'; meta.type = 'array'
} }
if (meta.type === 'array') { if (meta.type === 'array') {
meta.members = []; meta.members = []
for (i = 0, len = value.length; i < len; i++) { for (i = 0, len = value.length; i < len; i++) {
el = value[i]; el = value[i]
meta.members.push(valueToMeta(sender, el)); meta.members.push(valueToMeta(sender, el))
} }
} 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, value); meta.id = objectsRegistry.add(sender, value)
meta.members = getObjectMembers(value); meta.members = getObjectMembers(value)
meta.proto = getObjectPrototype(value); meta.proto = getObjectPrototype(value)
} else if (meta.type === 'buffer') { } else if (meta.type === 'buffer') {
meta.value = Array.prototype.slice.call(value, 0); meta.value = Array.prototype.slice.call(value, 0)
} else if (meta.type === 'promise') { } else if (meta.type === 'promise') {
meta.then = valueToMeta(sender, function(v) { value.then(v); }); meta.then = valueToMeta(sender, function (v) { value.then(v) })
} 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
}); })
} else if (meta.type === 'date') { } else if (meta.type === 'date') {
meta.value = value.getTime(); meta.value = value.getTime()
} else { } else {
meta.type = 'value'; meta.type = 'value'
meta.value = value; meta.value = value
}
return meta
} }
return meta;
};
// Convert object to meta by value. // Convert object to meta by value.
var plainObjectToMeta = function (obj) { var plainObjectToMeta = function (obj) {
@ -130,9 +129,9 @@ var plainObjectToMeta = function(obj) {
return { return {
name: name, name: name,
value: obj[name] value: obj[name]
}; }
}); })
}; }
// Convert Error into meta data. // Convert Error into meta data.
var exceptionToMeta = function (error) { var exceptionToMeta = function (error) {
@ -140,232 +139,239 @@ var exceptionToMeta = function(error) {
type: 'exception', type: 'exception',
message: error.message, message: error.message,
stack: error.stack || error stack: error.stack || 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.
var unwrapArgs = function (sender, args) { var unwrapArgs = function (sender, args) {
var metaToValue; var metaToValue
metaToValue = function (meta) { metaToValue = function (meta) {
var i, len, member, ref, returnValue; var i, len, member, ref, returnValue
switch (meta.type) { switch (meta.type) {
case 'value': case 'value':
return meta.value; return meta.value
case 'remote-object': case 'remote-object':
return objectsRegistry.get(meta.id); return objectsRegistry.get(meta.id)
case 'array': case 'array':
return unwrapArgs(sender, meta.value); return unwrapArgs(sender, meta.value)
case 'buffer': case 'buffer':
return new Buffer(meta.value); return new Buffer(meta.value)
case 'date': case 'date':
return new Date(meta.value); return new Date(meta.value)
case 'promise': case 'promise':
return Promise.resolve({ return Promise.resolve({
then: metaToValue(meta.then) then: metaToValue(meta.then)
}); })
case 'object': { case 'object':
let ret = {}; {
Object.defineProperty(ret.constructor, 'name', { value: meta.name }); let ret = {}
Object.defineProperty(ret.constructor, 'name', { value: meta.name })
ref = meta.members; ref = meta.members
for (i = 0, len = ref.length; i < len; i++) { for (i = 0, len = ref.length; i < len; i++) {
member = ref[i]; member = ref[i]
ret[member.name] = metaToValue(member.value); ret[member.name] = metaToValue(member.value)
} }
return ret; return ret
} }
case 'function-with-return-value': case 'function-with-return-value':
returnValue = metaToValue(meta.value); returnValue = metaToValue(meta.value)
return function () { return function () {
return returnValue; return returnValue
}; }
case 'function': { case 'function':
{
// Cache the callbacks in renderer. // Cache the callbacks in renderer.
let webContentsId = sender.getId(); let webContentsId = sender.getId()
let callbacks = rendererFunctions[webContentsId]; let callbacks = rendererFunctions[webContentsId]
if (!callbacks) { if (!callbacks) {
callbacks = rendererFunctions[webContentsId] = new IDWeakMap; callbacks = rendererFunctions[webContentsId] = new IDWeakMap()
sender.once('render-view-deleted', function (event, id) { sender.once('render-view-deleted', function (event, id) {
callbacks.clear(); callbacks.clear()
delete rendererFunctions[id]; delete rendererFunctions[id]
}); })
} }
if (callbacks.has(meta.id)) if (callbacks.has(meta.id)) return callbacks.get(meta.id)
return callbacks.get(meta.id);
let callIntoRenderer = function (...args) { let callIntoRenderer = function (...args) {
if ((webContentsId in rendererFunctions) && !sender.isDestroyed()) if ((webContentsId in rendererFunctions) && !sender.isDestroyed()) {
sender.send('ATOM_RENDERER_CALLBACK', meta.id, valueToMeta(sender, args)); sender.send('ATOM_RENDERER_CALLBACK', meta.id, valueToMeta(sender, args))
else } else {
throw new Error(`Attempting to call a function in a renderer window that has been closed or released. Function provided here: ${meta.location}.`); throw new Error(`Attempting to call a function in a renderer window that has been closed or released. Function provided here: ${meta.location}.`)
}; }
}
v8Util.setDestructor(callIntoRenderer, function () { v8Util.setDestructor(callIntoRenderer, function () {
if ((webContentsId in rendererFunctions) && !sender.isDestroyed()) if ((webContentsId in rendererFunctions) && !sender.isDestroyed()) {
sender.send('ATOM_RENDERER_RELEASE_CALLBACK', meta.id); sender.send('ATOM_RENDERER_RELEASE_CALLBACK', meta.id)
}); }
callbacks.set(meta.id, callIntoRenderer); })
return callIntoRenderer; callbacks.set(meta.id, callIntoRenderer)
return callIntoRenderer
} }
default: default:
throw new TypeError("Unknown type: " + meta.type); throw new TypeError(`Unknown type: ${meta.type}`)
}
}
return args.map(metaToValue)
} }
};
return args.map(metaToValue);
};
// Call a function and send reply asynchronously if it's a an asynchronous // Call a function and send reply asynchronously if it's a an asynchronous
// style function and the caller didn't pass a callback. // style function and the caller didn't pass a callback.
var callFunction = function (event, func, caller, args) { var callFunction = function (event, func, caller, args) {
var funcMarkedAsync, funcName, funcPassedCallback, ref, ret; var funcMarkedAsync, funcName, funcPassedCallback, ref, ret
funcMarkedAsync = v8Util.getHiddenValue(func, 'asynchronous'); funcMarkedAsync = v8Util.getHiddenValue(func, 'asynchronous')
funcPassedCallback = typeof args[args.length - 1] === 'function'; funcPassedCallback = typeof args[args.length - 1] === 'function'
try { try {
if (funcMarkedAsync && !funcPassedCallback) { if (funcMarkedAsync && !funcPassedCallback) {
args.push(function (ret) { args.push(function (ret) {
return event.returnValue = valueToMeta(event.sender, ret, true); event.returnValue = valueToMeta(event.sender, ret, true)
}); return event.returnValue
return func.apply(caller, args); })
return func.apply(caller, args)
} else { } else {
ret = func.apply(caller, args); ret = func.apply(caller, args)
return event.returnValue = valueToMeta(event.sender, ret, true); event.returnValue = valueToMeta(event.sender, ret, true)
return event.returnValue
} }
} catch (error) { } catch (error) {
// 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: " + error.message); throw new Error(`Could not call remote function '${funcName}'. Check that the function signature is correct. Underlying error: ${error.message}`)
}
} }
};
ipcMain.on('ATOM_BROWSER_REQUIRE', function (event, module) { ipcMain.on('ATOM_BROWSER_REQUIRE', function (event, module) {
try { try {
return event.returnValue = valueToMeta(event.sender, process.mainModule.require(module)); event.returnValue = valueToMeta(event.sender, process.mainModule.require(module))
event.returnValue
} catch (error) { } catch (error) {
return event.returnValue = exceptionToMeta(error); event.returnValue = exceptionToMeta(error)
event.returnValue
} }
}); })
ipcMain.on('ATOM_BROWSER_GET_BUILTIN', function (event, module) { ipcMain.on('ATOM_BROWSER_GET_BUILTIN', function (event, module) {
try { try {
return event.returnValue = valueToMeta(event.sender, electron[module]); event.returnValue = valueToMeta(event.sender, electron[module])
} catch (error) { } catch (error) {
return event.returnValue = exceptionToMeta(error); event.returnValue = exceptionToMeta(error)
} }
}); })
ipcMain.on('ATOM_BROWSER_GLOBAL', function (event, name) { ipcMain.on('ATOM_BROWSER_GLOBAL', function (event, name) {
try { try {
return event.returnValue = valueToMeta(event.sender, global[name]); event.returnValue = valueToMeta(event.sender, global[name])
} catch (error) { } catch (error) {
return event.returnValue = exceptionToMeta(error); event.returnValue = exceptionToMeta(error)
} }
}); })
ipcMain.on('ATOM_BROWSER_CURRENT_WINDOW', function (event) { ipcMain.on('ATOM_BROWSER_CURRENT_WINDOW', function (event) {
try { try {
return event.returnValue = valueToMeta(event.sender, event.sender.getOwnerBrowserWindow()); event.returnValue = valueToMeta(event.sender, event.sender.getOwnerBrowserWindow())
} catch (error) { } catch (error) {
return event.returnValue = exceptionToMeta(error); event.returnValue = exceptionToMeta(error)
} }
}); })
ipcMain.on('ATOM_BROWSER_CURRENT_WEB_CONTENTS', function (event) { ipcMain.on('ATOM_BROWSER_CURRENT_WEB_CONTENTS', function (event) {
return event.returnValue = valueToMeta(event.sender, event.sender); event.returnValue = valueToMeta(event.sender, event.sender)
}); })
ipcMain.on('ATOM_BROWSER_CONSTRUCTOR', function (event, id, args) { ipcMain.on('ATOM_BROWSER_CONSTRUCTOR', function (event, id, args) {
try { try {
args = unwrapArgs(event.sender, args); args = unwrapArgs(event.sender, args)
let constructor = objectsRegistry.get(id); let 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
let obj = new (Function.prototype.bind.apply(constructor, [null].concat(args))); let obj = new Function.prototype.bind.apply(constructor, [null].concat(args))
return event.returnValue = valueToMeta(event.sender, obj); event.returnValue = valueToMeta(event.sender, obj)
} catch (error) { } catch (error) {
return event.returnValue = exceptionToMeta(error); event.returnValue = exceptionToMeta(error)
} }
}); })
ipcMain.on('ATOM_BROWSER_FUNCTION_CALL', function (event, id, args) { ipcMain.on('ATOM_BROWSER_FUNCTION_CALL', function (event, id, args) {
try { try {
args = unwrapArgs(event.sender, args); args = unwrapArgs(event.sender, args)
let func = objectsRegistry.get(id); let func = objectsRegistry.get(id)
return callFunction(event, func, global, args); return callFunction(event, func, global, args)
} catch (error) { } catch (error) {
return event.returnValue = exceptionToMeta(error); event.returnValue = exceptionToMeta(error)
} }
}); })
ipcMain.on('ATOM_BROWSER_MEMBER_CONSTRUCTOR', function (event, id, method, args) { ipcMain.on('ATOM_BROWSER_MEMBER_CONSTRUCTOR', function (event, id, method, args) {
try { try {
args = unwrapArgs(event.sender, args); args = unwrapArgs(event.sender, args)
let constructor = objectsRegistry.get(id)[method]; let constructor = objectsRegistry.get(id)[method]
// Call new with array of arguments. // Call new with array of arguments.
let obj = new (Function.prototype.bind.apply(constructor, [null].concat(args))); let obj = new Function.prototype.bind.apply(constructor, [null].concat(args))
return event.returnValue = valueToMeta(event.sender, obj); event.returnValue = valueToMeta(event.sender, obj)
} catch (error) { } catch (error) {
return event.returnValue = exceptionToMeta(error); event.returnValue = exceptionToMeta(error)
} }
}); })
ipcMain.on('ATOM_BROWSER_MEMBER_CALL', function (event, id, method, args) { ipcMain.on('ATOM_BROWSER_MEMBER_CALL', function (event, id, method, args) {
try { try {
args = unwrapArgs(event.sender, args); args = unwrapArgs(event.sender, args)
let obj = objectsRegistry.get(id); let obj = objectsRegistry.get(id)
return callFunction(event, obj[method], obj, args); return callFunction(event, obj[method], obj, args)
} catch (error) { } catch (error) {
return event.returnValue = exceptionToMeta(error); event.returnValue = exceptionToMeta(error)
} }
}); })
ipcMain.on('ATOM_BROWSER_MEMBER_SET', function (event, id, name, value) { ipcMain.on('ATOM_BROWSER_MEMBER_SET', function (event, id, name, value) {
try { try {
let obj = objectsRegistry.get(id); let obj = objectsRegistry.get(id)
obj[name] = value; obj[name] = value
return event.returnValue = null; event.returnValue = null
} catch (error) { } catch (error) {
return event.returnValue = exceptionToMeta(error); event.returnValue = exceptionToMeta(error)
} }
}); })
ipcMain.on('ATOM_BROWSER_MEMBER_GET', function (event, id, name) { ipcMain.on('ATOM_BROWSER_MEMBER_GET', function (event, id, name) {
try { try {
let obj = objectsRegistry.get(id); let obj = objectsRegistry.get(id)
return event.returnValue = valueToMeta(event.sender, obj[name]); event.returnValue = valueToMeta(event.sender, obj[name])
} catch (error) { } catch (error) {
return event.returnValue = exceptionToMeta(error); event.returnValue = exceptionToMeta(error)
} }
}); })
ipcMain.on('ATOM_BROWSER_DEREFERENCE', function (event, id) { ipcMain.on('ATOM_BROWSER_DEREFERENCE', function (event, id) {
return objectsRegistry.remove(event.sender.getId(), id); return objectsRegistry.remove(event.sender.getId(), id)
}); })
ipcMain.on('ATOM_BROWSER_GUEST_WEB_CONTENTS', function (event, guestInstanceId) { ipcMain.on('ATOM_BROWSER_GUEST_WEB_CONTENTS', function (event, guestInstanceId) {
try { try {
let guestViewManager = require('./guest-view-manager'); let guestViewManager = require('./guest-view-manager')
return event.returnValue = valueToMeta(event.sender, guestViewManager.getGuest(guestInstanceId)); event.returnValue = valueToMeta(event.sender, guestViewManager.getGuest(guestInstanceId))
} catch (error) { } catch (error) {
return event.returnValue = exceptionToMeta(error); event.returnValue = exceptionToMeta(error)
} }
}); })
ipcMain.on('ATOM_BROWSER_ASYNC_CALL_TO_GUEST_VIEW', function (event, requestId, guestInstanceId, method, ...args) { ipcMain.on('ATOM_BROWSER_ASYNC_CALL_TO_GUEST_VIEW', function (event, requestId, guestInstanceId, method, ...args) {
try { try {
let guestViewManager = require('./guest-view-manager'); let guestViewManager = require('./guest-view-manager')
let guest = guestViewManager.getGuest(guestInstanceId); let guest = guestViewManager.getGuest(guestInstanceId)
if (requestId) { if (requestId) {
const responseCallback = function (result) { const responseCallback = function (result) {
event.sender.send(`ATOM_RENDERER_ASYNC_CALL_TO_GUEST_VIEW_RESPONSE_${requestId}`, result); event.sender.send(`ATOM_RENDERER_ASYNC_CALL_TO_GUEST_VIEW_RESPONSE_${requestId}`, result)
};
args.push(responseCallback);
} }
guest[method].apply(guest, args); args.push(responseCallback)
}
guest[method].apply(guest, args)
} catch (error) { } catch (error) {
return event.returnValue = exceptionToMeta(error); event.returnValue = exceptionToMeta(error)
} }
}); })