Merge pull request #3415 from atom/exports-electron

Move all public APIs to "electron" module
This commit is contained in:
Cheng Zhao 2015-11-13 11:21:45 +08:00
commit 3a5160f799
111 changed files with 594 additions and 438 deletions

View file

@ -1,5 +1,5 @@
deprecate = require 'deprecate' electron = require 'electron'
EventEmitter = require('events').EventEmitter {EventEmitter} = require 'events'
bindings = process.atomBinding 'app' bindings = process.atomBinding 'app'
sessionBindings = process.atomBinding 'session' sessionBindings = process.atomBinding 'session'
@ -9,10 +9,10 @@ app = bindings.app
app.__proto__ = EventEmitter.prototype app.__proto__ = EventEmitter.prototype
app.setApplicationMenu = (menu) -> app.setApplicationMenu = (menu) ->
require('menu').setApplicationMenu menu electron.Menu.setApplicationMenu menu
app.getApplicationMenu = -> app.getApplicationMenu = ->
require('menu').getApplicationMenu() electron.Menu.getApplicationMenu()
app.commandLine = app.commandLine =
appendSwitch: bindings.appendSwitch, appendSwitch: bindings.appendSwitch,
@ -39,6 +39,7 @@ app.getAppPath = ->
app.resolveProxy = (url, callback) -> @defaultSession.resolveProxy url, callback app.resolveProxy = (url, callback) -> @defaultSession.resolveProxy url, callback
# Deprecated. # Deprecated.
{deprecate} = electron
app.getHomeDir = deprecate 'app.getHomeDir', 'app.getPath', -> app.getHomeDir = deprecate 'app.getHomeDir', 'app.getPath', ->
@getPath 'home' @getPath 'home'
app.getDataPath = deprecate 'app.getDataPath', 'app.getPath', -> app.getDataPath = deprecate 'app.getDataPath', 'app.getPath', ->

View file

@ -1,7 +1,5 @@
switch process.platform module.exports =
when 'win32' if process.platform is 'win32'
module.exports = require './auto-updater/auto-updater-win' require './auto-updater/auto-updater-win'
when 'darwin'
module.exports = require './auto-updater/auto-updater-mac'
else else
throw new Error('auto-updater is not implemented on this platform') require './auto-updater/auto-updater-native'

View file

@ -1,6 +1,6 @@
app = require 'app' {app} = require 'electron'
url = require 'url'
{EventEmitter} = require 'events' {EventEmitter} = require 'events'
url = require 'url'
squirrelUpdate = require './squirrel-update-win' squirrelUpdate = require './squirrel-update-win'

View file

@ -1,7 +1,5 @@
EventEmitter = require('events').EventEmitter {app, ipcMain, deprecate} = require 'electron'
app = require 'app' {EventEmitter} = require 'events'
ipc = require 'ipc-main'
deprecate = require 'deprecate'
BrowserWindow = process.atomBinding('window').BrowserWindow BrowserWindow = process.atomBinding('window').BrowserWindow
BrowserWindow::__proto__ = EventEmitter.prototype BrowserWindow::__proto__ = EventEmitter.prototype
@ -15,7 +13,7 @@ BrowserWindow::_init = ->
# Make new windows requested by links behave like "window.open" # Make new windows requested by links behave like "window.open"
@webContents.on '-new-window', (event, url, frameName) -> @webContents.on '-new-window', (event, url, frameName) ->
options = show: true, width: 800, height: 600 options = show: true, width: 800, height: 600
ipc.emit 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPEN', event, url, frameName, options ipcMain.emit 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPEN', event, url, frameName, options
# window.resizeTo(...) # window.resizeTo(...)
# window.moveTo(...) # window.moveTo(...)

View file

@ -1,7 +1,7 @@
{app, BrowserWindow} = require 'electron'
binding = process.atomBinding 'dialog' binding = process.atomBinding 'dialog'
v8Util = process.atomBinding 'v8_util' v8Util = process.atomBinding 'v8_util'
app = require 'app'
BrowserWindow = require 'browser-window'
fileDialogProperties = fileDialogProperties =
openFile: 1 << 0 openFile: 1 << 0

View file

@ -0,0 +1,55 @@
# Import common modules.
module.exports = require '../../../../common/api/lib/exports/electron'
v8Util = process.atomBinding 'v8_util'
v8Util.setHiddenValue module.exports, 'electronModule', true
Object.defineProperties module.exports,
# Browser side modules, please sort with alphabet order.
app:
enumerable: true
get: -> require '../app'
autoUpdater:
enumerable: true
get: -> require '../auto-updater'
BrowserWindow:
enumerable: true
get: -> require '../browser-window'
contentTracing:
enumerable: true
get: -> require '../content-tracing'
dialog:
enumerable: true
get: -> require '../dialog'
ipcMain:
enumerable: true
get: -> require '../ipc-main'
globalShortcut:
enumerable: true
get: -> require '../global-shortcut'
Menu:
enumerable: true
get: -> require '../menu'
MenuItem:
enumerable: true
get: -> require '../menu-item'
powerMonitor:
enumerable: true
get: -> require '../power-monitor'
powerSaveBlocker:
enumerable: true
get: -> require '../power-save-blocker'
protocol:
enumerable: true
get: -> require '../protocol'
screen:
enumerable: true
get: -> require '../screen'
tray:
enumerable: true
get: -> require '../tray'
# The internal modules, invisible unless you know their names.
NavigationController:
get: -> require '../navigation-controller'
webContents:
get: -> require '../web-contents'

View file

@ -1,5 +1,3 @@
bindings = process.atomBinding 'global_shortcut' {globalShortcut} = process.atomBinding 'global_shortcut'
globalShortcut = bindings.globalShortcut
module.exports = globalShortcut module.exports = globalShortcut

View file

@ -1,6 +1,6 @@
deprecate = require 'deprecate' {deprecate, ipcMain} = require 'electron'
# This module is deprecated, we mirror everything from ipcMain. # This module is deprecated, we mirror everything from ipcMain.
deprecate.warn 'ipc module', 'ipcMain module' deprecate.warn 'ipc module', 'ipcMain module'
module.exports = require 'ipc-main' module.exports = ipcMain

View file

@ -1,4 +1,3 @@
BrowserWindow = require 'browser-window'
v8Util = process.atomBinding 'v8_util' v8Util = process.atomBinding 'v8_util'
nextCommandId = 0 nextCommandId = 0
@ -18,7 +17,7 @@ class MenuItem
@types = ['normal', 'separator', 'submenu', 'checkbox', 'radio'] @types = ['normal', 'separator', 'submenu', 'checkbox', 'radio']
constructor: (options) -> constructor: (options) ->
Menu = require 'menu' {Menu} = require 'electron'
{click, @selector, @type, @role, @label, @sublabel, @accelerator, @icon, @enabled, @visible, @checked, @submenu} = options {click, @selector, @type, @role, @label, @sublabel, @accelerator, @icon, @enabled, @visible, @checked, @submenu} = options

View file

@ -1,8 +1,7 @@
BrowserWindow = require 'browser-window' {BrowserWindow, MenuItem} = require 'electron'
EventEmitter = require('events').EventEmitter {EventEmitter} = require 'events'
MenuItem = require 'menu-item'
v8Util = process.atomBinding 'v8_util'
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.

View file

@ -1,10 +1,10 @@
ipc = require 'ipc-main' {ipcMain} = require 'electron'
# The history operation in renderer is redirected to browser. # The history operation in renderer is redirected to browser.
ipc.on 'ATOM_SHELL_NAVIGATION_CONTROLLER', (event, method, args...) -> ipcMain.on 'ATOM_SHELL_NAVIGATION_CONTROLLER', (event, method, args...) ->
event.sender[method] args... event.sender[method] args...
ipc.on 'ATOM_SHELL_SYNC_NAVIGATION_CONTROLLER', (event, method, args...) -> ipcMain.on 'ATOM_SHELL_SYNC_NAVIGATION_CONTROLLER', (event, method, args...) ->
event.returnValue = event.sender[method] args... event.returnValue = event.sender[method] args...
# JavaScript implementation of Chromium's NavigationController. # JavaScript implementation of Chromium's NavigationController.

View file

@ -1,5 +1,6 @@
powerMonitor = process.atomBinding('power_monitor').powerMonitor {EventEmitter} = require 'events'
EventEmitter = require('events').EventEmitter
{powerMonitor} = process.atomBinding 'power_monitor'
powerMonitor.__proto__ = EventEmitter.prototype powerMonitor.__proto__ = EventEmitter.prototype

View file

@ -1,3 +1,3 @@
bindings = process.atomBinding 'power_save_blocker' {powerSaveBlocker} = process.atomBinding 'power_save_blocker'
module.exports = bindings.powerSaveBlocker module.exports = powerSaveBlocker

View file

@ -1,7 +1,8 @@
app = require 'app' {app} = require 'electron'
throw new Error('Can not initialize protocol module before app is ready') unless app.isReady() throw new Error('Can not initialize protocol module before app is ready') unless app.isReady()
protocol = process.atomBinding('protocol').protocol {protocol} = process.atomBinding 'protocol'
# Warn about removed APIs. # Warn about removed APIs.
logAndThrow = (callback, message) -> logAndThrow = (callback, message) ->

View file

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

View file

@ -1,7 +1,6 @@
EventEmitter = require('events').EventEmitter {EventEmitter} = require 'events'
bindings = process.atomBinding 'tray' {Tray} = process.atomBinding 'tray'
Tray = bindings.Tray
Tray::__proto__ = EventEmitter.prototype Tray::__proto__ = EventEmitter.prototype
Tray::setContextMenu = (menu) -> Tray::setContextMenu = (menu) ->

View file

@ -1,8 +1,7 @@
EventEmitter = require('events').EventEmitter {EventEmitter} = require 'events'
Menu = require './menu' {ipcMain, NavigationController, Menu} = require 'electron'
NavigationController = require './navigation-controller'
binding = process.atomBinding 'web_contents' binding = process.atomBinding 'web_contents'
ipc = require 'ipc-main'
nextId = 0 nextId = 0
getNextId = -> ++nextId getNextId = -> ++nextId
@ -60,11 +59,11 @@ wrapWebContents = (webContents) ->
# Dispatch IPC messages to the ipc module. # Dispatch IPC messages to the ipc module.
webContents.on 'ipc-message', (event, packed) -> webContents.on 'ipc-message', (event, packed) ->
[channel, args...] = packed [channel, args...] = packed
ipc.emit channel, event, args... ipcMain.emit channel, event, args...
webContents.on 'ipc-message-sync', (event, packed) -> webContents.on 'ipc-message-sync', (event, packed) ->
[channel, args...] = packed [channel, args...] = packed
Object.defineProperty event, 'returnValue', set: (value) -> event.sendReply JSON.stringify(value) Object.defineProperty event, 'returnValue', set: (value) -> event.sendReply JSON.stringify(value)
ipc.emit channel, event, args... ipcMain.emit channel, event, args...
# Handle context menu action request from pepper plugin. # Handle context menu action request from pepper plugin.
webContents.on 'pepper-context-menu', (event, params) -> webContents.on 'pepper-context-menu', (event, params) ->

View file

@ -1,5 +1,6 @@
var app = require('app'); const electron = require('electron');
var BrowserWindow = require('browser-window'); const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
var mainWindow = null; var mainWindow = null;

View file

@ -57,13 +57,17 @@
</head> </head>
<body> <body>
<script> <script>
var execPath = require('remote').process.execPath; const electron = require('electron');
const remote = electron.remote;
const shell = electron.shell;
var execPath = remote.process.execPath;
var command = execPath + ' path-to-your-app'; var command = execPath + ' path-to-your-app';
document.onclick = function(e) { document.onclick = function(e) {
e.preventDefault(); e.preventDefault();
if (e.target.tagName == 'A') if (e.target.tagName == 'A')
require('shell').openExternal(e.target.href); shell.openExternal(e.target.href);
return false; return false;
}; };
document.ondragover = document.ondrop = function(e) { document.ondragover = document.ondrop = function(e) {

View file

@ -1,9 +1,11 @@
var app = require('app'); const electron = require('electron');
var dialog = require('dialog'); const app = electron.app;
const dialog = electron.dialog;
const shell = electron.shell;
const Menu = electron.Menu;
var fs = require('fs'); var fs = require('fs');
var path = require('path'); var path = require('path');
var Menu = require('menu');
var BrowserWindow = require('browser-window');
// Quit when all windows are closed and no other one is listening to this. // Quit when all windows are closed and no other one is listening to this.
app.on('window-all-closed', function() { app.on('window-all-closed', function() {
@ -142,19 +144,19 @@ app.once('ready', function() {
submenu: [ submenu: [
{ {
label: 'Learn More', label: 'Learn More',
click: function() { require('shell').openExternal('http://electron.atom.io') } click: function() { shell.openExternal('http://electron.atom.io') }
}, },
{ {
label: 'Documentation', label: 'Documentation',
click: function() { require('shell').openExternal('https://github.com/atom/electron/tree/master/docs#readme') } click: function() { shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme') }
}, },
{ {
label: 'Community Discussions', label: 'Community Discussions',
click: function() { require('shell').openExternal('https://discuss.atom.io/c/electron') } click: function() { shell.openExternal('https://discuss.atom.io/c/electron') }
}, },
{ {
label: 'Search Issues', label: 'Search Issues',
click: function() { require('shell').openExternal('https://github.com/atom/electron/issues') } click: function() { shell.openExternal('https://github.com/atom/electron/issues') }
} }
] ]
}, },
@ -269,5 +271,5 @@ if (option.file && !option.webdriver) {
console.log(helpMessage); console.log(helpMessage);
process.exit(0); process.exit(0);
} else { } else {
require('./default_app.js'); require('./default_app');
} }

View file

@ -1,4 +1,4 @@
app = require 'app' electron = require 'electron'
fs = require 'fs' fs = require 'fs'
path = require 'path' path = require 'path'
url = require 'url' url = require 'url'
@ -40,6 +40,7 @@ loadedExtensions = null
loadedExtensionsPath = null loadedExtensionsPath = null
# Persistent loaded extensions. # Persistent loaded extensions.
{app} = electron
app.on 'will-quit', -> app.on 'will-quit', ->
try try
loadedExtensions = Object.keys(extensionInfoMap).map (key) -> extensionInfoMap[key].srcDirectory loadedExtensions = Object.keys(extensionInfoMap).map (key) -> extensionInfoMap[key].srcDirectory
@ -51,8 +52,7 @@ app.on 'will-quit', ->
# 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', -> app.once 'ready', ->
protocol = require 'protocol' {protocol, BrowserWindow} = electron
BrowserWindow = require 'browser-window'
# Load persistented extensions. # Load persistented extensions.
loadedExtensionsPath = path.join app.getPath('userData'), 'DevTools Extensions' loadedExtensionsPath = path.join app.getPath('userData'), 'DevTools Extensions'

View file

@ -1,5 +1,5 @@
ipc = require 'ipc-main' {ipcMain, webContents} = require 'electron'
webContents = require 'web-contents'
webViewManager = null # Doesn't exist in early initialization. webViewManager = null # Doesn't exist in early initialization.
supportedWebViewEvents = [ supportedWebViewEvents = [
@ -140,19 +140,19 @@ destroyGuest = (embedder, id) ->
delete reverseEmbedderElementsMap[id] delete reverseEmbedderElementsMap[id]
delete embedderElementsMap[key] delete embedderElementsMap[key]
ipc.on 'ATOM_SHELL_GUEST_VIEW_MANAGER_CREATE_GUEST', (event, params, requestId) -> ipcMain.on 'ATOM_SHELL_GUEST_VIEW_MANAGER_CREATE_GUEST', (event, params, requestId) ->
event.sender.send "ATOM_SHELL_RESPONSE_#{requestId}", createGuest(event.sender, params) event.sender.send "ATOM_SHELL_RESPONSE_#{requestId}", createGuest(event.sender, params)
ipc.on 'ATOM_SHELL_GUEST_VIEW_MANAGER_ATTACH_GUEST', (event, elementInstanceId, guestInstanceId, params) -> ipcMain.on 'ATOM_SHELL_GUEST_VIEW_MANAGER_ATTACH_GUEST', (event, elementInstanceId, guestInstanceId, params) ->
attachGuest event.sender, elementInstanceId, guestInstanceId, params attachGuest event.sender, elementInstanceId, guestInstanceId, params
ipc.on 'ATOM_SHELL_GUEST_VIEW_MANAGER_DESTROY_GUEST', (event, id) -> ipcMain.on 'ATOM_SHELL_GUEST_VIEW_MANAGER_DESTROY_GUEST', (event, id) ->
destroyGuest event.sender, id destroyGuest event.sender, id
ipc.on 'ATOM_SHELL_GUEST_VIEW_MANAGER_SET_SIZE', (event, id, params) -> ipcMain.on 'ATOM_SHELL_GUEST_VIEW_MANAGER_SET_SIZE', (event, id, params) ->
guestInstances[id]?.guest.setSize params guestInstances[id]?.guest.setSize params
ipc.on 'ATOM_SHELL_GUEST_VIEW_MANAGER_SET_ALLOW_TRANSPARENCY', (event, id, allowtransparency) -> ipcMain.on 'ATOM_SHELL_GUEST_VIEW_MANAGER_SET_ALLOW_TRANSPARENCY', (event, id, allowtransparency) ->
guestInstances[id]?.guest.setAllowTransparency allowtransparency guestInstances[id]?.guest.setAllowTransparency allowtransparency
# Returns WebContents from its guest id. # Returns WebContents from its guest id.

View file

@ -1,6 +1,5 @@
ipc = require 'ipc-main' {ipcMain, BrowserWindow} = require 'electron'
v8Util = process.atomBinding 'v8_util' v8Util = process.atomBinding 'v8_util'
BrowserWindow = require 'browser-window'
frameToGuest = {} frameToGuest = {}
@ -58,7 +57,7 @@ createGuest = (embedder, url, frameName, options) ->
guest.id guest.id
# Routed window.open messages. # Routed window.open messages.
ipc.on 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPEN', (event, args...) -> ipcMain.on 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPEN', (event, args...) ->
[url, frameName, options] = args [url, frameName, options] = args
options = mergeBrowserWindowOptions event.sender, options options = mergeBrowserWindowOptions event.sender, options
event.sender.emit 'new-window', event, url, frameName, 'new-window', options event.sender.emit 'new-window', event, url, frameName, 'new-window', options
@ -67,26 +66,26 @@ ipc.on 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPEN', (event, args...) ->
else else
event.returnValue = createGuest event.sender, url, frameName, options event.returnValue = createGuest event.sender, url, frameName, options
ipc.on 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_CLOSE', (event, guestId) -> ipcMain.on 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_CLOSE', (event, guestId) ->
BrowserWindow.fromId(guestId)?.destroy() BrowserWindow.fromId(guestId)?.destroy()
ipc.on 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_METHOD', (event, guestId, method, args...) -> ipcMain.on 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_METHOD', (event, guestId, method, args...) ->
BrowserWindow.fromId(guestId)?[method] args... BrowserWindow.fromId(guestId)?[method] args...
ipc.on 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_POSTMESSAGE', (event, guestId, message, targetOrigin) -> ipcMain.on 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_POSTMESSAGE', (event, guestId, message, targetOrigin) ->
guestContents = BrowserWindow.fromId(guestId)?.webContents guestContents = BrowserWindow.fromId(guestId)?.webContents
if guestContents?.getUrl().indexOf(targetOrigin) is 0 or targetOrigin is '*' if guestContents?.getUrl().indexOf(targetOrigin) is 0 or targetOrigin is '*'
guestContents.send 'ATOM_SHELL_GUEST_WINDOW_POSTMESSAGE', guestId, message, targetOrigin guestContents.send 'ATOM_SHELL_GUEST_WINDOW_POSTMESSAGE', guestId, message, targetOrigin
ipc.on 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPENER_POSTMESSAGE', (event, guestId, message, targetOrigin, sourceOrigin) -> ipcMain.on 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPENER_POSTMESSAGE', (event, guestId, message, targetOrigin, sourceOrigin) ->
embedder = v8Util.getHiddenValue event.sender, 'embedder' embedder = v8Util.getHiddenValue event.sender, 'embedder'
if embedder?.getUrl().indexOf(targetOrigin) is 0 or targetOrigin is '*' if embedder?.getUrl().indexOf(targetOrigin) is 0 or targetOrigin is '*'
embedder.send 'ATOM_SHELL_GUEST_WINDOW_POSTMESSAGE', guestId, message, sourceOrigin embedder.send 'ATOM_SHELL_GUEST_WINDOW_POSTMESSAGE', guestId, message, sourceOrigin
ipc.on 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WEB_CONTENTS_METHOD', (event, guestId, method, args...) -> ipcMain.on 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WEB_CONTENTS_METHOD', (event, guestId, method, args...) ->
BrowserWindow.fromId(guestId)?.webContents?[method] args... BrowserWindow.fromId(guestId)?.webContents?[method] args...
ipc.on 'ATOM_SHELL_GUEST_WINDOW_MANAGER_GET_GUEST_ID', (event) -> ipcMain.on 'ATOM_SHELL_GUEST_WINDOW_MANAGER_GET_GUEST_ID', (event) ->
embedder = v8Util.getHiddenValue event.sender, 'embedder' embedder = v8Util.getHiddenValue event.sender, 'embedder'
if embedder? if embedder?
guest = BrowserWindow.fromWebContents event.sender guest = BrowserWindow.fromWebContents event.sender

View file

@ -13,10 +13,12 @@ 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')
# Add browser/api/lib to module search paths, which contains javascript part of
# Electron's built-in libraries.
globalPaths = Module.globalPaths globalPaths = Module.globalPaths
globalPaths.push path.resolve(__dirname, '..', 'api', 'lib') unless process.env.ELECTRON_HIDE_INTERNAL_MODULES
globalPaths.push path.resolve(__dirname, '..', 'api', 'lib')
# Expose public APIs.
globalPaths.push path.resolve(__dirname, '..', 'api', 'lib', 'exports')
if process.platform is 'win32' if process.platform is 'win32'
# Redirect node's console to use our own implementations, since node can not # Redirect node's console to use our own implementations, since node can not
@ -44,12 +46,13 @@ process.on 'uncaughtException', (error) ->
return return
# Show error in GUI. # Show error in GUI.
{dialog} = require 'electron'
stack = error.stack ? "#{error.name}: #{error.message}" stack = error.stack ? "#{error.name}: #{error.message}"
message = "Uncaught Exception:\n#{stack}" message = "Uncaught Exception:\n#{stack}"
require('dialog').showErrorBox 'A JavaScript error occurred in the main process', message dialog.showErrorBox 'A JavaScript error occurred in the main process', message
# Emit 'exit' event on quit. # Emit 'exit' event on quit.
app = require 'app' {app} = require 'electron'
app.on 'quit', -> app.on 'quit', ->
process.emit 'exit' process.emit 'exit'

View file

@ -1,4 +1,4 @@
EventEmitter = require('events').EventEmitter {EventEmitter} = require 'events'
v8Util = process.atomBinding 'v8_util' v8Util = process.atomBinding 'v8_util'
class ObjectsRegistry extends EventEmitter class ObjectsRegistry extends EventEmitter

View file

@ -1,8 +1,11 @@
ipc = require 'ipc-main'
path = require 'path' path = require 'path'
objectsRegistry = require './objects-registry.js'
electron = require 'electron'
{ipcMain} = electron
objectsRegistry = require './objects-registry'
v8Util = process.atomBinding 'v8_util' v8Util = process.atomBinding 'v8_util'
IDWeakMap = process.atomBinding('id_weak_map').IDWeakMap {IDWeakMap} = process.atomBinding 'id_weak_map'
# Convert a real value into meta data. # Convert a real value into meta data.
valueToMeta = (sender, value, optimizeSimpleObject=false) -> valueToMeta = (sender, value, optimizeSimpleObject=false) ->
@ -13,7 +16,11 @@ valueToMeta = (sender, value, optimizeSimpleObject=false) ->
meta.type = 'array' if Array.isArray value meta.type = 'array' if Array.isArray value
meta.type = 'error' if value instanceof Error meta.type = 'error' if value instanceof Error
meta.type = 'date' if value instanceof Date meta.type = 'date' if value instanceof Date
meta.type = 'promise' if value? and value.constructor.name is 'Promise' meta.type = 'promise' if value?.constructor.name is 'Promise'
# require('electron').
if meta.type is 'object' and v8Util.getHiddenValue value, 'electronModule'
meta.type = 'electronModule'
# Treat simple objects as value. # Treat simple objects as value.
if optimizeSimpleObject and meta.type is 'object' and v8Util.getHiddenValue value, 'simple' if optimizeSimpleObject and meta.type is 'object' and v8Util.getHiddenValue value, 'simple'
@ -42,6 +49,8 @@ valueToMeta = (sender, value, optimizeSimpleObject=false) ->
meta.members = plainObjectToMeta value meta.members = plainObjectToMeta value
else if meta.type is 'date' else if meta.type is 'date'
meta.value = value.getTime() meta.value = value.getTime()
else if meta.type is 'electronModule'
meta.members = (name for name of value)
else else
meta.type = 'value' meta.type = 'value'
meta.value = value meta.value = value
@ -115,28 +124,34 @@ callFunction = (event, func, caller, args) ->
process.on 'ATOM_BROWSER_RELEASE_RENDER_VIEW', (id) -> process.on 'ATOM_BROWSER_RELEASE_RENDER_VIEW', (id) ->
objectsRegistry.clear id objectsRegistry.clear id
ipc.on 'ATOM_BROWSER_REQUIRE', (event, module) -> ipcMain.on 'ATOM_BROWSER_REQUIRE', (event, module) ->
try try
event.returnValue = valueToMeta event.sender, process.mainModule.require(module) event.returnValue = valueToMeta event.sender, process.mainModule.require(module)
catch e catch e
event.returnValue = exceptionToMeta e event.returnValue = exceptionToMeta e
ipc.on 'ATOM_BROWSER_GLOBAL', (event, name) -> ipcMain.on 'ATOM_BROWSER_GET_BUILTIN', (event, module) ->
try
event.returnValue = valueToMeta event.sender, electron[module]
catch e
event.returnValue = exceptionToMeta e
ipcMain.on 'ATOM_BROWSER_GLOBAL', (event, name) ->
try try
event.returnValue = valueToMeta event.sender, global[name] event.returnValue = valueToMeta event.sender, global[name]
catch e catch e
event.returnValue = exceptionToMeta e event.returnValue = exceptionToMeta e
ipc.on 'ATOM_BROWSER_CURRENT_WINDOW', (event) -> ipcMain.on 'ATOM_BROWSER_CURRENT_WINDOW', (event) ->
try try
event.returnValue = valueToMeta event.sender, event.sender.getOwnerBrowserWindow() event.returnValue = valueToMeta event.sender, event.sender.getOwnerBrowserWindow()
catch e catch e
event.returnValue = exceptionToMeta e event.returnValue = exceptionToMeta e
ipc.on 'ATOM_BROWSER_CURRENT_WEB_CONTENTS', (event) -> ipcMain.on 'ATOM_BROWSER_CURRENT_WEB_CONTENTS', (event) ->
event.returnValue = valueToMeta event.sender, event.sender event.returnValue = valueToMeta event.sender, event.sender
ipc.on 'ATOM_BROWSER_CONSTRUCTOR', (event, id, args) -> ipcMain.on 'ATOM_BROWSER_CONSTRUCTOR', (event, id, args) ->
try try
args = unwrapArgs event.sender, args args = unwrapArgs event.sender, args
constructor = objectsRegistry.get id constructor = objectsRegistry.get id
@ -147,7 +162,7 @@ ipc.on 'ATOM_BROWSER_CONSTRUCTOR', (event, id, args) ->
catch e catch e
event.returnValue = exceptionToMeta e event.returnValue = exceptionToMeta e
ipc.on 'ATOM_BROWSER_FUNCTION_CALL', (event, id, args) -> ipcMain.on 'ATOM_BROWSER_FUNCTION_CALL', (event, id, args) ->
try try
args = unwrapArgs event.sender, args args = unwrapArgs event.sender, args
func = objectsRegistry.get id func = objectsRegistry.get id
@ -155,7 +170,7 @@ ipc.on 'ATOM_BROWSER_FUNCTION_CALL', (event, id, args) ->
catch e catch e
event.returnValue = exceptionToMeta e event.returnValue = exceptionToMeta e
ipc.on 'ATOM_BROWSER_MEMBER_CONSTRUCTOR', (event, id, method, args) -> ipcMain.on 'ATOM_BROWSER_MEMBER_CONSTRUCTOR', (event, id, method, args) ->
try try
args = unwrapArgs event.sender, args args = unwrapArgs event.sender, args
constructor = objectsRegistry.get(id)[method] constructor = objectsRegistry.get(id)[method]
@ -165,7 +180,7 @@ ipc.on 'ATOM_BROWSER_MEMBER_CONSTRUCTOR', (event, id, method, args) ->
catch e catch e
event.returnValue = exceptionToMeta e event.returnValue = exceptionToMeta e
ipc.on 'ATOM_BROWSER_MEMBER_CALL', (event, id, method, args) -> ipcMain.on 'ATOM_BROWSER_MEMBER_CALL', (event, id, method, args) ->
try try
args = unwrapArgs event.sender, args args = unwrapArgs event.sender, args
obj = objectsRegistry.get id obj = objectsRegistry.get id
@ -173,7 +188,7 @@ ipc.on 'ATOM_BROWSER_MEMBER_CALL', (event, id, method, args) ->
catch e catch e
event.returnValue = exceptionToMeta e event.returnValue = exceptionToMeta e
ipc.on 'ATOM_BROWSER_MEMBER_SET', (event, id, name, value) -> ipcMain.on 'ATOM_BROWSER_MEMBER_SET', (event, id, name, value) ->
try try
obj = objectsRegistry.get id obj = objectsRegistry.get id
obj[name] = value obj[name] = value
@ -181,17 +196,17 @@ ipc.on 'ATOM_BROWSER_MEMBER_SET', (event, id, name, value) ->
catch e catch e
event.returnValue = exceptionToMeta e event.returnValue = exceptionToMeta e
ipc.on 'ATOM_BROWSER_MEMBER_GET', (event, id, name) -> ipcMain.on 'ATOM_BROWSER_MEMBER_GET', (event, id, name) ->
try try
obj = objectsRegistry.get id obj = objectsRegistry.get id
event.returnValue = valueToMeta event.sender, obj[name] event.returnValue = valueToMeta event.sender, obj[name]
catch e catch e
event.returnValue = exceptionToMeta e event.returnValue = exceptionToMeta e
ipc.on 'ATOM_BROWSER_DEREFERENCE', (event, id) -> ipcMain.on 'ATOM_BROWSER_DEREFERENCE', (event, id) ->
objectsRegistry.remove event.sender.getId(), id objectsRegistry.remove event.sender.getId(), id
ipc.on 'ATOM_BROWSER_GUEST_WEB_CONTENTS', (event, guestInstanceId) -> ipcMain.on 'ATOM_BROWSER_GUEST_WEB_CONTENTS', (event, guestInstanceId) ->
try try
guestViewManager = require './guest-view-manager' guestViewManager = require './guest-view-manager'
event.returnValue = valueToMeta event.sender, guestViewManager.getGuest(guestInstanceId) event.returnValue = valueToMeta event.sender, guestViewManager.getGuest(guestInstanceId)

View file

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

View file

@ -8,11 +8,12 @@ class CrashReporter
start: (options={}) -> start: (options={}) ->
{@productName, companyName, submitUrl, autoSubmit, ignoreSystemCrashHandler, extra} = options {@productName, companyName, submitUrl, autoSubmit, ignoreSystemCrashHandler, extra} = options
app = electron = require 'electron'
{app} =
if process.type is 'browser' if process.type is 'browser'
require 'app' electron
else else
require('remote').require 'app' electron.remote.require 'electron'
@productName ?= app.getName() @productName ?= app.getName()
companyName ?= 'GitHub, Inc' companyName ?= 'GitHub, Inc'

View file

@ -0,0 +1,27 @@
# Do not expose the internal modules to `require`.
exports.hideInternalModules = ->
{globalPaths} = require 'module'
if globalPaths.length is 3
# Remove the "common/api/lib" and "browser-or-renderer/api/lib".
globalPaths.splice 0, 2
Object.defineProperties exports,
# Common modules, please sort with alphabet order.
clipboard:
# Must be enumerable, otherwise it woulde be invisible to remote module.
enumerable: true
get: -> require '../clipboard'
crashReporter:
enumerable: true
get: -> require '../crash-reporter'
nativeImage:
enumerable: true
get: -> require '../native-image'
shell:
enumerable: true
get: -> require '../shell'
# The internal modules, invisible unless you know their names.
CallbacksRegistry:
get: -> require '../callbacks-registry'
deprecate:
get: -> require '../deprecate'

View file

@ -9,8 +9,9 @@ process.atomBinding = (name) ->
catch e catch e
process.binding "atom_common_#{name}" if /No such module/.test e.message process.binding "atom_common_#{name}" if /No such module/.test e.message
# Add common/api/lib to module search paths. unless process.env.ELECTRON_HIDE_INTERNAL_MODULES
Module.globalPaths.push path.resolve(__dirname, '..', 'api', 'lib') # Add common/api/lib to module search paths.
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

View file

@ -0,0 +1,17 @@
# Import common modules.
module.exports = require '../../../../common/api/lib/exports/electron'
Object.defineProperties module.exports,
# Renderer side modules, please sort with alphabet order.
ipcRenderer:
enumerable: true
get: -> require '../ipc-renderer'
remote:
enumerable: true
get: -> require '../remote'
screen:
enumerable: true
get: -> require '../screen'
webFrame:
enumerable: true
get: -> require '../web-frame'

View file

@ -1,5 +1,4 @@
deprecate = require 'deprecate' {ipcRenderer, deprecate} = require 'electron'
ipcRenderer = require 'ipc-renderer'
{EventEmitter} = require 'events' {EventEmitter} = require 'events'
# This module is deprecated, we mirror everything from ipcRenderer. # This module is deprecated, we mirror everything from ipcRenderer.

View file

@ -1,6 +1,5 @@
ipc = require 'ipc-renderer' {ipcRenderer, CallbacksRegistry} = require 'electron'
v8Util = process.atomBinding 'v8_util' v8Util = process.atomBinding 'v8_util'
CallbacksRegistry = require 'callbacks-registry'
callbacksRegistry = new CallbacksRegistry callbacksRegistry = new CallbacksRegistry
@ -19,7 +18,7 @@ wrapArgs = (args, visited=[]) ->
type: 'array', value: wrapArgs(value, visited) type: 'array', value: wrapArgs(value, visited)
else if Buffer.isBuffer value else if Buffer.isBuffer value
type: 'buffer', value: Array::slice.call(value, 0) type: 'buffer', value: Array::slice.call(value, 0)
else if value? and value.constructor.name is 'Promise' else if value?.constructor.name is 'Promise'
type: 'promise', then: valueToMeta(value.then.bind(value)) type: 'promise', then: valueToMeta(value.then.bind(value))
else if value? and typeof value is 'object' and v8Util.getHiddenValue value, 'atomId' else if value? and typeof value is 'object' and v8Util.getHiddenValue value, 'atomId'
type: 'remote-object', id: v8Util.getHiddenValue value, 'atomId' type: 'remote-object', id: v8Util.getHiddenValue value, 'atomId'
@ -50,6 +49,15 @@ metaToValue = (meta) ->
when 'date' then new Date(meta.value) when 'date' then new Date(meta.value)
when 'exception' when 'exception'
throw new Error("#{meta.message}\n#{meta.stack}") throw new Error("#{meta.message}\n#{meta.stack}")
when 'electronModule'
# require('electron').
ret = {}
for member in meta.members
do (member) ->
Object.defineProperty ret, member,
enumerable: true
get: -> exports.getBuiltin member
ret
else else
if meta.type is 'function' if meta.type is 'function'
# A shadow class to represent the remote function object. # A shadow class to represent the remote function object.
@ -58,7 +66,7 @@ metaToValue = (meta) ->
constructor: -> constructor: ->
if @constructor == RemoteFunction if @constructor == RemoteFunction
# Constructor call. # Constructor call.
obj = ipc.sendSync 'ATOM_BROWSER_CONSTRUCTOR', meta.id, wrapArgs(arguments) obj = ipcRenderer.sendSync 'ATOM_BROWSER_CONSTRUCTOR', meta.id, wrapArgs(arguments)
# Returning object in constructor will replace constructed object # Returning object in constructor will replace constructed object
# with the returned object. # with the returned object.
@ -66,7 +74,7 @@ metaToValue = (meta) ->
return metaToValue obj return metaToValue obj
else else
# Function call. # Function call.
ret = ipc.sendSync 'ATOM_BROWSER_FUNCTION_CALL', meta.id, wrapArgs(arguments) ret = ipcRenderer.sendSync 'ATOM_BROWSER_FUNCTION_CALL', meta.id, wrapArgs(arguments)
return metaToValue ret return metaToValue ret
else else
ret = v8Util.createObjectWithName meta.name ret = v8Util.createObjectWithName meta.name
@ -80,11 +88,11 @@ metaToValue = (meta) ->
constructor: -> constructor: ->
if @constructor is RemoteMemberFunction if @constructor is RemoteMemberFunction
# Constructor call. # Constructor call.
obj = ipc.sendSync 'ATOM_BROWSER_MEMBER_CONSTRUCTOR', meta.id, member.name, wrapArgs(arguments) obj = ipcRenderer.sendSync 'ATOM_BROWSER_MEMBER_CONSTRUCTOR', meta.id, member.name, wrapArgs(arguments)
return metaToValue obj return metaToValue obj
else else
# Call member function. # Call member function.
ret = ipc.sendSync 'ATOM_BROWSER_MEMBER_CALL', meta.id, member.name, wrapArgs(arguments) ret = ipcRenderer.sendSync 'ATOM_BROWSER_MEMBER_CALL', meta.id, member.name, wrapArgs(arguments)
return metaToValue ret return metaToValue ret
else else
Object.defineProperty ret, member.name, Object.defineProperty ret, member.name,
@ -92,18 +100,18 @@ metaToValue = (meta) ->
configurable: false, configurable: false,
set: (value) -> set: (value) ->
# Set member data. # Set member data.
ipc.sendSync 'ATOM_BROWSER_MEMBER_SET', meta.id, member.name, value ipcRenderer.sendSync 'ATOM_BROWSER_MEMBER_SET', meta.id, member.name, value
value value
get: -> get: ->
# Get member data. # Get member data.
ret = ipc.sendSync 'ATOM_BROWSER_MEMBER_GET', meta.id, member.name ret = ipcRenderer.sendSync 'ATOM_BROWSER_MEMBER_GET', meta.id, member.name
metaToValue ret metaToValue ret
# 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, -> v8Util.setDestructor ret, ->
ipc.send 'ATOM_BROWSER_DEREFERENCE', meta.id 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
@ -119,11 +127,11 @@ metaToPlainObject = (meta) ->
obj obj
# Browser calls a callback in renderer. # Browser calls a callback in renderer.
ipc.on 'ATOM_RENDERER_CALLBACK', (event, id, args) -> ipcRenderer.on 'ATOM_RENDERER_CALLBACK', (event, id, args) ->
callbacksRegistry.apply id, metaToValue(args) callbacksRegistry.apply id, metaToValue(args)
# A callback in browser is released. # A callback in browser is released.
ipc.on 'ATOM_RENDERER_RELEASE_CALLBACK', (event, id) -> ipcRenderer.on 'ATOM_RENDERER_RELEASE_CALLBACK', (event, id) ->
callbacksRegistry.remove id callbacksRegistry.remove id
# Get remote module. # Get remote module.
@ -133,26 +141,34 @@ moduleCache = {}
exports.require = (module) -> exports.require = (module) ->
return moduleCache[module] if moduleCache[module]? return moduleCache[module] if moduleCache[module]?
meta = ipc.sendSync 'ATOM_BROWSER_REQUIRE', module meta = ipcRenderer.sendSync 'ATOM_BROWSER_REQUIRE', module
moduleCache[module] = metaToValue meta moduleCache[module] = metaToValue meta
# Alias to remote.require('electron').xxx.
builtinCache = {}
exports.getBuiltin = (module) ->
return builtinCache[module] if builtinCache[module]?
meta = ipcRenderer.sendSync 'ATOM_BROWSER_GET_BUILTIN', module
builtinCache[module] = metaToValue meta
# Get current BrowserWindow object. # Get current BrowserWindow object.
windowCache = null windowCache = null
exports.getCurrentWindow = -> exports.getCurrentWindow = ->
return windowCache if windowCache? return windowCache if windowCache?
meta = ipc.sendSync 'ATOM_BROWSER_CURRENT_WINDOW' meta = ipcRenderer.sendSync 'ATOM_BROWSER_CURRENT_WINDOW'
windowCache = metaToValue meta windowCache = metaToValue meta
# Get current WebContents object. # Get current WebContents object.
webContentsCache = null webContentsCache = null
exports.getCurrentWebContents = -> exports.getCurrentWebContents = ->
return webContentsCache if webContentsCache? return webContentsCache if webContentsCache?
meta = ipc.sendSync 'ATOM_BROWSER_CURRENT_WEB_CONTENTS' meta = ipcRenderer.sendSync 'ATOM_BROWSER_CURRENT_WEB_CONTENTS'
webContentsCache = metaToValue meta webContentsCache = metaToValue meta
# Get a global object in browser. # Get a global object in browser.
exports.getGlobal = (name) -> exports.getGlobal = (name) ->
meta = ipc.sendSync 'ATOM_BROWSER_GLOBAL', name meta = ipcRenderer.sendSync 'ATOM_BROWSER_GLOBAL', name
metaToValue meta metaToValue meta
# Get the process object in browser. # Get the process object in browser.
@ -169,5 +185,5 @@ exports.createFunctionWithReturnValue = (returnValue) ->
# Get the guest WebContents from guestInstanceId. # Get the guest WebContents from guestInstanceId.
exports.getGuestWebContents = (guestInstanceId) -> exports.getGuestWebContents = (guestInstanceId) ->
meta = ipc.sendSync 'ATOM_BROWSER_GUEST_WEB_CONTENTS', guestInstanceId meta = ipcRenderer.sendSync 'ATOM_BROWSER_GUEST_WEB_CONTENTS', guestInstanceId
metaToValue meta metaToValue meta

View file

@ -1 +1 @@
module.exports = require('remote').require('screen') module.exports = require('electron').remote.require('electron').screen

View file

@ -13,10 +13,12 @@ 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')
# Add renderer/api/lib to require's search paths, which contains javascript part
# of Atom's built-in libraries.
globalPaths = Module.globalPaths globalPaths = Module.globalPaths
globalPaths.push path.resolve(__dirname, '..', 'api', 'lib') unless process.env.ELECTRON_HIDE_INTERNAL_MODULES
globalPaths.push path.resolve(__dirname, '..', 'api', 'lib')
# Expose public APIs.
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'

View file

@ -32,8 +32,8 @@ convertToMenuTemplate = (items) ->
template template
createMenu = (x, y, items, document) -> createMenu = (x, y, items, document) ->
remote = require 'remote' {remote} = require 'electron'
Menu = remote.require 'menu' {Menu} = remote.require 'electron'
menu = Menu.buildFromTemplate convertToMenuTemplate(items) menu = Menu.buildFromTemplate convertToMenuTemplate(items)
# The menu is expected to show asynchronously. # The menu is expected to show asynchronously.
@ -42,8 +42,8 @@ createMenu = (x, y, items, document) ->
DevToolsAPI.contextMenuCleared() DevToolsAPI.contextMenuCleared()
showFileChooserDialog = (callback) -> showFileChooserDialog = (callback) ->
remote = require 'remote' {remote} = require 'electron'
dialog = remote.require 'dialog' {dialog} = remote.require 'electron'
files = dialog.showOpenDialog {} files = dialog.showOpenDialog {}
callback pathToHtml5FileObject files[0] if files? callback pathToHtml5FileObject files[0] if files?

View file

@ -1,5 +1,4 @@
ipc = require 'ipc-renderer' {ipcRenderer, remote} = require 'electron'
remote = require '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'
@ -11,24 +10,24 @@ resolveUrl = (url) ->
class BrowserWindowProxy class BrowserWindowProxy
constructor: (@guestId) -> constructor: (@guestId) ->
@closed = false @closed = false
ipc.on 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_CLOSED', (event, guestId) => ipcRenderer.on 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_CLOSED', (event, guestId) =>
if guestId is @guestId if guestId is @guestId
@closed = true @closed = true
close: -> close: ->
ipc.send 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_CLOSE', @guestId ipcRenderer.send 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_CLOSE', @guestId
focus: -> focus: ->
ipc.send 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_METHOD', @guestId, 'focus' ipcRenderer.send 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_METHOD', @guestId, 'focus'
blur: -> blur: ->
ipc.send 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_METHOD', @guestId, 'blur' ipcRenderer.send 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_METHOD', @guestId, 'blur'
postMessage: (message, targetOrigin='*') -> postMessage: (message, targetOrigin='*') ->
ipc.send 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_POSTMESSAGE', @guestId, message, targetOrigin ipcRenderer.send 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_POSTMESSAGE', @guestId, message, targetOrigin
eval: (args...) -> eval: (args...) ->
ipc.send 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WEB_CONTENTS_METHOD', @guestId, 'executeJavaScript', args... ipcRenderer.send 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WEB_CONTENTS_METHOD', @guestId, 'executeJavaScript', args...
unless process.guestInstanceId? unless process.guestInstanceId?
# Override default window.close. # Override default window.close.
@ -60,7 +59,7 @@ window.open = (url, frameName='', features='') ->
(options[name] = parseInt(options[name], 10) if options[name]?) for name in ints (options[name] = parseInt(options[name], 10) if options[name]?) for name in ints
guestId = ipc.sendSync 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPEN', url, frameName, options guestId = ipcRenderer.sendSync 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPEN', url, frameName, options
if guestId if guestId
new BrowserWindowProxy(guestId) new BrowserWindowProxy(guestId)
else else
@ -87,13 +86,13 @@ window.prompt = ->
throw new Error('prompt() is and will not be supported.') throw new Error('prompt() is and will not be supported.')
# Implement window.postMessage if current window is a guest window. # Implement window.postMessage if current window is a guest window.
guestId = ipc.sendSync 'ATOM_SHELL_GUEST_WINDOW_MANAGER_GET_GUEST_ID' guestId = ipcRenderer.sendSync 'ATOM_SHELL_GUEST_WINDOW_MANAGER_GET_GUEST_ID'
if guestId? if guestId?
window.opener = window.opener =
postMessage: (message, targetOrigin='*') -> postMessage: (message, targetOrigin='*') ->
ipc.send 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPENER_POSTMESSAGE', guestId, message, targetOrigin, location.origin ipcRenderer.send 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPENER_POSTMESSAGE', guestId, message, targetOrigin, location.origin
ipc.on 'ATOM_SHELL_GUEST_WINDOW_POSTMESSAGE', (event, guestId, message, sourceOrigin) -> ipcRenderer.on 'ATOM_SHELL_GUEST_WINDOW_POSTMESSAGE', (event, guestId, 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'
@ -105,10 +104,10 @@ ipc.on 'ATOM_SHELL_GUEST_WINDOW_POSTMESSAGE', (event, guestId, message, sourceOr
# Forward history operations to browser. # Forward history operations to browser.
sendHistoryOperation = (args...) -> sendHistoryOperation = (args...) ->
ipc.send 'ATOM_SHELL_NAVIGATION_CONTROLLER', args... ipcRenderer.send 'ATOM_SHELL_NAVIGATION_CONTROLLER', args...
getHistoryOperation = (args...) -> getHistoryOperation = (args...) ->
ipc.sendSync 'ATOM_SHELL_SYNC_NAVIGATION_CONTROLLER', args... ipcRenderer.sendSync 'ATOM_SHELL_SYNC_NAVIGATION_CONTROLLER', args...
window.history.back = -> sendHistoryOperation 'goBack' window.history.back = -> sendHistoryOperation 'goBack'
window.history.forward = -> sendHistoryOperation 'goForward' window.history.forward = -> sendHistoryOperation 'goForward'

View file

@ -1,5 +1,4 @@
ipc = require 'ipc-renderer' {ipcRenderer, webFrame} = require 'electron'
webFrame = require 'web-frame'
requestId = 0 requestId = 0
@ -37,40 +36,40 @@ dispatchEvent = (webView, event, args...) ->
module.exports = module.exports =
registerEvents: (webView, viewInstanceId) -> registerEvents: (webView, viewInstanceId) ->
ipc.on "ATOM_SHELL_GUEST_VIEW_INTERNAL_DISPATCH_EVENT-#{viewInstanceId}", (event, domEvent, args...) -> ipcRenderer.on "ATOM_SHELL_GUEST_VIEW_INTERNAL_DISPATCH_EVENT-#{viewInstanceId}", (event, domEvent, args...) ->
dispatchEvent webView, domEvent, args... dispatchEvent webView, domEvent, args...
ipc.on "ATOM_SHELL_GUEST_VIEW_INTERNAL_IPC_MESSAGE-#{viewInstanceId}", (event, channel, args...) -> ipcRenderer.on "ATOM_SHELL_GUEST_VIEW_INTERNAL_IPC_MESSAGE-#{viewInstanceId}", (event, channel, args...) ->
domEvent = new Event('ipc-message') domEvent = new Event('ipc-message')
domEvent.channel = channel domEvent.channel = channel
domEvent.args = [args...] domEvent.args = [args...]
webView.dispatchEvent domEvent webView.dispatchEvent domEvent
ipc.on "ATOM_SHELL_GUEST_VIEW_INTERNAL_SIZE_CHANGED-#{viewInstanceId}", (event, args...) -> ipcRenderer.on "ATOM_SHELL_GUEST_VIEW_INTERNAL_SIZE_CHANGED-#{viewInstanceId}", (event, args...) ->
domEvent = new Event('size-changed') domEvent = new Event('size-changed')
for f, i in ['oldWidth', 'oldHeight', 'newWidth', 'newHeight'] for f, i in ['oldWidth', 'oldHeight', 'newWidth', 'newHeight']
domEvent[f] = args[i] domEvent[f] = args[i]
webView.onSizeChanged domEvent webView.onSizeChanged domEvent
deregisterEvents: (viewInstanceId) -> deregisterEvents: (viewInstanceId) ->
ipc.removeAllListeners "ATOM_SHELL_GUEST_VIEW_INTERNAL_DISPATCH_EVENT-#{viewInstanceId}" ipcRenderer.removeAllListeners "ATOM_SHELL_GUEST_VIEW_INTERNAL_DISPATCH_EVENT-#{viewInstanceId}"
ipc.removeAllListeners "ATOM_SHELL_GUEST_VIEW_INTERNAL_IPC_MESSAGE-#{viewInstanceId}" ipcRenderer.removeAllListeners "ATOM_SHELL_GUEST_VIEW_INTERNAL_IPC_MESSAGE-#{viewInstanceId}"
ipc.removeAllListeners "ATOM_SHELL_GUEST_VIEW_INTERNAL_SIZE_CHANGED-#{viewInstanceId}" ipcRenderer.removeAllListeners "ATOM_SHELL_GUEST_VIEW_INTERNAL_SIZE_CHANGED-#{viewInstanceId}"
createGuest: (params, callback) -> createGuest: (params, callback) ->
requestId++ requestId++
ipc.send 'ATOM_SHELL_GUEST_VIEW_MANAGER_CREATE_GUEST', params, requestId ipcRenderer.send 'ATOM_SHELL_GUEST_VIEW_MANAGER_CREATE_GUEST', params, requestId
ipc.once "ATOM_SHELL_RESPONSE_#{requestId}", callback ipcRenderer.once "ATOM_SHELL_RESPONSE_#{requestId}", callback
attachGuest: (elementInstanceId, guestInstanceId, params) -> attachGuest: (elementInstanceId, guestInstanceId, params) ->
ipc.send 'ATOM_SHELL_GUEST_VIEW_MANAGER_ATTACH_GUEST', elementInstanceId, guestInstanceId, params ipcRenderer.send 'ATOM_SHELL_GUEST_VIEW_MANAGER_ATTACH_GUEST', elementInstanceId, guestInstanceId, params
webFrame.attachGuest elementInstanceId webFrame.attachGuest elementInstanceId
destroyGuest: (guestInstanceId) -> destroyGuest: (guestInstanceId) ->
ipc.send 'ATOM_SHELL_GUEST_VIEW_MANAGER_DESTROY_GUEST', guestInstanceId ipcRenderer.send 'ATOM_SHELL_GUEST_VIEW_MANAGER_DESTROY_GUEST', guestInstanceId
setSize: (guestInstanceId, params) -> setSize: (guestInstanceId, params) ->
ipc.send 'ATOM_SHELL_GUEST_VIEW_MANAGER_SET_SIZE', guestInstanceId, params ipcRenderer.send 'ATOM_SHELL_GUEST_VIEW_MANAGER_SET_SIZE', guestInstanceId, params
setAllowTransparency: (guestInstanceId, allowtransparency) -> setAllowTransparency: (guestInstanceId, allowtransparency) ->
ipc.send 'ATOM_SHELL_GUEST_VIEW_MANAGER_SET_ALLOW_TRANSPARENCY', guestInstanceId, allowtransparency ipcRenderer.send 'ATOM_SHELL_GUEST_VIEW_MANAGER_SET_ALLOW_TRANSPARENCY', guestInstanceId, allowtransparency

View file

@ -1,7 +1,8 @@
WebViewImpl = require './web-view' WebViewImpl = require './web-view'
guestViewInternal = require './guest-view-internal' guestViewInternal = require './guest-view-internal'
webViewConstants = require './web-view-constants' webViewConstants = require './web-view-constants'
remote = require 'remote'
{remote} = require 'electron'
# Helper function to resolve url set in attribute. # Helper function to resolve url set in attribute.
a = document.createElement 'a' a = document.createElement 'a'

View file

@ -1,8 +1,8 @@
{webFrame, remote} = require 'electron'
v8Util = process.atomBinding 'v8_util' v8Util = process.atomBinding 'v8_util'
guestViewInternal = require './guest-view-internal' guestViewInternal = require './guest-view-internal'
webViewConstants = require './web-view-constants' webViewConstants = require './web-view-constants'
webFrame = require 'web-frame'
remote = require 'remote'
# ID generator. # ID generator.
nextId = 0 nextId = 0

View file

@ -31,32 +31,32 @@
### Modules for the Main Process: ### Modules for the Main Process:
* [app](api/app.md) * [app](api/app.md)
* [auto-updater](api/auto-updater.md) * [autoUpdater](api/auto-updater.md)
* [browser-window](api/browser-window.md) * [BrowserWindow](api/browser-window.md)
* [content-tracing](api/content-tracing.md) * [contentTracing](api/content-tracing.md)
* [dialog](api/dialog.md) * [dialog](api/dialog.md)
* [global-shortcut](api/global-shortcut.md) * [globalShortcut](api/global-shortcut.md)
* [ipc-main](api/ipc-main.md) * [ipcMain](api/ipc-main.md)
* [menu](api/menu.md) * [Menu](api/menu.md)
* [menu-item](api/menu-item.md) * [MenuItem](api/menu-item.md)
* [power-monitor](api/power-monitor.md) * [powerMonitor](api/power-monitor.md)
* [power-save-blocker](api/power-save-blocker.md) * [powerSaveBlocker](api/power-save-blocker.md)
* [protocol](api/protocol.md) * [protocol](api/protocol.md)
* [session](api/session.md) * [session](api/session.md)
* [web-contents](api/web-contents.md) * [webContents](api/web-contents.md)
* [tray](api/tray.md) * [Tray](api/tray.md)
### Modules for the Renderer Process (Web Page): ### Modules for the Renderer Process (Web Page):
* [ipc-renderer](api/ipc-renderer.md) * [ipcRenderer](api/ipc-renderer.md)
* [remote](api/remote.md) * [remote](api/remote.md)
* [web-frame](api/web-frame.md) * [webFrame](api/web-frame.md)
### Modules for Both Processes: ### Modules for Both Processes:
* [clipboard](api/clipboard.md) * [clipboard](api/clipboard.md)
* [crash-reporter](api/crash-reporter.md) * [crashReporter](api/crash-reporter.md)
* [native-image](api/native-image.md) * [nativeImage](api/native-image.md)
* [screen](api/screen.md) * [screen](api/screen.md)
* [shell](api/shell.md) * [shell](api/shell.md)

View file

@ -6,7 +6,7 @@ The following example shows how to quit the application when the last window is
closed: closed:
```javascript ```javascript
var app = require('app'); const app = require('electron').app;
app.on('window-all-closed', function() { app.on('window-all-closed', function() {
app.quit(); app.quit();
}); });

View file

@ -4,7 +4,7 @@ The `BrowserWindow` class gives you the ability to create a browser window. For
example: example:
```javascript ```javascript
var BrowserWindow = require('browser-window'); const BrowserWindow = require('electron').BrowserWindow;
var win = new BrowserWindow({ width: 800, height: 600, show: false }); var win = new BrowserWindow({ width: 800, height: 600, show: false });
win.on('closed', function() { win.on('closed', function() {
@ -291,11 +291,8 @@ Remove the DevTools extension whose name is `name`.
Objects created with `new BrowserWindow` have the following properties: Objects created with `new BrowserWindow` have the following properties:
```javascript ```javascript
var BrowserWindow = require('browser-window');
// In this example `win` is our instance // In this example `win` is our instance
var win = new BrowserWindow({ width: 800, height: 600 }); var win = new BrowserWindow({ width: 800, height: 600 });
``` ```
### `win.webContents` ### `win.webContents`
@ -316,14 +313,6 @@ Objects created with `new BrowserWindow` have the following instance methods:
**Note:** Some methods are only available on specific operating systems and are labeled as such. **Note:** Some methods are only available on specific operating systems and are labeled as such.
```javascript
var BrowserWindow = require('browser-window');
// In this example `win` is our instance
var win = new BrowserWindow({ width: 800, height: 600 });
```
### `win.destroy()` ### `win.destroy()`
Force closing the window, the `unload` and `beforeunload` event won't be emitted Force closing the window, the `unload` and `beforeunload` event won't be emitted

View file

@ -6,7 +6,7 @@ them in your app's main script before the [ready][ready] event of [app][app]
module is emitted: module is emitted:
```javascript ```javascript
var app = require('app'); const app = require('electron').app;
app.commandLine.appendSwitch('remote-debugging-port', '8315'); app.commandLine.appendSwitch('remote-debugging-port', '8315');
app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1'); app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1');

View file

@ -4,7 +4,7 @@ The `clipboard` module provides methods to perform copy and paste operations.
The following example shows how to write a string to the clipboard: The following example shows how to write a string to the clipboard:
```javascript ```javascript
var clipboard = require('clipboard'); const clipboard = require('electron').clipboard;
clipboard.writeText('Example String'); clipboard.writeText('Example String');
``` ```
@ -12,7 +12,6 @@ On X Window systems, there is also a selection clipboard. To manipulate it
you need to pass `selection` to each method: you need to pass `selection` to each method:
```javascript ```javascript
var clipboard = require('clipboard');
clipboard.writeText('Example String', 'selection'); clipboard.writeText('Example String', 'selection');
console.log(clipboard.readText('selection')); console.log(clipboard.readText('selection'));
``` ```
@ -82,7 +81,6 @@ Returns an array of supported formats for the clipboard `type`.
Returns whether the clipboard supports the format of specified `data`. Returns whether the clipboard supports the format of specified `data`.
```javascript ```javascript
var clipboard = require('clipboard');
console.log(clipboard.has('<p>selection</p>')); console.log(clipboard.has('<p>selection</p>'));
``` ```
@ -102,7 +100,6 @@ Reads `data` from the clipboard.
* `type` String (optional) * `type` String (optional)
```javascript ```javascript
var clipboard = require('clipboard');
clipboard.write({text: 'test', html: "<b>test</b>"}); clipboard.write({text: 'test', html: "<b>test</b>"});
``` ```
Writes `data` to the clipboard. Writes `data` to the clipboard.

View file

@ -6,7 +6,7 @@ so you need to open `chrome://tracing/` in a Chrome browser and load the
generated file to view the result. generated file to view the result.
```javascript ```javascript
var contentTracing = require('content-tracing'); const contentTracing = require('electron').contentTracing;
contentTracing.startRecording('*', contentTracing.DEFAULT_OPTIONS, function() { contentTracing.startRecording('*', contentTracing.DEFAULT_OPTIONS, function() {
console.log('Tracing started'); console.log('Tracing started');

View file

@ -6,7 +6,7 @@ The following is an example of automatically submitting a crash report to a
remote server: remote server:
```javascript ```javascript
var crashReporter = require('crash-reporter'); const crashReporter = require('electron').crashReporter;
crashReporter.start({ crashReporter.start({
productName: 'YourName', productName: 'YourName',

View file

@ -8,7 +8,7 @@ An example of showing a dialog to select multiple files and directories:
```javascript ```javascript
var win = ...; // BrowserWindow in which to show the dialog var win = ...; // BrowserWindow in which to show the dialog
var dialog = require('dialog'); const dialog = require('electron').dialog;
console.log(dialog.showOpenDialog({ properties: [ 'openFile', 'openDirectory', 'multiSelections' ]})); console.log(dialog.showOpenDialog({ properties: [ 'openFile', 'openDirectory', 'multiSelections' ]}));
``` ```

View file

@ -9,7 +9,7 @@ To create a frameless window, you need to set `frame` to `false` in
```javascript ```javascript
var BrowserWindow = require('browser-window'); const BrowserWindow = require('electron').BrowserWindow;
var win = new BrowserWindow({ width: 800, height: 600, frame: false }); var win = new BrowserWindow({ width: 800, height: 600, frame: false });
``` ```
@ -23,8 +23,7 @@ the window controls ("traffic lights") for standard window actions.
You can do so by specifying the new `title-bar-style` option: You can do so by specifying the new `title-bar-style` option:
```javascript ```javascript
var BrowserWindow = require('browser-window'); var win = new BrowserWindow({ 'title-bar-style': 'hidden' });
var win = new BrowserWindow({ width: 800, height: 600, 'title-bar-style': 'hidden' });
``` ```
## Transparent window ## Transparent window

View file

@ -9,8 +9,9 @@ not have the keyboard focus. You should not use this module until the `ready`
event of the app module is emitted. event of the app module is emitted.
```javascript ```javascript
var app = require('app'); const electron = require('electron');
var globalShortcut = require('global-shortcut'); const app = electron.app;
const globalShortcut = electron.globalShortcut;
app.on('ready', function() { app.on('ready', function() {
// Register a 'ctrl+x' shortcut listener. // Register a 'ctrl+x' shortcut listener.

View file

@ -19,7 +19,7 @@ processes:
```javascript ```javascript
// In main process. // In main process.
var ipcMain = require('ipc-main'); const ipcMain = require('electron').ipcMain;
ipcMain.on('asynchronous-message', function(event, arg) { ipcMain.on('asynchronous-message', function(event, arg) {
console.log(arg); // prints "ping" console.log(arg); // prints "ping"
event.sender.send('asynchronous-reply', 'pong'); event.sender.send('asynchronous-reply', 'pong');
@ -33,7 +33,7 @@ ipcMain.on('synchronous-message', function(event, arg) {
```javascript ```javascript
// In renderer process (web page). // In renderer process (web page).
var ipcRenderer = require('ipc-renderer'); const ipcRenderer = require('electron').ipcRenderer;
console.log(ipcRenderer.sendSync('synchronous-message', 'ping')); // prints "pong" console.log(ipcRenderer.sendSync('synchronous-message', 'ping')); // prints "pong"
ipcRenderer.on('asynchronous-reply', function(event, arg) { ipcRenderer.on('asynchronous-reply', function(event, arg) {

View file

@ -16,9 +16,9 @@ the user right clicks the page:
```html ```html
<!-- index.html --> <!-- index.html -->
<script> <script>
var remote = require('remote'); const remote = require('electron').remote;
var Menu = remote.require('menu'); const Menu = remote.require('electron').Menu;
var MenuItem = remote.require('menu-item'); const MenuItem = remote.require('electron').MenuItem;
var menu = new Menu(); var menu = new Menu();
menu.append(new MenuItem({ label: 'MenuItem1', click: function() { console.log('item 1 clicked'); } })); menu.append(new MenuItem({ label: 'MenuItem1', click: function() { console.log('item 1 clicked'); } }));
@ -136,14 +136,14 @@ var template = [
submenu: [ submenu: [
{ {
label: 'Learn More', label: 'Learn More',
click: function() { require('shell').openExternal('http://electron.atom.io') } click: function() { require('electron').shell.openExternal('http://electron.atom.io') }
}, },
] ]
}, },
]; ];
if (process.platform == 'darwin') { if (process.platform == 'darwin') {
var name = require('app').getName(); var name = require('electron').app.getName();
template.unshift({ template.unshift({
label: name, label: name,
submenu: [ submenu: [

View file

@ -1,7 +1,7 @@
# NativeImage # nativeImage
In Electron, for the APIs that take images, you can pass either file paths or In Electron, for the APIs that take images, you can pass either file paths or
`NativeImage` instances. An empty image will be used when `null` is passed. `nativeImage` instances. An empty image will be used when `null` is passed.
For example, when creating a tray or setting a window's icon, you can pass an For example, when creating a tray or setting a window's icon, you can pass an
image file path as a `String`: image file path as a `String`:
@ -11,10 +11,9 @@ var appIcon = new Tray('/Users/somebody/images/icon.png');
var window = new BrowserWindow({icon: '/Users/somebody/images/window.png'}); var window = new BrowserWindow({icon: '/Users/somebody/images/window.png'});
``` ```
Or read the image from the clipboard which returns a `NativeImage`: Or read the image from the clipboard which returns a `nativeImage`:
```javascript ```javascript
var clipboard = require('clipboard');
var image = clipboard.readImage(); var image = clipboard.readImage();
var appIcon = new Tray(image); var appIcon = new Tray(image);
``` ```
@ -84,40 +83,40 @@ To mark an image as a template image, its filename should end with the word
## Methods ## Methods
The `NativeImage` class has the following methods: The `nativeImage` class has the following methods:
### `NativeImage.createEmpty()` ### `nativeImage.createEmpty()`
Creates an empty `NativeImage` instance. Creates an empty `nativeImage` instance.
### `NativeImage.createFromPath(path)` ### `nativeImage.createFromPath(path)`
* `path` String * `path` String
Creates a new `NativeImage` instance from a file located at `path`. Creates a new `nativeImage` instance from a file located at `path`.
### `NativeImage.createFromBuffer(buffer[, scaleFactor])` ### `nativeImage.createFromBuffer(buffer[, scaleFactor])`
* `buffer` [Buffer][buffer] * `buffer` [Buffer][buffer]
* `scaleFactor` Double (optional) * `scaleFactor` Double (optional)
Creates a new `NativeImage` instance from `buffer`. The default `scaleFactor` is Creates a new `nativeImage` instance from `buffer`. The default `scaleFactor` is
1.0. 1.0.
### `NativeImage.createFromDataUrl(dataUrl)` ### `nativeImage.createFromDataUrl(dataUrl)`
* `dataUrl` String * `dataUrl` String
Creates a new `NativeImage` instance from `dataUrl`. Creates a new `nativeImage` instance from `dataUrl`.
## Instance Methods ## Instance Methods
The following methods are available on instances of `nativeImage`: The following methods are available on instances of `nativeImage`:
```javascript ```javascript
var NativeImage = require('native-image'); const nativeImage = require('electron').nativeImage;
var image = NativeImage.createFromPath('/Users/somebody/images/icon.png'); var image = nativeImage.createFromPath('/Users/somebody/images/icon.png');
``` ```
### `image.toPng()` ### `image.toPng()`

View file

@ -1,4 +1,4 @@
# power-monitor # powerMonitor
The `power-monitor` module is used to monitor power state changes. You can The `power-monitor` module is used to monitor power state changes. You can
only use it in the main process. You should not use this module until the `ready` only use it in the main process. You should not use this module until the `ready`
@ -7,10 +7,8 @@ event of the `app` module is emitted.
For example: For example:
```javascript ```javascript
var app = require('app');
app.on('ready', function() { app.on('ready', function() {
require('power-monitor').on('suspend', function() { require('electron').powerMonitor.on('suspend', function() {
console.log('The system is going to sleep'); console.log('The system is going to sleep');
}); });
}); });

View file

@ -1,13 +1,13 @@
# powerSaveBlocker # powerSaveBlocker
The `power-save-blocker` module is used to block the system from entering The `powerSaveBlocker` module is used to block the system from entering
low-power (sleep) mode and thus allowing the app to keep the system and screen low-power (sleep) mode and thus allowing the app to keep the system and screen
active. active.
For example: For example:
```javascript ```javascript
var powerSaveBlocker = require('power-save-blocker'); const powerSaveBlocker = require('electron').powerSaveBlocker;
var id = powerSaveBlocker.start('prevent-display-sleep'); var id = powerSaveBlocker.start('prevent-display-sleep');
console.log(powerSaveBlocker.isStarted(id)); console.log(powerSaveBlocker.isStarted(id));

View file

@ -7,11 +7,12 @@ An example of implementing a protocol that has the same effect as the
`file://` protocol: `file://` protocol:
```javascript ```javascript
var app = require('app'); const electron = require('electron');
var path = require('path'); const app = electron.app;
const path = require('path');
app.on('ready', function() { app.on('ready', function() {
var protocol = require('protocol'); var protocol = electron.protocol;
protocol.registerFileProtocol('atom', function(request, callback) { protocol.registerFileProtocol('atom', function(request, callback) {
var url = request.url.substr(7); var url = request.url.substr(7);
callback({path: path.normalize(__dirname + '/' + url)}); callback({path: path.normalize(__dirname + '/' + url)});

View file

@ -3,13 +3,17 @@
The `remote` module provides a simple way to do inter-process communication The `remote` module provides a simple way to do inter-process communication
(IPC) between the renderer process (web page) and the main process. (IPC) between the renderer process (web page) and the main process.
In Electron, GUI-related modules (such as `dialog`, `menu` etc.) are only available in the main process, not in the renderer process. In order to use them from the renderer process, the `ipc` module is necessary to send inter-process messages to the main process. With the `remote` module, you can invoke methods of the main process object without explicitly sending inter-process messages, similar to Java's [RMI](http://en.wikipedia.org/wiki/Java_remote_method_invocation). In Electron, GUI-related modules (such as `dialog`, `menu` etc.) are only
available in the main process, not in the renderer process. In order to use them
An example of creating a browser window from a renderer process: from the renderer process, the `ipc` module is necessary to send inter-process
messages to the main process. With the `remote` module, you can invoke methods
of the main process object without explicitly sending inter-process messages,
similar to Java's [RMI][rmi]. An example of creating a browser window from a
renderer process:
```javascript ```javascript
var remote = require('remote'); const remote = require('electron').remote;
var BrowserWindow = remote.require('browser-window'); const BrowserWindow = remote.require('electron').BrowserWindow;
var win = new BrowserWindow({ width: 800, height: 600 }); var win = new BrowserWindow({ width: 800, height: 600 });
win.loadUrl('https://github.com'); win.loadUrl('https://github.com');
@ -96,8 +100,6 @@ For example, the following code seems innocent at first glance. It installs a
callback for the `close` event on a remote object: callback for the `close` event on a remote object:
```javascript ```javascript
var remote = require('remote');
remote.getCurrentWindow().on('close', function() { remote.getCurrentWindow().on('close', function() {
// blabla... // blabla...
}); });
@ -146,3 +148,5 @@ process.
Returns the `process` object in the main process. This is the same as Returns the `process` object in the main process. This is the same as
`remote.getGlobal('process')` but is cached. `remote.getGlobal('process')` but is cached.
[rmi]: http://en.wikipedia.org/wiki/Java_remote_method_invocation

View file

@ -6,20 +6,20 @@ position, etc. You should not use this module until the `ready` event of the
`screen` is an [EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter). `screen` is an [EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter).
**Note:** In the renderer / DevTools, `window.screen` is a reserved **Note:** In the renderer / DevTools, `window.screen` is a reserved DOM
DOM property, so writing `var screen = require('screen')` will not work. In our property, so writing `var screen = require('electron').screen` will not work.
examples below, we use `electronScreen` as the variable name instead. In our examples below, we use `electronScreen` as the variable name instead.
An example of creating a window that fills the whole screen: An example of creating a window that fills the whole screen:
```javascript ```javascript
var app = require('app'); const electron = require('electron');
var BrowserWindow = require('browser-window'); const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
var mainWindow; var mainWindow;
app.on('ready', function() { app.on('ready', function() {
var electronScreen = require('screen'); var electronScreen = electron.screen;
var size = electronScreen.getPrimaryDisplay().workAreaSize; var size = electronScreen.getPrimaryDisplay().workAreaSize;
mainWindow = new BrowserWindow({ width: size.width, height: size.height }); mainWindow = new BrowserWindow({ width: size.width, height: size.height });
}); });
@ -28,13 +28,14 @@ app.on('ready', function() {
Another example of creating a window in the external display: Another example of creating a window in the external display:
```javascript ```javascript
var app = require('app'); const electron = require('electron');
var BrowserWindow = require('browser-window'); const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
var mainWindow; var mainWindow;
app.on('ready', function() { app.on('ready', function() {
var electronScreen = require('screen'); var electronScreen = electron.screen;
var displays = electronScreen.getAllDisplays(); var displays = electronScreen.getAllDisplays();
var externalDisplay = null; var externalDisplay = null;
for (var i in displays) { for (var i in displays) {

View file

@ -5,7 +5,7 @@ a property of [`BrowserWindow`](browser-window.md). You can access it through an
instance of `BrowserWindow`. For example: instance of `BrowserWindow`. For example:
```javascript ```javascript
var BrowserWindow = require('browser-window'); const BrowserWindow = require('electron').BrowserWindow;
var win = new BrowserWindow({ width: 800, height: 600 }); var win = new BrowserWindow({ width: 800, height: 600 });
win.loadUrl("http://github.com"); win.loadUrl("http://github.com");
@ -43,7 +43,7 @@ The `session` object has the following methods:
The `cookies` gives you ability to query and modify cookies. For example: The `cookies` gives you ability to query and modify cookies. For example:
```javascript ```javascript
var BrowserWindow = require('browser-window'); const BrowserWindow = require('electron').BrowserWindow;
var win = new BrowserWindow({ width: 800, height: 600 }); var win = new BrowserWindow({ width: 800, height: 600 });

View file

@ -5,7 +5,7 @@ The `shell` module provides functions related to desktop integration.
An example of opening a URL in the user's default browser: An example of opening a URL in the user's default browser:
```javascript ```javascript
var shell = require('shell'); const shell = require('electron').shell;
shell.openExternal('https://github.com'); shell.openExternal('https://github.com');
``` ```

View file

@ -9,18 +9,17 @@ desktop applications. Some modules are only available in the main process, some
are only available in the renderer process (web page), and some can be used in are only available in the renderer process (web page), and some can be used in
both processes. both processes.
The basic rule is: if a module is The basic rule is: if a module is [GUI][gui] or low-level system related, then
[GUI](https://en.wikipedia.org/wiki/Graphical_user_interface) or low-level it should be only available in the main process. You need to be familiar with
system related, then it should be only available in the main process. You need the concept of [main process vs. renderer process][mai-process] scripts to be
to be familiar with the concept of able to use those modules.
[main process vs. renderer process](../tutorial/quick-start.md#the-main-process)
scripts to be able to use those modules.
The main process script is just like a normal Node.js script: The main process script is just like a normal Node.js script:
```javascript ```javascript
var app = require('app'); const electron = require('electron');
var BrowserWindow = require('browser-window'); const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
var window = null; var window = null;
@ -30,19 +29,56 @@ app.on('ready', function() {
}); });
``` ```
The renderer process is no different than a normal web page, except for the extra The renderer process is no different than a normal web page, except for the
ability to use node modules: extra ability to use node modules:
```html ```html
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<body> <body>
<script> <script>
var remote = require('remote'); const remote = require('electron').remote;
console.log(remote.require('app').getVersion()); console.log(remote.require('electron').app.getVersion());
</script> </script>
</body> </body>
</html> </html>
``` ```
To run your app, read [Run your app](../tutorial/quick-start.md#run-your-app). To run your app, read [Run your app](../tutorial/quick-start.md#run-your-app).
## Destructuring assignment
If you are using CoffeeScript or Babel, you can also use
[destructuring assignment][desctructuring-assignment] to make it easier to use
built-in modules:
```javascript
const {app, BrowserWindow} = require('electron')
```
However if you are using plain JavaScript, you have to wait until Chrome fully
supports ES6.
## Disable old styles of using built-in modules
Before v0.35.0, all built-in modules have to be used in the form of
`require('module-name')`, though it has [many disadvantages][issue-387], we are
still supporting it for compatibility with old apps.
To disable the old styles completely, you can set the
`ELECTRON_HIDE_INTERNAL_MODULES` environment variable:
```javascript
process.env.ELECTRON_HIDE_INTERNAL_MODULES = 'true'
```
Or call the `hideInternalModules` API:
```javascript
require('electron').hideInternalModules()
```
[gui]: https://en.wikipedia.org/wiki/Graphical_user_interface
[main-process]: ../tutorial/quick-start.md#the-main-process
[desctructuring-assignment]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
[issue-387]: https://github.com/atom/electron/issues/387

View file

@ -4,9 +4,10 @@ A `Tray` represents an icon in an operating system's notification area, it is
usually attached with a context menu. usually attached with a context menu.
```javascript ```javascript
var app = require('app'); const electron = require('electron');
var Menu = require('menu'); const app = electron.app;
var Tray = require('tray'); const Menu = electron.Menu;
const Tray = electron.Tray;
var appIcon = null; var appIcon = null;
app.on('ready', function(){ app.on('ready', function(){

View file

@ -8,7 +8,7 @@ the [`BrowserWindow`](browser-window.md) object. An example of accessing the
`webContents` object: `webContents` object:
```javascript ```javascript
var BrowserWindow = require('browser-window'); const BrowserWindow = require('electron').BrowserWindow;
var win = new BrowserWindow({width: 800, height: 1500}); var win = new BrowserWindow({width: 800, height: 1500});
win.loadUrl("http://github.com"); win.loadUrl("http://github.com");
@ -211,17 +211,15 @@ e.g. the `http://` or `file://`.
### `webContents.getUrl()` ### `webContents.getUrl()`
```javascript Returns URL of the current web page.
var BrowserWindow = require('browser-window');
```javascript
var win = new BrowserWindow({width: 800, height: 600}); var win = new BrowserWindow({width: 800, height: 600});
win.loadUrl("http://github.com"); win.loadUrl("http://github.com");
var currentUrl = win.webContents.getUrl(); var currentUrl = win.webContents.getUrl();
``` ```
Returns URL of the current web page.
### `webContents.getTitle()` ### `webContents.getTitle()`
Returns the title of the current web page. Returns the title of the current web page.
@ -445,8 +443,8 @@ By default, an empty `options` will be regarded as:
``` ```
```javascript ```javascript
var BrowserWindow = require('browser-window'); const BrowserWindow = require('electron').BrowserWindow;
var fs = require('fs'); const fs = require('fs');
var win = new BrowserWindow({width: 800, height: 600}); var win = new BrowserWindow({width: 800, height: 600});
win.loadUrl("http://github.com"); win.loadUrl("http://github.com");
@ -538,7 +536,7 @@ app.on('ready', function() {
<html> <html>
<body> <body>
<script> <script>
require('ipcRenderer').on('ping', function(event, message) { require('electron').ipcRenderer.on('ping', function(event, message) {
console.log(message); // Prints "whoooooooh!" console.log(message); // Prints "whoooooooh!"
}); });
</script> </script>

View file

@ -6,7 +6,7 @@ web page.
An example of zooming current page to 200%. An example of zooming current page to 200%.
```javascript ```javascript
var webFrame = require('web-frame'); var webFrame = require('electron').webFrame;
webFrame.setZoomFactor(2); webFrame.setZoomFactor(2);
``` ```
@ -59,7 +59,7 @@ whether the word passed is correctly spelled.
An example of using [node-spellchecker][spellchecker] as provider: An example of using [node-spellchecker][spellchecker] as provider:
```javascript ```javascript
require('web-frame').setSpellCheckProvider("en-US", true, { webFrame.setSpellCheckProvider("en-US", true, {
spellCheck: function(text) { spellCheck: function(text) {
return !(require('spellchecker').isMisspelled(text)); return !(require('spellchecker').isMisspelled(text));
} }

View file

@ -515,7 +515,7 @@ The following example code opens the new url in system's default browser.
```javascript ```javascript
webview.addEventListener('new-window', function(e) { webview.addEventListener('new-window', function(e) {
require('shell').openExternal(e.url); require('electron').shell.openExternal(e.url);
}); });
``` ```
@ -555,9 +555,9 @@ webview.send('ping');
```javascript ```javascript
// In guest page. // In guest page.
var ipc = require('ipc'); var ipcRenderer = require('electron').ipcRenderer;
ipc.on('ping', function() { ipcRenderer.on('ping', function() {
ipc.sendToHost('pong'); ipcRenderer.sendToHost('pong');
}); });
``` ```

View file

@ -51,14 +51,14 @@ $ asar list /path/to/example.asar
Read a file in the `asar` archive: Read a file in the `asar` archive:
```javascript ```javascript
var fs = require('fs'); const fs = require('fs');
fs.readFileSync('/path/to/example.asar/file.txt'); fs.readFileSync('/path/to/example.asar/file.txt');
``` ```
List all files under the root of the archive: List all files under the root of the archive:
```javascript ```javascript
var fs = require('fs'); const fs = require('fs');
fs.readdirSync('/path/to/example.asar'); fs.readdirSync('/path/to/example.asar');
``` ```
@ -71,7 +71,7 @@ require('/path/to/example.asar/dir/module.js');
You can also display a web page in an `asar` archive with `BrowserWindow`: You can also display a web page in an `asar` archive with `BrowserWindow`:
```javascript ```javascript
var BrowserWindow = require('browser-window'); const BrowserWindow = require('electron').BrowserWindow;
var win = new BrowserWindow({width: 800, height: 600}); var win = new BrowserWindow({width: 800, height: 600});
win.loadUrl('file:///path/to/example.asar/static/index.html'); win.loadUrl('file:///path/to/example.asar/static/index.html');
``` ```

View file

@ -86,7 +86,6 @@ To add a file to recent documents, you can use the
[app.addRecentDocument][addrecentdocument] API: [app.addRecentDocument][addrecentdocument] API:
```javascript ```javascript
var app = require('app');
app.addRecentDocument('/Users/USERNAME/Desktop/work.type'); app.addRecentDocument('/Users/USERNAME/Desktop/work.type');
``` ```
@ -125,8 +124,10 @@ To set your custom dock menu, you can use the `app.dock.setMenu` API, which is
only available on OS X: only available on OS X:
```javascript ```javascript
var app = require('app'); const electron = require('electron');
var Menu = require('menu'); const app = electron.app;
const Menu = electron.Menu;
var dockMenu = Menu.buildFromTemplate([ var dockMenu = Menu.buildFromTemplate([
{ label: 'New Window', click: function() { console.log('New Window'); } }, { label: 'New Window', click: function() { console.log('New Window'); } },
{ label: 'New Window with Settings', submenu: [ { label: 'New Window with Settings', submenu: [
@ -172,7 +173,6 @@ To set user tasks for your application, you can use
[app.setUserTasks][setusertaskstasks] API: [app.setUserTasks][setusertaskstasks] API:
```javascript ```javascript
var app = require('app');
app.setUserTasks([ app.setUserTasks([
{ {
program: process.execPath, program: process.execPath,
@ -220,8 +220,9 @@ You can use [BrowserWindow.setThumbarButtons][setthumbarbuttons] to set
thumbnail toolbar in your application: thumbnail toolbar in your application:
```javascript ```javascript
var BrowserWindow = require('browser-window'); const BrowserWindow = require('electron').BrowserWindow;
var path = require('path'); const path = require('path');
var win = new BrowserWindow({ var win = new BrowserWindow({
width: 800, width: 800,
height: 600 height: 600

View file

@ -24,14 +24,15 @@ Then you can load the extension in Electron by opening DevTools in any window,
and running the following code in the DevTools console: and running the following code in the DevTools console:
```javascript ```javascript
require('remote').require('browser-window').addDevToolsExtension('/some-directory/react-devtools/shells/chrome'); const BrowserWindow = require('electron').remote.require('electron').BrowserWindow;
BrowserWindow.addDevToolsExtension('/some-directory/react-devtools/shells/chrome');
``` ```
To unload the extension, you can call the `BrowserWindow.removeDevToolsExtension` To unload the extension, you can call the `BrowserWindow.removeDevToolsExtension`
API with its name and it will not load the next time you open the DevTools: API with its name and it will not load the next time you open the DevTools:
```javascript ```javascript
require('remote').require('browser-window').removeDevToolsExtension('React Developer Tools'); BrowserWindow.removeDevToolsExtension('React Developer Tools');
``` ```
## Format of DevTools Extension ## Format of DevTools Extension

View file

@ -6,10 +6,11 @@ using standard HTML5 APIs, as shown in the following example.
_main.js_ _main.js_
```javascript ```javascript
var app = require('app'); const electron = require('electron');
var BrowserWindow = require('browser-window'); const app = electron.app;
var onlineStatusWindow; const BrowserWindow = electron.BrowserWindow;
var onlineStatusWindow;
app.on('ready', function() { app.on('ready', function() {
onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false }); onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false });
onlineStatusWindow.loadUrl('file://' + __dirname + '/online-status.html'); onlineStatusWindow.loadUrl('file://' + __dirname + '/online-status.html');
@ -45,11 +46,12 @@ to the main process and handled as needed, as shown in the following example.
_main.js_ _main.js_
```javascript ```javascript
var app = require('app'); const electron = require('electron');
var ipcMain = require('ipc-main'); const app = electron.app;
var BrowserWindow = require('browser-window'); const ipcMain = electron.ipcMain;
var onlineStatusWindow; const BrowserWindow = electron.BrowserWindow;
var onlineStatusWindow;
app.on('ready', function() { app.on('ready', function() {
onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false }); onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false });
onlineStatusWindow.loadUrl('file://' + __dirname + '/online-status.html'); onlineStatusWindow.loadUrl('file://' + __dirname + '/online-status.html');
@ -67,7 +69,7 @@ _online-status.html_
<html> <html>
<body> <body>
<script> <script>
var ipcRenderer = require('ipc-renderer'); const ipcRenderer = require('electron').ipcRenderer;
var updateOnlineStatus = function() { var updateOnlineStatus = function() {
ipcRenderer.send('online-status-changed', navigator.onLine ? 'online' : 'offline'); ipcRenderer.send('online-status-changed', navigator.onLine ? 'online' : 'offline');
}; };

View file

@ -78,11 +78,12 @@ The `main.js` should create windows and handle system events, a typical
example being: example being:
```javascript ```javascript
var app = require('app'); // Module to control application life. const electron = require('electron');
var BrowserWindow = require('browser-window'); // Module to create native browser window. const app = electron.app; // Module to control application life.
const BrowserWindow = electron.BrowserWindow; // Module to create native browser window.
// Report crashes to our server. // Report crashes to our server.
require('crash-reporter').start(); electron.crashReporter.start();
// Keep a global reference of the window object, if you don't, the window will // Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected. // be closed automatically when the JavaScript object is garbage collected.

View file

@ -19,23 +19,6 @@ before the app ready event. Also, add the `plugins` switch of `browser-window`.
For example: For example:
```javascript ```javascript
var app = require('app');
var BrowserWindow = require('browser-window');
// Report crashes to our server.
require('crash-reporter').start();
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the javascript object is GCed.
var mainWindow = null;
// Quit when all windows are closed.
app.on('window-all-closed', function() {
if (process.platform != 'darwin') {
app.quit();
}
});
// Specify flash path. // Specify flash path.
// On Windows, it might be /path/to/pepflashplayer.dll // On Windows, it might be /path/to/pepflashplayer.dll
// On OS X, /path/to/PepperFlashPlayer.plugin // On OS X, /path/to/PepperFlashPlayer.plugin

View file

@ -41,7 +41,7 @@ upstream, except that you have to manually specify how to connect chrome driver
and where to find Electron's binary: and where to find Electron's binary:
```javascript ```javascript
var webdriver = require('selenium-webdriver'); const webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder() var driver = new webdriver.Builder()
// The "9515" is the port opened by chrome driver. // The "9515" is the port opened by chrome driver.
@ -93,7 +93,7 @@ $ npm install webdriverio
### 3. Connect to chrome driver ### 3. Connect to chrome driver
```javascript ```javascript
var webdriverio = require('webdriverio'); const webdriverio = require('webdriverio');
var options = { var options = {
host: "localhost", // Use localhost as chrome driver server host: "localhost", // Use localhost as chrome driver server
port: 9515, // "9515" is the port opened by chrome driver. port: 9515, // "9515" is the port opened by chrome driver.

View file

@ -10,12 +10,13 @@
'coffee_sources': [ 'coffee_sources': [
'atom/browser/api/lib/app.coffee', 'atom/browser/api/lib/app.coffee',
'atom/browser/api/lib/auto-updater.coffee', 'atom/browser/api/lib/auto-updater.coffee',
'atom/browser/api/lib/auto-updater/auto-updater-mac.coffee', 'atom/browser/api/lib/auto-updater/auto-updater-native.coffee',
'atom/browser/api/lib/auto-updater/auto-updater-win.coffee', 'atom/browser/api/lib/auto-updater/auto-updater-win.coffee',
'atom/browser/api/lib/auto-updater/squirrel-update-win.coffee', 'atom/browser/api/lib/auto-updater/squirrel-update-win.coffee',
'atom/browser/api/lib/browser-window.coffee', 'atom/browser/api/lib/browser-window.coffee',
'atom/browser/api/lib/content-tracing.coffee', 'atom/browser/api/lib/content-tracing.coffee',
'atom/browser/api/lib/dialog.coffee', 'atom/browser/api/lib/dialog.coffee',
'atom/browser/api/lib/exports/electron.coffee',
'atom/browser/api/lib/global-shortcut.coffee', 'atom/browser/api/lib/global-shortcut.coffee',
'atom/browser/api/lib/ipc.coffee', 'atom/browser/api/lib/ipc.coffee',
'atom/browser/api/lib/ipc-main.coffee', 'atom/browser/api/lib/ipc-main.coffee',
@ -38,6 +39,7 @@
'atom/common/api/lib/clipboard.coffee', 'atom/common/api/lib/clipboard.coffee',
'atom/common/api/lib/crash-reporter.coffee', 'atom/common/api/lib/crash-reporter.coffee',
'atom/common/api/lib/deprecate.coffee', 'atom/common/api/lib/deprecate.coffee',
'atom/common/api/lib/exports/electron.coffee',
'atom/common/api/lib/native-image.coffee', 'atom/common/api/lib/native-image.coffee',
'atom/common/api/lib/shell.coffee', 'atom/common/api/lib/shell.coffee',
'atom/common/lib/init.coffee', 'atom/common/lib/init.coffee',
@ -50,6 +52,7 @@
'atom/renderer/lib/web-view/web-view.coffee', 'atom/renderer/lib/web-view/web-view.coffee',
'atom/renderer/lib/web-view/web-view-attributes.coffee', 'atom/renderer/lib/web-view/web-view-attributes.coffee',
'atom/renderer/lib/web-view/web-view-constants.coffee', 'atom/renderer/lib/web-view/web-view-constants.coffee',
'atom/renderer/api/lib/exports/electron.coffee',
'atom/renderer/api/lib/ipc.coffee', 'atom/renderer/api/lib/ipc.coffee',
'atom/renderer/api/lib/ipc-renderer.coffee', 'atom/renderer/api/lib/ipc-renderer.coffee',
'atom/renderer/api/lib/remote.coffee', 'atom/renderer/api/lib/remote.coffee',

View file

@ -16,6 +16,9 @@ PRODUCT_NAME = atom_gyp()['product_name%']
def main(): def main():
os.chdir(SOURCE_ROOT) os.chdir(SOURCE_ROOT)
# Disable old APIs
os.environ['ELECTRON_HIDE_INTERNAL_MODULES'] = 'true'
config = 'D' config = 'D'
if len(sys.argv) == 2 and sys.argv[1] == '-R': if len(sys.argv) == 2 and sys.argv[1] == '-R':
config = 'R' config = 'R'

View file

@ -1,7 +1,6 @@
assert = require 'assert' assert = require 'assert'
remote = require 'remote' {remote} = require 'electron'
app = remote.require 'app' {app, BrowserWindow} = remote.require 'electron'
BrowserWindow = remote.require 'browser-window'
describe 'app module', -> describe 'app module', ->
describe 'app.getVersion()', -> describe 'app.getVersion()', ->

View file

@ -1,12 +1,12 @@
assert = require 'assert' assert = require 'assert'
fs = require 'fs' fs = require 'fs'
path = require 'path' path = require 'path'
remote = require 'remote'
http = require 'http' http = require 'http'
url = require 'url' url = require 'url'
os = require 'os' os = require 'os'
BrowserWindow = remote.require 'browser-window' {remote, screen} = require 'electron'
{ipcMain, BrowserWindow} = remote.require 'electron'
isCI = remote.process.argv[2] == '--ci' isCI = remote.process.argv[2] == '--ci'
@ -191,7 +191,7 @@ describe 'browser-window module', ->
assert.equal after[1], -10 assert.equal after[1], -10
it 'can set the window larger than screen', -> it 'can set the window larger than screen', ->
size = require('screen').getPrimaryDisplay().size size = screen.getPrimaryDisplay().size
size.width += 100 size.width += 100
size.height += 100 size.height += 100
w.setSize size.width, size.height w.setSize size.width, size.height
@ -201,12 +201,12 @@ describe 'browser-window module', ->
describe '"web-preferences" option', -> describe '"web-preferences" option', ->
afterEach -> afterEach ->
remote.require('ipc-main').removeAllListeners('answer') ipcMain.removeAllListeners('answer')
describe '"preload" option', -> describe '"preload" option', ->
it 'loads the script before other scripts in window', (done) -> it 'loads the script before other scripts in window', (done) ->
preload = path.join fixtures, 'module', 'set-global.js' preload = path.join fixtures, 'module', 'set-global.js'
remote.require('ipc-main').once 'answer', (event, test) -> ipcMain.once 'answer', (event, test) ->
assert.equal(test, 'preload') assert.equal(test, 'preload')
done() done()
w.destroy() w.destroy()
@ -219,7 +219,7 @@ describe 'browser-window module', ->
describe '"node-integration" option', -> describe '"node-integration" option', ->
it 'disables node integration when specified to false', (done) -> it 'disables node integration when specified to false', (done) ->
preload = path.join fixtures, 'module', 'send-later.js' preload = path.join fixtures, 'module', 'send-later.js'
remote.require('ipc-main').once 'answer', (event, test) -> ipcMain.once 'answer', (event, test) ->
assert.equal(test, 'undefined') assert.equal(test, 'undefined')
done() done()
w.destroy() w.destroy()

View file

@ -1,8 +1,8 @@
assert = require 'assert' assert = require 'assert'
clipboard = require 'clipboard'
nativeImage = require 'native-image'
path = require 'path' path = require 'path'
{clipboard, nativeImage} = require 'electron'
describe 'clipboard module', -> describe 'clipboard module', ->
fixtures = path.resolve __dirname, 'fixtures' fixtures = path.resolve __dirname, 'fixtures'

View file

@ -2,11 +2,10 @@ assert = require 'assert'
path = require 'path' path = require 'path'
http = require 'http' http = require 'http'
url = require 'url' url = require 'url'
remote = require 'remote'
multiparty = require 'multiparty' multiparty = require 'multiparty'
crashReporter = remote.require 'crash-reporter' {remote} = require 'electron'
BrowserWindow = remote.require 'browser-window' {app, crashReporter, BrowserWindow} = remote.require 'electron'
describe 'crash-reporter module', -> describe 'crash-reporter module', ->
fixtures = path.resolve __dirname, 'fixtures' fixtures = path.resolve __dirname, 'fixtures'
@ -41,7 +40,7 @@ describe 'crash-reporter module', ->
assert.equal fields['extra2'], 'extra2' assert.equal fields['extra2'], 'extra2'
assert.equal fields['_productName'], 'Zombies' assert.equal fields['_productName'], 'Zombies'
assert.equal fields['_companyName'], 'Umbrella Corporation' assert.equal fields['_companyName'], 'Umbrella Corporation'
assert.equal fields['_version'], require('remote').require('app').getVersion() assert.equal fields['_version'], app.getVersion()
res.end('abc-123-def') res.end('abc-123-def')
done() done()

View file

@ -1,9 +1,8 @@
assert = require 'assert' assert = require 'assert'
ipc = require 'ipc-renderer'
path = require 'path' path = require 'path'
remote = require 'remote'
BrowserWindow = remote.require 'browser-window' {ipcRenderer, remote} = require 'electron'
{ipcMain, BrowserWindow} = remote.require 'electron'
comparePaths = (path1, path2) -> comparePaths = (path1, path2) ->
if process.platform is 'win32' if process.platform is 'win32'
@ -17,8 +16,8 @@ describe 'ipc module', ->
describe 'remote.require', -> describe 'remote.require', ->
it 'should returns same object for the same module', -> it 'should returns same object for the same module', ->
dialog1 = remote.require 'dialog' dialog1 = remote.require 'electron'
dialog2 = remote.require 'dialog' dialog2 = remote.require 'electron'
assert.equal dialog1, dialog2 assert.equal dialog1, dialog2
it 'should work when object contains id property', -> it 'should work when object contains id property', ->
@ -70,20 +69,20 @@ describe 'ipc module', ->
describe 'ipc.sender.send', -> describe 'ipc.sender.send', ->
it 'should work when sending an object containing id property', (done) -> it 'should work when sending an object containing id property', (done) ->
obj = id: 1, name: 'ly' obj = id: 1, name: 'ly'
ipc.once 'message', (event, message) -> ipcRenderer.once 'message', (event, message) ->
assert.deepEqual message, obj assert.deepEqual message, obj
done() done()
ipc.send 'message', obj ipcRenderer.send 'message', obj
describe 'ipc.sendSync', -> describe 'ipc.sendSync', ->
it 'can be replied by setting event.returnValue', -> it 'can be replied by setting event.returnValue', ->
msg = ipc.sendSync 'echo', 'test' msg = ipcRenderer.sendSync 'echo', 'test'
assert.equal msg, 'test' assert.equal msg, 'test'
it 'does not crash when reply is not sent and browser is destroyed', (done) -> it 'does not crash when reply is not sent and browser is destroyed', (done) ->
@timeout 10000 @timeout 10000
w = new BrowserWindow(show: false) w = new BrowserWindow(show: false)
remote.require('ipc-main').once 'send-sync-message', (event) -> ipcMain.once 'send-sync-message', (event) ->
event.returnValue = null event.returnValue = null
w.destroy() w.destroy()
done() done()

View file

@ -1,8 +1,7 @@
assert = require 'assert' assert = require 'assert'
remote = require 'remote'
Menu = remote.require 'menu' {remote} = require 'electron'
MenuItem = remote.require 'menu-item' {Menu, MenuItem} = remote.require 'electron'
describe 'menu module', -> describe 'menu module', ->
describe 'Menu.buildFromTemplate', -> describe 'Menu.buildFromTemplate', ->

View file

@ -1,8 +1,9 @@
assert = require 'assert' assert = require 'assert'
http = require 'http' http = require 'http'
path = require 'path' path = require 'path'
remote = require 'remote'
protocol = remote.require 'protocol' {remote} = require 'electron'
{protocol} = remote.require 'electron'
describe 'protocol module', -> describe 'protocol module', ->
protocolName = 'sp' protocolName = 'sp'

View file

@ -1,5 +1,6 @@
assert = require 'assert' assert = require 'assert'
screen = require 'screen'
{screen} = require 'electron'
describe 'screen module', -> describe 'screen module', ->
describe 'screen.getCursorScreenPoint()', -> describe 'screen.getCursorScreenPoint()', ->

View file

@ -1,10 +1,10 @@
assert = require 'assert' assert = require 'assert'
remote = require 'remote'
http = require 'http' http = require 'http'
path = require 'path' path = require 'path'
fs = require 'fs' fs = require 'fs'
app = remote.require 'app'
BrowserWindow = remote.require 'browser-window' {ipcRenderer, remote} = require 'electron'
{app, ipcMain, BrowserWindow} = remote.require 'electron'
describe 'session module', -> describe 'session module', ->
@timeout 10000 @timeout 10000
@ -60,7 +60,6 @@ describe 'session module', ->
describe 'session.clearStorageData(options)', -> describe 'session.clearStorageData(options)', ->
fixtures = path.resolve __dirname, 'fixtures' fixtures = path.resolve __dirname, 'fixtures'
it 'clears localstorage data', (done) -> it 'clears localstorage data', (done) ->
ipcMain = remote.require('ipc-main')
ipcMain.on 'count', (event, count) -> ipcMain.on 'count', (event, count) ->
ipcMain.removeAllListeners 'count' ipcMain.removeAllListeners 'count'
assert not count assert not count
@ -78,7 +77,6 @@ describe 'session module', ->
# A 5 MB mock pdf. # A 5 MB mock pdf.
mockPDF = new Buffer 1024 * 1024 * 5 mockPDF = new Buffer 1024 * 1024 * 5
contentDisposition = 'inline; filename="mock.pdf"' contentDisposition = 'inline; filename="mock.pdf"'
ipc = require 'ipc-renderer'
downloadFilePath = path.join fixtures, 'mock.pdf' downloadFilePath = path.join fixtures, 'mock.pdf'
downloadServer = http.createServer (req, res) -> downloadServer = http.createServer (req, res) ->
res.writeHead 200, { res.writeHead 200, {
@ -92,9 +90,9 @@ describe 'session module', ->
it 'can download successfully', (done) -> it 'can download successfully', (done) ->
downloadServer.listen 0, '127.0.0.1', -> downloadServer.listen 0, '127.0.0.1', ->
{port} = downloadServer.address() {port} = downloadServer.address()
ipc.sendSync 'set-download-option', false ipcRenderer.sendSync 'set-download-option', false
w.loadUrl "#{url}:#{port}" w.loadUrl "#{url}:#{port}"
ipc.once 'download-done', (event, state, url, mimeType, receivedBytes, totalBytes, disposition, filename) -> ipcRenderer.once 'download-done', (event, state, url, mimeType, receivedBytes, totalBytes, disposition, filename) ->
assert.equal state, 'completed' assert.equal state, 'completed'
assert.equal filename, 'mock.pdf' assert.equal filename, 'mock.pdf'
assert.equal url, "http://127.0.0.1:#{port}/" assert.equal url, "http://127.0.0.1:#{port}/"
@ -109,9 +107,9 @@ describe 'session module', ->
it 'can cancel download', (done) -> it 'can cancel download', (done) ->
downloadServer.listen 0, '127.0.0.1', -> downloadServer.listen 0, '127.0.0.1', ->
{port} = downloadServer.address() {port} = downloadServer.address()
ipc.sendSync 'set-download-option', true ipcRenderer.sendSync 'set-download-option', true
w.loadUrl "#{url}:#{port}/" w.loadUrl "#{url}:#{port}/"
ipc.once 'download-done', (event, state, url, mimeType, receivedBytes, totalBytes, disposition, filename) -> ipcRenderer.once 'download-done', (event, state, url, mimeType, receivedBytes, totalBytes, disposition, filename) ->
assert.equal state, 'cancelled' assert.equal state, 'cancelled'
assert.equal filename, 'mock.pdf' assert.equal filename, 'mock.pdf'
assert.equal mimeType, 'application/pdf' assert.equal mimeType, 'application/pdf'

View file

@ -3,6 +3,9 @@ child_process = require 'child_process'
fs = require 'fs' fs = require 'fs'
path = require 'path' path = require 'path'
{nativeImage, remote} = require 'electron'
{ipcMain, BrowserWindow} = remote.require 'electron'
describe 'asar package', -> describe 'asar package', ->
fixtures = path.join __dirname, 'fixtures' fixtures = path.join __dirname, 'fixtures'
@ -406,9 +409,6 @@ describe 'asar package', ->
describe 'asar protocol', -> describe 'asar protocol', ->
url = require 'url' url = require 'url'
remote = require 'remote'
ipc = remote.require 'ipc-main'
BrowserWindow = remote.require 'browser-window'
it 'can request a file in package', (done) -> it 'can request a file in package', (done) ->
p = path.resolve fixtures, 'asar', 'a.asar', 'file1' p = path.resolve fixtures, 'asar', 'a.asar', 'file1'
@ -445,12 +445,12 @@ describe 'asar package', ->
it 'sets __dirname correctly', (done) -> it 'sets __dirname correctly', (done) ->
after -> after ->
w.destroy() w.destroy()
ipc.removeAllListeners 'dirname' ipcMain.removeAllListeners 'dirname'
w = new BrowserWindow(show: false, width: 400, height: 400) w = new BrowserWindow(show: false, width: 400, height: 400)
p = path.resolve fixtures, 'asar', 'web.asar', 'index.html' p = path.resolve fixtures, 'asar', 'web.asar', 'index.html'
u = url.format protocol: 'file', slashed: true, pathname: p u = url.format protocol: 'file', slashed: true, pathname: p
ipc.once 'dirname', (event, dirname) -> ipcMain.once 'dirname', (event, dirname) ->
assert.equal dirname, path.dirname(p) assert.equal dirname, path.dirname(p)
done() done()
w.loadUrl u w.loadUrl u
@ -458,13 +458,13 @@ describe 'asar package', ->
it 'loads script tag in html', (done) -> it 'loads script tag in html', (done) ->
after -> after ->
w.destroy() w.destroy()
ipc.removeAllListeners 'ping' ipcMain.removeAllListeners 'ping'
w = new BrowserWindow(show: false, width: 400, height: 400) w = new BrowserWindow(show: false, width: 400, height: 400)
p = path.resolve fixtures, 'asar', 'script.asar', 'index.html' p = path.resolve fixtures, 'asar', 'script.asar', 'index.html'
u = url.format protocol: 'file', slashed: true, pathname: p u = url.format protocol: 'file', slashed: true, pathname: p
w.loadUrl u w.loadUrl u
ipc.once 'ping', (event, message) -> ipcMain.once 'ping', (event, message) ->
assert.equal message, 'pong' assert.equal message, 'pong'
done() done()
@ -496,10 +496,10 @@ describe 'asar package', ->
describe 'native-image', -> describe 'native-image', ->
it 'reads image from asar archive', -> it 'reads image from asar archive', ->
p = path.join fixtures, 'asar', 'logo.asar', 'logo.png' p = path.join fixtures, 'asar', 'logo.asar', 'logo.png'
logo = require('native-image').createFromPath p logo = nativeImage.createFromPath p
assert.deepEqual logo.getSize(), {width: 55, height: 55} assert.deepEqual logo.getSize(), {width: 55, height: 55}
it 'reads image from asar archive with unpacked files', -> it 'reads image from asar archive with unpacked files', ->
p = path.join fixtures, 'asar', 'unpack.asar', 'atom.png' p = path.join fixtures, 'asar', 'unpack.asar', 'atom.png'
logo = require('native-image').createFromPath p logo = nativeImage.createFromPath p
assert.deepEqual logo.getSize(), {width: 1024, height: 1024} assert.deepEqual logo.getSize(), {width: 1024, height: 1024}

View file

@ -3,8 +3,9 @@ http = require 'http'
https = require 'https' https = require 'https'
path = require 'path' path = require 'path'
ws = require 'ws' ws = require 'ws'
remote = require 'remote'
BrowserWindow = remote.require 'browser-window' {remote} = require 'electron'
{BrowserWindow} = remote.require 'electron'
describe 'chromium feature', -> describe 'chromium feature', ->
fixtures = path.resolve __dirname, 'fixtures' fixtures = path.resolve __dirname, 'fixtures'

View file

@ -3,7 +3,7 @@
<script type="text/javascript" charset="utf-8"> <script type="text/javascript" charset="utf-8">
window.onbeforeunload = function() { window.onbeforeunload = function() {
setTimeout(function() { setTimeout(function() {
require('remote').getCurrentWindow().emit('onbeforeunload'); require('electron').remote.getCurrentWindow().emit('onbeforeunload');
}, 0); }, 0);
return false; return false;
} }

View file

@ -3,7 +3,7 @@
<script type="text/javascript" charset="utf-8"> <script type="text/javascript" charset="utf-8">
window.onbeforeunload = function() { window.onbeforeunload = function() {
setTimeout(function() { setTimeout(function() {
require('remote').getCurrentWindow().emit('onbeforeunload'); require('electron').remote.getCurrentWindow().emit('onbeforeunload');
}, 0); }, 0);
return ''; return '';
} }

View file

@ -3,7 +3,7 @@
<script type="text/javascript" charset="utf-8"> <script type="text/javascript" charset="utf-8">
window.onbeforeunload = function() { window.onbeforeunload = function() {
setTimeout(function() { setTimeout(function() {
require('remote').getCurrentWindow().emit('onbeforeunload'); require('electron').remote.getCurrentWindow().emit('onbeforeunload');
}, 0); }, 0);
return false; return false;
} }

View file

@ -3,7 +3,7 @@
<script type="text/javascript" charset="utf-8"> <script type="text/javascript" charset="utf-8">
window.onbeforeunload = function() { window.onbeforeunload = function() {
setTimeout(function() { setTimeout(function() {
require('remote').getCurrentWindow().emit('onbeforeunload'); require('electron').remote.getCurrentWindow().emit('onbeforeunload');
}, 0); }, 0);
return 'string'; return 'string';
} }

View file

@ -3,7 +3,7 @@
<script type="text/javascript" charset="utf-8"> <script type="text/javascript" charset="utf-8">
window.onbeforeunload = function() { window.onbeforeunload = function() {
setTimeout(function() { setTimeout(function() {
require('remote').getCurrentWindow().emit('onbeforeunload'); require('electron').remote.getCurrentWindow().emit('onbeforeunload');
}, 0); }, 0);
return true; return true;
} }

View file

@ -2,7 +2,7 @@
<body> <body>
<script type="text/javascript" charset="utf-8"> <script type="text/javascript" charset="utf-8">
var port = require('url').parse(window.location.href, true).query.port; var port = require('url').parse(window.location.href, true).query.port;
var crashReporter = require('crash-reporter'); var crashReporter = require('electron').crashReporter;
crashReporter.start({ crashReporter.start({
productName: 'Zombies', productName: 'Zombies',
companyName: 'Umbrella Corporation', companyName: 'Umbrella Corporation',

View file

@ -2,9 +2,9 @@
<body> <body>
<script type="text/javascript" charset="utf-8"> <script type="text/javascript" charset="utf-8">
window.localStorage.setItem('test', 'test'); window.localStorage.setItem('test', 'test');
var ipc = require('ipc-renderer'); var ipcRenderer = require('electron').ipcRenderer;
ipc.on('getcount', function() { ipcRenderer.on('getcount', function() {
ipc.send('count', window.localStorage.length); ipcRenderer.send('count', window.localStorage.length);
}) })
</script> </script>
</body> </body>

View file

@ -3,7 +3,7 @@
<script type="text/javascript" charset="utf-8"> <script type="text/javascript" charset="utf-8">
if (!window.test) if (!window.test)
window.test = 'window' window.test = 'window'
require('ipc-renderer').send('answer', window.test); require('electron').ipcRenderer.send('answer', window.test);
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,8 +1,8 @@
<html> <html>
<body> <body>
<script type="text/javascript" charset="utf-8"> <script type="text/javascript" charset="utf-8">
var ipc = require('ipc-renderer'); var ipcRenderer = require('electron').ipcRenderer;
ipc.sendSync('send-sync-message', 'message'); ipcRenderer.sendSync('send-sync-message', 'message');
</script> </script>
</body> </body>
</html> </html>

Binary file not shown.

Binary file not shown.

View file

@ -1,4 +1,4 @@
var ipc = require('ipc-renderer'); var ipcRenderer = require('electron').ipcRenderer;
ipc.on('ping', function(event, message) { ipcRenderer.on('ping', function(event, message) {
ipc.sendToHost('pong', message); ipcRenderer.sendToHost('pong', message);
}); });

View file

@ -1,4 +1,4 @@
var ipc = require('ipc-renderer'); var ipcRenderer = require('electron').ipcRenderer;
window.onload = function() { window.onload = function() {
ipc.send('answer', typeof window.process); ipcRenderer.send('answer', typeof window.process);
} }

View file

@ -2,7 +2,7 @@
<body> <body>
<script src="../../static/jquery-2.0.3.min.js"></script> <script src="../../static/jquery-2.0.3.min.js"></script>
<script type="text/javascript" charset="utf-8"> <script type="text/javascript" charset="utf-8">
var ipc = require('ipc-renderer'); var ipcRenderer = require('electron').ipcRenderer;
var port = location.search.substr("?port=".length); var port = location.search.substr("?port=".length);
$.ajax({ $.ajax({
type: "GET", type: "GET",
@ -11,10 +11,10 @@
"Authorization": "Basic " + btoa("test:test") "Authorization": "Basic " + btoa("test:test")
}, },
success: function(result) { success: function(result) {
ipc.sendToHost(result); ipcRenderer.sendToHost(result);
}, },
error: function(xhr, status, error) { error: function(xhr, status, error) {
ipc.sendToHost(error); ipcRenderer.sendToHost(error);
}, },
}); });
</script> </script>

Some files were not shown because too many files have changed in this diff Show more