From ce0167756e2a587eea6a31c6fad7660a68fab8f5 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 12 Nov 2015 16:27:28 +0800 Subject: [PATCH 01/31] Update node for atom/node#13 --- vendor/node | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vendor/node b/vendor/node index edfbc29d09..1445826ca7 160000 --- a/vendor/node +++ b/vendor/node @@ -1 +1 @@ -Subproject commit edfbc29d09425f2f387c52d77f6351b6ce101659 +Subproject commit 1445826ca73cc79bc57d503dd11d4ffaf695625c From c2c09daa236bc57c7bb79cbae617fc6ca72842da Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 12 Nov 2015 16:28:22 +0800 Subject: [PATCH 02/31] Add "electron" module --- atom/browser/api/lib/exports/electron.coffee | 47 +++++++++++++++++++ atom/browser/lib/init.coffee | 1 + atom/common/api/lib/exports/electron.coffee | 15 ++++++ atom/renderer/api/lib/exports/electron.coffee | 17 +++++++ atom/renderer/lib/init.coffee | 1 + filenames.gypi | 3 ++ 6 files changed, 84 insertions(+) create mode 100644 atom/browser/api/lib/exports/electron.coffee create mode 100644 atom/common/api/lib/exports/electron.coffee create mode 100644 atom/renderer/api/lib/exports/electron.coffee diff --git a/atom/browser/api/lib/exports/electron.coffee b/atom/browser/api/lib/exports/electron.coffee new file mode 100644 index 0000000000..6c7929706c --- /dev/null +++ b/atom/browser/api/lib/exports/electron.coffee @@ -0,0 +1,47 @@ +# Import common modules. +module.exports = require '../../../../common/api/lib/exports/electron' + +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' diff --git a/atom/browser/lib/init.coffee b/atom/browser/lib/init.coffee index 80d2da31b7..fd6059bd73 100644 --- a/atom/browser/lib/init.coffee +++ b/atom/browser/lib/init.coffee @@ -17,6 +17,7 @@ require path.resolve(__dirname, '..', '..', 'common', 'lib', 'init') # Electron's built-in libraries. globalPaths = Module.globalPaths globalPaths.push path.resolve(__dirname, '..', 'api', 'lib') +globalPaths.push path.resolve(__dirname, '..', 'api', 'lib', 'exports') if process.platform is 'win32' # Redirect node's console to use our own implementations, since node can not diff --git a/atom/common/api/lib/exports/electron.coffee b/atom/common/api/lib/exports/electron.coffee new file mode 100644 index 0000000000..a57d5be94c --- /dev/null +++ b/atom/common/api/lib/exports/electron.coffee @@ -0,0 +1,15 @@ +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' + crashRepoter: + enumerable: true + get: -> require '../crash-reporter' + nativeImage: + enumerable: true + get: -> require '../native-image' + shell: + enumerable: true + get: -> require '../shell' diff --git a/atom/renderer/api/lib/exports/electron.coffee b/atom/renderer/api/lib/exports/electron.coffee new file mode 100644 index 0000000000..5d7f2a57ed --- /dev/null +++ b/atom/renderer/api/lib/exports/electron.coffee @@ -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' diff --git a/atom/renderer/lib/init.coffee b/atom/renderer/lib/init.coffee index ed3482fb97..4779794278 100644 --- a/atom/renderer/lib/init.coffee +++ b/atom/renderer/lib/init.coffee @@ -17,6 +17,7 @@ require path.resolve(__dirname, '..', '..', 'common', 'lib', 'init') # of Atom's built-in libraries. globalPaths = Module.globalPaths globalPaths.push path.resolve(__dirname, '..', 'api', 'lib') +globalPaths.push path.resolve(__dirname, '..', 'api', 'lib', 'exports') # The global variable will be used by ipc for event dispatching v8Util = process.atomBinding 'v8_util' diff --git a/filenames.gypi b/filenames.gypi index 4dc709c5ec..de7ee26c5e 100644 --- a/filenames.gypi +++ b/filenames.gypi @@ -16,6 +16,7 @@ 'atom/browser/api/lib/browser-window.coffee', 'atom/browser/api/lib/content-tracing.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/ipc.coffee', 'atom/browser/api/lib/ipc-main.coffee', @@ -38,6 +39,7 @@ 'atom/common/api/lib/clipboard.coffee', 'atom/common/api/lib/crash-reporter.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/shell.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-attributes.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-renderer.coffee', 'atom/renderer/api/lib/remote.coffee', From f9d7e7ce559d28307058cf196e280e8e2d2eed0e Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 12 Nov 2015 17:02:04 +0800 Subject: [PATCH 03/31] Add ELECTRON_DISABLE_OLD_STYLE_MODULES env --- atom/browser/lib/init.coffee | 7 ++++--- atom/common/lib/init.coffee | 5 +++-- atom/renderer/lib/init.coffee | 7 ++++--- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/atom/browser/lib/init.coffee b/atom/browser/lib/init.coffee index fd6059bd73..a9092e3f95 100644 --- a/atom/browser/lib/init.coffee +++ b/atom/browser/lib/init.coffee @@ -13,12 +13,13 @@ require path.resolve(__dirname, '..', '..', 'common', 'lib', 'reset-search-paths # Import common settings. 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. +# Expose public APIs. globalPaths = Module.globalPaths -globalPaths.push path.resolve(__dirname, '..', 'api', 'lib') globalPaths.push path.resolve(__dirname, '..', 'api', 'lib', 'exports') +unless process.env.ELECTRON_DISABLE_OLD_STYLE_MODULES + globalPaths.push path.resolve(__dirname, '..', 'api', 'lib') + if process.platform is 'win32' # Redirect node's console to use our own implementations, since node can not # handle console output when running as GUI program. diff --git a/atom/common/lib/init.coffee b/atom/common/lib/init.coffee index 1c80e6171a..a92871994d 100644 --- a/atom/common/lib/init.coffee +++ b/atom/common/lib/init.coffee @@ -9,8 +9,9 @@ process.atomBinding = (name) -> catch e process.binding "atom_common_#{name}" if /No such module/.test e.message -# Add common/api/lib to module search paths. -Module.globalPaths.push path.resolve(__dirname, '..', 'api', 'lib') +unless process.env.ELECTRON_DISABLE_OLD_STYLE_MODULES + # 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 # run the callbacks, however since we only run uv loop on requests, the diff --git a/atom/renderer/lib/init.coffee b/atom/renderer/lib/init.coffee index 4779794278..4f0e6a3287 100644 --- a/atom/renderer/lib/init.coffee +++ b/atom/renderer/lib/init.coffee @@ -13,12 +13,13 @@ require path.resolve(__dirname, '..', '..', 'common', 'lib', 'reset-search-paths # Import common settings. 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. +# Expose public APIs. globalPaths = Module.globalPaths -globalPaths.push path.resolve(__dirname, '..', 'api', 'lib') globalPaths.push path.resolve(__dirname, '..', 'api', 'lib', 'exports') +unless process.env.ELECTRON_DISABLE_OLD_STYLE_MODULES + globalPaths.push path.resolve(__dirname, '..', 'api', 'lib') + # The global variable will be used by ipc for event dispatching v8Util = process.atomBinding 'v8_util' v8Util.setHiddenValue global, 'ipc', new events.EventEmitter From fb5beb9af541d3405329789ad61945c20b03ef39 Mon Sep 17 00:00:00 2001 From: Shawn K Date: Thu, 12 Nov 2015 01:00:41 -0800 Subject: [PATCH 04/31] Add --js-flags support for main thread. Allow use of flags that must be set before V8 is initialized, such as "--harmony_proxies", e.g. --js-flags="--harmony_proxies --harmony_collections" --- atom/browser/javascript_environment.cc | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/atom/browser/javascript_environment.cc b/atom/browser/javascript_environment.cc index cc06bb6ff9..ae4f8e55e7 100644 --- a/atom/browser/javascript_environment.cc +++ b/atom/browser/javascript_environment.cc @@ -2,6 +2,8 @@ // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. +#include + #include "atom/browser/javascript_environment.h" #include "base/command_line.h" @@ -27,8 +29,18 @@ bool JavascriptEnvironment::Initialize() { const char expose_debug_as[] = "--expose_debug_as=v8debug"; v8::V8::SetFlagsFromString(expose_debug_as, sizeof(expose_debug_as) - 1); } + + const std::string js_flags_switch = "js-flags"; + + if (cmd->HasSwitch(js_flags_switch)) { + const char *js_flags_value = + (cmd->GetSwitchValueASCII(js_flags_switch)).c_str(); + v8::V8::SetFlagsFromString(js_flags_value, strlen(js_flags_value)); + } + gin::IsolateHolder::Initialize(gin::IsolateHolder::kNonStrictMode, gin::ArrayBufferAllocator::SharedInstance()); + return true; } From 1d1f911b095ce29206f4b7f74221f3bac7b28e0d Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 12 Nov 2015 18:28:04 +0800 Subject: [PATCH 05/31] Use require('electron') in Electron's code --- atom/browser/api/lib/app.coffee | 9 ++--- atom/browser/api/lib/browser-window.coffee | 8 ++--- atom/browser/api/lib/dialog.coffee | 4 +-- atom/browser/api/lib/exports/electron.coffee | 5 +++ atom/browser/api/lib/global-shortcut.coffee | 4 +-- atom/browser/api/lib/ipc.coffee | 4 +-- atom/browser/api/lib/menu-item.coffee | 3 +- atom/browser/api/lib/menu.coffee | 7 ++-- .../api/lib/navigation-controller.coffee | 6 ++-- atom/browser/api/lib/power-monitor.coffee | 5 +-- .../browser/api/lib/power-save-blocker.coffee | 4 +-- atom/browser/api/lib/protocol.coffee | 5 +-- atom/browser/api/lib/screen.coffee | 4 +-- atom/browser/api/lib/tray.coffee | 5 ++- atom/browser/api/lib/web-contents.coffee | 11 +++---- atom/browser/default_app/default_app.js | 5 +-- atom/browser/default_app/index.html | 8 +++-- atom/browser/default_app/main.js | 20 ++++++----- atom/browser/lib/chrome-extension.coffee | 6 ++-- atom/browser/lib/guest-view-manager.coffee | 14 ++++---- atom/browser/lib/guest-window-manager.coffee | 17 +++++----- atom/browser/lib/init.coffee | 5 +-- atom/browser/lib/objects-registry.coffee | 2 +- atom/browser/lib/rpc-server.coffee | 31 +++++++++--------- atom/common/api/lib/clipboard.coffee | 3 +- atom/common/api/lib/crash-reporter.coffee | 7 ++-- atom/common/api/lib/exports/electron.coffee | 5 +++ atom/renderer/api/lib/ipc.coffee | 3 +- atom/renderer/api/lib/remote.coffee | 31 +++++++++--------- atom/renderer/api/lib/screen.coffee | 2 +- atom/renderer/lib/inspector.coffee | 8 ++--- atom/renderer/lib/override.coffee | 27 ++++++++------- .../lib/web-view/guest-view-internal.coffee | 27 ++++++++------- .../lib/web-view/web-view-attributes.coffee | 3 +- atom/renderer/lib/web-view/web-view.coffee | 4 +-- spec/api-app-spec.coffee | 5 ++- spec/api-browser-window-spec.coffee | 12 +++---- spec/api-clipboard-spec.coffee | 4 +-- spec/api-crash-reporter-spec.coffee | 7 ++-- spec/api-ipc-spec.coffee | 17 +++++----- spec/api-menu-spec.coffee | 5 ++- spec/api-protocol-spec.coffee | 5 +-- spec/api-screen-spec.coffee | 3 +- spec/api-session-spec.coffee | 16 ++++----- spec/asar-spec.coffee | 18 +++++----- spec/chromium-spec.coffee | 5 +-- spec/fixtures/api/beforeunload-false.html | 2 +- .../api/close-beforeunload-empty-string.html | 2 +- .../api/close-beforeunload-false.html | 2 +- .../api/close-beforeunload-string.html | 2 +- .../fixtures/api/close-beforeunload-true.html | 2 +- spec/fixtures/api/crash.html | 2 +- spec/fixtures/api/localstorage.html | 6 ++-- spec/fixtures/api/preload.html | 2 +- spec/fixtures/api/send-sync-message.html | 4 +-- spec/fixtures/asar/script.asar | Bin 204 -> 221 bytes spec/fixtures/asar/web.asar | Bin 201 -> 218 bytes spec/fixtures/module/preload-ipc.js | 6 ++-- spec/fixtures/module/send-later.js | 4 +-- spec/fixtures/pages/basic-auth.html | 6 ++-- spec/fixtures/pages/beforeunload-false.html | 4 +-- spec/fixtures/pages/document-hidden.html | 2 +- spec/fixtures/pages/history.html | 2 +- spec/fixtures/pages/ipc-message.html | 2 +- spec/fixtures/pages/onkeyup.html | 2 +- spec/fixtures/pages/onmouseup.html | 2 +- spec/fixtures/pages/window-open-size.html | 2 +- spec/fixtures/pages/window-opener.html | 2 +- spec/node-spec.coffee | 3 +- spec/static/index.html | 17 ++++++---- spec/static/main.js | 28 ++++++++-------- 71 files changed, 265 insertions(+), 250 deletions(-) diff --git a/atom/browser/api/lib/app.coffee b/atom/browser/api/lib/app.coffee index b5025a3a4f..0113e90a1a 100644 --- a/atom/browser/api/lib/app.coffee +++ b/atom/browser/api/lib/app.coffee @@ -1,5 +1,5 @@ -deprecate = require 'deprecate' -EventEmitter = require('events').EventEmitter +electron = require 'electron' +{EventEmitter} = require 'events' bindings = process.atomBinding 'app' sessionBindings = process.atomBinding 'session' @@ -9,10 +9,10 @@ app = bindings.app app.__proto__ = EventEmitter.prototype app.setApplicationMenu = (menu) -> - require('menu').setApplicationMenu menu + electron.menu.setApplicationMenu menu app.getApplicationMenu = -> - require('menu').getApplicationMenu() + electron.menu.getApplicationMenu() app.commandLine = appendSwitch: bindings.appendSwitch, @@ -39,6 +39,7 @@ app.getAppPath = -> app.resolveProxy = (url, callback) -> @defaultSession.resolveProxy url, callback # Deprecated. +{deprecate} = electron app.getHomeDir = deprecate 'app.getHomeDir', 'app.getPath', -> @getPath 'home' app.getDataPath = deprecate 'app.getDataPath', 'app.getPath', -> diff --git a/atom/browser/api/lib/browser-window.coffee b/atom/browser/api/lib/browser-window.coffee index 5bb6332088..3cefa1bf60 100644 --- a/atom/browser/api/lib/browser-window.coffee +++ b/atom/browser/api/lib/browser-window.coffee @@ -1,7 +1,5 @@ -EventEmitter = require('events').EventEmitter -app = require 'app' -ipc = require 'ipc-main' -deprecate = require 'deprecate' +{app, ipcMain, deprecate} = require 'electron' +{EventEmitter} = require 'events' BrowserWindow = process.atomBinding('window').BrowserWindow BrowserWindow::__proto__ = EventEmitter.prototype @@ -15,7 +13,7 @@ BrowserWindow::_init = -> # Make new windows requested by links behave like "window.open" @webContents.on '-new-window', (event, url, frameName) -> 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.moveTo(...) diff --git a/atom/browser/api/lib/dialog.coffee b/atom/browser/api/lib/dialog.coffee index 0843af0428..f10ce58c17 100644 --- a/atom/browser/api/lib/dialog.coffee +++ b/atom/browser/api/lib/dialog.coffee @@ -1,7 +1,7 @@ +{app, BrowserWindow} = require 'electron' + binding = process.atomBinding 'dialog' v8Util = process.atomBinding 'v8_util' -app = require 'app' -BrowserWindow = require 'browser-window' fileDialogProperties = openFile: 1 << 0 diff --git a/atom/browser/api/lib/exports/electron.coffee b/atom/browser/api/lib/exports/electron.coffee index 6c7929706c..a09a6441c3 100644 --- a/atom/browser/api/lib/exports/electron.coffee +++ b/atom/browser/api/lib/exports/electron.coffee @@ -45,3 +45,8 @@ Object.defineProperties module.exports, 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' diff --git a/atom/browser/api/lib/global-shortcut.coffee b/atom/browser/api/lib/global-shortcut.coffee index 8b24d27253..56c3e12876 100644 --- a/atom/browser/api/lib/global-shortcut.coffee +++ b/atom/browser/api/lib/global-shortcut.coffee @@ -1,5 +1,3 @@ -bindings = process.atomBinding 'global_shortcut' - -globalShortcut = bindings.globalShortcut +{globalShortcut} = process.atomBinding 'global_shortcut' module.exports = globalShortcut diff --git a/atom/browser/api/lib/ipc.coffee b/atom/browser/api/lib/ipc.coffee index b8ab05a886..8019a385dd 100644 --- a/atom/browser/api/lib/ipc.coffee +++ b/atom/browser/api/lib/ipc.coffee @@ -1,6 +1,6 @@ -deprecate = require 'deprecate' +{deprecate, ipcMain} = require 'electron' # This module is deprecated, we mirror everything from ipcMain. deprecate.warn 'ipc module', 'ipcMain module' -module.exports = require 'ipc-main' +module.exports = ipcMain diff --git a/atom/browser/api/lib/menu-item.coffee b/atom/browser/api/lib/menu-item.coffee index cfefeec4ed..92e2283b41 100644 --- a/atom/browser/api/lib/menu-item.coffee +++ b/atom/browser/api/lib/menu-item.coffee @@ -1,4 +1,3 @@ -BrowserWindow = require 'browser-window' v8Util = process.atomBinding 'v8_util' nextCommandId = 0 @@ -18,7 +17,7 @@ class MenuItem @types = ['normal', 'separator', 'submenu', 'checkbox', 'radio'] constructor: (options) -> - Menu = require 'menu' + {Menu} = require 'electron' {click, @selector, @type, @role, @label, @sublabel, @accelerator, @icon, @enabled, @visible, @checked, @submenu} = options diff --git a/atom/browser/api/lib/menu.coffee b/atom/browser/api/lib/menu.coffee index f66c1568c0..26e2dc2335 100644 --- a/atom/browser/api/lib/menu.coffee +++ b/atom/browser/api/lib/menu.coffee @@ -1,8 +1,7 @@ -BrowserWindow = require 'browser-window' -EventEmitter = require('events').EventEmitter -MenuItem = require 'menu-item' -v8Util = process.atomBinding 'v8_util' +{BrowserWindow, MenuItem} = require 'electron' +{EventEmitter} = require 'events' +v8Util = process.atomBinding 'v8_util' bindings = process.atomBinding 'menu' # Automatically generated radio menu item's group id. diff --git a/atom/browser/api/lib/navigation-controller.coffee b/atom/browser/api/lib/navigation-controller.coffee index 34911dd759..88b1ed30dd 100644 --- a/atom/browser/api/lib/navigation-controller.coffee +++ b/atom/browser/api/lib/navigation-controller.coffee @@ -1,10 +1,10 @@ -ipc = require 'ipc-main' +{ipcMain} = require 'electron' # 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... -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... # JavaScript implementation of Chromium's NavigationController. diff --git a/atom/browser/api/lib/power-monitor.coffee b/atom/browser/api/lib/power-monitor.coffee index f13e60eb9d..54bf939182 100644 --- a/atom/browser/api/lib/power-monitor.coffee +++ b/atom/browser/api/lib/power-monitor.coffee @@ -1,5 +1,6 @@ -powerMonitor = process.atomBinding('power_monitor').powerMonitor -EventEmitter = require('events').EventEmitter +{EventEmitter} = require 'events' + +{powerMonitor} = process.atomBinding 'power_monitor' powerMonitor.__proto__ = EventEmitter.prototype diff --git a/atom/browser/api/lib/power-save-blocker.coffee b/atom/browser/api/lib/power-save-blocker.coffee index 7f428bc40f..58392bc9aa 100644 --- a/atom/browser/api/lib/power-save-blocker.coffee +++ b/atom/browser/api/lib/power-save-blocker.coffee @@ -1,3 +1,3 @@ -bindings = process.atomBinding 'power_save_blocker' +{powerSaveBlocker} = process.atomBinding 'power_save_blocker' -module.exports = bindings.powerSaveBlocker +module.exports = powerSaveBlocker diff --git a/atom/browser/api/lib/protocol.coffee b/atom/browser/api/lib/protocol.coffee index 13f2a6d102..a1dbc7c17d 100644 --- a/atom/browser/api/lib/protocol.coffee +++ b/atom/browser/api/lib/protocol.coffee @@ -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() -protocol = process.atomBinding('protocol').protocol +{protocol} = process.atomBinding 'protocol' # Warn about removed APIs. logAndThrow = (callback, message) -> diff --git a/atom/browser/api/lib/screen.coffee b/atom/browser/api/lib/screen.coffee index 6ef5a5f663..87c42f091d 100644 --- a/atom/browser/api/lib/screen.coffee +++ b/atom/browser/api/lib/screen.coffee @@ -1,6 +1,6 @@ -EventEmitter = require('events').EventEmitter +{EventEmitter} = require 'events' +{screen} = process.atomBinding 'screen' -screen = process.atomBinding('screen').screen screen.__proto__ = EventEmitter.prototype module.exports = screen diff --git a/atom/browser/api/lib/tray.coffee b/atom/browser/api/lib/tray.coffee index 1c225ddd40..41cfc96d3f 100644 --- a/atom/browser/api/lib/tray.coffee +++ b/atom/browser/api/lib/tray.coffee @@ -1,7 +1,6 @@ -EventEmitter = require('events').EventEmitter -bindings = process.atomBinding 'tray' +{EventEmitter} = require 'events' +{Tray} = process.atomBinding 'tray' -Tray = bindings.Tray Tray::__proto__ = EventEmitter.prototype Tray::setContextMenu = (menu) -> diff --git a/atom/browser/api/lib/web-contents.coffee b/atom/browser/api/lib/web-contents.coffee index 958c3f8270..b3b1e7ed9f 100644 --- a/atom/browser/api/lib/web-contents.coffee +++ b/atom/browser/api/lib/web-contents.coffee @@ -1,8 +1,7 @@ -EventEmitter = require('events').EventEmitter -Menu = require './menu' -NavigationController = require './navigation-controller' +{EventEmitter} = require 'events' +{ipcMain, NavigationController, Menu} = require 'electron' + binding = process.atomBinding 'web_contents' -ipc = require 'ipc-main' nextId = 0 getNextId = -> ++nextId @@ -60,11 +59,11 @@ wrapWebContents = (webContents) -> # Dispatch IPC messages to the ipc module. webContents.on 'ipc-message', (event, packed) -> [channel, args...] = packed - ipc.emit channel, event, args... + ipcMain.emit channel, event, args... webContents.on 'ipc-message-sync', (event, packed) -> [channel, args...] = packed 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. webContents.on 'pepper-context-menu', (event, params) -> diff --git a/atom/browser/default_app/default_app.js b/atom/browser/default_app/default_app.js index de8b14d5f4..6a94db4836 100644 --- a/atom/browser/default_app/default_app.js +++ b/atom/browser/default_app/default_app.js @@ -1,5 +1,6 @@ -var app = require('app'); -var BrowserWindow = require('browser-window'); +const electron = require('electron'); +const app = electron.app; +const BrowserWindow = electron.BrowserWindow; var mainWindow = null; diff --git a/atom/browser/default_app/index.html b/atom/browser/default_app/index.html index 96e45806d5..e55cdf77b7 100644 --- a/atom/browser/default_app/index.html +++ b/atom/browser/default_app/index.html @@ -57,13 +57,17 @@ diff --git a/spec/fixtures/api/preload.html b/spec/fixtures/api/preload.html index 5e73c92971..b0e42ebe2e 100644 --- a/spec/fixtures/api/preload.html +++ b/spec/fixtures/api/preload.html @@ -3,7 +3,7 @@ diff --git a/spec/fixtures/api/send-sync-message.html b/spec/fixtures/api/send-sync-message.html index 40bae94b81..8095074057 100644 --- a/spec/fixtures/api/send-sync-message.html +++ b/spec/fixtures/api/send-sync-message.html @@ -1,8 +1,8 @@ diff --git a/spec/fixtures/asar/script.asar b/spec/fixtures/asar/script.asar index 152045ad2a6bb6e1337bc70448fecde5100e3709..7239786ec90ea4317573ac9e080073a42b13e6d6 100755 GIT binary patch delta 58 zcmX@Zc$aZPFq5gt#L#Hn)ST4hlA`=Pbxpm@g5;poyp+_U)FQoNAVWjFATuvrT}MH^ LARkC;T5|yaT{;tO delta 41 vcmcc1c!qI8Fq5(Q#L#G&%z|WfO}*mOyc7-fg3P>hbsYuuf_xyYY0U)y91IMc diff --git a/spec/fixtures/asar/web.asar b/spec/fixtures/asar/web.asar index 0c7a788e759dc131689de6fb977bbbba4d795260..1e9db65b8128ec9ab0fa415ccf7dc6e6dc874b28 100644 GIT binary patch delta 38 tcmX@fc#Cm@0h6i0M5Ac2)ST4hlA`=Pbxpm@g5;poyp+_U)S`)#%mMz_4X6MB delta 21 ccmcb`c#?5~0h6)uM5Acd%z|Wf&54W60Zj!4=l}o! diff --git a/spec/fixtures/module/preload-ipc.js b/spec/fixtures/module/preload-ipc.js index 76bd481cab..ed95055c12 100644 --- a/spec/fixtures/module/preload-ipc.js +++ b/spec/fixtures/module/preload-ipc.js @@ -1,4 +1,4 @@ -var ipc = require('ipc-renderer'); -ipc.on('ping', function(event, message) { - ipc.sendToHost('pong', message); +var ipcRenderer = require('electron').ipcRenderer; +ipcRenderer.on('ping', function(event, message) { + ipcRenderer.sendToHost('pong', message); }); diff --git a/spec/fixtures/module/send-later.js b/spec/fixtures/module/send-later.js index 9cd5bfd388..13f02452db 100644 --- a/spec/fixtures/module/send-later.js +++ b/spec/fixtures/module/send-later.js @@ -1,4 +1,4 @@ -var ipc = require('ipc-renderer'); +var ipcRenderer = require('electron').ipcRenderer; window.onload = function() { - ipc.send('answer', typeof window.process); + ipcRenderer.send('answer', typeof window.process); } diff --git a/spec/fixtures/pages/basic-auth.html b/spec/fixtures/pages/basic-auth.html index f2b9fab199..ec9383ca4d 100644 --- a/spec/fixtures/pages/basic-auth.html +++ b/spec/fixtures/pages/basic-auth.html @@ -2,7 +2,7 @@ diff --git a/spec/fixtures/pages/beforeunload-false.html b/spec/fixtures/pages/beforeunload-false.html index 4f14613bf3..0b71b07c83 100644 --- a/spec/fixtures/pages/beforeunload-false.html +++ b/spec/fixtures/pages/beforeunload-false.html @@ -3,8 +3,8 @@ diff --git a/spec/fixtures/pages/history.html b/spec/fixtures/pages/history.html index ef00835359..6100293fda 100644 --- a/spec/fixtures/pages/history.html +++ b/spec/fixtures/pages/history.html @@ -2,7 +2,7 @@ diff --git a/spec/fixtures/pages/ipc-message.html b/spec/fixtures/pages/ipc-message.html index 65e347275c..f543c9abf0 100644 --- a/spec/fixtures/pages/ipc-message.html +++ b/spec/fixtures/pages/ipc-message.html @@ -1,7 +1,7 @@ diff --git a/spec/fixtures/pages/onkeyup.html b/spec/fixtures/pages/onkeyup.html index 87e6dc596b..4e75dbb1e4 100644 --- a/spec/fixtures/pages/onkeyup.html +++ b/spec/fixtures/pages/onkeyup.html @@ -2,7 +2,7 @@ diff --git a/spec/fixtures/pages/onmouseup.html b/spec/fixtures/pages/onmouseup.html index ea486fdf80..123825a28f 100644 --- a/spec/fixtures/pages/onmouseup.html +++ b/spec/fixtures/pages/onmouseup.html @@ -2,7 +2,7 @@ diff --git a/spec/fixtures/pages/window-open-size.html b/spec/fixtures/pages/window-open-size.html index 7b06cfddf5..b32e39889a 100644 --- a/spec/fixtures/pages/window-open-size.html +++ b/spec/fixtures/pages/window-open-size.html @@ -1,7 +1,7 @@ diff --git a/spec/fixtures/pages/window-opener.html b/spec/fixtures/pages/window-opener.html index a7b59bd1a4..58a8b6ea1a 100644 --- a/spec/fixtures/pages/window-opener.html +++ b/spec/fixtures/pages/window-opener.html @@ -4,7 +4,7 @@ if (window.opener !== null) window.opener.postMessage(typeof window.opener, '*'); else - require('ipc-renderer').send('opener', window.opener); + require('electron').ipcRenderer.send('opener', window.opener); diff --git a/spec/node-spec.coffee b/spec/node-spec.coffee index 969fc76f41..e6b2aa1582 100644 --- a/spec/node-spec.coffee +++ b/spec/node-spec.coffee @@ -3,7 +3,8 @@ child_process = require 'child_process' fs = require 'fs' path = require 'path' os = require 'os' -remote = require 'remote' + +{remote} = require 'electron' describe 'node feature', -> fixtures = path.join __dirname, 'fixtures' diff --git a/spec/static/index.html b/spec/static/index.html index e7c69f5ba7..ea86f6ee30 100644 --- a/spec/static/index.html +++ b/spec/static/index.html @@ -14,22 +14,25 @@ process.throwDeprecation = true; // Check if we are running in CI. - var argv = require('remote').process.argv; + var electron = require ('electron'); + var remote = electron.remote; + var ipcRenderer = electron.ipcRenderer; + + var argv = remote.process.argv; var isCi = argv[2] == '--ci'; if (!isCi) { - var win = require('remote').getCurrentWindow(); + var win = remote.getCurrentWindow(); win.show(); win.focus(); } // Show DevTools. document.oncontextmenu = function(e) { - require('remote').getCurrentWindow().inspectElement(e.clientX, e.clientY); + remote.getCurrentWindow().inspectElement(e.clientX, e.clientY); } require('coffee-script/register'); // Supports .coffee tests. - var ipc = require('ipc-renderer'); // Rediret all output to browser. if (isCi) { @@ -37,11 +40,11 @@ return { log: function() { args = Array.prototype.slice.call(arguments); - ipc.send('console.log', args); + ipcRenderer.send('console.log', args); }, error: function() { args = Array.prototype.slice.call(arguments); - ipc.send('console.error', args); + ipcRenderer.send('console.error', args); }, } }); @@ -70,7 +73,7 @@ var runner = mocha.run(function() { Mocha.utils.highlightTags('code'); if (isCi) - ipc.send('process.exit', runner.failures); + ipcRenderer.send('process.exit', runner.failures); }); }); })(); diff --git a/spec/static/main.js b/spec/static/main.js index 70c47cc37e..e071474f9a 100644 --- a/spec/static/main.js +++ b/spec/static/main.js @@ -1,8 +1,10 @@ -var app = require('app'); -var ipc = require('ipc-main'); -var dialog = require('dialog'); -var path = require('path'); -var BrowserWindow = require('browser-window'); +const electron = require('electron'); +const app = electron.app; +const ipcMain = electron.ipcMain; +const dialog = electron.dialog; +const BrowserWindow = electron.BrowserWindow; + +const path = require('path'); var window = null; process.port = 0; // will be used by crash-reporter spec. @@ -16,27 +18,27 @@ app.commandLine.appendSwitch('disable-renderer-backgrounding'); // sure we can reproduce it in renderer process. process.stdout; -ipc.on('message', function(event, arg) { +ipcMain.on('message', function(event, arg) { event.sender.send('message', arg); }); -ipc.on('console.log', function(event, args) { +ipcMain.on('console.log', function(event, args) { console.error.apply(console, args); }); -ipc.on('console.error', function(event, args) { +ipcMain.on('console.error', function(event, args) { console.error.apply(console, args); }); -ipc.on('process.exit', function(event, code) { +ipcMain.on('process.exit', function(event, code) { process.exit(code); }); -ipc.on('eval', function(event, script) { +ipcMain.on('eval', function(event, script) { event.returnValue = eval(script); }); -ipc.on('echo', function(event, msg) { +ipcMain.on('echo', function(event, msg) { event.returnValue = msg; }); @@ -54,7 +56,7 @@ app.on('window-all-closed', function() { app.on('ready', function() { // Test if using protocol module would crash. - require('protocol').registerStringProtocol('test-if-crashes', function() {}); + electron.protocol.registerStringProtocol('test-if-crashes', function() {}); window = new BrowserWindow({ title: 'Electron Tests', @@ -79,7 +81,7 @@ app.on('ready', function() { // For session's download test, listen 'will-download' event in browser, and // reply the result to renderer for verifying var downloadFilePath = path.join(__dirname, '..', 'fixtures', 'mock.pdf'); - ipc.on('set-download-option', function(event, need_cancel) { + ipcMain.on('set-download-option', function(event, need_cancel) { window.webContents.session.once('will-download', function(e, item, webContents) { item.setSavePath(downloadFilePath); From 8b2942c2795d2371aea0dacfddd2b58a66752c58 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 12 Nov 2015 20:30:40 +0800 Subject: [PATCH 06/31] Optimize remote.require('electron') --- atom/browser/api/lib/exports/electron.coffee | 3 +++ atom/browser/lib/rpc-server.coffee | 18 ++++++++++++++++-- atom/common/api/lib/exports/electron.coffee | 2 +- atom/renderer/api/lib/remote.coffee | 19 ++++++++++++++++++- 4 files changed, 38 insertions(+), 4 deletions(-) diff --git a/atom/browser/api/lib/exports/electron.coffee b/atom/browser/api/lib/exports/electron.coffee index a09a6441c3..6f70e6b38b 100644 --- a/atom/browser/api/lib/exports/electron.coffee +++ b/atom/browser/api/lib/exports/electron.coffee @@ -1,6 +1,9 @@ # 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: diff --git a/atom/browser/lib/rpc-server.coffee b/atom/browser/lib/rpc-server.coffee index 3479f30f0b..5c67026deb 100644 --- a/atom/browser/lib/rpc-server.coffee +++ b/atom/browser/lib/rpc-server.coffee @@ -1,5 +1,7 @@ -{ipcMain} = require 'electron' path = require 'path' + +electron = require 'electron' +{ipcMain} = electron objectsRegistry = require './objects-registry' v8Util = process.atomBinding 'v8_util' @@ -14,7 +16,11 @@ valueToMeta = (sender, value, optimizeSimpleObject=false) -> meta.type = 'array' if Array.isArray value meta.type = 'error' if value instanceof Error 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. if optimizeSimpleObject and meta.type is 'object' and v8Util.getHiddenValue value, 'simple' @@ -43,6 +49,8 @@ valueToMeta = (sender, value, optimizeSimpleObject=false) -> meta.members = plainObjectToMeta value else if meta.type is 'date' meta.value = value.getTime() + else if meta.type is 'electronModule' + meta.members = (name for name of value) else meta.type = 'value' meta.value = value @@ -122,6 +130,12 @@ ipcMain.on 'ATOM_BROWSER_REQUIRE', (event, module) -> catch e event.returnValue = exceptionToMeta e +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 event.returnValue = valueToMeta event.sender, global[name] diff --git a/atom/common/api/lib/exports/electron.coffee b/atom/common/api/lib/exports/electron.coffee index 26e8ce2f18..7bcb23a2ca 100644 --- a/atom/common/api/lib/exports/electron.coffee +++ b/atom/common/api/lib/exports/electron.coffee @@ -4,7 +4,7 @@ Object.defineProperties exports, # Must be enumerable, otherwise it woulde be invisible to remote module. enumerable: true get: -> require '../clipboard' - crashRepoter: + crashReporter: enumerable: true get: -> require '../crash-reporter' nativeImage: diff --git a/atom/renderer/api/lib/remote.coffee b/atom/renderer/api/lib/remote.coffee index 9faed14bf5..09e7dcdcb5 100644 --- a/atom/renderer/api/lib/remote.coffee +++ b/atom/renderer/api/lib/remote.coffee @@ -18,7 +18,7 @@ wrapArgs = (args, visited=[]) -> type: 'array', value: wrapArgs(value, visited) else if Buffer.isBuffer value 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)) else if value? and typeof value is 'object' and v8Util.getHiddenValue value, 'atomId' type: 'remote-object', id: v8Util.getHiddenValue value, 'atomId' @@ -49,6 +49,15 @@ metaToValue = (meta) -> when 'date' then new Date(meta.value) when 'exception' 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 if meta.type is 'function' # A shadow class to represent the remote function object. @@ -135,6 +144,14 @@ exports.require = (module) -> meta = ipcRenderer.sendSync 'ATOM_BROWSER_REQUIRE', module 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. windowCache = null exports.getCurrentWindow = -> From eac2e7cc614d4e98e2828921f63d55f7b5e2c85c Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 12 Nov 2015 21:20:09 +0800 Subject: [PATCH 07/31] docs: Update codes in docs to use require('electron') --- docs/README.md | 30 +++++++++---------- docs/api/app.md | 2 +- docs/api/browser-window.md | 13 +------- docs/api/chrome-command-line-switches.md | 2 +- docs/api/clipboard.md | 5 +--- docs/api/content-tracing.md | 2 +- docs/api/crash-reporter.md | 4 +-- docs/api/dialog.md | 6 ++-- docs/api/frameless-window.md | 5 ++-- docs/api/global-shortcut.md | 5 ++-- docs/api/ipc-main.md | 4 +-- docs/api/menu.md | 10 +++---- docs/api/native-image.md | 29 +++++++++--------- docs/api/power-monitor.md | 6 ++-- docs/api/power-save-blocker.md | 4 +-- docs/api/protocol.md | 7 +++-- docs/api/remote.md | 18 ++++++----- docs/api/screen.md | 21 ++++++------- docs/api/session.md | 4 +-- docs/api/shell.md | 2 +- docs/api/synopsis.md | 9 +++--- docs/api/tray.md | 7 +++-- docs/api/web-contents.md | 14 ++++----- docs/api/web-frame.md | 4 +-- docs/api/web-view-tag.md | 8 ++--- docs/tutorial/application-packaging.md | 6 ++-- .../desktop-environment-integration.md | 13 ++++---- docs/tutorial/devtools-extension.md | 5 ++-- docs/tutorial/online-offline-events.md | 18 ++++++----- docs/tutorial/quick-start.md | 7 +++-- docs/tutorial/using-pepper-flash-plugin.md | 17 ----------- docs/tutorial/using-selenium-and-webdriver.md | 4 +-- 32 files changed, 134 insertions(+), 157 deletions(-) diff --git a/docs/README.md b/docs/README.md index fb5c64a8f1..208ff8bf47 100644 --- a/docs/README.md +++ b/docs/README.md @@ -31,32 +31,32 @@ ### Modules for the Main Process: * [app](api/app.md) -* [auto-updater](api/auto-updater.md) -* [browser-window](api/browser-window.md) -* [content-tracing](api/content-tracing.md) +* [autoUpdater](api/auto-updater.md) +* [BrowserWindow](api/browser-window.md) +* [contentTracing](api/content-tracing.md) * [dialog](api/dialog.md) -* [global-shortcut](api/global-shortcut.md) -* [ipc-main](api/ipc-main.md) -* [menu](api/menu.md) -* [menu-item](api/menu-item.md) -* [power-monitor](api/power-monitor.md) -* [power-save-blocker](api/power-save-blocker.md) +* [globalShortcut](api/global-shortcut.md) +* [ipcMain](api/ipc-main.md) +* [Menu](api/menu.md) +* [MenuItem](api/menu-item.md) +* [powerMonitor](api/power-monitor.md) +* [powerSaveBlocker](api/power-save-blocker.md) * [protocol](api/protocol.md) * [session](api/session.md) -* [web-contents](api/web-contents.md) -* [tray](api/tray.md) +* [webContents](api/web-contents.md) +* [Tray](api/tray.md) ### Modules for the Renderer Process (Web Page): -* [ipc-renderer](api/ipc-renderer.md) +* [ipcRenderer](api/ipc-renderer.md) * [remote](api/remote.md) -* [web-frame](api/web-frame.md) +* [webFrame](api/web-frame.md) ### Modules for Both Processes: * [clipboard](api/clipboard.md) -* [crash-reporter](api/crash-reporter.md) -* [native-image](api/native-image.md) +* [crashReporter](api/crash-reporter.md) +* [nativeImage](api/native-image.md) * [screen](api/screen.md) * [shell](api/shell.md) diff --git a/docs/api/app.md b/docs/api/app.md index fdb9f99805..1edc40fb89 100644 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -6,7 +6,7 @@ The following example shows how to quit the application when the last window is closed: ```javascript -var app = require('app'); +const app = require('electron').app; app.on('window-all-closed', function() { app.quit(); }); diff --git a/docs/api/browser-window.md b/docs/api/browser-window.md index 0499b6355a..670c814c74 100644 --- a/docs/api/browser-window.md +++ b/docs/api/browser-window.md @@ -4,7 +4,7 @@ The `BrowserWindow` class gives you the ability to create a browser window. For example: ```javascript -var BrowserWindow = require('browser-window'); +const BrowserWindow = require('electron').BrowserWindow; var win = new BrowserWindow({ width: 800, height: 600, show: false }); 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: ```javascript -var BrowserWindow = require('browser-window'); - // In this example `win` is our instance var win = new BrowserWindow({ width: 800, height: 600 }); - ``` ### `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. -```javascript -var BrowserWindow = require('browser-window'); - -// In this example `win` is our instance -var win = new BrowserWindow({ width: 800, height: 600 }); - -``` - ### `win.destroy()` Force closing the window, the `unload` and `beforeunload` event won't be emitted diff --git a/docs/api/chrome-command-line-switches.md b/docs/api/chrome-command-line-switches.md index 96dffb9631..d163a726d4 100644 --- a/docs/api/chrome-command-line-switches.md +++ b/docs/api/chrome-command-line-switches.md @@ -6,7 +6,7 @@ them in your app's main script before the [ready][ready] event of [app][app] module is emitted: ```javascript -var app = require('app'); +const app = require('electron').app; app.commandLine.appendSwitch('remote-debugging-port', '8315'); app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1'); diff --git a/docs/api/clipboard.md b/docs/api/clipboard.md index a99605baea..7cb5b840bc 100644 --- a/docs/api/clipboard.md +++ b/docs/api/clipboard.md @@ -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: ```javascript -var clipboard = require('clipboard'); +const clipboard = require('electron').clipboard; 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: ```javascript -var clipboard = require('clipboard'); clipboard.writeText('Example String', '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`. ```javascript -var clipboard = require('clipboard'); console.log(clipboard.has('

selection

')); ``` @@ -102,7 +100,6 @@ Reads `data` from the clipboard. * `type` String (optional) ```javascript -var clipboard = require('clipboard'); clipboard.write({text: 'test', html: "test"}); ``` Writes `data` to the clipboard. diff --git a/docs/api/content-tracing.md b/docs/api/content-tracing.md index 2e05fc6766..734e2c47cf 100644 --- a/docs/api/content-tracing.md +++ b/docs/api/content-tracing.md @@ -6,7 +6,7 @@ so you need to open `chrome://tracing/` in a Chrome browser and load the generated file to view the result. ```javascript -var contentTracing = require('content-tracing'); +const contentTracing = require('electron').contentTracing; contentTracing.startRecording('*', contentTracing.DEFAULT_OPTIONS, function() { console.log('Tracing started'); diff --git a/docs/api/crash-reporter.md b/docs/api/crash-reporter.md index 64a3b2cf74..8127c9bc1c 100644 --- a/docs/api/crash-reporter.md +++ b/docs/api/crash-reporter.md @@ -6,7 +6,7 @@ The following is an example of automatically submitting a crash report to a remote server: ```javascript -var crashReporter = require('crash-reporter'); +const crashReporter = require('electron').crashReporter; crashReporter.start({ productName: 'YourName', @@ -62,7 +62,7 @@ The crash reporter will send the following data to the `submitUrl` as `POST`: * `ver` String - The version of Electron. * `platform` String - e.g. 'win32'. * `process_type` String - e.g. 'renderer'. -* `guid` String - e.g. '5e1286fc-da97-479e-918b-6bfb0c3d1c72' +* `guid` String - e.g. '5e1286fc-da97-479e-918b-6bfb0c3d1c72' * `_version` String - The version in `package.json`. * `_productName` String - The product name in the `crashReporter` `options` object. diff --git a/docs/api/dialog.md b/docs/api/dialog.md index 6acfb79884..884fb7c073 100644 --- a/docs/api/dialog.md +++ b/docs/api/dialog.md @@ -8,7 +8,7 @@ An example of showing a dialog to select multiple files and directories: ```javascript 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' ]})); ``` @@ -114,6 +114,6 @@ will be passed via `callback(response)`. Displays a modal dialog that shows an error message. This API can be called safely before the `ready` event the `app` module emits, -it is usually used to report errors in early stage of startup. If called -before the app `ready`event on Linux, the message will be emitted to stderr, +it is usually used to report errors in early stage of startup. If called +before the app `ready`event on Linux, the message will be emitted to stderr, and no GUI dialog will appear. diff --git a/docs/api/frameless-window.md b/docs/api/frameless-window.md index 707a928f9d..e70749f289 100644 --- a/docs/api/frameless-window.md +++ b/docs/api/frameless-window.md @@ -9,7 +9,7 @@ To create a frameless window, you need to set `frame` to `false` in ```javascript -var BrowserWindow = require('browser-window'); +const BrowserWindow = require('electron').BrowserWindow; 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: ```javascript -var BrowserWindow = require('browser-window'); -var win = new BrowserWindow({ width: 800, height: 600, 'title-bar-style': 'hidden' }); +var win = new BrowserWindow({ 'title-bar-style': 'hidden' }); ``` ## Transparent window diff --git a/docs/api/global-shortcut.md b/docs/api/global-shortcut.md index c9dfb19452..a0f069d7f1 100644 --- a/docs/api/global-shortcut.md +++ b/docs/api/global-shortcut.md @@ -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. ```javascript -var app = require('app'); -var globalShortcut = require('global-shortcut'); +const electron = require('electron'); +const app = electron.app; +const globalShortcut = electron.globalShortcut; app.on('ready', function() { // Register a 'ctrl+x' shortcut listener. diff --git a/docs/api/ipc-main.md b/docs/api/ipc-main.md index f74c70426a..cdbc0ce34e 100644 --- a/docs/api/ipc-main.md +++ b/docs/api/ipc-main.md @@ -19,7 +19,7 @@ processes: ```javascript // In main process. -var ipcMain = require('ipc-main'); +const ipcMain = require('electron').ipcMain; ipcMain.on('asynchronous-message', function(event, arg) { console.log(arg); // prints "ping" event.sender.send('asynchronous-reply', 'pong'); @@ -33,7 +33,7 @@ ipcMain.on('synchronous-message', function(event, arg) { ```javascript // In renderer process (web page). -var ipcRenderer = require('ipc-renderer'); +const ipcRenderer = require('electron').ipcRenderer; console.log(ipcRenderer.sendSync('synchronous-message', 'ping')); // prints "pong" ipcRenderer.on('asynchronous-reply', function(event, arg) { diff --git a/docs/api/menu.md b/docs/api/menu.md index cabd04ca85..c947f36d47 100644 --- a/docs/api/menu.md +++ b/docs/api/menu.md @@ -16,9 +16,9 @@ the user right clicks the page: ```html diff --git a/docs/api/tray.md b/docs/api/tray.md index 47f02c5478..ff4310308a 100644 --- a/docs/api/tray.md +++ b/docs/api/tray.md @@ -4,9 +4,10 @@ A `Tray` represents an icon in an operating system's notification area, it is usually attached with a context menu. ```javascript -var app = require('app'); -var Menu = require('menu'); -var Tray = require('tray'); +const electron = require('electron'); +const app = electron.app; +const Menu = electron.Menu; +const Tray = electron.Tray; var appIcon = null; app.on('ready', function(){ diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index d62706b2ba..aff5752ab5 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -8,7 +8,7 @@ the [`BrowserWindow`](browser-window.md) object. An example of accessing the `webContents` object: ```javascript -var BrowserWindow = require('browser-window'); +const BrowserWindow = require('electron').BrowserWindow; var win = new BrowserWindow({width: 800, height: 1500}); win.loadUrl("http://github.com"); @@ -211,17 +211,15 @@ e.g. the `http://` or `file://`. ### `webContents.getUrl()` -```javascript -var BrowserWindow = require('browser-window'); +Returns URL of the current web page. +```javascript var win = new BrowserWindow({width: 800, height: 600}); win.loadUrl("http://github.com"); var currentUrl = win.webContents.getUrl(); ``` -Returns URL of the current web page. - ### `webContents.getTitle()` Returns the title of the current web page. @@ -445,8 +443,8 @@ By default, an empty `options` will be regarded as: ``` ```javascript -var BrowserWindow = require('browser-window'); -var fs = require('fs'); +const BrowserWindow = require('electron').BrowserWindow; +const fs = require('fs'); var win = new BrowserWindow({width: 800, height: 600}); win.loadUrl("http://github.com"); @@ -538,7 +536,7 @@ app.on('ready', function() { diff --git a/docs/api/web-frame.md b/docs/api/web-frame.md index 33597543b7..c9cfb48f34 100644 --- a/docs/api/web-frame.md +++ b/docs/api/web-frame.md @@ -6,7 +6,7 @@ web page. An example of zooming current page to 200%. ```javascript -var webFrame = require('web-frame'); +var webFrame = require('electron').webFrame; webFrame.setZoomFactor(2); ``` @@ -59,7 +59,7 @@ whether the word passed is correctly spelled. An example of using [node-spellchecker][spellchecker] as provider: ```javascript -require('web-frame').setSpellCheckProvider("en-US", true, { +webFrame.setSpellCheckProvider("en-US", true, { spellCheck: function(text) { return !(require('spellchecker').isMisspelled(text)); } diff --git a/docs/api/web-view-tag.md b/docs/api/web-view-tag.md index 9a0e0be33b..a12ec44713 100644 --- a/docs/api/web-view-tag.md +++ b/docs/api/web-view-tag.md @@ -515,7 +515,7 @@ The following example code opens the new url in system's default browser. ```javascript 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 // In guest page. -var ipc = require('ipc'); -ipc.on('ping', function() { - ipc.sendToHost('pong'); +var ipcRenderer = require('electron').ipcRenderer; +ipcRenderer.on('ping', function() { + ipcRenderer.sendToHost('pong'); }); ``` diff --git a/docs/tutorial/application-packaging.md b/docs/tutorial/application-packaging.md index 0cf3a6b596..7c1ea773e2 100644 --- a/docs/tutorial/application-packaging.md +++ b/docs/tutorial/application-packaging.md @@ -51,14 +51,14 @@ $ asar list /path/to/example.asar Read a file in the `asar` archive: ```javascript -var fs = require('fs'); +const fs = require('fs'); fs.readFileSync('/path/to/example.asar/file.txt'); ``` List all files under the root of the archive: ```javascript -var fs = require('fs'); +const fs = require('fs'); 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`: ```javascript -var BrowserWindow = require('browser-window'); +const BrowserWindow = require('electron').BrowserWindow; var win = new BrowserWindow({width: 800, height: 600}); win.loadUrl('file:///path/to/example.asar/static/index.html'); ``` diff --git a/docs/tutorial/desktop-environment-integration.md b/docs/tutorial/desktop-environment-integration.md index 39f74ff107..7c4807d8f4 100644 --- a/docs/tutorial/desktop-environment-integration.md +++ b/docs/tutorial/desktop-environment-integration.md @@ -86,7 +86,6 @@ To add a file to recent documents, you can use the [app.addRecentDocument][addrecentdocument] API: ```javascript -var app = require('app'); 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: ```javascript -var app = require('app'); -var Menu = require('menu'); +const electron = require('electron'); +const app = electron.app; +const Menu = electron.Menu; + var dockMenu = Menu.buildFromTemplate([ { label: 'New Window', click: function() { console.log('New Window'); } }, { label: 'New Window with Settings', submenu: [ @@ -172,7 +173,6 @@ To set user tasks for your application, you can use [app.setUserTasks][setusertaskstasks] API: ```javascript -var app = require('app'); app.setUserTasks([ { program: process.execPath, @@ -220,8 +220,9 @@ You can use [BrowserWindow.setThumbarButtons][setthumbarbuttons] to set thumbnail toolbar in your application: ```javascript -var BrowserWindow = require('browser-window'); -var path = require('path'); +const BrowserWindow = require('electron').BrowserWindow; +const path = require('path'); + var win = new BrowserWindow({ width: 800, height: 600 diff --git a/docs/tutorial/devtools-extension.md b/docs/tutorial/devtools-extension.md index 8a2144be69..258fb41947 100644 --- a/docs/tutorial/devtools-extension.md +++ b/docs/tutorial/devtools-extension.md @@ -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: ```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` API with its name and it will not load the next time you open the DevTools: ```javascript -require('remote').require('browser-window').removeDevToolsExtension('React Developer Tools'); +BrowserWindow.removeDevToolsExtension('React Developer Tools'); ``` ## Format of DevTools Extension diff --git a/docs/tutorial/online-offline-events.md b/docs/tutorial/online-offline-events.md index 46d659e07d..6e031282b5 100644 --- a/docs/tutorial/online-offline-events.md +++ b/docs/tutorial/online-offline-events.md @@ -6,10 +6,11 @@ using standard HTML5 APIs, as shown in the following example. _main.js_ ```javascript -var app = require('app'); -var BrowserWindow = require('browser-window'); -var onlineStatusWindow; +const electron = require('electron'); +const app = electron.app; +const BrowserWindow = electron.BrowserWindow; +var onlineStatusWindow; app.on('ready', function() { onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false }); 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_ ```javascript -var app = require('app'); -var ipcMain = require('ipc-main'); -var BrowserWindow = require('browser-window'); -var onlineStatusWindow; +const electron = require('electron'); +const app = electron.app; +const ipcMain = electron.ipcMain; +const BrowserWindow = electron.BrowserWindow; +var onlineStatusWindow; app.on('ready', function() { onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false }); onlineStatusWindow.loadUrl('file://' + __dirname + '/online-status.html'); @@ -67,7 +69,7 @@ _online-status.html_ - + + + ``` 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 From edd807d2271634dbe1228f13863a034e5801ed29 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 12 Nov 2015 22:56:18 +0800 Subject: [PATCH 11/31] Fix a typo --- atom/browser/api/lib/app.coffee | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/atom/browser/api/lib/app.coffee b/atom/browser/api/lib/app.coffee index 0113e90a1a..3494a6e6e4 100644 --- a/atom/browser/api/lib/app.coffee +++ b/atom/browser/api/lib/app.coffee @@ -9,10 +9,10 @@ app = bindings.app app.__proto__ = EventEmitter.prototype app.setApplicationMenu = (menu) -> - electron.menu.setApplicationMenu menu + electron.Menu.setApplicationMenu menu app.getApplicationMenu = -> - electron.menu.getApplicationMenu() + electron.Menu.getApplicationMenu() app.commandLine = appendSwitch: bindings.appendSwitch, From ce6a7c7d088eb0dc387a99c6ed74fd9ee839a0eb Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 12 Nov 2015 23:02:39 +0800 Subject: [PATCH 12/31] spec: Disable old APIs in tests --- script/test.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/script/test.py b/script/test.py index 28aeac9dc1..7f75d3113d 100755 --- a/script/test.py +++ b/script/test.py @@ -16,6 +16,9 @@ PRODUCT_NAME = atom_gyp()['product_name%'] def main(): os.chdir(SOURCE_ROOT) + # Disable old APIs + os.environ['ELECTRON_HIDE_INTERNAL_MODULES'] = 'true' + config = 'D' if len(sys.argv) == 2 and sys.argv[1] == '-R': config = 'R' From 3d5437e0a45b884d850ff125d38c0c49edc4d86f Mon Sep 17 00:00:00 2001 From: Robo Date: Fri, 13 Nov 2015 02:36:38 +0530 Subject: [PATCH 13/31] tracing: fix docs and allow null values in file path conversion fromv8 --- atom/common/native_mate_converters/file_path_converter.h | 3 +++ docs/api/content-tracing.md | 9 +++++++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/atom/common/native_mate_converters/file_path_converter.h b/atom/common/native_mate_converters/file_path_converter.h index 468f506de8..7df1289e24 100644 --- a/atom/common/native_mate_converters/file_path_converter.h +++ b/atom/common/native_mate_converters/file_path_converter.h @@ -21,6 +21,9 @@ struct Converter { static bool FromV8(v8::Isolate* isolate, v8::Local val, base::FilePath* out) { + if (val->IsNull()) + return true; + base::FilePath::StringType path; if (Converter::FromV8(isolate, val, &path)) { *out = base::FilePath(path); diff --git a/docs/api/content-tracing.md b/docs/api/content-tracing.md index 2e05fc6766..9fc335b3bc 100644 --- a/docs/api/content-tracing.md +++ b/docs/api/content-tracing.md @@ -6,9 +6,14 @@ so you need to open `chrome://tracing/` in a Chrome browser and load the generated file to view the result. ```javascript -var contentTracing = require('content-tracing'); +const contentTracing = require('content-tracing'); -contentTracing.startRecording('*', contentTracing.DEFAULT_OPTIONS, function() { +const options = { + categoryFilter: '*', + traceOptions: 'record-until-full,enable-sampling' +} + +contentTracing.startRecording(options, function() { console.log('Tracing started'); setTimeout(function() { From bb439c5f1c1a6a4af88f80067bc7eac262c11dff Mon Sep 17 00:00:00 2001 From: Robo Date: Fri, 13 Nov 2015 02:43:21 +0530 Subject: [PATCH 14/31] browser: check window liveness before setting title --- atom/browser/native_window.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/atom/browser/native_window.cc b/atom/browser/native_window.cc index 8027fdfa4c..ba5dad74f5 100644 --- a/atom/browser/native_window.cc +++ b/atom/browser/native_window.cc @@ -512,7 +512,7 @@ void NativeWindow::TitleWasSet(content::NavigationEntry* entry, FOR_EACH_OBSERVER(NativeWindowObserver, observers_, OnPageTitleUpdated(&prevent_default, text)); - if (!prevent_default) + if (!prevent_default && !is_closed_) SetTitle(text); } From 852500e5faade74d7cf41f257150af7f6c752a63 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 13 Nov 2015 09:38:22 +0800 Subject: [PATCH 15/31] Fix a few places using old style require --- atom/browser/api/lib/auto-updater/auto-updater-win.coffee | 4 ++-- atom/common/api/lib/clipboard.coffee | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/atom/browser/api/lib/auto-updater/auto-updater-win.coffee b/atom/browser/api/lib/auto-updater/auto-updater-win.coffee index a9a61d8efe..12ebedaaf7 100644 --- a/atom/browser/api/lib/auto-updater/auto-updater-win.coffee +++ b/atom/browser/api/lib/auto-updater/auto-updater-win.coffee @@ -1,6 +1,6 @@ -app = require 'app' -url = require 'url' +{app} = require 'electron' {EventEmitter} = require 'events' +url = require 'url' squirrelUpdate = require './squirrel-update-win' diff --git a/atom/common/api/lib/clipboard.coffee b/atom/common/api/lib/clipboard.coffee index b337f71950..0ea97d86ba 100644 --- a/atom/common/api/lib/clipboard.coffee +++ b/atom/common/api/lib/clipboard.coffee @@ -1,6 +1,6 @@ if process.platform is 'linux' and process.type is 'renderer' {remote} = require 'electron' # On Linux we could not access clipboard in renderer process. - module.exports = remote.require 'clipboard' + module.exports = remote.getBuiltin 'clipboard' else module.exports = process.atomBinding 'clipboard' From bfaa50a79ea2c28c7a0c71fde17efd048ed6eaff Mon Sep 17 00:00:00 2001 From: Robo Date: Fri, 13 Nov 2015 07:44:05 +0530 Subject: [PATCH 16/31] retrieve download directory using on linux --- atom/browser/api/atom_api_app.cc | 17 ++++++++++++++++- docs/api/app.md | 1 + 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index 1c5c2c04f1..d6d961a08d 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -22,6 +22,7 @@ #include "base/command_line.h" #include "base/environment.h" #include "base/files/file_path.h" +#include "base/nix/xdg_util.h" #include "base/path_service.h" #include "brightray/browser/brightray_paths.h" #include "content/public/browser/client_certificate_delegate.h" @@ -155,6 +156,17 @@ void PassLoginInformation(scoped_refptr login_handler, login_handler->CancelAuth(); } +bool GetUserDownloadsDirectory(base::FilePath* path) { +#if defined(OS_LINUX) + *path = base::nix::GetXDGUserDirectory("DOWNLOAD", "Downloads"); + return true; +#elif defined(OS_MACOSX) + return false; +#elif defined(OS_WIN) + return false; +#endif +} + } // namespace App::App() { @@ -272,8 +284,11 @@ base::FilePath App::GetPath(mate::Arguments* args, const std::string& name) { int key = GetPathConstant(name); if (key >= 0) succeed = PathService::Get(key, &path); - if (!succeed) + if (!succeed) { + if (name == "downloads" && GetUserDownloadsDirectory(&path)) + return path; args->ThrowError("Failed to get path"); + } return path; } diff --git a/docs/api/app.md b/docs/api/app.md index fdb9f99805..4282b2d133 100644 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -241,6 +241,7 @@ You can request the following paths by the name: * `userDesktop` The current user's Desktop directory. * `exe` The current executable file. * `module` The `libchromiumcontent` library. +* `downloads` User's download directory. ### `app.setPath(name, path)` From f2439cefd0dba89df02993011ac46dd32a1f79a6 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 13 Nov 2015 10:58:10 +0800 Subject: [PATCH 17/31] linux: Don't throw error when using autoUpdater Fix #3194. --- atom/browser/api/lib/auto-updater.coffee | 10 ++++------ ...o-updater-mac.coffee => auto-updater-native.coffee} | 0 filenames.gypi | 2 +- 3 files changed, 5 insertions(+), 7 deletions(-) rename atom/browser/api/lib/auto-updater/{auto-updater-mac.coffee => auto-updater-native.coffee} (100%) diff --git a/atom/browser/api/lib/auto-updater.coffee b/atom/browser/api/lib/auto-updater.coffee index 41b78a00d7..d5e69e2a5c 100644 --- a/atom/browser/api/lib/auto-updater.coffee +++ b/atom/browser/api/lib/auto-updater.coffee @@ -1,7 +1,5 @@ -switch process.platform - when 'win32' - module.exports = require './auto-updater/auto-updater-win' - when 'darwin' - module.exports = require './auto-updater/auto-updater-mac' +module.exports = + if process.platform is 'win32' + require './auto-updater/auto-updater-win' else - throw new Error('auto-updater is not implemented on this platform') + require './auto-updater/auto-updater-native' diff --git a/atom/browser/api/lib/auto-updater/auto-updater-mac.coffee b/atom/browser/api/lib/auto-updater/auto-updater-native.coffee similarity index 100% rename from atom/browser/api/lib/auto-updater/auto-updater-mac.coffee rename to atom/browser/api/lib/auto-updater/auto-updater-native.coffee diff --git a/filenames.gypi b/filenames.gypi index de7ee26c5e..658c8e76b6 100644 --- a/filenames.gypi +++ b/filenames.gypi @@ -10,7 +10,7 @@ 'coffee_sources': [ 'atom/browser/api/lib/app.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/squirrel-update-win.coffee', 'atom/browser/api/lib/browser-window.coffee', From 78934dceb9dee799b07aedd8c3bdc1ddf42cae6c Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 13 Nov 2015 12:22:08 +0800 Subject: [PATCH 18/31] Cleanup and docs for the --js-flags --- atom/browser/javascript_environment.cc | 17 +++++++---------- docs/api/chrome-command-line-switches.md | 9 +++++++++ 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/atom/browser/javascript_environment.cc b/atom/browser/javascript_environment.cc index ae4f8e55e7..dc27cedee5 100644 --- a/atom/browser/javascript_environment.cc +++ b/atom/browser/javascript_environment.cc @@ -2,11 +2,12 @@ // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. -#include - #include "atom/browser/javascript_environment.h" +#include + #include "base/command_line.h" +#include "content/public/common/content_switches.h" #include "gin/array_buffer.h" #include "gin/v8_initializer.h" @@ -30,17 +31,13 @@ bool JavascriptEnvironment::Initialize() { v8::V8::SetFlagsFromString(expose_debug_as, sizeof(expose_debug_as) - 1); } - const std::string js_flags_switch = "js-flags"; - - if (cmd->HasSwitch(js_flags_switch)) { - const char *js_flags_value = - (cmd->GetSwitchValueASCII(js_flags_switch)).c_str(); - v8::V8::SetFlagsFromString(js_flags_value, strlen(js_flags_value)); - } + // --js-flags. + std::string js_flags = cmd->GetSwitchValueASCII(switches::kJavaScriptFlags); + if (!js_flags.empty()) + v8::V8::SetFlagsFromString(js_flags.c_str(), js_flags.size()); gin::IsolateHolder::Initialize(gin::IsolateHolder::kNonStrictMode, gin::ArrayBufferAllocator::SharedInstance()); - return true; } diff --git a/docs/api/chrome-command-line-switches.md b/docs/api/chrome-command-line-switches.md index d163a726d4..c1adf3c425 100644 --- a/docs/api/chrome-command-line-switches.md +++ b/docs/api/chrome-command-line-switches.md @@ -31,6 +31,15 @@ Disables the disk cache for HTTP requests. Enables remote debugging over HTTP on the specified `port`. +## --js-flags=`flags` + +Specifies the flags passed to JS engine. It has to be passed when starting +Electron if you want to enable the `flags` in the main process. + +```bash +$ electron --js-flags="--harmony_proxies --harmony_collections" your-app +``` + ## --proxy-server=`address:port` Use a specified proxy server, which overrides the system setting. This switch From 83ae9f8d71007944b9f9e5b631740ea7a416e1b9 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 13 Nov 2015 12:37:12 +0800 Subject: [PATCH 19/31] Import the chrome_paths code --- .../chrome/common/chrome_constants.cc | 68 ++ chromium_src/chrome/common/chrome_constants.h | 50 ++ chromium_src/chrome/common/chrome_paths.cc | 610 ++++++++++++++++++ chromium_src/chrome/common/chrome_paths.h | 152 +++++ .../chrome/common/chrome_paths_internal.h | 112 ++++ .../chrome/common/chrome_paths_linux.cc | 145 +++++ .../chrome/common/chrome_paths_mac.mm | 252 ++++++++ .../chrome/common/chrome_paths_win.cc | 122 ++++ filenames.gypi | 8 + 9 files changed, 1519 insertions(+) create mode 100644 chromium_src/chrome/common/chrome_constants.cc create mode 100644 chromium_src/chrome/common/chrome_constants.h create mode 100644 chromium_src/chrome/common/chrome_paths.cc create mode 100644 chromium_src/chrome/common/chrome_paths.h create mode 100644 chromium_src/chrome/common/chrome_paths_internal.h create mode 100644 chromium_src/chrome/common/chrome_paths_linux.cc create mode 100644 chromium_src/chrome/common/chrome_paths_mac.mm create mode 100644 chromium_src/chrome/common/chrome_paths_win.cc diff --git a/chromium_src/chrome/common/chrome_constants.cc b/chromium_src/chrome/common/chrome_constants.cc new file mode 100644 index 0000000000..1e7bd33a96 --- /dev/null +++ b/chromium_src/chrome/common/chrome_constants.cc @@ -0,0 +1,68 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/common/chrome_constants.h" +#include "chrome/common/chrome_version.h" + +namespace chrome { + +// filenames +const base::FilePath::CharType kCacheDirname[] = FPL("Cache"); +const base::FilePath::CharType kChannelIDFilename[] = FPL("Origin Bound Certs"); +const base::FilePath::CharType kCookieFilename[] = FPL("Cookies"); +const base::FilePath::CharType kCRLSetFilename[] = + FPL("Certificate Revocation Lists"); +const base::FilePath::CharType kCustomDictionaryFileName[] = + FPL("Custom Dictionary.txt"); +const base::FilePath::CharType kExtensionActivityLogFilename[] = + FPL("Extension Activity"); +const base::FilePath::CharType kExtensionsCookieFilename[] = + FPL("Extension Cookies"); +const base::FilePath::CharType kFirstRunSentinel[] = FPL("First Run"); +const base::FilePath::CharType kGCMStoreDirname[] = FPL("GCM Store"); +const base::FilePath::CharType kLocalStateFilename[] = FPL("Local State"); +const base::FilePath::CharType kLocalStorePoolName[] = FPL("LocalStorePool"); +const base::FilePath::CharType kMediaCacheDirname[] = FPL("Media Cache"); +const base::FilePath::CharType kNetworkPersistentStateFilename[] = + FPL("Network Persistent State"); +const base::FilePath::CharType kOfflinePageArchviesDirname[] = + FPL("Offline Pages/archives"); +const base::FilePath::CharType kOfflinePageMetadataDirname[] = + FPL("Offline Pages/metadata"); +const base::FilePath::CharType kPreferencesFilename[] = FPL("Preferences"); +const base::FilePath::CharType kProtectedPreferencesFilenameDeprecated[] = + FPL("Protected Preferences"); +const base::FilePath::CharType kReadmeFilename[] = FPL("README"); +const base::FilePath::CharType kResetPromptMementoFilename[] = + FPL("Reset Prompt Memento"); +const base::FilePath::CharType kSafeBrowsingBaseFilename[] = + FPL("Safe Browsing"); +const base::FilePath::CharType kSecurePreferencesFilename[] = + FPL("Secure Preferences"); +const base::FilePath::CharType kServiceStateFileName[] = FPL("Service State"); +const base::FilePath::CharType kSingletonCookieFilename[] = + FPL("SingletonCookie"); +const base::FilePath::CharType kSingletonLockFilename[] = FPL("SingletonLock"); +const base::FilePath::CharType kSingletonSocketFilename[] = + FPL("SingletonSocket"); +const base::FilePath::CharType kSupervisedUserSettingsFilename[] = + FPL("Managed Mode Settings"); +const base::FilePath::CharType kThemePackFilename[] = FPL("Cached Theme.pak"); +const base::FilePath::CharType kThemePackMaterialDesignFilename[] = + FPL("Cached Theme Material Design.pak"); +const base::FilePath::CharType kWebAppDirname[] = FPL("Web Applications"); + +// File name of the Pepper Flash plugin on different platforms. +const base::FilePath::CharType kPepperFlashPluginFilename[] = +#if defined(OS_MACOSX) + FPL("PepperFlashPlayer.plugin"); +#elif defined(OS_WIN) + FPL("pepflashplayer.dll"); +#else // OS_LINUX, etc. + FPL("libpepflashplayer.so"); +#endif + +} // namespace chrome + +#undef FPL diff --git a/chromium_src/chrome/common/chrome_constants.h b/chromium_src/chrome/common/chrome_constants.h new file mode 100644 index 0000000000..e36eeeeff4 --- /dev/null +++ b/chromium_src/chrome/common/chrome_constants.h @@ -0,0 +1,50 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// A handful of resource-like constants related to the Chrome application. + +#ifndef CHROME_COMMON_CHROME_CONSTANTS_H_ +#define CHROME_COMMON_CHROME_CONSTANTS_H_ + +#include "base/files/file_path.h" + +namespace chrome { + +// filenames +extern const base::FilePath::CharType kCacheDirname[]; +extern const base::FilePath::CharType kChannelIDFilename[]; +extern const base::FilePath::CharType kCookieFilename[]; +extern const base::FilePath::CharType kCRLSetFilename[]; +extern const base::FilePath::CharType kCustomDictionaryFileName[]; +extern const base::FilePath::CharType kExtensionActivityLogFilename[]; +extern const base::FilePath::CharType kExtensionsCookieFilename[]; +extern const base::FilePath::CharType kFirstRunSentinel[]; +extern const base::FilePath::CharType kGCMStoreDirname[]; +extern const base::FilePath::CharType kLocalStateFilename[]; +extern const base::FilePath::CharType kLocalStorePoolName[]; +extern const base::FilePath::CharType kMediaCacheDirname[]; +extern const base::FilePath::CharType kNetworkPersistentStateFilename[]; +extern const base::FilePath::CharType kOfflinePageArchviesDirname[]; +extern const base::FilePath::CharType kOfflinePageMetadataDirname[]; +extern const base::FilePath::CharType kPreferencesFilename[]; +extern const base::FilePath::CharType kProtectedPreferencesFilenameDeprecated[]; +extern const base::FilePath::CharType kReadmeFilename[]; +extern const base::FilePath::CharType kResetPromptMementoFilename[]; +extern const base::FilePath::CharType kSafeBrowsingBaseFilename[]; +extern const base::FilePath::CharType kSecurePreferencesFilename[]; +extern const base::FilePath::CharType kServiceStateFileName[]; +extern const base::FilePath::CharType kSingletonCookieFilename[]; +extern const base::FilePath::CharType kSingletonLockFilename[]; +extern const base::FilePath::CharType kSingletonSocketFilename[]; +extern const base::FilePath::CharType kSupervisedUserSettingsFilename[]; +extern const base::FilePath::CharType kThemePackFilename[]; +extern const base::FilePath::CharType kThemePackMaterialDesignFilename[]; +extern const base::FilePath::CharType kWebAppDirname[]; + +// File name of the Pepper Flash plugin on different platforms. +extern const base::FilePath::CharType kPepperFlashPluginFilename[]; + +} // namespace chrome + +#endif // CHROME_COMMON_CHROME_CONSTANTS_H_ diff --git a/chromium_src/chrome/common/chrome_paths.cc b/chromium_src/chrome/common/chrome_paths.cc new file mode 100644 index 0000000000..d8a32446fe --- /dev/null +++ b/chromium_src/chrome/common/chrome_paths.cc @@ -0,0 +1,610 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/common/chrome_paths.h" + +#include "base/files/file_util.h" +#include "base/lazy_instance.h" +#include "base/logging.h" +#include "base/mac/bundle_locations.h" +#include "base/path_service.h" +#include "base/strings/string_util.h" +#include "base/sys_info.h" +#include "base/threading/thread_restrictions.h" +#include "base/version.h" +#include "chrome/common/chrome_constants.h" +#include "chrome/common/chrome_paths_internal.h" + +#if defined(OS_ANDROID) +#include "base/android/path_utils.h" +#include "base/base_paths_android.h" +// ui/base must only be used on Android. See BUILD.gn for dependency info. +#include "ui/base/ui_base_paths.h" // nogncheck +#endif + +#if defined(OS_MACOSX) +#include "base/mac/foundation_util.h" +#endif + +#if defined(OS_WIN) +#include "base/win/registry.h" +#endif + +namespace { + +// The Pepper Flash plugins are in a directory with this name. +const base::FilePath::CharType kPepperFlashBaseDirectory[] = + FILE_PATH_LITERAL("PepperFlash"); + +#if defined(OS_MACOSX) && !defined(OS_IOS) +const base::FilePath::CharType kPepperFlashSystemBaseDirectory[] = + FILE_PATH_LITERAL("Internet Plug-Ins/PepperFlashPlayer"); +const base::FilePath::CharType kFlashSystemBaseDirectory[] = + FILE_PATH_LITERAL("Internet Plug-Ins"); +const base::FilePath::CharType kFlashSystemPluginName[] = + FILE_PATH_LITERAL("Flash Player.plugin"); +#endif + +const base::FilePath::CharType kInternalNaClPluginFileName[] = + FILE_PATH_LITERAL("internal-nacl-plugin"); + +#if defined(OS_LINUX) +// The path to the external extension .json files. +// /usr/share seems like a good choice, see: http://www.pathname.com/fhs/ +const base::FilePath::CharType kFilepathSinglePrefExtensions[] = +#if defined(GOOGLE_CHROME_BUILD) + FILE_PATH_LITERAL("/usr/share/google-chrome/extensions"); +#else + FILE_PATH_LITERAL("/usr/share/chromium/extensions"); +#endif // defined(GOOGLE_CHROME_BUILD) + +// The path to the hint file that tells the pepper plugin loader +// where it can find the latest component updated flash. +const base::FilePath::CharType kComponentUpdatedFlashHint[] = + FILE_PATH_LITERAL("latest-component-updated-flash"); +#endif // defined(OS_LINUX) + +static base::LazyInstance + g_invalid_specified_user_data_dir = LAZY_INSTANCE_INITIALIZER; + +// Gets the path for internal plugins. +bool GetInternalPluginsDirectory(base::FilePath* result) { +#if defined(OS_MACOSX) && !defined(OS_IOS) + // If called from Chrome, get internal plugins from a subdirectory of the + // framework. + if (base::mac::AmIBundled()) { + *result = chrome::GetFrameworkBundlePath(); + DCHECK(!result->empty()); + *result = result->Append("Internet Plug-Ins"); + return true; + } + // In tests, just look in the module directory (below). +#endif + + // The rest of the world expects plugins in the module directory. + return PathService::Get(base::DIR_MODULE, result); +} + +#if defined(OS_WIN) +// Gets the Flash path if installed on the system. |is_npapi| determines whether +// to return the NPAPI of the PPAPI version of the system plugin. +bool GetSystemFlashFilename(base::FilePath* out_path, bool is_npapi) { + const wchar_t kNpapiFlashRegistryRoot[] = + L"SOFTWARE\\Macromedia\\FlashPlayerPlugin"; + const wchar_t kPepperFlashRegistryRoot[] = + L"SOFTWARE\\Macromedia\\FlashPlayerPepper"; + const wchar_t kFlashPlayerPathValueName[] = L"PlayerPath"; + + base::win::RegKey path_key( + HKEY_LOCAL_MACHINE, + is_npapi ? kNpapiFlashRegistryRoot : kPepperFlashRegistryRoot, KEY_READ); + base::string16 path_str; + if (FAILED(path_key.ReadValue(kFlashPlayerPathValueName, &path_str))) + return false; + + *out_path = base::FilePath(path_str); + return true; +} +#endif + +} // namespace + +namespace chrome { + +bool PathProvider(int key, base::FilePath* result) { + // Some keys are just aliases... + switch (key) { + case chrome::DIR_APP: + return PathService::Get(base::DIR_MODULE, result); + case chrome::DIR_LOGS: +#ifdef NDEBUG + // Release builds write to the data dir + return PathService::Get(chrome::DIR_USER_DATA, result); +#else + // Debug builds write next to the binary (in the build tree) +#if defined(OS_MACOSX) + if (!PathService::Get(base::DIR_EXE, result)) + return false; + if (base::mac::AmIBundled()) { + // If we're called from chrome, dump it beside the app (outside the + // app bundle), if we're called from a unittest, we'll already + // outside the bundle so use the exe dir. + // exe_dir gave us .../Chromium.app/Contents/MacOS/Chromium. + *result = result->DirName(); + *result = result->DirName(); + *result = result->DirName(); + } + return true; +#else + return PathService::Get(base::DIR_EXE, result); +#endif // defined(OS_MACOSX) +#endif // NDEBUG + case chrome::FILE_RESOURCE_MODULE: + return PathService::Get(base::FILE_MODULE, result); + } + + // Assume that we will not need to create the directory if it does not exist. + // This flag can be set to true for the cases where we want to create it. + bool create_dir = false; + + base::FilePath cur; + switch (key) { + case chrome::DIR_USER_DATA: + if (!GetDefaultUserDataDirectory(&cur)) { + NOTREACHED(); + return false; + } + create_dir = true; + break; + case chrome::DIR_USER_DOCUMENTS: + if (!GetUserDocumentsDirectory(&cur)) + return false; + create_dir = true; + break; + case chrome::DIR_USER_MUSIC: + if (!GetUserMusicDirectory(&cur)) + return false; + break; + case chrome::DIR_USER_PICTURES: + if (!GetUserPicturesDirectory(&cur)) + return false; + break; + case chrome::DIR_USER_VIDEOS: + if (!GetUserVideosDirectory(&cur)) + return false; + break; + case chrome::DIR_DEFAULT_DOWNLOADS_SAFE: +#if defined(OS_WIN) || defined(OS_LINUX) + if (!GetUserDownloadsDirectorySafe(&cur)) + return false; + break; +#else + // Fall through for all other platforms. +#endif + case chrome::DIR_DEFAULT_DOWNLOADS: +#if defined(OS_ANDROID) + if (!base::android::GetDownloadsDirectory(&cur)) + return false; +#else + if (!GetUserDownloadsDirectory(&cur)) + return false; + // Do not create the download directory here, we have done it twice now + // and annoyed a lot of users. +#endif + break; + case chrome::DIR_CRASH_DUMPS: +#if defined(OS_CHROMEOS) + // ChromeOS uses a separate directory. See http://crosbug.com/25089 + cur = base::FilePath("/var/log/chrome"); +#elif defined(OS_ANDROID) + if (!base::android::GetCacheDirectory(&cur)) + return false; +#else + // The crash reports are always stored relative to the default user data + // directory. This avoids the problem of having to re-initialize the + // exception handler after parsing command line options, which may + // override the location of the app's profile directory. + if (!GetDefaultUserDataDirectory(&cur)) + return false; +#endif +#if defined(OS_MACOSX) + cur = cur.Append(FILE_PATH_LITERAL("Crashpad")); +#else + cur = cur.Append(FILE_PATH_LITERAL("Crash Reports")); +#endif + create_dir = true; + break; +#if defined(OS_WIN) + case chrome::DIR_WATCHER_DATA: + // The watcher data is always stored relative to the default user data + // directory. This allows the watcher to be initialized before + // command-line options have been parsed. + if (!GetDefaultUserDataDirectory(&cur)) + return false; + cur = cur.Append(FILE_PATH_LITERAL("Diagnostics")); + break; +#endif + case chrome::DIR_RESOURCES: +#if defined(OS_MACOSX) + cur = base::mac::FrameworkBundlePath(); + cur = cur.Append(FILE_PATH_LITERAL("Resources")); +#else + if (!PathService::Get(chrome::DIR_APP, &cur)) + return false; + cur = cur.Append(FILE_PATH_LITERAL("resources")); +#endif + break; + case chrome::DIR_INSPECTOR: + if (!PathService::Get(chrome::DIR_RESOURCES, &cur)) + return false; + cur = cur.Append(FILE_PATH_LITERAL("inspector")); + break; + case chrome::DIR_APP_DICTIONARIES: +#if defined(OS_POSIX) + // We can't write into the EXE dir on Linux, so keep dictionaries + // alongside the safe browsing database in the user data dir. + // And we don't want to write into the bundle on the Mac, so push + // it to the user data dir there also. + if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) + return false; +#else + if (!PathService::Get(base::DIR_EXE, &cur)) + return false; +#endif + cur = cur.Append(FILE_PATH_LITERAL("Dictionaries")); + create_dir = true; + break; + case chrome::DIR_INTERNAL_PLUGINS: + if (!GetInternalPluginsDirectory(&cur)) + return false; + break; + case chrome::DIR_PEPPER_FLASH_PLUGIN: + if (!GetInternalPluginsDirectory(&cur)) + return false; + cur = cur.Append(kPepperFlashBaseDirectory); + break; + case chrome::DIR_COMPONENT_UPDATED_PEPPER_FLASH_PLUGIN: + if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) + return false; + cur = cur.Append(kPepperFlashBaseDirectory); + break; + case chrome::FILE_PEPPER_FLASH_SYSTEM_PLUGIN: +#if defined(OS_WIN) + if (!GetSystemFlashFilename(&cur, false)) + return false; +#elif defined(OS_MACOSX) && !defined(OS_IOS) + if (!GetLocalLibraryDirectory(&cur)) + return false; + cur = cur.Append(kPepperFlashSystemBaseDirectory); + cur = cur.Append(chrome::kPepperFlashPluginFilename); +#else + // Chrome on iOS does not supports PPAPI binaries, return false. + // TODO(wfh): If Adobe release PPAPI binaries for Linux, add support here. + return false; +#endif + break; + case chrome::FILE_FLASH_SYSTEM_PLUGIN: +#if defined(OS_WIN) + if (!GetSystemFlashFilename(&cur, true)) + return false; +#elif defined(OS_MACOSX) && !defined(OS_IOS) + if (!GetLocalLibraryDirectory(&cur)) + return false; + cur = cur.Append(kFlashSystemBaseDirectory); + cur = cur.Append(kFlashSystemPluginName); +#else + // Chrome on other platforms does not supports system NPAPI binaries. + return false; +#endif + break; + case chrome::FILE_LOCAL_STATE: + if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) + return false; + cur = cur.Append(chrome::kLocalStateFilename); + break; + case chrome::FILE_RECORDED_SCRIPT: + if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) + return false; + cur = cur.Append(FILE_PATH_LITERAL("script.log")); + break; + case chrome::FILE_PEPPER_FLASH_PLUGIN: + if (!PathService::Get(chrome::DIR_PEPPER_FLASH_PLUGIN, &cur)) + return false; + cur = cur.Append(chrome::kPepperFlashPluginFilename); + break; + // TODO(teravest): Remove this case once the internal NaCl plugin is gone. + // We currently need a path here to look up whether the plugin is disabled + // and what its permissions are. + case chrome::FILE_NACL_PLUGIN: + if (!GetInternalPluginsDirectory(&cur)) + return false; + cur = cur.Append(kInternalNaClPluginFileName); + break; + // PNaCl is currenly installable via the component updater or by being + // simply built-in. DIR_PNACL_BASE is used as the base directory for + // installation via component updater. DIR_PNACL_COMPONENT will be + // the final location of pnacl, which is a subdir of DIR_PNACL_BASE. + case chrome::DIR_PNACL_BASE: + if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) + return false; + cur = cur.Append(FILE_PATH_LITERAL("pnacl")); + break; + // Where PNaCl files are ultimately located. The default finds the files + // inside the InternalPluginsDirectory / build directory, as if it + // was shipped along with chrome. The value can be overridden + // if it is installed via component updater. + case chrome::DIR_PNACL_COMPONENT: +#if defined(OS_MACOSX) + // PNaCl really belongs in the InternalPluginsDirectory but actually + // copying it there would result in the files also being shipped, which + // we don't want yet. So for now, just find them in the directory where + // they get built. + if (!PathService::Get(base::DIR_EXE, &cur)) + return false; + if (base::mac::AmIBundled()) { + // If we're called from chrome, it's beside the app (outside the + // app bundle), if we're called from a unittest, we'll already be + // outside the bundle so use the exe dir. + // exe_dir gave us .../Chromium.app/Contents/MacOS/Chromium. + cur = cur.DirName(); + cur = cur.DirName(); + cur = cur.DirName(); + } +#else + if (!GetInternalPluginsDirectory(&cur)) + return false; +#endif + cur = cur.Append(FILE_PATH_LITERAL("pnacl")); + break; +#if defined(WIDEVINE_CDM_AVAILABLE) && defined(ENABLE_PEPPER_CDMS) +#if defined(WIDEVINE_CDM_IS_COMPONENT) + case chrome::DIR_COMPONENT_WIDEVINE_CDM: + if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) + return false; + cur = cur.Append(FILE_PATH_LITERAL("WidevineCDM")); + break; +#endif // defined(WIDEVINE_CDM_IS_COMPONENT) + // TODO(xhwang): FILE_WIDEVINE_CDM_ADAPTER has different meanings. + // In the component case, this is the source adapter. Otherwise, it is the + // actual Pepper module that gets loaded. + case chrome::FILE_WIDEVINE_CDM_ADAPTER: + if (!GetInternalPluginsDirectory(&cur)) + return false; + cur = cur.AppendASCII(kWidevineCdmAdapterFileName); + break; +#endif // defined(WIDEVINE_CDM_AVAILABLE) && defined(ENABLE_PEPPER_CDMS) + case chrome::FILE_RESOURCES_PACK: +#if defined(OS_MACOSX) && !defined(OS_IOS) + if (base::mac::AmIBundled()) { + cur = base::mac::FrameworkBundlePath(); + cur = cur.Append(FILE_PATH_LITERAL("Resources")) + .Append(FILE_PATH_LITERAL("resources.pak")); + break; + } +#elif defined(OS_ANDROID) + if (!PathService::Get(ui::DIR_RESOURCE_PAKS_ANDROID, &cur)) + return false; +#else + // If we're not bundled on mac or Android, resources.pak should be next + // to the binary (e.g., for unit tests). + if (!PathService::Get(base::DIR_MODULE, &cur)) + return false; +#endif + cur = cur.Append(FILE_PATH_LITERAL("resources.pak")); + break; + case chrome::DIR_RESOURCES_EXTENSION: + if (!PathService::Get(base::DIR_MODULE, &cur)) + return false; + cur = cur.Append(FILE_PATH_LITERAL("resources")) + .Append(FILE_PATH_LITERAL("extension")); + break; +#if defined(OS_CHROMEOS) + case chrome::DIR_CHROMEOS_WALLPAPERS: + if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) + return false; + cur = cur.Append(FILE_PATH_LITERAL("wallpapers")); + break; + case chrome::DIR_CHROMEOS_WALLPAPER_THUMBNAILS: + if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) + return false; + cur = cur.Append(FILE_PATH_LITERAL("wallpaper_thumbnails")); + break; + case chrome::DIR_CHROMEOS_CUSTOM_WALLPAPERS: + if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) + return false; + cur = cur.Append(FILE_PATH_LITERAL("custom_wallpapers")); + break; +#endif +#if defined(ENABLE_SUPERVISED_USERS) +#if defined(OS_LINUX) + case chrome::DIR_SUPERVISED_USERS_DEFAULT_APPS: + if (!PathService::Get(chrome::DIR_STANDALONE_EXTERNAL_EXTENSIONS, &cur)) + return false; + cur = cur.Append(FILE_PATH_LITERAL("managed_users")); + break; +#endif + case chrome::DIR_SUPERVISED_USER_INSTALLED_WHITELISTS: + if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) + return false; + cur = cur.Append(FILE_PATH_LITERAL("SupervisedUserInstalledWhitelists")); + break; +#endif + // The following are only valid in the development environment, and + // will fail if executed from an installed executable (because the + // generated path won't exist). + case chrome::DIR_GEN_TEST_DATA: +#if defined(OS_ANDROID) + // On Android, our tests don't have permission to write to DIR_MODULE. + // gtest/test_runner.py pushes data to external storage. + if (!PathService::Get(base::DIR_ANDROID_EXTERNAL_STORAGE, &cur)) + return false; +#else + if (!PathService::Get(base::DIR_MODULE, &cur)) + return false; +#endif + cur = cur.Append(FILE_PATH_LITERAL("test_data")); + if (!base::PathExists(cur)) // We don't want to create this. + return false; + break; + case chrome::DIR_TEST_DATA: + if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur)) + return false; + cur = cur.Append(FILE_PATH_LITERAL("chrome")); + cur = cur.Append(FILE_PATH_LITERAL("test")); + cur = cur.Append(FILE_PATH_LITERAL("data")); + if (!base::PathExists(cur)) // We don't want to create this. + return false; + break; + case chrome::DIR_TEST_TOOLS: + if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur)) + return false; + cur = cur.Append(FILE_PATH_LITERAL("chrome")); + cur = cur.Append(FILE_PATH_LITERAL("tools")); + cur = cur.Append(FILE_PATH_LITERAL("test")); + if (!base::PathExists(cur)) // We don't want to create this + return false; + break; +#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) + case chrome::DIR_POLICY_FILES: { +#if defined(GOOGLE_CHROME_BUILD) + cur = base::FilePath(FILE_PATH_LITERAL("/etc/opt/chrome/policies")); +#else + cur = base::FilePath(FILE_PATH_LITERAL("/etc/chromium/policies")); +#endif + break; + } +#endif +#if defined(OS_MACOSX) && !defined(OS_IOS) + case chrome::DIR_USER_LIBRARY: { + if (!GetUserLibraryDirectory(&cur)) + return false; + if (!base::PathExists(cur)) // We don't want to create this. + return false; + break; + } + case chrome::DIR_USER_APPLICATIONS: { + if (!GetUserApplicationsDirectory(&cur)) + return false; + if (!base::PathExists(cur)) // We don't want to create this. + return false; + break; + } +#endif +#if defined(OS_CHROMEOS) || (defined(OS_LINUX) && defined(CHROMIUM_BUILD)) || \ + (defined(OS_MACOSX) && !defined(OS_IOS)) + case chrome::DIR_USER_EXTERNAL_EXTENSIONS: { + if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) + return false; + cur = cur.Append(FILE_PATH_LITERAL("External Extensions")); + break; + } +#endif +#if defined(OS_LINUX) + case chrome::DIR_STANDALONE_EXTERNAL_EXTENSIONS: { + cur = base::FilePath(kFilepathSinglePrefExtensions); + break; + } +#endif + case chrome::DIR_EXTERNAL_EXTENSIONS: +#if defined(OS_MACOSX) && !defined(OS_IOS) + if (!chrome::GetGlobalApplicationSupportDirectory(&cur)) + return false; + + cur = cur.Append(FILE_PATH_LITERAL("Google")) + .Append(FILE_PATH_LITERAL("Chrome")) + .Append(FILE_PATH_LITERAL("External Extensions")); + create_dir = false; +#else + if (!PathService::Get(base::DIR_MODULE, &cur)) + return false; + + cur = cur.Append(FILE_PATH_LITERAL("extensions")); + create_dir = true; +#endif + break; + + case chrome::DIR_DEFAULT_APPS: +#if defined(OS_MACOSX) + cur = base::mac::FrameworkBundlePath(); + cur = cur.Append(FILE_PATH_LITERAL("Default Apps")); +#else + if (!PathService::Get(chrome::DIR_APP, &cur)) + return false; + cur = cur.Append(FILE_PATH_LITERAL("default_apps")); +#endif + break; + +#if defined(OS_LINUX) || (defined(OS_MACOSX) && !defined(OS_IOS)) + case chrome::DIR_NATIVE_MESSAGING: +#if defined(OS_MACOSX) +#if defined(GOOGLE_CHROME_BUILD) + cur = base::FilePath(FILE_PATH_LITERAL( + "/Library/Google/Chrome/NativeMessagingHosts")); +#else + cur = base::FilePath(FILE_PATH_LITERAL( + "/Library/Application Support/Chromium/NativeMessagingHosts")); +#endif +#else // defined(OS_MACOSX) +#if defined(GOOGLE_CHROME_BUILD) + cur = base::FilePath(FILE_PATH_LITERAL( + "/etc/opt/chrome/native-messaging-hosts")); +#else + cur = base::FilePath(FILE_PATH_LITERAL( + "/etc/chromium/native-messaging-hosts")); +#endif +#endif // !defined(OS_MACOSX) + break; + + case chrome::DIR_USER_NATIVE_MESSAGING: + if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) + return false; + cur = cur.Append(FILE_PATH_LITERAL("NativeMessagingHosts")); + break; +#endif // defined(OS_LINUX) || (defined(OS_MACOSX) && !defined(OS_IOS)) +#if !defined(OS_ANDROID) + case chrome::DIR_GLOBAL_GCM_STORE: + if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) + return false; + cur = cur.Append(kGCMStoreDirname); + break; +#endif // !defined(OS_ANDROID) +#if defined(OS_LINUX) + case chrome::FILE_COMPONENT_FLASH_HINT: + if (!PathService::Get(chrome::DIR_COMPONENT_UPDATED_PEPPER_FLASH_PLUGIN, + &cur)) { + return false; + } + cur = cur.Append(kComponentUpdatedFlashHint); + break; +#endif // defined(OS_LINUX) + + default: + return false; + } + + // TODO(bauerb): http://crbug.com/259796 + base::ThreadRestrictions::ScopedAllowIO allow_io; + if (create_dir && !base::PathExists(cur) && + !base::CreateDirectory(cur)) + return false; + + *result = cur; + return true; +} + +// This cannot be done as a static initializer sadly since Visual Studio will +// eliminate this object file if there is no direct entry point into it. +void RegisterPathProvider() { + PathService::RegisterProvider(PathProvider, PATH_START, PATH_END); +} + +void SetInvalidSpecifiedUserDataDir(const base::FilePath& user_data_dir) { + g_invalid_specified_user_data_dir.Get() = user_data_dir; +} + +const base::FilePath& GetInvalidSpecifiedUserDataDir() { + return g_invalid_specified_user_data_dir.Get(); +} + +} // namespace chrome diff --git a/chromium_src/chrome/common/chrome_paths.h b/chromium_src/chrome/common/chrome_paths.h new file mode 100644 index 0000000000..581fdc06f7 --- /dev/null +++ b/chromium_src/chrome/common/chrome_paths.h @@ -0,0 +1,152 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_COMMON_CHROME_PATHS_H__ +#define CHROME_COMMON_CHROME_PATHS_H__ + +#include "build/build_config.h" + +namespace base { +class FilePath; +} + +// This file declares path keys for the chrome module. These can be used with +// the PathService to access various special directories and files. + +namespace chrome { + +enum { + PATH_START = 1000, + + DIR_APP = PATH_START, // Directory where dlls and data reside. + DIR_LOGS, // Directory where logs should be written. + DIR_USER_DATA, // Directory where user data can be written. + DIR_CRASH_DUMPS, // Directory where crash dumps are written. +#if defined(OS_WIN) + DIR_WATCHER_DATA, // Directory where the Chrome watcher stores + // data. +#endif + DIR_RESOURCES, // Directory containing separate file resources + // used by Chrome at runtime. + DIR_INSPECTOR, // Directory where web inspector is located. + DIR_APP_DICTIONARIES, // Directory where the global dictionaries are. + DIR_USER_DOCUMENTS, // Directory for a user's "My Documents". + DIR_USER_MUSIC, // Directory for a user's music. + DIR_USER_PICTURES, // Directory for a user's pictures. + DIR_USER_VIDEOS, // Directory for a user's videos. + DIR_DEFAULT_DOWNLOADS_SAFE, // Directory for a user's + // "My Documents/Downloads", (Windows) or + // "Downloads". (Linux) + DIR_DEFAULT_DOWNLOADS, // Directory for a user's downloads. + DIR_INTERNAL_PLUGINS, // Directory where internal plugins reside. +#if defined(OS_POSIX) && !defined(OS_MACOSX) + DIR_POLICY_FILES, // Directory for system-wide read-only + // policy files that allow sys-admins + // to set policies for chrome. This directory + // contains subdirectories. +#endif +#if defined(OS_MACOSX) && !defined(OS_IOS) + DIR_USER_APPLICATIONS, // ~/Applications + DIR_USER_LIBRARY, // ~/Library +#endif +#if defined(OS_CHROMEOS) || (defined(OS_LINUX) && defined(CHROMIUM_BUILD)) || \ + (defined(OS_MACOSX) && !defined(OS_IOS)) + DIR_USER_EXTERNAL_EXTENSIONS, // Directory for per-user external extensions + // on Chrome Mac and Chromium Linux. + // On Chrome OS, this path is used for OEM + // customization. Getting this path does not + // create it. +#endif + +#if defined(OS_LINUX) + DIR_STANDALONE_EXTERNAL_EXTENSIONS, // Directory for 'per-extension' + // definition manifest files that + // describe extensions which are to be + // installed when chrome is run. +#endif + DIR_EXTERNAL_EXTENSIONS, // Directory where installer places .crx files. + + DIR_DEFAULT_APPS, // Directory where installer places .crx files + // to be installed when chrome is first run. + DIR_PEPPER_FLASH_PLUGIN, // Directory to the bundled Pepper Flash plugin, + // containing the plugin and the manifest. + DIR_COMPONENT_UPDATED_PEPPER_FLASH_PLUGIN, // Base directory of the Pepper + // Flash plugins downloaded by the + // component updater. + FILE_RESOURCE_MODULE, // Full path and filename of the module that + // contains embedded resources (version, + // strings, images, etc.). + FILE_LOCAL_STATE, // Path and filename to the file in which + // machine/installation-specific state is saved. + FILE_RECORDED_SCRIPT, // Full path to the script.log file that + // contains recorded browser events for + // playback. + FILE_PEPPER_FLASH_PLUGIN, // Full path to the bundled Pepper Flash plugin + // file. + FILE_PEPPER_FLASH_SYSTEM_PLUGIN, // Full path to the system version of the + // Pepper Flash plugin, downloadable from + // Adobe website. Querying this path might + // succeed no matter the file exists or not. + FILE_FLASH_SYSTEM_PLUGIN, // Full path to the system version of NPAPI + // Flash plugin, downloadable from Adobe + // website. Querying this path might succeed no + // matter the file exists or not. + FILE_NACL_PLUGIN, // Full path to the internal NaCl plugin file. + DIR_PNACL_BASE, // Full path to the base dir for PNaCl. + DIR_PNACL_COMPONENT, // Full path to the latest PNaCl version + // (subdir of DIR_PNACL_BASE). + DIR_COMPONENT_WIDEVINE_CDM, // Directory that contains component-updated + // Widevine CDM files. + FILE_WIDEVINE_CDM_ADAPTER, // Full path to the Widevine CDM adapter file. + FILE_RESOURCES_PACK, // Full path to the .pak file containing + // binary data (e.g., html files and images + // used by internal pages). + DIR_RESOURCES_EXTENSION, // Full path to extension resources. +#if defined(OS_CHROMEOS) + DIR_CHROMEOS_WALLPAPERS, // Directory where downloaded chromeos + // wallpapers reside. + DIR_CHROMEOS_WALLPAPER_THUMBNAILS, // Directory where downloaded chromeos + // wallpaper thumbnails reside. + DIR_CHROMEOS_CUSTOM_WALLPAPERS, // Directory where custom wallpapers + // reside. +#endif + DIR_SUPERVISED_USERS_DEFAULT_APPS, // Directory where installer places .crx + // files to be installed when managed user + // session starts. + DIR_SUPERVISED_USER_INSTALLED_WHITELISTS, // Directory where sanitized + // supervised user whitelists are + // installed. +#if defined(OS_LINUX) || (defined(OS_MACOSX) && !defined(OS_IOS)) + DIR_NATIVE_MESSAGING, // System directory where native messaging host + // manifest files are stored. + DIR_USER_NATIVE_MESSAGING, // Directory with Native Messaging Hosts + // installed per-user. +#endif +#if !defined(OS_ANDROID) + DIR_GLOBAL_GCM_STORE, // Directory where the global GCM instance + // stores its data. +#endif + + // Valid only in development environment; TODO(darin): move these + DIR_GEN_TEST_DATA, // Directory where generated test data resides. + DIR_TEST_DATA, // Directory where unit test data resides. + DIR_TEST_TOOLS, // Directory where unit test tools reside. +#if defined(OS_LINUX) + FILE_COMPONENT_FLASH_HINT, // A file in a known location that points to + // the component updated flash plugin. +#endif // defined(OS_LINUX) + + PATH_END +}; + +// Call once to register the provider for the path keys defined above. +void RegisterPathProvider(); + +// Get or set the invalid user data dir that was originally specified. +void SetInvalidSpecifiedUserDataDir(const base::FilePath& user_data_dir); +const base::FilePath& GetInvalidSpecifiedUserDataDir(); + +} // namespace chrome + +#endif // CHROME_COMMON_CHROME_PATHS_H__ diff --git a/chromium_src/chrome/common/chrome_paths_internal.h b/chromium_src/chrome/common/chrome_paths_internal.h new file mode 100644 index 0000000000..ae1cd623d7 --- /dev/null +++ b/chromium_src/chrome/common/chrome_paths_internal.h @@ -0,0 +1,112 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_COMMON_CHROME_PATHS_INTERNAL_H_ +#define CHROME_COMMON_CHROME_PATHS_INTERNAL_H_ + +#include + +#include "build/build_config.h" + +#if defined(OS_MACOSX) +#if defined(__OBJC__) +@class NSBundle; +#else +class NSBundle; +#endif +#endif + +namespace base { +class FilePath; +} + +namespace chrome { + +// Get the path to the user's data directory, regardless of whether +// DIR_USER_DATA has been overridden by a command-line option. +bool GetDefaultUserDataDirectory(base::FilePath* result); + +// Get the path to the user's cache directory. This is normally the +// same as the profile directory, but on Linux it can also be +// $XDG_CACHE_HOME and on Mac it can be under ~/Library/Caches. +// Note that the Chrome cache directories are actually subdirectories +// of this directory, with names like "Cache" and "Media Cache". +// This will always fill in |result| with a directory, sometimes +// just |profile_dir|. +void GetUserCacheDirectory(const base::FilePath& profile_dir, base::FilePath* result); + +// Get the path to the user's documents directory. +bool GetUserDocumentsDirectory(base::FilePath* result); + +#if defined(OS_WIN) || defined(OS_LINUX) +// Gets the path to a safe default download directory for a user. +bool GetUserDownloadsDirectorySafe(base::FilePath* result); +#endif + +// Get the path to the user's downloads directory. +bool GetUserDownloadsDirectory(base::FilePath* result); + +// Gets the path to the user's music directory. +bool GetUserMusicDirectory(base::FilePath* result); + +// Gets the path to the user's pictures directory. +bool GetUserPicturesDirectory(base::FilePath* result); + +// Gets the path to the user's videos directory. +bool GetUserVideosDirectory(base::FilePath* result); + +#if defined(OS_MACOSX) && !defined(OS_IOS) +// The "versioned directory" is a directory in the browser .app bundle. It +// contains the bulk of the application, except for the things that the system +// requires be located at spepcific locations. The versioned directory is +// in the .app at Contents/Versions/w.x.y.z. +base::FilePath GetVersionedDirectory(); + +// This overrides the directory returned by |GetVersionedDirectory()|, to be +// used when |GetVersionedDirectory()| can't automatically determine the proper +// location. This is the case when the browser didn't load itself but by, e.g., +// the app mode loader. This should be called before |ChromeMain()|. This takes +// ownership of the object |path| and the caller must not delete it. +void SetOverrideVersionedDirectory(const base::FilePath* path); + +// Most of the application is further contained within the framework. The +// framework bundle is located within the versioned directory at a specific +// path. The only components in the versioned directory not included in the +// framework are things that also depend on the framework, such as the helper +// app bundle. +base::FilePath GetFrameworkBundlePath(); + +// Get the local library directory. +bool GetLocalLibraryDirectory(base::FilePath* result); + +// Get the user library directory. +bool GetUserLibraryDirectory(base::FilePath* result); + +// Get the user applications directory. +bool GetUserApplicationsDirectory(base::FilePath* result); + +// Get the global Application Support directory (under /Library/). +bool GetGlobalApplicationSupportDirectory(base::FilePath* result); + +// Returns the NSBundle for the outer browser application, even when running +// inside the helper. In unbundled applications, such as tests, returns nil. +NSBundle* OuterAppBundle(); + +// Get the user data directory for the Chrome browser bundle at |bundle|. +// |bundle| should be the same value that would be returned from +[NSBundle +// mainBundle] if Chrome were launched normaly. This is used by app shims, +// which run from a bundle which isn't Chrome itself, but which need access to +// the user data directory to connect to a UNIX-domain socket therein. +// Returns false if there was a problem fetching the app data directory. +bool GetUserDataDirectoryForBrowserBundle(NSBundle* bundle, + base::FilePath* result); + +#endif // OS_MACOSX && !OS_IOS + +// Checks if the |process_type| has the rights to access the profile. +bool ProcessNeedsProfileDir(const std::string& process_type); + +} // namespace chrome + +#endif // CHROME_COMMON_CHROME_PATHS_INTERNAL_H_ diff --git a/chromium_src/chrome/common/chrome_paths_linux.cc b/chromium_src/chrome/common/chrome_paths_linux.cc new file mode 100644 index 0000000000..91348fec48 --- /dev/null +++ b/chromium_src/chrome/common/chrome_paths_linux.cc @@ -0,0 +1,145 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/common/chrome_paths_internal.h" + +#include "base/base_paths.h" +#include "base/environment.h" +#include "base/files/file_util.h" +#include "base/memory/scoped_ptr.h" +#include "base/nix/xdg_util.h" +#include "base/path_service.h" +#include "chrome/common/chrome_paths.h" + +namespace chrome { + +using base::nix::GetXDGDirectory; +using base::nix::GetXDGUserDirectory; +using base::nix::kDotConfigDir; +using base::nix::kXdgConfigHomeEnvVar; + +namespace { + +const char kDownloadsDir[] = "Downloads"; +const char kMusicDir[] = "Music"; +const char kPicturesDir[] = "Pictures"; +const char kVideosDir[] = "Videos"; + +// Generic function for GetUser{Music,Pictures,Video}Directory. +bool GetUserMediaDirectory(const std::string& xdg_name, + const std::string& fallback_name, + base::FilePath* result) { +#if defined(OS_CHROMEOS) + // No local media directories on CrOS. + return false; +#else + *result = GetXDGUserDirectory(xdg_name.c_str(), fallback_name.c_str()); + + base::FilePath home; + PathService::Get(base::DIR_HOME, &home); + if (*result != home) { + base::FilePath desktop; + if (!PathService::Get(base::DIR_USER_DESKTOP, &desktop)) + return false; + if (*result != desktop) { + return true; + } + } + + *result = home.Append(fallback_name); + return true; +#endif +} + +} // namespace + +// See http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html +// for a spec on where config files go. The net effect for most +// systems is we use ~/.config/chromium/ for Chromium and +// ~/.config/google-chrome/ for official builds. +// (This also helps us sidestep issues with other apps grabbing ~/.chromium .) +bool GetDefaultUserDataDirectory(base::FilePath* result) { + scoped_ptr env(base::Environment::Create()); + base::FilePath config_dir(GetXDGDirectory(env.get(), + kXdgConfigHomeEnvVar, + kDotConfigDir)); +#if defined(GOOGLE_CHROME_BUILD) + *result = config_dir.Append("google-chrome"); +#else + *result = config_dir.Append("chromium"); +#endif + return true; +} + +void GetUserCacheDirectory(const base::FilePath& profile_dir, + base::FilePath* result) { + // See http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html + // for a spec on where cache files go. Our rule is: + // - if the user-data-dir in the standard place, + // use same subdirectory of the cache directory. + // (this maps ~/.config/google-chrome to ~/.cache/google-chrome as well + // as the same thing for ~/.config/chromium) + // - otherwise, use the profile dir directly. + + // Default value in cases where any of the following fails. + *result = profile_dir; + + scoped_ptr env(base::Environment::Create()); + + base::FilePath cache_dir; + if (!PathService::Get(base::DIR_CACHE, &cache_dir)) + return; + base::FilePath config_dir(GetXDGDirectory(env.get(), + kXdgConfigHomeEnvVar, + kDotConfigDir)); + + if (!config_dir.AppendRelativePath(profile_dir, &cache_dir)) + return; + + *result = cache_dir; +} + +bool GetUserDocumentsDirectory(base::FilePath* result) { + *result = GetXDGUserDirectory("DOCUMENTS", "Documents"); + return true; +} + +bool GetUserDownloadsDirectorySafe(base::FilePath* result) { + base::FilePath home; + PathService::Get(base::DIR_HOME, &home); + *result = home.Append(kDownloadsDir); + return true; +} + +bool GetUserDownloadsDirectory(base::FilePath* result) { + *result = GetXDGUserDirectory("DOWNLOAD", kDownloadsDir); + return true; +} + +// We respect the user's preferred pictures location, unless it is +// ~ or their desktop directory, in which case we default to ~/Music. +bool GetUserMusicDirectory(base::FilePath* result) { + return GetUserMediaDirectory("MUSIC", kMusicDir, result); +} + +// We respect the user's preferred pictures location, unless it is +// ~ or their desktop directory, in which case we default to ~/Pictures. +bool GetUserPicturesDirectory(base::FilePath* result) { + return GetUserMediaDirectory("PICTURES", kPicturesDir, result); +} + +// We respect the user's preferred pictures location, unless it is +// ~ or their desktop directory, in which case we default to ~/Videos. +bool GetUserVideosDirectory(base::FilePath* result) { + return GetUserMediaDirectory("VIDEOS", kVideosDir, result); +} + +bool ProcessNeedsProfileDir(const std::string& process_type) { + // For now we have no reason to forbid this on Linux as we don't + // have the roaming profile troubles there. Moreover the Linux breakpad needs + // profile dir access in all process if enabled on Linux. + return true; +} + +} // namespace chrome diff --git a/chromium_src/chrome/common/chrome_paths_mac.mm b/chromium_src/chrome/common/chrome_paths_mac.mm new file mode 100644 index 0000000000..09cf13bfe1 --- /dev/null +++ b/chromium_src/chrome/common/chrome_paths_mac.mm @@ -0,0 +1,252 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/common/chrome_paths_internal.h" + +#import +#include + +#include + +#include "base/base_paths.h" +#include "base/logging.h" +#import "base/mac/foundation_util.h" +#import "base/mac/scoped_nsautorelease_pool.h" +#include "base/memory/scoped_ptr.h" +#include "base/path_service.h" +#include "chrome/common/chrome_constants.h" + +namespace { + +#if !defined(OS_IOS) +const base::FilePath* g_override_versioned_directory = NULL; + +// Return a retained (NOT autoreleased) NSBundle* as the internal +// implementation of chrome::OuterAppBundle(), which should be the only +// caller. +NSBundle* OuterAppBundleInternal() { + base::mac::ScopedNSAutoreleasePool pool; + + if (!base::mac::AmIBundled()) { + // If unbundled (as in a test), there's no app bundle. + return nil; + } + + if (!base::mac::IsBackgroundOnlyProcess()) { + // Shortcut: in the browser process, just return the main app bundle. + return [[NSBundle mainBundle] retain]; + } + + // From C.app/Contents/Versions/1.2.3.4, go up three steps to get to C.app. + base::FilePath versioned_dir = chrome::GetVersionedDirectory(); + base::FilePath outer_app_dir = versioned_dir.DirName().DirName().DirName(); + const char* outer_app_dir_c = outer_app_dir.value().c_str(); + NSString* outer_app_dir_ns = [NSString stringWithUTF8String:outer_app_dir_c]; + + return [[NSBundle bundleWithPath:outer_app_dir_ns] retain]; +} +#endif // !defined(OS_IOS) + +char* ProductDirNameForBundle(NSBundle* chrome_bundle) { + const char* product_dir_name = NULL; +#if !defined(OS_IOS) + base::mac::ScopedNSAutoreleasePool pool; + + NSString* product_dir_name_ns = + [chrome_bundle objectForInfoDictionaryKey:@"CrProductDirName"]; + product_dir_name = [product_dir_name_ns fileSystemRepresentation]; +#else + DCHECK(!chrome_bundle); +#endif + + if (!product_dir_name) { +#if defined(GOOGLE_CHROME_BUILD) + product_dir_name = "Google/Chrome"; +#else + product_dir_name = "Chromium"; +#endif + } + + // Leaked, but the only caller initializes a static with this result, so it + // only happens once, and that's OK. + return strdup(product_dir_name); +} + +// ProductDirName returns the name of the directory inside +// ~/Library/Application Support that should hold the product application +// data. This can be overridden by setting the CrProductDirName key in the +// outer browser .app's Info.plist. The default is "Google/Chrome" for +// officially-branded builds, and "Chromium" for unbranded builds. For the +// official canary channel, the Info.plist will have CrProductDirName set +// to "Google/Chrome Canary". +std::string ProductDirName() { +#if defined(OS_IOS) + static const char* product_dir_name = ProductDirNameForBundle(nil); +#else + // Use OuterAppBundle() to get the main app's bundle. This key needs to live + // in the main app's bundle because it will be set differently on the canary + // channel, and the autoupdate system dictates that there can be no + // differences between channels within the versioned directory. This would + // normally use base::mac::FrameworkBundle(), but that references the + // framework bundle within the versioned directory. Ordinarily, the profile + // should not be accessed from non-browser processes, but those processes do + // attempt to get the profile directory, so direct them to look in the outer + // browser .app's Info.plist for the CrProductDirName key. + static const char* product_dir_name = + ProductDirNameForBundle(chrome::OuterAppBundle()); +#endif + return std::string(product_dir_name); +} + +bool GetDefaultUserDataDirectoryForProduct(const std::string& product_dir, + base::FilePath* result) { + bool success = false; + if (result && PathService::Get(base::DIR_APP_DATA, result)) { + *result = result->Append(product_dir); + success = true; + } + return success; +} + +} // namespace + +namespace chrome { + +bool GetDefaultUserDataDirectory(base::FilePath* result) { + return GetDefaultUserDataDirectoryForProduct(ProductDirName(), result); +} + +bool GetUserDocumentsDirectory(base::FilePath* result) { + return base::mac::GetUserDirectory(NSDocumentDirectory, result); +} + +void GetUserCacheDirectory(const base::FilePath& profile_dir, + base::FilePath* result) { + // If the profile directory is under ~/Library/Application Support, + // use a suitable cache directory under ~/Library/Caches. For + // example, a profile directory of ~/Library/Application + // Support/Google/Chrome/MyProfileName would use the cache directory + // ~/Library/Caches/Google/Chrome/MyProfileName. + + // Default value in cases where any of the following fails. + *result = profile_dir; + + base::FilePath app_data_dir; + if (!PathService::Get(base::DIR_APP_DATA, &app_data_dir)) + return; + base::FilePath cache_dir; + if (!PathService::Get(base::DIR_CACHE, &cache_dir)) + return; + if (!app_data_dir.AppendRelativePath(profile_dir, &cache_dir)) + return; + + *result = cache_dir; +} + +bool GetUserDownloadsDirectory(base::FilePath* result) { + return base::mac::GetUserDirectory(NSDownloadsDirectory, result); +} + +bool GetUserMusicDirectory(base::FilePath* result) { + return base::mac::GetUserDirectory(NSMusicDirectory, result); +} + +bool GetUserPicturesDirectory(base::FilePath* result) { + return base::mac::GetUserDirectory(NSPicturesDirectory, result); +} + +bool GetUserVideosDirectory(base::FilePath* result) { + return base::mac::GetUserDirectory(NSMoviesDirectory, result); +} + +#if !defined(OS_IOS) + +base::FilePath GetVersionedDirectory() { + if (g_override_versioned_directory) + return *g_override_versioned_directory; + + // Start out with the path to the running executable. + base::FilePath path; + PathService::Get(base::FILE_EXE, &path); + + // One step up to MacOS, another to Contents. + path = path.DirName().DirName(); + DCHECK_EQ(path.BaseName().value(), "Contents"); + + if (base::mac::IsBackgroundOnlyProcess()) { + // path identifies the helper .app's Contents directory in the browser + // .app's versioned directory. Go up two steps to get to the browser + // .app's versioned directory. + path = path.DirName().DirName(); + DCHECK_EQ(path.BaseName().value(), kChromeVersion); + } else { + // Go into the versioned directory. + path = path.Append("Versions").Append(kChromeVersion); + } + + return path; +} + +void SetOverrideVersionedDirectory(const base::FilePath* path) { + if (path != g_override_versioned_directory) { + delete g_override_versioned_directory; + g_override_versioned_directory = path; + } +} + +base::FilePath GetFrameworkBundlePath() { + // It's tempting to use +[NSBundle bundleWithIdentifier:], but it's really + // slow (about 30ms on 10.5 and 10.6), despite Apple's documentation stating + // that it may be more efficient than +bundleForClass:. +bundleForClass: + // itself takes 1-2ms. Getting an NSBundle from a path, on the other hand, + // essentially takes no time at all, at least when the bundle has already + // been loaded as it will have been in this case. The FilePath operations + // needed to compute the framework's path are also effectively free, so that + // is the approach that is used here. NSBundle is also documented as being + // not thread-safe, and thread safety may be a concern here. + + // The framework bundle is at a known path and name from the browser .app's + // versioned directory. + return GetVersionedDirectory().Append(kFrameworkName); +} + +bool GetLocalLibraryDirectory(base::FilePath* result) { + return base::mac::GetLocalDirectory(NSLibraryDirectory, result); +} + +bool GetUserLibraryDirectory(base::FilePath* result) { + return base::mac::GetUserDirectory(NSLibraryDirectory, result); +} + +bool GetUserApplicationsDirectory(base::FilePath* result) { + return base::mac::GetUserDirectory(NSApplicationDirectory, result); +} + +bool GetGlobalApplicationSupportDirectory(base::FilePath* result) { + return base::mac::GetLocalDirectory(NSApplicationSupportDirectory, result); +} + +NSBundle* OuterAppBundle() { + // Cache this. Foundation leaks it anyway, and this should be the only call + // to OuterAppBundleInternal(). + static NSBundle* bundle = OuterAppBundleInternal(); + return bundle; +} + +bool GetUserDataDirectoryForBrowserBundle(NSBundle* bundle, + base::FilePath* result) { + scoped_ptr + product_dir_name(ProductDirNameForBundle(bundle)); + return GetDefaultUserDataDirectoryForProduct(product_dir_name.get(), result); +} + +#endif // !defined(OS_IOS) + +bool ProcessNeedsProfileDir(const std::string& process_type) { + // For now we have no reason to forbid this on other MacOS as we don't + // have the roaming profile troubles there. + return true; +} + +} // namespace chrome diff --git a/chromium_src/chrome/common/chrome_paths_win.cc b/chromium_src/chrome/common/chrome_paths_win.cc new file mode 100644 index 0000000000..18073ca047 --- /dev/null +++ b/chromium_src/chrome/common/chrome_paths_win.cc @@ -0,0 +1,122 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/common/chrome_paths_internal.h" + +#include +#include +#include +#include +#include + +#include "base/files/file_path.h" +#include "base/path_service.h" +#include "base/win/metro.h" +#include "base/win/scoped_co_mem.h" +#include "chrome/common/chrome_constants.h" +#include "chrome/common/chrome_switches.h" +#include "chrome/installer/util/browser_distribution.h" +#include "components/nacl/common/nacl_switches.h" + +namespace chrome { + +namespace { + +// Generic function to call SHGetFolderPath(). +bool GetUserDirectory(int csidl_folder, base::FilePath* result) { + // We need to go compute the value. It would be nice to support paths + // with names longer than MAX_PATH, but the system functions don't seem + // to be designed for it either, with the exception of GetTempPath + // (but other things will surely break if the temp path is too long, + // so we don't bother handling it. + wchar_t path_buf[MAX_PATH]; + path_buf[0] = 0; + if (FAILED(SHGetFolderPath(NULL, csidl_folder, NULL, + SHGFP_TYPE_CURRENT, path_buf))) { + return false; + } + *result = base::FilePath(path_buf); + return true; +} + +} // namespace + +bool GetDefaultUserDataDirectory(base::FilePath* result) { + if (!PathService::Get(base::DIR_LOCAL_APP_DATA, result)) + return false; + BrowserDistribution* dist = BrowserDistribution::GetDistribution(); + *result = result->Append(dist->GetInstallSubDir()); + *result = result->Append(chrome::kUserDataDirname); + return true; +} + +void GetUserCacheDirectory(const base::FilePath& profile_dir, + base::FilePath* result) { + // This function does more complicated things on Mac/Linux. + *result = profile_dir; +} + +bool GetUserDocumentsDirectory(base::FilePath* result) { + return GetUserDirectory(CSIDL_MYDOCUMENTS, result); +} + +// Return a default path for downloads that is safe. +// We just use 'Downloads' under DIR_USER_DOCUMENTS. Localizing +// 'downloads' is not a good idea because Chrome's UI language +// can be changed. +bool GetUserDownloadsDirectorySafe(base::FilePath* result) { + if (!GetUserDocumentsDirectory(result)) + return false; + + *result = result->Append(L"Downloads"); + return true; +} + +// On Vista and higher, use the downloads known folder. Since it can be +// relocated to point to a "dangerous" folder, callers should validate that the +// returned path is not dangerous before using it. +bool GetUserDownloadsDirectory(base::FilePath* result) { + typedef HRESULT (WINAPI *GetKnownFolderPath)( + REFKNOWNFOLDERID, DWORD, HANDLE, PWSTR*); + GetKnownFolderPath f = reinterpret_cast( + GetProcAddress(GetModuleHandle(L"shell32.dll"), "SHGetKnownFolderPath")); + base::win::ScopedCoMem path_buf; + if (f && SUCCEEDED(f(FOLDERID_Downloads, 0, NULL, &path_buf))) { + *result = base::FilePath(std::wstring(path_buf)); + return true; + } + return GetUserDownloadsDirectorySafe(result); +} + +bool GetUserMusicDirectory(base::FilePath* result) { + return GetUserDirectory(CSIDL_MYMUSIC, result); +} + +bool GetUserPicturesDirectory(base::FilePath* result) { + return GetUserDirectory(CSIDL_MYPICTURES, result); +} + +bool GetUserVideosDirectory(base::FilePath* result) { + return GetUserDirectory(CSIDL_MYVIDEO, result); +} + +bool ProcessNeedsProfileDir(const std::string& process_type) { + // On windows we don't want subprocesses other than the browser process and + // service processes to be able to use the profile directory because if it + // lies on a network share the sandbox will prevent us from accessing it. + + if (process_type.empty() || process_type == switches::kServiceProcess) + return true; + +#if !defined(DISABLE_NACL) + if (process_type == switches::kNaClBrokerProcess || + process_type == switches::kNaClLoaderProcess) { + return true; + } +#endif + + return false; +} + +} // namespace chrome diff --git a/filenames.gypi b/filenames.gypi index 658c8e76b6..0e91dd21e1 100644 --- a/filenames.gypi +++ b/filenames.gypi @@ -419,6 +419,14 @@ 'chromium_src/chrome/browser/ui/views/color_chooser_aura.h', 'chromium_src/chrome/browser/ui/views/frame/global_menu_bar_registrar_x11.cc', 'chromium_src/chrome/browser/ui/views/frame/global_menu_bar_registrar_x11.h', + 'chromium_src/chrome/common/chrome_constants.cc', + 'chromium_src/chrome/common/chrome_constants.h', + 'chromium_src/chrome/common/chrome_paths.cc', + 'chromium_src/chrome/common/chrome_paths.h', + 'chromium_src/chrome/common/chrome_paths_internal.h', + 'chromium_src/chrome/common/chrome_paths_linux.cc', + 'chromium_src/chrome/common/chrome_paths_mac.mm', + 'chromium_src/chrome/common/chrome_paths_win.cc', 'chromium_src/chrome/common/chrome_utility_messages.h', 'chromium_src/chrome/common/pref_names.cc', 'chromium_src/chrome/common/pref_names.h', From 05d2e431debde75edd84d83b357fb7b3a6eea9c7 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 13 Nov 2015 13:03:00 +0800 Subject: [PATCH 20/31] Fix building on OS X --- chromium_src/chrome/common/chrome_constants.cc | 8 +++++++- chromium_src/chrome/common/chrome_constants.h | 8 ++++++++ chromium_src/chrome/common/chrome_paths_mac.mm | 3 +-- 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/chromium_src/chrome/common/chrome_constants.cc b/chromium_src/chrome/common/chrome_constants.cc index 1e7bd33a96..43a6ccdc7c 100644 --- a/chromium_src/chrome/common/chrome_constants.cc +++ b/chromium_src/chrome/common/chrome_constants.cc @@ -3,10 +3,16 @@ // found in the LICENSE file. #include "chrome/common/chrome_constants.h" -#include "chrome/common/chrome_version.h" + +#define FPL FILE_PATH_LITERAL namespace chrome { +#if defined(OS_MACOSX) +const base::FilePath::CharType kFrameworkName[] = + FPL(ATOM_PRODUCT_NAME " Framework.framework"); +#endif // OS_MACOSX + // filenames const base::FilePath::CharType kCacheDirname[] = FPL("Cache"); const base::FilePath::CharType kChannelIDFilename[] = FPL("Origin Bound Certs"); diff --git a/chromium_src/chrome/common/chrome_constants.h b/chromium_src/chrome/common/chrome_constants.h index e36eeeeff4..2df506ac5d 100644 --- a/chromium_src/chrome/common/chrome_constants.h +++ b/chromium_src/chrome/common/chrome_constants.h @@ -11,6 +11,14 @@ namespace chrome { +#if defined(OS_MACOSX) +// NOTE: if you change the value of kFrameworkName, please don't forget to +// update components/test/run_all_unittests.cc as well. +// TODO(tfarina): Remove the comment above, when you fix components to use plist +// on Mac. +extern const base::FilePath::CharType kFrameworkName[]; +#endif // OS_MACOSX + // filenames extern const base::FilePath::CharType kCacheDirname[]; extern const base::FilePath::CharType kChannelIDFilename[]; diff --git a/chromium_src/chrome/common/chrome_paths_mac.mm b/chromium_src/chrome/common/chrome_paths_mac.mm index 09cf13bfe1..4a4eb87dc2 100644 --- a/chromium_src/chrome/common/chrome_paths_mac.mm +++ b/chromium_src/chrome/common/chrome_paths_mac.mm @@ -179,10 +179,9 @@ base::FilePath GetVersionedDirectory() { // .app's versioned directory. Go up two steps to get to the browser // .app's versioned directory. path = path.DirName().DirName(); - DCHECK_EQ(path.BaseName().value(), kChromeVersion); } else { // Go into the versioned directory. - path = path.Append("Versions").Append(kChromeVersion); + path = path.Append("Frameworks"); } return path; From d3caea91b073b1c38117135c7e720b2a7deef047 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 13 Nov 2015 13:05:16 +0800 Subject: [PATCH 21/31] Add paths from chrome_paths --- atom/app/atom_main_delegate.cc | 3 +++ atom/browser/api/atom_api_app.cc | 30 +++++++++++++----------------- docs/api/app.md | 8 ++++++-- 3 files changed, 22 insertions(+), 19 deletions(-) diff --git a/atom/app/atom_main_delegate.cc b/atom/app/atom_main_delegate.cc index 3bc1ac4970..8028313106 100644 --- a/atom/app/atom_main_delegate.cc +++ b/atom/app/atom_main_delegate.cc @@ -16,6 +16,7 @@ #include "base/debug/stack_trace.h" #include "base/environment.h" #include "base/logging.h" +#include "chrome/common/chrome_paths.h" #include "content/public/common/content_switches.h" #include "ui/base/resource/resource_bundle.h" @@ -79,6 +80,8 @@ bool AtomMainDelegate::BasicStartupComplete(int* exit_code) { if (enable_stack_dumping) base::debug::EnableInProcessStackDumping(); + chrome::RegisterPathProvider(); + return brightray::MainDelegate::BasicStartupComplete(exit_code); } diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index d6d961a08d..e1fa03af5f 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -22,9 +22,9 @@ #include "base/command_line.h" #include "base/environment.h" #include "base/files/file_path.h" -#include "base/nix/xdg_util.h" #include "base/path_service.h" #include "brightray/browser/brightray_paths.h" +#include "chrome/common/chrome_paths.h" #include "content/public/browser/client_certificate_delegate.h" #include "content/public/browser/gpu_data_manager.h" #include "content/public/common/content_switches.h" @@ -100,12 +100,22 @@ int GetPathConstant(const std::string& name) { return base::DIR_HOME; else if (name == "temp") return base::DIR_TEMP; - else if (name == "userDesktop") + else if (name == "userDesktop" || name == "desktop") return base::DIR_USER_DESKTOP; else if (name == "exe") return base::FILE_EXE; else if (name == "module") return base::FILE_MODULE; + else if (name == "documents") + return chrome::DIR_USER_DOCUMENTS; + else if (name == "downloads") + return chrome::DIR_DEFAULT_DOWNLOADS; + else if (name == "music") + return chrome::DIR_USER_MUSIC; + else if (name == "pictures") + return chrome::DIR_USER_PICTURES; + else if (name == "videos") + return chrome::DIR_USER_VIDEOS; else return -1; } @@ -156,17 +166,6 @@ void PassLoginInformation(scoped_refptr login_handler, login_handler->CancelAuth(); } -bool GetUserDownloadsDirectory(base::FilePath* path) { -#if defined(OS_LINUX) - *path = base::nix::GetXDGUserDirectory("DOWNLOAD", "Downloads"); - return true; -#elif defined(OS_MACOSX) - return false; -#elif defined(OS_WIN) - return false; -#endif -} - } // namespace App::App() { @@ -284,11 +283,8 @@ base::FilePath App::GetPath(mate::Arguments* args, const std::string& name) { int key = GetPathConstant(name); if (key >= 0) succeed = PathService::Get(key, &path); - if (!succeed) { - if (name == "downloads" && GetUserDownloadsDirectory(&path)) - return path; + if (!succeed) args->ThrowError("Failed to get path"); - } return path; } diff --git a/docs/api/app.md b/docs/api/app.md index b145ce7f01..9d10bbb835 100644 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -238,10 +238,14 @@ You can request the following paths by the name: * `userData` The directory for storing your app's configuration files, which by default it is the `appData` directory appended with your app's name. * `temp` Temporary directory. -* `userDesktop` The current user's Desktop directory. * `exe` The current executable file. * `module` The `libchromiumcontent` library. -* `downloads` User's download directory. +* `desktop` The current user's Desktop directory. +* `documents` Directory for a user's "My Documents". +* `downloads` Directory for a user's downloads. +* `music` Directory for a user's music. +* `pictures` Directory for a user's pictures. +* `videos` Directory for a user's videos. ### `app.setPath(name, path)` From fdc19f2d3a16e703fbcc6985a4a98673a0292936 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 13 Nov 2015 13:23:13 +0800 Subject: [PATCH 22/31] Fix building on Windows --- .../chrome/common/chrome_paths_win.cc | 19 ++----------------- 1 file changed, 2 insertions(+), 17 deletions(-) diff --git a/chromium_src/chrome/common/chrome_paths_win.cc b/chromium_src/chrome/common/chrome_paths_win.cc index 18073ca047..37f4ec2b05 100644 --- a/chromium_src/chrome/common/chrome_paths_win.cc +++ b/chromium_src/chrome/common/chrome_paths_win.cc @@ -15,9 +15,6 @@ #include "base/win/metro.h" #include "base/win/scoped_co_mem.h" #include "chrome/common/chrome_constants.h" -#include "chrome/common/chrome_switches.h" -#include "chrome/installer/util/browser_distribution.h" -#include "components/nacl/common/nacl_switches.h" namespace chrome { @@ -43,12 +40,7 @@ bool GetUserDirectory(int csidl_folder, base::FilePath* result) { } // namespace bool GetDefaultUserDataDirectory(base::FilePath* result) { - if (!PathService::Get(base::DIR_LOCAL_APP_DATA, result)) - return false; - BrowserDistribution* dist = BrowserDistribution::GetDistribution(); - *result = result->Append(dist->GetInstallSubDir()); - *result = result->Append(chrome::kUserDataDirname); - return true; + return PathService::Get(base::DIR_LOCAL_APP_DATA, result); } void GetUserCacheDirectory(const base::FilePath& profile_dir, @@ -106,16 +98,9 @@ bool ProcessNeedsProfileDir(const std::string& process_type) { // service processes to be able to use the profile directory because if it // lies on a network share the sandbox will prevent us from accessing it. - if (process_type.empty() || process_type == switches::kServiceProcess) + if (process_type.empty()) return true; -#if !defined(DISABLE_NACL) - if (process_type == switches::kNaClBrokerProcess || - process_type == switches::kNaClLoaderProcess) { - return true; - } -#endif - return false; } From 860c46b3c1fb05aae557971a17adbed9601e151c Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 13 Nov 2015 13:58:31 +0800 Subject: [PATCH 23/31] Separate options from switches On Windows the case sensitivity of command line switches are ignored, so --nodeIntegraion will become --nodeintegration. We should separate options from switches so we use "nodeIntegraion" in options, while passing "--node-integration" in command line. --- atom/browser/api/atom_api_window.cc | 14 +++---- atom/browser/native_window.cc | 38 +++++++++---------- atom/browser/native_window_mac.mm | 18 ++++----- atom/browser/native_window_views.cc | 20 +++++----- atom/browser/web_contents_preferences.cc | 48 ++++++++++++++---------- atom/common/options_switches.cc | 31 +++++++++++---- atom/common/options_switches.h | 22 ++++++++++- atom/renderer/lib/init.coffee | 4 +- 8 files changed, 119 insertions(+), 76 deletions(-) diff --git a/atom/browser/api/atom_api_window.cc b/atom/browser/api/atom_api_window.cc index 048a8eff1d..61f43f9aac 100644 --- a/atom/browser/api/atom_api_window.cc +++ b/atom/browser/api/atom_api_window.cc @@ -127,16 +127,16 @@ Window::Window(v8::Isolate* isolate, const mate::Dictionary& options) { // Use options.webPreferences to create WebContents. mate::Dictionary web_preferences = mate::Dictionary::CreateEmpty(isolate); - options.Get(switches::kWebPreferences, &web_preferences); + options.Get(options::kWebPreferences, &web_preferences); // Be compatible with old options which are now in web_preferences. v8::Local value; - if (options.Get(switches::kNodeIntegration, &value)) - web_preferences.Set(switches::kNodeIntegration, value); - if (options.Get(switches::kPreloadScript, &value)) - web_preferences.Set(switches::kPreloadScript, value); - if (options.Get(switches::kZoomFactor, &value)) - web_preferences.Set(switches::kZoomFactor, value); + if (options.Get(options::kNodeIntegration, &value)) + web_preferences.Set(options::kNodeIntegration, value); + if (options.Get(options::kPreloadScript, &value)) + web_preferences.Set(options::kPreloadScript, value); + if (options.Get(options::kZoomFactor, &value)) + web_preferences.Set(options::kZoomFactor, value); // Creates the WebContents used by BrowserWindow. auto web_contents = WebContents::Create(isolate, web_preferences); diff --git a/atom/browser/native_window.cc b/atom/browser/native_window.cc index ba5dad74f5..ad7a6c4b06 100644 --- a/atom/browser/native_window.cc +++ b/atom/browser/native_window.cc @@ -56,16 +56,16 @@ NativeWindow::NativeWindow( aspect_ratio_(0.0), inspectable_web_contents_(inspectable_web_contents), weak_factory_(this) { - options.Get(switches::kFrame, &has_frame_); - options.Get(switches::kTransparent, &transparent_); - options.Get(switches::kEnableLargerThanScreen, &enable_larger_than_screen_); + options.Get(options::kFrame, &has_frame_); + options.Get(options::kTransparent, &transparent_); + options.Get(options::kEnableLargerThanScreen, &enable_larger_than_screen_); // Tell the content module to initialize renderer widget with transparent // mode. ui::GpuSwitchingManager::SetTransparent(transparent_); // Read icon before window is created. - options.Get(switches::kIcon, &icon_); + options.Get(options::kIcon, &icon_); WindowList::AddWindow(this); } @@ -91,25 +91,25 @@ void NativeWindow::InitFromOptions(const mate::Dictionary& options) { // Setup window from options. int x = -1, y = -1; bool center; - if (options.Get(switches::kX, &x) && options.Get(switches::kY, &y)) { + if (options.Get(options::kX, &x) && options.Get(options::kY, &y)) { SetPosition(gfx::Point(x, y)); - } else if (options.Get(switches::kCenter, ¢er) && center) { + } else if (options.Get(options::kCenter, ¢er) && center) { Center(); } // On Linux and Window we may already have maximum size defined. extensions::SizeConstraints size_constraints(GetContentSizeConstraints()); int min_height = 0, min_width = 0; - if (options.Get(switches::kMinHeight, &min_height) | - options.Get(switches::kMinWidth, &min_width)) { + if (options.Get(options::kMinHeight, &min_height) | + options.Get(options::kMinWidth, &min_width)) { size_constraints.set_minimum_size(gfx::Size(min_width, min_height)); } int max_height = INT_MAX, max_width = INT_MAX; - if (options.Get(switches::kMaxHeight, &max_height) | - options.Get(switches::kMaxWidth, &max_width)) { + if (options.Get(options::kMaxHeight, &max_height) | + options.Get(options::kMaxWidth, &max_width)) { size_constraints.set_maximum_size(gfx::Size(max_width, max_height)); } bool use_content_size = false; - options.Get(switches::kUseContentSize, &use_content_size); + options.Get(options::kUseContentSize, &use_content_size); if (use_content_size) { SetContentSizeConstraints(size_constraints); } else { @@ -117,39 +117,39 @@ void NativeWindow::InitFromOptions(const mate::Dictionary& options) { } #if defined(OS_WIN) || defined(USE_X11) bool resizable; - if (options.Get(switches::kResizable, &resizable)) { + if (options.Get(options::kResizable, &resizable)) { SetResizable(resizable); } #endif bool top; - if (options.Get(switches::kAlwaysOnTop, &top) && top) { + if (options.Get(options::kAlwaysOnTop, &top) && top) { SetAlwaysOnTop(true); } #if defined(OS_MACOSX) || defined(OS_WIN) bool fullscreen; - if (options.Get(switches::kFullscreen, &fullscreen) && fullscreen) { + if (options.Get(options::kFullscreen, &fullscreen) && fullscreen) { SetFullScreen(true); } #endif bool skip; - if (options.Get(switches::kSkipTaskbar, &skip) && skip) { + if (options.Get(options::kSkipTaskbar, &skip) && skip) { SetSkipTaskbar(skip); } bool kiosk; - if (options.Get(switches::kKiosk, &kiosk) && kiosk) { + if (options.Get(options::kKiosk, &kiosk) && kiosk) { SetKiosk(kiosk); } std::string color; - if (options.Get(switches::kBackgroundColor, &color)) { + if (options.Get(options::kBackgroundColor, &color)) { SetBackgroundColor(color); } std::string title("Electron"); - options.Get(switches::kTitle, &title); + options.Get(options::kTitle, &title); SetTitle(title); // Then show it. bool show = true; - options.Get(switches::kShow, &show); + options.Get(options::kShow, &show); if (show) Show(); } diff --git a/atom/browser/native_window_mac.mm b/atom/browser/native_window_mac.mm index 28c8a5ae59..b129ded6f8 100644 --- a/atom/browser/native_window_mac.mm +++ b/atom/browser/native_window_mac.mm @@ -320,8 +320,8 @@ NativeWindowMac::NativeWindowMac( is_kiosk_(false), attention_request_id_(0) { int width = 800, height = 600; - options.Get(switches::kWidth, &width); - options.Get(switches::kHeight, &height); + options.Get(options::kWidth, &width); + options.Get(options::kHeight, &height); NSRect main_screen_rect = [[[NSScreen screens] objectAtIndex:0] frame]; NSRect cocoa_bounds = NSMakeRect( @@ -331,14 +331,14 @@ NativeWindowMac::NativeWindowMac( height); bool useStandardWindow = true; - options.Get(switches::kStandardWindow, &useStandardWindow); + options.Get(options::kStandardWindow, &useStandardWindow); bool resizable = true; - options.Get(switches::kResizable, &resizable); + options.Get(options::kResizable, &resizable); // New title bar styles are available in Yosemite or newer std::string titleBarStyle; if (base::mac::IsOSYosemiteOrLater()) - options.Get(switches::kTitleBarStyle, &titleBarStyle); + options.Get(options::kTitleBarStyle, &titleBarStyle); NSUInteger styleMask = NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask; @@ -394,23 +394,23 @@ NativeWindowMac::NativeWindowMac( // On OS X the initial window size doesn't include window frame. bool use_content_size = false; - options.Get(switches::kUseContentSize, &use_content_size); + options.Get(options::kUseContentSize, &use_content_size); if (!has_frame() || !use_content_size) SetSize(gfx::Size(width, height)); // Enable the NSView to accept first mouse event. bool acceptsFirstMouse = false; - options.Get(switches::kAcceptFirstMouse, &acceptsFirstMouse); + options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse); [window_ setAcceptsFirstMouse:acceptsFirstMouse]; // Disable auto-hiding cursor. bool disableAutoHideCursor = false; - options.Get(switches::kDisableAutoHideCursor, &disableAutoHideCursor); + options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor); [window_ setDisableAutoHideCursor:disableAutoHideCursor]; // Disable fullscreen button when 'fullscreen' is specified to false. bool fullscreen; - if (!(options.Get(switches::kFullscreen, &fullscreen) && + if (!(options.Get(options::kFullscreen, &fullscreen) && !fullscreen)) { NSUInteger collectionBehavior = [window_ collectionBehavior]; collectionBehavior |= NSWindowCollectionBehaviorFullScreenPrimary; diff --git a/atom/browser/native_window_views.cc b/atom/browser/native_window_views.cc index 876058789d..c12ae1986c 100644 --- a/atom/browser/native_window_views.cc +++ b/atom/browser/native_window_views.cc @@ -132,13 +132,13 @@ NativeWindowViews::NativeWindowViews( keyboard_event_handler_(new views::UnhandledKeyboardEventHandler), use_content_size_(false), resizable_(true) { - options.Get(switches::kTitle, &title_); - options.Get(switches::kAutoHideMenuBar, &menu_bar_autohide_); + options.Get(options::kTitle, &title_); + options.Get(options::kAutoHideMenuBar, &menu_bar_autohide_); #if defined(OS_WIN) // On Windows we rely on the CanResize() to indicate whether window can be // resized, and it should be set before window is created. - options.Get(switches::kResizable, &resizable_); + options.Get(options::kResizable, &resizable_); #endif if (enable_larger_than_screen()) @@ -150,8 +150,8 @@ NativeWindowViews::NativeWindowViews( gfx::Size(), gfx::Size(INT_MAX / 10, INT_MAX / 10))); int width = 800, height = 600; - options.Get(switches::kWidth, &width); - options.Get(switches::kHeight, &height); + options.Get(options::kWidth, &width); + options.Get(options::kHeight, &height); gfx::Rect bounds(0, 0, width, height); widget_size_ = bounds.size(); @@ -187,7 +187,7 @@ NativeWindowViews::NativeWindowViews( window_->Init(params); bool fullscreen = false; - options.Get(switches::kFullscreen, &fullscreen); + options.Get(options::kFullscreen, &fullscreen); #if defined(USE_X11) // Start monitoring window states. @@ -195,7 +195,7 @@ NativeWindowViews::NativeWindowViews( // Set _GTK_THEME_VARIANT to dark if we have "dark-theme" option set. bool use_dark_theme = false; - if (options.Get(switches::kDarkTheme, &use_dark_theme) && use_dark_theme) { + if (options.Get(options::kDarkTheme, &use_dark_theme) && use_dark_theme) { XDisplay* xdisplay = gfx::GetXDisplay(); XChangeProperty(xdisplay, GetAcceleratedWidget(), XInternAtom(xdisplay, "_GTK_THEME_VARIANT", False), @@ -209,7 +209,7 @@ NativeWindowViews::NativeWindowViews( // to manually set the _NET_WM_STATE. std::vector<::Atom> state_atom_list; bool skip_taskbar = false; - if (options.Get(switches::kSkipTaskbar, &skip_taskbar) && skip_taskbar) { + if (options.Get(options::kSkipTaskbar, &skip_taskbar) && skip_taskbar) { state_atom_list.push_back(GetAtom("_NET_WM_STATE_SKIP_TASKBAR")); } @@ -223,7 +223,7 @@ NativeWindowViews::NativeWindowViews( // Set the _NET_WM_WINDOW_TYPE. std::string window_type; - if (options.Get(switches::kType, &window_type)) + if (options.Get(options::kType, &window_type)) SetWindowType(GetAcceleratedWidget(), window_type); #endif @@ -274,7 +274,7 @@ NativeWindowViews::NativeWindowViews( gfx::Size size = bounds.size(); if (has_frame() && - options.Get(switches::kUseContentSize, &use_content_size_) && + options.Get(options::kUseContentSize, &use_content_size_) && use_content_size_) size = ContentSizeToWindowSize(size); diff --git a/atom/browser/web_contents_preferences.cc b/atom/browser/web_contents_preferences.cc index 2adb77211b..188de4d1bf 100644 --- a/atom/browser/web_contents_preferences.cc +++ b/atom/browser/web_contents_preferences.cc @@ -25,13 +25,23 @@ namespace atom { namespace { // Array of available web runtime features. -const char* kWebRuntimeFeatures[] = { - switches::kExperimentalFeatures, - switches::kExperimentalCanvasFeatures, - switches::kOverlayScrollbars, - switches::kOverlayFullscreenVideo, - switches::kSharedWorker, - switches::kPageVisibility, +struct FeaturePair { + const char* name; + const char* cmd; +}; +FeaturePair kWebRuntimeFeatures[] = { + { options::kExperimentalFeatures, + switches::kExperimentalFeatures }, + { options::kExperimentalCanvasFeatures, + switches::kExperimentalCanvasFeatures }, + { options::kOverlayScrollbars, + switches::kOverlayScrollbars }, + { options::kOverlayFullscreenVideo, + switches::kOverlayFullscreenVideo }, + { options::kSharedWorker, + switches::kSharedWorker }, + { options::kPageVisibility, + switches::kPageVisibility }, }; } // namespace @@ -69,7 +79,7 @@ void WebContentsPreferences::AppendExtraCommandLineSwitches( bool b; #if defined(OS_WIN) // Check if DirectWrite is disabled. - if (web_preferences.GetBoolean(switches::kDirectWrite, &b) && !b) + if (web_preferences.GetBoolean(options::kDirectWrite, &b) && !b) command_line->AppendSwitch(::switches::kDisableDirectWrite); #endif @@ -80,17 +90,17 @@ void WebContentsPreferences::AppendExtraCommandLineSwitches( // This set of options are not availabe in WebPreferences, so we have to pass // them via command line and enable them in renderer procss. for (size_t i = 0; i < arraysize(kWebRuntimeFeatures); ++i) { - const char* feature = kWebRuntimeFeatures[i]; - if (web_preferences.GetBoolean(feature, &b)) - command_line->AppendSwitchASCII(feature, b ? "true" : "false"); + const auto& feature = kWebRuntimeFeatures[i]; + if (web_preferences.GetBoolean(feature.name, &b)) + command_line->AppendSwitchASCII(feature.cmd, b ? "true" : "false"); } // Check if we have node integration specified. bool node_integration = true; - web_preferences.GetBoolean(switches::kNodeIntegration, &node_integration); + web_preferences.GetBoolean(options::kNodeIntegration, &node_integration); // Be compatible with old API of "node-integration" option. std::string old_token; - if (web_preferences.GetString(switches::kNodeIntegration, &old_token) && + if (web_preferences.GetString(options::kNodeIntegration, &old_token) && old_token != "disable") node_integration = true; command_line->AppendSwitchASCII(switches::kNodeIntegration, @@ -98,12 +108,12 @@ void WebContentsPreferences::AppendExtraCommandLineSwitches( // The preload script. base::FilePath::StringType preload; - if (web_preferences.GetString(switches::kPreloadScript, &preload)) { + if (web_preferences.GetString(options::kPreloadScript, &preload)) { if (base::FilePath(preload).IsAbsolute()) command_line->AppendSwitchNative(switches::kPreloadScript, preload); else LOG(ERROR) << "preload script must have absolute path."; - } else if (web_preferences.GetString(switches::kPreloadUrl, &preload)) { + } else if (web_preferences.GetString(options::kPreloadUrl, &preload)) { // Translate to file path if there is "preload-url" option. base::FilePath preload_path; if (net::FileURLToFilePath(GURL(preload), &preload_path)) @@ -114,15 +124,14 @@ void WebContentsPreferences::AppendExtraCommandLineSwitches( // The zoom factor. double zoom_factor = 1.0; - if (web_preferences.GetDouble(switches::kZoomFactor, &zoom_factor) && + if (web_preferences.GetDouble(options::kZoomFactor, &zoom_factor) && zoom_factor != 1.0) command_line->AppendSwitchASCII(switches::kZoomFactor, base::DoubleToString(zoom_factor)); // --guest-instance-id, which is used to identify guest WebContents. int guest_instance_id; - if (web_preferences.GetInteger(switches::kGuestInstanceID, - &guest_instance_id)) + if (web_preferences.GetInteger(options::kGuestInstanceID, &guest_instance_id)) command_line->AppendSwitchASCII(switches::kGuestInstanceID, base::IntToString(guest_instance_id)); } @@ -152,8 +161,7 @@ void WebContentsPreferences::OverrideWebkitPrefs( prefs->allow_displaying_insecure_content = !b; prefs->allow_running_insecure_content = !b; } - if (self->web_preferences_.GetBoolean("allowDisplayingInsecureContent", - &b)) + if (self->web_preferences_.GetBoolean("allowDisplayingInsecureContent", &b)) prefs->allow_displaying_insecure_content = b; if (self->web_preferences_.GetBoolean("allowRunningInsecureContent", &b)) prefs->allow_running_insecure_content = b; diff --git a/atom/common/options_switches.cc b/atom/common/options_switches.cc index 9b3b50b4bf..1d375ba0fc 100644 --- a/atom/common/options_switches.cc +++ b/atom/common/options_switches.cc @@ -6,7 +6,7 @@ namespace atom { -namespace switches { +namespace options { const char kTitle[] = "title"; const char kIcon[] = "icon"; @@ -85,6 +85,12 @@ const char kNodeIntegration[] = "nodeIntegration"; // Instancd ID of guest WebContents. const char kGuestInstanceID[] = "guestInstanceId"; +// Set page visiblity to always visible. +const char kPageVisibility[] = "pageVisibility"; + +// Enable DirectWrite on Windows. +const char kDirectWrite[] = "directWrite"; + // Web runtime features. const char kExperimentalFeatures[] = "experimentalFeatures"; const char kExperimentalCanvasFeatures[] = "experimentalCanvasFeatures"; @@ -92,6 +98,10 @@ const char kOverlayScrollbars[] = "overlayScrollbars"; const char kOverlayFullscreenVideo[] = "overlayFullscreenVideo"; const char kSharedWorker[] = "sharedWorker"; +} // namespace options + +namespace switches { + // Enable plugins. const char kEnablePlugins[] = "enable-plugins"; @@ -101,12 +111,6 @@ const char kPpapiFlashPath[] = "ppapi-flash-path"; // Ppapi Flash version. const char kPpapiFlashVersion[] = "ppapi-flash-version"; -// Set page visiblity to always visible. -const char kPageVisibility[] = "page-visibility"; - -// Enable DirectWrite on Windows. -const char kDirectWrite[] = "direct-write"; - // Path to client certificate. const char kClientCertificate[] = "client-certificate"; @@ -126,6 +130,19 @@ const char kCipherSuiteBlacklist[] = "cipher-suite-blacklist"; // The browser process app model ID const char kAppUserModelId[] = "app-user-model-id"; +// The command line switch versions of the options. +const char kZoomFactor[] = "zoom-factor"; +const char kPreloadScript[] = "preload"; +const char kPreloadUrl[] = "preload-url"; +const char kNodeIntegration[] = "node-integration"; +const char kGuestInstanceID[] = "guest-instance-id"; +const char kExperimentalFeatures[] = "experimental-features"; +const char kExperimentalCanvasFeatures[] = "experimental-canvas-features"; +const char kOverlayScrollbars[] = "overlay-scrollbars"; +const char kOverlayFullscreenVideo[] = "overlay-fullscreen-video"; +const char kSharedWorker[] = "shared-worker"; +const char kPageVisibility[] = "page-visiblity"; + } // namespace switches } // namespace atom diff --git a/atom/common/options_switches.h b/atom/common/options_switches.h index 9f171836f6..7f262fb0f7 100644 --- a/atom/common/options_switches.h +++ b/atom/common/options_switches.h @@ -7,7 +7,7 @@ namespace atom { -namespace switches { +namespace options { extern const char kTitle[]; extern const char kIcon[]; @@ -41,6 +41,7 @@ extern const char kBackgroundColor[]; extern const char kWebPreferences[]; // WebPreferences. +extern const char kDirectWrite[]; extern const char kZoomFactor[]; extern const char kPreloadScript[]; extern const char kPreloadUrl[]; @@ -52,9 +53,14 @@ extern const char kOverlayScrollbars[]; extern const char kOverlayFullscreenVideo[]; extern const char kSharedWorker[]; extern const char kPageVisibility[]; -extern const char kDirectWrite[]; + +} // namespace options + // Following are actually command line switches, should be moved to other files. + +namespace switches { + extern const char kEnablePlugins[]; extern const char kPpapiFlashPath[]; extern const char kPpapiFlashVersion[]; @@ -65,6 +71,18 @@ extern const char kSSLVersionFallbackMin[]; extern const char kCipherSuiteBlacklist[]; extern const char kAppUserModelId[]; +extern const char kZoomFactor[]; +extern const char kPreloadScript[]; +extern const char kPreloadUrl[]; +extern const char kNodeIntegration[]; +extern const char kGuestInstanceID[]; +extern const char kExperimentalFeatures[]; +extern const char kExperimentalCanvasFeatures[]; +extern const char kOverlayScrollbars[]; +extern const char kOverlayFullscreenVideo[]; +extern const char kSharedWorker[]; +extern const char kPageVisibility[]; + } // namespace switches } // namespace atom diff --git a/atom/renderer/lib/init.coffee b/atom/renderer/lib/init.coffee index b7155c1cc5..d9f104f8d4 100644 --- a/atom/renderer/lib/init.coffee +++ b/atom/renderer/lib/init.coffee @@ -27,10 +27,10 @@ v8Util.setHiddenValue global, 'ipc', new events.EventEmitter # Process command line arguments. nodeIntegration = 'false' for arg in process.argv - if arg.indexOf('--guestInstanceId=') == 0 + if arg.indexOf('--guest-instance-id=') == 0 # This is a guest web view. process.guestInstanceId = parseInt arg.substr(arg.indexOf('=') + 1) - else if arg.indexOf('--nodeIntegration=') == 0 + else if arg.indexOf('--node-integration=') == 0 nodeIntegration = arg.substr arg.indexOf('=') + 1 else if arg.indexOf('--preload=') == 0 preloadScript = arg.substr arg.indexOf('=') + 1 From fbb8e61958c8950455883e2a4ae12088ba030a12 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 13 Nov 2015 16:03:40 +0800 Subject: [PATCH 24/31] Replace "Url" in API names with "URL" --- atom/browser/api/atom_api_auto_updater.cc | 2 +- atom/browser/api/atom_api_cookies.cc | 6 +- atom/browser/api/atom_api_download_item.cc | 6 +- atom/browser/api/atom_api_download_item.h | 2 +- atom/browser/api/atom_api_protocol.cc | 4 +- atom/browser/api/atom_api_web_contents.cc | 4 +- atom/browser/api/lib/app.coffee | 3 +- atom/browser/api/lib/auto-updater.coffee | 9 +- .../lib/auto-updater/auto-updater-win.coffee | 12 +-- .../auto-updater/squirrel-update-win.coffee | 8 +- atom/browser/api/lib/browser-window.coffee | 8 +- .../api/lib/navigation-controller.coffee | 20 ++-- atom/browser/api/lib/web-contents.coffee | 8 +- atom/browser/atom_access_token_store.cc | 6 +- atom/browser/default_app/default_app.js | 2 +- atom/browser/lib/guest-view-manager.coffee | 4 +- atom/browser/lib/guest-window-manager.coffee | 8 +- .../browser/net/url_request_async_asar_job.cc | 4 +- atom/browser/net/url_request_async_asar_job.h | 6 +- atom/browser/web_contents_preferences.cc | 2 +- atom/common/api/atom_api_native_image.cc | 5 +- atom/common/api/lib/crash-reporter.coffee | 19 ++-- atom/common/api/lib/native-image.coffee | 8 +- atom/common/options_switches.cc | 4 +- atom/common/options_switches.h | 4 +- atom/common/platform_util_win.cc | 4 +- atom/renderer/api/atom_api_web_frame.cc | 10 +- atom/renderer/api/atom_api_web_frame.h | 2 +- atom/renderer/api/lib/web-frame.coffee | 10 +- atom/renderer/lib/override.coffee | 4 +- .../lib/web-view/guest-view-internal.coffee | 6 +- .../lib/web-view/web-view-attributes.coffee | 8 +- atom/renderer/lib/web-view/web-view.coffee | 91 ++++++++++--------- docs/api/auto-updater.md | 6 +- docs/api/browser-window.md | 6 +- docs/api/crash-reporter.md | 6 +- docs/api/download-item.md | 2 +- docs/api/native-image.md | 8 +- docs/api/remote.md | 2 +- docs/api/session.md | 6 +- docs/api/synopsis.md | 2 +- docs/api/web-contents.md | 30 +++--- docs/api/web-frame.md | 6 +- docs/api/web-view-tag.md | 14 +-- docs/tutorial/application-packaging.md | 2 +- docs/tutorial/online-offline-events.md | 4 +- docs/tutorial/quick-start.md | 2 +- docs/tutorial/using-pepper-flash-plugin.md | 2 +- spec/api-browser-window-spec.coffee | 34 +++---- spec/api-clipboard-spec.coffee | 4 +- spec/api-crash-reporter-spec.coffee | 4 +- spec/api-ipc-spec.coffee | 2 +- spec/api-session-spec.coffee | 8 +- spec/asar-spec.coffee | 4 +- spec/chromium-spec.coffee | 4 +- spec/fixtures/api/crash.html | 2 +- spec/static/main.js | 4 +- 57 files changed, 251 insertions(+), 212 deletions(-) diff --git a/atom/browser/api/atom_api_auto_updater.cc b/atom/browser/api/atom_api_auto_updater.cc index 1c80f73f7a..1a02a54d45 100644 --- a/atom/browser/api/atom_api_auto_updater.cc +++ b/atom/browser/api/atom_api_auto_updater.cc @@ -81,7 +81,7 @@ void AutoUpdater::OnWindowAllClosed() { mate::ObjectTemplateBuilder AutoUpdater::GetObjectTemplateBuilder( v8::Isolate* isolate) { return mate::ObjectTemplateBuilder(isolate) - .SetMethod("setFeedUrl", &auto_updater::AutoUpdater::SetFeedURL) + .SetMethod("setFeedURL", &auto_updater::AutoUpdater::SetFeedURL) .SetMethod("checkForUpdates", &auto_updater::AutoUpdater::CheckForUpdates) .SetMethod("quitAndInstall", &AutoUpdater::QuitAndInstall); } diff --git a/atom/browser/api/atom_api_cookies.cc b/atom/browser/api/atom_api_cookies.cc index 4f989eff72..a3b2c37c9a 100644 --- a/atom/browser/api/atom_api_cookies.cc +++ b/atom/browser/api/atom_api_cookies.cc @@ -204,7 +204,7 @@ void Cookies::GetCookiesOnIOThread(scoped_ptr filter, Passed(&filter), callback))) { BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&RunGetCookiesCallbackOnUIThread, isolate(), - "Url is not valid", net::CookieList(), callback)); + "URL is not valid", net::CookieList(), callback)); } } @@ -229,7 +229,7 @@ void Cookies::Remove(const mate::Dictionary& details, error_message = "Details(url, name) of removing cookie are required."; } if (error_message.empty() && !url.is_valid()) { - error_message = "Url is not valid."; + error_message = "URL is not valid."; } if (!error_message.empty()) { RunRemoveCookiesCallbackOnUIThread(isolate(), error_message, callback); @@ -261,7 +261,7 @@ void Cookies::Set(const base::DictionaryValue& options, GURL gurl(url); if (error_message.empty() && !gurl.is_valid()) { - error_message = "Url is not valid."; + error_message = "URL is not valid."; } if (!error_message.empty()) { diff --git a/atom/browser/api/atom_api_download_item.cc b/atom/browser/api/atom_api_download_item.cc index 691cfbfef5..7dd271304a 100644 --- a/atom/browser/api/atom_api_download_item.cc +++ b/atom/browser/api/atom_api_download_item.cc @@ -103,7 +103,7 @@ int64 DownloadItem::GetTotalBytes() { return download_item_->GetTotalBytes(); } -const GURL& DownloadItem::GetUrl() { +const GURL& DownloadItem::GetURL() { return download_item_->GetURL(); } @@ -116,7 +116,7 @@ bool DownloadItem::HasUserGesture() { } std::string DownloadItem::GetFilename() { - return base::UTF16ToUTF8(net::GenerateFileName(GetUrl(), + return base::UTF16ToUTF8(net::GenerateFileName(GetURL(), GetContentDisposition(), std::string(), download_item_->GetSuggestedFilename(), @@ -152,7 +152,7 @@ mate::ObjectTemplateBuilder DownloadItem::GetObjectTemplateBuilder( .SetMethod("cancel", &DownloadItem::Cancel) .SetMethod("getReceivedBytes", &DownloadItem::GetReceivedBytes) .SetMethod("getTotalBytes", &DownloadItem::GetTotalBytes) - .SetMethod("getUrl", &DownloadItem::GetUrl) + .SetMethod("getURL", &DownloadItem::GetURL) .SetMethod("getMimeType", &DownloadItem::GetMimeType) .SetMethod("hasUserGesture", &DownloadItem::HasUserGesture) .SetMethod("getFilename", &DownloadItem::GetFilename) diff --git a/atom/browser/api/atom_api_download_item.h b/atom/browser/api/atom_api_download_item.h index 14074a4bed..955801cd99 100644 --- a/atom/browser/api/atom_api_download_item.h +++ b/atom/browser/api/atom_api_download_item.h @@ -49,7 +49,7 @@ class DownloadItem : public mate::EventEmitter, bool HasUserGesture(); std::string GetFilename(); std::string GetContentDisposition(); - const GURL& GetUrl(); + const GURL& GetURL(); void SetSavePath(const base::FilePath& path); private: diff --git a/atom/browser/api/atom_api_protocol.cc b/atom/browser/api/atom_api_protocol.cc index e76f26f0d4..b1ad798137 100644 --- a/atom/browser/api/atom_api_protocol.cc +++ b/atom/browser/api/atom_api_protocol.cc @@ -37,7 +37,7 @@ mate::ObjectTemplateBuilder Protocol::GetObjectTemplateBuilder( .SetMethod("registerBufferProtocol", &Protocol::RegisterProtocol) .SetMethod("registerFileProtocol", - &Protocol::RegisterProtocol) + &Protocol::RegisterProtocol) .SetMethod("registerHttpProtocol", &Protocol::RegisterProtocol) .SetMethod("unregisterProtocol", &Protocol::UnregisterProtocol) @@ -47,7 +47,7 @@ mate::ObjectTemplateBuilder Protocol::GetObjectTemplateBuilder( .SetMethod("interceptBufferProtocol", &Protocol::InterceptProtocol) .SetMethod("interceptFileProtocol", - &Protocol::InterceptProtocol) + &Protocol::InterceptProtocol) .SetMethod("interceptHttpProtocol", &Protocol::InterceptProtocol) .SetMethod("uninterceptProtocol", &Protocol::UninterceptProtocol); diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index d67794a91a..601a4ba63f 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -1003,8 +1003,8 @@ mate::ObjectTemplateBuilder WebContents::GetObjectTemplateBuilder( .SetMethod("isAlive", &WebContents::IsAlive, true) .SetMethod("getId", &WebContents::GetID) .SetMethod("equal", &WebContents::Equal) - .SetMethod("_loadUrl", &WebContents::LoadURL) - .SetMethod("_getUrl", &WebContents::GetURL) + .SetMethod("_loadURL", &WebContents::LoadURL) + .SetMethod("_getURL", &WebContents::GetURL) .SetMethod("getTitle", &WebContents::GetTitle) .SetMethod("isLoading", &WebContents::IsLoading) .SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse) diff --git a/atom/browser/api/lib/app.coffee b/atom/browser/api/lib/app.coffee index 3494a6e6e4..f8d3cedd38 100644 --- a/atom/browser/api/lib/app.coffee +++ b/atom/browser/api/lib/app.coffee @@ -63,10 +63,11 @@ wrapDownloadItem = (downloadItem) -> # downloadItem is an EventEmitter. downloadItem.__proto__ = EventEmitter.prototype # Deprecated. - deprecate.property downloadItem, 'url', 'getUrl' + deprecate.property downloadItem, 'url', 'getURL' deprecate.property downloadItem, 'filename', 'getFilename' deprecate.property downloadItem, 'mimeType', 'getMimeType' deprecate.property downloadItem, 'hasUserGesture', 'hasUserGesture' + deprecate.rename downloadItem, 'getUrl', 'getURL' downloadItemBindings._setWrapDownloadItem wrapDownloadItem # Only one App object pemitted. diff --git a/atom/browser/api/lib/auto-updater.coffee b/atom/browser/api/lib/auto-updater.coffee index d5e69e2a5c..28df59fbc3 100644 --- a/atom/browser/api/lib/auto-updater.coffee +++ b/atom/browser/api/lib/auto-updater.coffee @@ -1,5 +1,12 @@ -module.exports = +{deprecate} = require 'electron' + +autoUpdater = if process.platform is 'win32' require './auto-updater/auto-updater-win' else require './auto-updater/auto-updater-native' + +# Deprecated. +deprecate.rename autoUpdater, 'setFeedUrl', 'setFeedURL' + +module.exports = autoUpdater diff --git a/atom/browser/api/lib/auto-updater/auto-updater-win.coffee b/atom/browser/api/lib/auto-updater/auto-updater-win.coffee index 12ebedaaf7..e7cb194ffc 100644 --- a/atom/browser/api/lib/auto-updater/auto-updater-win.coffee +++ b/atom/browser/api/lib/auto-updater/auto-updater-win.coffee @@ -9,28 +9,28 @@ class AutoUpdater extends EventEmitter squirrelUpdate.processStart() app.quit() - setFeedUrl: (updateUrl) -> - @updateUrl = updateUrl + setFeedURL: (updateURL) -> + @updateURL = updateURL checkForUpdates: -> - return @emitError 'Update URL is not set' unless @updateUrl + return @emitError 'Update URL is not set' unless @updateURL return @emitError 'Can not find Squirrel' unless squirrelUpdate.supported() @emit 'checking-for-update' - squirrelUpdate.download @updateUrl, (error, update) => + squirrelUpdate.download @updateURL, (error, update) => return @emitError error if error? return @emit 'update-not-available' unless update? @emit 'update-available' - squirrelUpdate.update @updateUrl, (error) => + squirrelUpdate.update @updateURL, (error) => return @emitError error if error? {releaseNotes, version} = update # Following information is not available on Windows, so fake them. date = new Date - url = @updateUrl + url = @updateURL @emit 'update-downloaded', {}, releaseNotes, version, date, url, => @quitAndInstall() diff --git a/atom/browser/api/lib/auto-updater/squirrel-update-win.coffee b/atom/browser/api/lib/auto-updater/squirrel-update-win.coffee index ed302124e5..ee914c4fa8 100644 --- a/atom/browser/api/lib/auto-updater/squirrel-update-win.coffee +++ b/atom/browser/api/lib/auto-updater/squirrel-update-win.coffee @@ -41,8 +41,8 @@ exports.processStart = (callback) -> spawnUpdate ['--processStart', exeName], true, -> # Download the releases specified by the URL and write new results to stdout. -exports.download = (updateUrl, callback) -> - spawnUpdate ['--download', updateUrl], false, (error, stdout) -> +exports.download = (updateURL, callback) -> + spawnUpdate ['--download', updateURL], false, (error, stdout) -> return callback(error) if error? try @@ -55,8 +55,8 @@ exports.download = (updateUrl, callback) -> callback null, update # Update the application to the latest remote version specified by URL. -exports.update = (updateUrl, callback) -> - spawnUpdate ['--update', updateUrl], false, callback +exports.update = (updateURL, callback) -> + spawnUpdate ['--update', updateURL], false, callback # Is the Update.exe installed with the current application? exports.supported = -> diff --git a/atom/browser/api/lib/browser-window.coffee b/atom/browser/api/lib/browser-window.coffee index 3cefa1bf60..9947bc1a50 100644 --- a/atom/browser/api/lib/browser-window.coffee +++ b/atom/browser/api/lib/browser-window.coffee @@ -69,7 +69,8 @@ BrowserWindow.fromDevToolsWebContents = (webContents) -> return window for window in windows when window.devToolsWebContents?.equal webContents # Helpers. -BrowserWindow::loadUrl = -> @webContents.loadUrl.apply @webContents, arguments +BrowserWindow::loadURL = -> @webContents.loadURL.apply @webContents, arguments +BrowserWindow::getURL = -> @webContents.getURL() BrowserWindow::reload = -> @webContents.reload.apply @webContents, arguments BrowserWindow::send = -> @webContents.send.apply @webContents, arguments BrowserWindow::openDevTools = -> @webContents.openDevTools.apply @webContents, arguments @@ -80,14 +81,12 @@ BrowserWindow::inspectElement = -> @webContents.inspectElement.apply @webContent BrowserWindow::inspectServiceWorker = -> @webContents.inspectServiceWorker() # Deprecated. -deprecate.rename BrowserWindow, 'restart', 'reload' deprecate.member BrowserWindow, 'undo', 'webContents' deprecate.member BrowserWindow, 'redo', 'webContents' deprecate.member BrowserWindow, 'cut', 'webContents' deprecate.member BrowserWindow, 'copy', 'webContents' deprecate.member BrowserWindow, 'paste', 'webContents' deprecate.member BrowserWindow, 'selectAll', 'webContents' -deprecate.member BrowserWindow, 'getUrl', 'webContents' deprecate.member BrowserWindow, 'reloadIgnoringCache', 'webContents' deprecate.member BrowserWindow, 'getPageTitle', 'webContents' deprecate.member BrowserWindow, 'isLoading', 'webContents' @@ -97,5 +96,8 @@ deprecate.member BrowserWindow, 'isCrashed', 'webContents' deprecate.member BrowserWindow, 'executeJavaScriptInDevTools', 'webContents' deprecate.member BrowserWindow, 'print', 'webContents' deprecate.member BrowserWindow, 'printToPDF', 'webContents' +deprecate.rename BrowserWindow, 'restart', 'reload' +deprecate.rename BrowserWindow, 'loadUrl', 'loadURL' +deprecate.rename BrowserWindow, 'getUrl', 'getURL' module.exports = BrowserWindow diff --git a/atom/browser/api/lib/navigation-controller.coffee b/atom/browser/api/lib/navigation-controller.coffee index 88b1ed30dd..7d276e57e3 100644 --- a/atom/browser/api/lib/navigation-controller.coffee +++ b/atom/browser/api/lib/navigation-controller.coffee @@ -9,7 +9,7 @@ ipcMain.on 'ATOM_SHELL_SYNC_NAVIGATION_CONTROLLER', (event, method, args...) -> # JavaScript implementation of Chromium's NavigationController. # Instead of relying on Chromium for history control, we compeletely do history -# control on user land, and only rely on WebContents.loadUrl for navigation. +# control on user land, and only rely on WebContents.loadURL for navigation. # This helps us avoid Chromium's various optimizations so we can ensure renderer # process is restarted everytime. class NavigationController @@ -17,9 +17,9 @@ class NavigationController @clearHistory() # webContents may have already navigated to a page. - if @webContents._getUrl() + if @webContents._getURL() @currentIndex++ - @history.push @webContents._getUrl() + @history.push @webContents._getURL() @webContents.on 'navigation-entry-commited', (event, url, inPage, replaceEntry) => if @inPageIndex > -1 and not inPage @@ -42,12 +42,12 @@ class NavigationController @currentIndex++ @history.push url - loadUrl: (url, options={}) -> + loadURL: (url, options={}) -> @pendingIndex = -1 - @webContents._loadUrl url, options + @webContents._loadURL url, options @webContents.emit 'load-url', url, options - getUrl: -> + getURL: -> if @currentIndex is -1 '' else @@ -59,7 +59,7 @@ class NavigationController reload: -> @pendingIndex = @currentIndex - @webContents._loadUrl @getUrl(), {} + @webContents._loadURL @getURL(), {} reloadIgnoringCache: -> @webContents._reloadIgnoringCache() # Rely on WebContents to clear cache. @@ -89,7 +89,7 @@ class NavigationController if @inPageIndex > -1 and @pendingIndex >= @inPageIndex @webContents._goBack() else - @webContents._loadUrl @history[@pendingIndex], {} + @webContents._loadURL @history[@pendingIndex], {} goForward: -> return unless @canGoForward() @@ -97,12 +97,12 @@ class NavigationController if @inPageIndex > -1 and @pendingIndex >= @inPageIndex @webContents._goForward() else - @webContents._loadUrl @history[@pendingIndex], {} + @webContents._loadURL @history[@pendingIndex], {} goToIndex: (index) -> return unless @canGoToIndex index @pendingIndex = index - @webContents._loadUrl @history[@pendingIndex], {} + @webContents._loadURL @history[@pendingIndex], {} goToOffset: (offset) -> return unless @canGoToOffset offset diff --git a/atom/browser/api/lib/web-contents.coffee b/atom/browser/api/lib/web-contents.coffee index b3b1e7ed9f..1a224c7416 100644 --- a/atom/browser/api/lib/web-contents.coffee +++ b/atom/browser/api/lib/web-contents.coffee @@ -1,5 +1,5 @@ {EventEmitter} = require 'events' -{ipcMain, NavigationController, Menu} = require 'electron' +{deprecate, ipcMain, NavigationController, Menu} = require 'electron' binding = process.atomBinding 'web_contents' @@ -45,7 +45,7 @@ wrapWebContents = (webContents) -> # Make sure webContents.executeJavaScript would run the code only when the # web contents has been loaded. webContents.executeJavaScript = (code, hasUserGesture=false) -> - if @getUrl() and not @isLoading() + if @getURL() and not @isLoading() @_executeJavaScript code, hasUserGesture else webContents.once 'did-finish-load', @_executeJavaScript.bind(this, code, hasUserGesture) @@ -70,6 +70,10 @@ wrapWebContents = (webContents) -> menu = Menu.buildFromTemplate params.menu menu.popup params.x, params.y + # Deprecated. + deprecate.rename webContents, 'loadUrl', 'loadURL' + deprecate.rename webContents, 'getUrl', 'getURL' + webContents.printToPDF = (options, callback) -> printingSetting = pageRage: [] diff --git a/atom/browser/atom_access_token_store.cc b/atom/browser/atom_access_token_store.cc index 3d254f0601..adf2f5061c 100644 --- a/atom/browser/atom_access_token_store.cc +++ b/atom/browser/atom_access_token_store.cc @@ -18,7 +18,7 @@ namespace { // Notice that we just combined the api key with the url together here, because // if we use the standard {url: key} format Chromium would override our key with // the predefined one in common.gypi of libchromiumcontent, which is empty. -const char* kGeolocationProviderUrl = +const char* kGeolocationProviderURL = "https://www.googleapis.com/geolocation/v1/geolocate?key=" GOOGLEAPIS_API_KEY; @@ -35,11 +35,11 @@ void AtomAccessTokenStore::LoadAccessTokens( const LoadAccessTokensCallbackType& callback) { AccessTokenSet access_token_set; - // Equivelent to access_token_set[kGeolocationProviderUrl]. + // Equivelent to access_token_set[kGeolocationProviderURL]. // Somehow base::string16 is causing compilation errors when used in a pair // of std::map on Linux, this can work around it. std::pair token_pair; - token_pair.first = GURL(kGeolocationProviderUrl); + token_pair.first = GURL(kGeolocationProviderURL); access_token_set.insert(token_pair); auto browser_context = AtomBrowserMainParts::Get()->browser_context(); diff --git a/atom/browser/default_app/default_app.js b/atom/browser/default_app/default_app.js index 6a94db4836..2ec765d0d6 100644 --- a/atom/browser/default_app/default_app.js +++ b/atom/browser/default_app/default_app.js @@ -16,6 +16,6 @@ app.on('ready', function() { autoHideMenuBar: true, useContentSize: true, }); - mainWindow.loadUrl('file://' + __dirname + '/index.html'); + mainWindow.loadURL('file://' + __dirname + '/index.html'); mainWindow.focus(); }); diff --git a/atom/browser/lib/guest-view-manager.coffee b/atom/browser/lib/guest-view-manager.coffee index 4a33b281c9..e6be05a907 100644 --- a/atom/browser/lib/guest-view-manager.coffee +++ b/atom/browser/lib/guest-view-manager.coffee @@ -79,7 +79,7 @@ createGuest = (embedder, params) -> opts = {} opts.httpReferrer = params.httpreferrer if params.httpreferrer opts.userAgent = params.useragent if params.useragent - @loadUrl params.src, opts + @loadURL params.src, opts if params.allowtransparency? @setAllowTransparency params.allowtransparency @@ -122,7 +122,7 @@ attachGuest = (embedder, elementInstanceId, guestInstanceId, params) -> nodeIntegration: params.nodeintegration ? false plugins: params.plugins webSecurity: !params.disablewebsecurity - webPreferences.preloadUrl = params.preload if params.preload + webPreferences.preloadURL = params.preload if params.preload webViewManager.addGuest guestInstanceId, elementInstanceId, embedder, guest, webPreferences guest.attachParams = params diff --git a/atom/browser/lib/guest-window-manager.coffee b/atom/browser/lib/guest-window-manager.coffee index c602d370ba..c311e01cf4 100644 --- a/atom/browser/lib/guest-window-manager.coffee +++ b/atom/browser/lib/guest-window-manager.coffee @@ -27,11 +27,11 @@ mergeBrowserWindowOptions = (embedder, options) -> createGuest = (embedder, url, frameName, options) -> guest = frameToGuest[frameName] if frameName and guest? - guest.loadUrl url + guest.loadURL url return guest.id guest = new BrowserWindow(options) - guest.loadUrl url + guest.loadURL url # Remember the embedder, will be used by window.opener methods. v8Util.setHiddenValue guest.webContents, 'embedder', embedder @@ -74,12 +74,12 @@ ipcMain.on 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_METHOD', (event, guestId, met ipcMain.on 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_POSTMESSAGE', (event, guestId, message, targetOrigin) -> 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 ipcMain.on 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPENER_POSTMESSAGE', (event, guestId, message, targetOrigin, sourceOrigin) -> 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 ipcMain.on 'ATOM_SHELL_GUEST_WINDOW_MANAGER_WEB_CONTENTS_METHOD', (event, guestId, method, args...) -> diff --git a/atom/browser/net/url_request_async_asar_job.cc b/atom/browser/net/url_request_async_asar_job.cc index ba0189e5f6..303bfc0170 100644 --- a/atom/browser/net/url_request_async_asar_job.cc +++ b/atom/browser/net/url_request_async_asar_job.cc @@ -6,13 +6,13 @@ namespace atom { -UrlRequestAsyncAsarJob::UrlRequestAsyncAsarJob( +URLRequestAsyncAsarJob::URLRequestAsyncAsarJob( net::URLRequest* request, net::NetworkDelegate* network_delegate) : JsAsker(request, network_delegate) { } -void UrlRequestAsyncAsarJob::StartAsync(scoped_ptr options) { +void URLRequestAsyncAsarJob::StartAsync(scoped_ptr options) { base::FilePath::StringType file_path; if (options->IsType(base::Value::TYPE_DICTIONARY)) { static_cast(options.get())->GetString( diff --git a/atom/browser/net/url_request_async_asar_job.h b/atom/browser/net/url_request_async_asar_job.h index 748b96d84d..df1aed350b 100644 --- a/atom/browser/net/url_request_async_asar_job.h +++ b/atom/browser/net/url_request_async_asar_job.h @@ -11,15 +11,15 @@ namespace atom { // Like URLRequestAsarJob, but asks the JavaScript handler for file path. -class UrlRequestAsyncAsarJob : public JsAsker { +class URLRequestAsyncAsarJob : public JsAsker { public: - UrlRequestAsyncAsarJob(net::URLRequest*, net::NetworkDelegate*); + URLRequestAsyncAsarJob(net::URLRequest*, net::NetworkDelegate*); // JsAsker: void StartAsync(scoped_ptr options) override; private: - DISALLOW_COPY_AND_ASSIGN(UrlRequestAsyncAsarJob); + DISALLOW_COPY_AND_ASSIGN(URLRequestAsyncAsarJob); }; } // namespace atom diff --git a/atom/browser/web_contents_preferences.cc b/atom/browser/web_contents_preferences.cc index 188de4d1bf..83145368c5 100644 --- a/atom/browser/web_contents_preferences.cc +++ b/atom/browser/web_contents_preferences.cc @@ -113,7 +113,7 @@ void WebContentsPreferences::AppendExtraCommandLineSwitches( command_line->AppendSwitchNative(switches::kPreloadScript, preload); else LOG(ERROR) << "preload script must have absolute path."; - } else if (web_preferences.GetString(options::kPreloadUrl, &preload)) { + } else if (web_preferences.GetString(options::kPreloadURL, &preload)) { // Translate to file path if there is "preload-url" option. base::FilePath preload_path; if (net::FileURLToFilePath(GURL(preload), &preload_path)) diff --git a/atom/common/api/atom_api_native_image.cc b/atom/common/api/atom_api_native_image.cc index df6c14dab3..e0f0940a74 100644 --- a/atom/common/api/atom_api_native_image.cc +++ b/atom/common/api/atom_api_native_image.cc @@ -168,7 +168,8 @@ mate::ObjectTemplateBuilder NativeImage::GetObjectTemplateBuilder( template_.Reset(isolate, mate::ObjectTemplateBuilder(isolate) .SetMethod("toPng", &NativeImage::ToPNG) .SetMethod("toJpeg", &NativeImage::ToJPEG) - .SetMethod("toDataUrl", &NativeImage::ToDataURL) + .SetMethod("toDataURL", &NativeImage::ToDataURL) + .SetMethod("toDataUrl", &NativeImage::ToDataURL) // deprecated. .SetMethod("isEmpty", &NativeImage::IsEmpty) .SetMethod("getSize", &NativeImage::GetSize) .SetMethod("setTemplateImage", &NativeImage::SetTemplateImage) @@ -309,7 +310,7 @@ void Initialize(v8::Local exports, v8::Local unused, dict.SetMethod("createEmpty", &atom::api::NativeImage::CreateEmpty); dict.SetMethod("createFromPath", &atom::api::NativeImage::CreateFromPath); dict.SetMethod("createFromBuffer", &atom::api::NativeImage::CreateFromBuffer); - dict.SetMethod("createFromDataUrl", + dict.SetMethod("createFromDataURL", &atom::api::NativeImage::CreateFromDataURL); } diff --git a/atom/common/api/lib/crash-reporter.coffee b/atom/common/api/lib/crash-reporter.coffee index 873fc1848c..0713da99da 100644 --- a/atom/common/api/lib/crash-reporter.coffee +++ b/atom/common/api/lib/crash-reporter.coffee @@ -1,14 +1,21 @@ -binding = process.atomBinding 'crash_reporter' fs = require 'fs' os = require 'os' path = require 'path' {spawn} = require 'child_process' +electron = require 'electron' +binding = process.atomBinding 'crash_reporter' + class CrashReporter start: (options={}) -> - {@productName, companyName, submitUrl, autoSubmit, ignoreSystemCrashHandler, extra} = options + {@productName, companyName, submitURL, autoSubmit, ignoreSystemCrashHandler, extra} = options + + # Deprecated. + {deprecate} = electron + if options.submitUrl + submitURL ?= options.submitUrl + deprecate.warn 'submitUrl', 'submitURL' - electron = require 'electron' {app} = if process.type is 'browser' electron @@ -17,7 +24,7 @@ class CrashReporter @productName ?= app.getName() companyName ?= 'GitHub, Inc' - submitUrl ?= 'http://54.249.141.255:1127/post' + submitURL ?= 'http://54.249.141.255:1127/post' autoSubmit ?= true ignoreSystemCrashHandler ?= false extra ?= {} @@ -26,11 +33,11 @@ class CrashReporter extra._companyName ?= companyName extra._version ?= app.getVersion() - start = => binding.start @productName, companyName, submitUrl, autoSubmit, ignoreSystemCrashHandler, extra + start = => binding.start @productName, companyName, submitURL, autoSubmit, ignoreSystemCrashHandler, extra if process.platform is 'win32' args = [ - "--reporter-url=#{submitUrl}" + "--reporter-url=#{submitURL}" "--application-name=#{@productName}" "--v=1" ] diff --git a/atom/common/api/lib/native-image.coffee b/atom/common/api/lib/native-image.coffee index c3cbb60ef0..2bdfd494f4 100644 --- a/atom/common/api/lib/native-image.coffee +++ b/atom/common/api/lib/native-image.coffee @@ -1 +1,7 @@ -module.exports = process.atomBinding 'native_image' +{deprecate} = require 'electron' +nativeImage = process.atomBinding 'native_image' + +# Deprecated. +deprecate.rename nativeImage, 'createFromDataUrl', 'createFromDataURL' + +module.exports = nativeImage diff --git a/atom/common/options_switches.cc b/atom/common/options_switches.cc index 1d375ba0fc..1124cfba4b 100644 --- a/atom/common/options_switches.cc +++ b/atom/common/options_switches.cc @@ -77,7 +77,7 @@ const char kZoomFactor[] = "zoomFactor"; const char kPreloadScript[] = "preload"; // Like --preload, but the passed argument is an URL. -const char kPreloadUrl[] = "preloadUrl"; +const char kPreloadURL[] = "preloadURL"; // Enable the node integration. const char kNodeIntegration[] = "nodeIntegration"; @@ -133,7 +133,7 @@ const char kAppUserModelId[] = "app-user-model-id"; // The command line switch versions of the options. const char kZoomFactor[] = "zoom-factor"; const char kPreloadScript[] = "preload"; -const char kPreloadUrl[] = "preload-url"; +const char kPreloadURL[] = "preload-url"; const char kNodeIntegration[] = "node-integration"; const char kGuestInstanceID[] = "guest-instance-id"; const char kExperimentalFeatures[] = "experimental-features"; diff --git a/atom/common/options_switches.h b/atom/common/options_switches.h index 7f262fb0f7..cd52c97597 100644 --- a/atom/common/options_switches.h +++ b/atom/common/options_switches.h @@ -44,7 +44,7 @@ extern const char kWebPreferences[]; extern const char kDirectWrite[]; extern const char kZoomFactor[]; extern const char kPreloadScript[]; -extern const char kPreloadUrl[]; +extern const char kPreloadURL[]; extern const char kNodeIntegration[]; extern const char kGuestInstanceID[]; extern const char kExperimentalFeatures[]; @@ -73,7 +73,7 @@ extern const char kAppUserModelId[]; extern const char kZoomFactor[]; extern const char kPreloadScript[]; -extern const char kPreloadUrl[]; +extern const char kPreloadURL[]; extern const char kNodeIntegration[]; extern const char kGuestInstanceID[]; extern const char kExperimentalFeatures[]; diff --git a/atom/common/platform_util_win.cc b/atom/common/platform_util_win.cc index 87f45e5cb2..cca392952e 100644 --- a/atom/common/platform_util_win.cc +++ b/atom/common/platform_util_win.cc @@ -307,8 +307,8 @@ bool OpenExternal(const GURL& url) { // "Some versions of windows (Win2k before SP3, Win XP before SP1) crash in // ShellExecute on long URLs (bug 161357 on bugzilla.mozilla.org). IE 5 and 6 // support URLS of 2083 chars in length, 2K is safe." - const size_t kMaxUrlLength = 2048; - if (escaped_url.length() > kMaxUrlLength) { + const size_t kMaxURLLength = 2048; + if (escaped_url.length() > kMaxURLLength) { NOTREACHED(); return false; } diff --git a/atom/renderer/api/atom_api_web_frame.cc b/atom/renderer/api/atom_api_web_frame.cc index 6961304304..e9b2b03055 100644 --- a/atom/renderer/api/atom_api_web_frame.cc +++ b/atom/renderer/api/atom_api_web_frame.cc @@ -98,7 +98,7 @@ void WebFrame::RegisterURLSchemeAsSecure(const std::string& scheme) { blink::WebString::fromUTF8(scheme)); } -void WebFrame::RegisterURLSchemeAsBypassingCsp(const std::string& scheme) { +void WebFrame::RegisterURLSchemeAsBypassingCSP(const std::string& scheme) { // Register scheme to bypass pages's Content Security Policy. blink::WebSecurityPolicy::registerURLSchemeAsBypassingContentSecurityPolicy( blink::WebString::fromUTF8(scheme)); @@ -129,11 +129,11 @@ mate::ObjectTemplateBuilder WebFrame::GetObjectTemplateBuilder( &WebFrame::RegisterElementResizeCallback) .SetMethod("attachGuest", &WebFrame::AttachGuest) .SetMethod("setSpellCheckProvider", &WebFrame::SetSpellCheckProvider) - .SetMethod("registerUrlSchemeAsSecure", + .SetMethod("registerURLSchemeAsSecure", &WebFrame::RegisterURLSchemeAsSecure) - .SetMethod("registerUrlSchemeAsBypassingCsp", - &WebFrame::RegisterURLSchemeAsBypassingCsp) - .SetMethod("registerUrlSchemeAsPrivileged", + .SetMethod("registerURLSchemeAsBypassingCSP", + &WebFrame::RegisterURLSchemeAsBypassingCSP) + .SetMethod("registerURLSchemeAsPrivileged", &WebFrame::RegisterURLSchemeAsPrivileged); } diff --git a/atom/renderer/api/atom_api_web_frame.h b/atom/renderer/api/atom_api_web_frame.h index a3dec6cb76..95a5a82a31 100644 --- a/atom/renderer/api/atom_api_web_frame.h +++ b/atom/renderer/api/atom_api_web_frame.h @@ -57,7 +57,7 @@ class WebFrame : public mate::Wrappable { v8::Local provider); void RegisterURLSchemeAsSecure(const std::string& scheme); - void RegisterURLSchemeAsBypassingCsp(const std::string& scheme); + void RegisterURLSchemeAsBypassingCSP(const std::string& scheme); void RegisterURLSchemeAsPrivileged(const std::string& scheme); // mate::Wrappable: diff --git a/atom/renderer/api/lib/web-frame.coffee b/atom/renderer/api/lib/web-frame.coffee index 6525730e86..53564c615c 100644 --- a/atom/renderer/api/lib/web-frame.coffee +++ b/atom/renderer/api/lib/web-frame.coffee @@ -1 +1,9 @@ -module.exports = process.atomBinding('web_frame').webFrame +{deprecate} = require 'electron' +{webFrame} = process.atomBinding 'web_frame' + +# Deprecated. +deprecate.rename webFrame, 'registerUrlSchemeAsSecure', 'registerURLSchemeAsSecure' +deprecate.rename webFrame, 'registerUrlSchemeAsBypassingCSP', 'registerURLSchemeAsBypassingCSP' +deprecate.rename webFrame, 'registerUrlSchemeAsPrivileged', 'registerURLSchemeAsPrivileged' + +module.exports = webFrame diff --git a/atom/renderer/lib/override.coffee b/atom/renderer/lib/override.coffee index d12952a1b8..a3a2f9ac62 100644 --- a/atom/renderer/lib/override.coffee +++ b/atom/renderer/lib/override.coffee @@ -2,7 +2,7 @@ # Helper function to resolve relative url. a = window.top.document.createElement 'a' -resolveUrl = (url) -> +resolveURL = (url) -> a.href = url a.href @@ -55,7 +55,7 @@ window.open = (url, frameName='', features='') -> options.height ?= 600 # Resolve relative urls. - url = resolveUrl url + url = resolveURL url (options[name] = parseInt(options[name], 10) if options[name]?) for name in ints diff --git a/atom/renderer/lib/web-view/guest-view-internal.coffee b/atom/renderer/lib/web-view/guest-view-internal.coffee index a01a994b5b..61a93d8cb6 100644 --- a/atom/renderer/lib/web-view/guest-view-internal.coffee +++ b/atom/renderer/lib/web-view/guest-view-internal.coffee @@ -5,14 +5,14 @@ requestId = 0 WEB_VIEW_EVENTS = 'load-commit': ['url', 'isMainFrame'] 'did-finish-load': [] - 'did-fail-load': ['errorCode', 'errorDescription', 'validatedUrl'] + 'did-fail-load': ['errorCode', 'errorDescription', 'validatedURL'] 'did-frame-finish-load': ['isMainFrame'] 'did-start-loading': [] 'did-stop-loading': [] - 'did-get-response-details': ['status', 'newUrl', 'originalUrl', + 'did-get-response-details': ['status', 'newURL', 'originalURL', 'httpResponseCode', 'requestMethod', 'referrer', 'headers'] - 'did-get-redirect-request': ['oldUrl', 'newUrl', 'isMainFrame'] + 'did-get-redirect-request': ['oldURL', 'newURL', 'isMainFrame'] 'dom-ready': [] 'console-message': ['level', 'message', 'line', 'sourceId'] 'new-window': ['url', 'frameName', 'disposition', 'options'] diff --git a/atom/renderer/lib/web-view/web-view-attributes.coffee b/atom/renderer/lib/web-view/web-view-attributes.coffee index 48e57ea95a..7760b400ce 100644 --- a/atom/renderer/lib/web-view/web-view-attributes.coffee +++ b/atom/renderer/lib/web-view/web-view-attributes.coffee @@ -6,7 +6,7 @@ webViewConstants = require './web-view-constants' # Helper function to resolve url set in attribute. a = document.createElement 'a' -resolveUrl = (url) -> +resolveURL = (url) -> a.href = url a.href @@ -116,7 +116,7 @@ class SrcAttribute extends WebViewAttribute getValue: -> if @webViewImpl.webviewNode.hasAttribute @name - resolveUrl @webViewImpl.webviewNode.getAttribute(@name) + resolveURL @webViewImpl.webviewNode.getAttribute(@name) else '' @@ -178,7 +178,7 @@ class SrcAttribute extends WebViewAttribute if useragent then opts.userAgent = useragent guestContents = remote.getGuestWebContents(@webViewImpl.guestInstanceId) - guestContents.loadUrl @getValue(), opts + guestContents.loadURL @getValue(), opts # Attribute specifies HTTP referrer. class HttpReferrerAttribute extends WebViewAttribute @@ -197,7 +197,7 @@ class PreloadAttribute extends WebViewAttribute getValue: -> return '' unless @webViewImpl.webviewNode.hasAttribute @name - preload = resolveUrl @webViewImpl.webviewNode.getAttribute(@name) + preload = resolveURL @webViewImpl.webviewNode.getAttribute(@name) protocol = preload.substr 0, 5 unless protocol is 'file:' console.error webViewConstants.ERROR_MSG_INVALID_PRELOAD_ATTRIBUTE diff --git a/atom/renderer/lib/web-view/web-view.coffee b/atom/renderer/lib/web-view/web-view.coffee index 204889de79..5e3f7d6bae 100644 --- a/atom/renderer/lib/web-view/web-view.coffee +++ b/atom/renderer/lib/web-view/web-view.coffee @@ -1,4 +1,4 @@ -{webFrame, remote} = require 'electron' +{deprecate, webFrame, remote} = require 'electron' v8Util = process.atomBinding 'v8_util' guestViewInternal = require './guest-view-internal' @@ -252,49 +252,49 @@ registerWebViewElement = -> # Public-facing API methods. methods = [ - "getUrl" - "getTitle" - "isLoading" - "isWaitingForResponse" - "stop" - "reload" - "reloadIgnoringCache" - "canGoBack" - "canGoForward" - "canGoToOffset" - "clearHistory" - "goBack" - "goForward" - "goToIndex" - "goToOffset" - "isCrashed" - "setUserAgent" - "getUserAgent" - "executeJavaScript" - "insertCSS" - "openDevTools" - "closeDevTools" - "isDevToolsOpened" - "inspectElement" - "setAudioMuted" - "isAudioMuted" - "undo" - "redo" - "cut" - "copy" - "paste" - "pasteAndMatchStyle" - "delete" - "selectAll" - "unselect" - "replace" - "replaceMisspelling" - "send" - "getId" - "inspectServiceWorker" - "print" - "printToPDF" - "sendInputEvent" + 'getURL' + 'getTitle' + 'isLoading' + 'isWaitingForResponse' + 'stop' + 'reload' + 'reloadIgnoringCache' + 'canGoBack' + 'canGoForward' + 'canGoToOffset' + 'clearHistory' + 'goBack' + 'goForward' + 'goToIndex' + 'goToOffset' + 'isCrashed' + 'setUserAgent' + 'getUserAgent' + 'executeJavaScript' + 'insertCSS' + 'openDevTools' + 'closeDevTools' + 'isDevToolsOpened' + 'inspectElement' + 'setAudioMuted' + 'isAudioMuted' + 'undo' + 'redo' + 'cut' + 'copy' + 'paste' + 'pasteAndMatchStyle' + 'delete' + 'selectAll' + 'unselect' + 'replace' + 'replaceMisspelling' + 'send' + 'getId' + 'inspectServiceWorker' + 'print' + 'printToPDF' + 'sendInputEvent' ] # Forward proto.foo* method calls to WebViewImpl.foo*. @@ -304,6 +304,9 @@ registerWebViewElement = -> internal.webContents[m] args... proto[m] = createHandler m for m in methods + # Deprecated. + deprecate.rename proto, 'getUrl', 'getURL' + window.WebView = webFrame.registerEmbedderCustomElement 'webview', prototype: proto diff --git a/docs/api/auto-updater.md b/docs/api/auto-updater.md index eb0ea37529..fa4f92cb93 100644 --- a/docs/api/auto-updater.md +++ b/docs/api/auto-updater.md @@ -67,7 +67,7 @@ Returns: * `releaseNotes` String * `releaseName` String * `releaseDate` Date -* `updateUrl` String +* `updateURL` String Emitted when an update has been downloaded. @@ -77,7 +77,7 @@ On Windows only `releaseName` is available. The `autoUpdater` object has the following methods: -### `autoUpdater.setFeedUrl(url)` +### `autoUpdater.setFeedURL(url)` * `url` String @@ -86,7 +86,7 @@ once it is set. ### `autoUpdater.checkForUpdates()` -Asks the server whether there is an update. You must call `setFeedUrl` before +Asks the server whether there is an update. You must call `setFeedURL` before using this API. ### `autoUpdater.quitAndInstall()` diff --git a/docs/api/browser-window.md b/docs/api/browser-window.md index 670c814c74..3b293e9962 100644 --- a/docs/api/browser-window.md +++ b/docs/api/browser-window.md @@ -11,7 +11,7 @@ win.on('closed', function() { win = null; }); -win.loadUrl('https://github.com'); +win.loadURL('https://github.com'); win.show(); ``` @@ -613,9 +613,9 @@ Same as `webContents.print([options])` Same as `webContents.printToPDF(options, callback)` -### `win.loadUrl(url[, options])` +### `win.loadURL(url[, options])` -Same as `webContents.loadUrl(url[, options])`. +Same as `webContents.loadURL(url[, options])`. ### `win.reload()` diff --git a/docs/api/crash-reporter.md b/docs/api/crash-reporter.md index 8127c9bc1c..6c66a855f7 100644 --- a/docs/api/crash-reporter.md +++ b/docs/api/crash-reporter.md @@ -11,7 +11,7 @@ const crashReporter = require('electron').crashReporter; crashReporter.start({ productName: 'YourName', companyName: 'YourCompany', - submitUrl: 'https://your-domain.com/url-to-submit', + submitURL: 'https://your-domain.com/url-to-submit', autoSubmit: true }); ``` @@ -26,7 +26,7 @@ The `crash-reporter` module has the following methods: * `productName` String, default: Electron. * `companyName` String, default: GitHub, Inc. -* `submitUrl` String, default: http://54.249.141.255:1127/post. +* `submitURL` String, default: http://54.249.141.255:1127/post. * URL that crash reports will be sent to as POST. * `autoSubmit` Boolean, default: `true`. * Send the crash report without user interaction. @@ -57,7 +57,7 @@ ID. ## crash-reporter Payload -The crash reporter will send the following data to the `submitUrl` as `POST`: +The crash reporter will send the following data to the `submitURL` as `POST`: * `ver` String - The version of Electron. * `platform` String - e.g. 'win32'. diff --git a/docs/api/download-item.md b/docs/api/download-item.md index 53cd56cca9..756353b8ba 100644 --- a/docs/api/download-item.md +++ b/docs/api/download-item.md @@ -66,7 +66,7 @@ Resumes the download that has been paused. Cancels the download operation. -### `downloadItem.getUrl()` +### `downloadItem.getURL()` Returns a `String` represents the origin url where the item is downloaded from. diff --git a/docs/api/native-image.md b/docs/api/native-image.md index 74dc7a68fa..c08788965a 100644 --- a/docs/api/native-image.md +++ b/docs/api/native-image.md @@ -103,11 +103,11 @@ Creates a new `nativeImage` instance from a file located at `path`. Creates a new `nativeImage` instance from `buffer`. The default `scaleFactor` is 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 @@ -129,7 +129,7 @@ Returns a [Buffer][buffer] that contains the image's `PNG` encoded data. Returns a [Buffer][buffer] that contains the image's `JPEG` encoded data. -### `image.toDataUrl()` +### `image.toDataURL()` Returns the data URL of the image. diff --git a/docs/api/remote.md b/docs/api/remote.md index 6eaa206465..d6aca3ec26 100644 --- a/docs/api/remote.md +++ b/docs/api/remote.md @@ -16,7 +16,7 @@ const remote = require('electron').remote; const BrowserWindow = remote.require('electron').BrowserWindow; var win = new BrowserWindow({ width: 800, height: 600 }); -win.loadUrl('https://github.com'); +win.loadURL('https://github.com'); ``` **Note:** for the reverse (access the renderer process from the main process), diff --git a/docs/api/session.md b/docs/api/session.md index 0fa72585b9..c3a3c91eea 100644 --- a/docs/api/session.md +++ b/docs/api/session.md @@ -8,7 +8,7 @@ instance of `BrowserWindow`. For example: const BrowserWindow = require('electron').BrowserWindow; var win = new BrowserWindow({ width: 800, height: 600 }); -win.loadUrl("http://github.com"); +win.loadURL("http://github.com"); var session = win.webContents.session ``` @@ -28,7 +28,7 @@ Calling `event.preventDefault()` will cancel the download. ```javascript session.on('will-download', function(event, item, webContents) { event.preventDefault(); - require('request')(item.getUrl(), function(data) { + require('request')(item.getURL(), function(data) { require('fs').writeFileSync('/somewhere', data); }); }); @@ -47,7 +47,7 @@ const BrowserWindow = require('electron').BrowserWindow; var win = new BrowserWindow({ width: 800, height: 600 }); -win.loadUrl('https://github.com'); +win.loadURL('https://github.com'); win.webContents.on('did-finish-load', function() { // Query all cookies. diff --git a/docs/api/synopsis.md b/docs/api/synopsis.md index f6c161b696..4cacf52cab 100644 --- a/docs/api/synopsis.md +++ b/docs/api/synopsis.md @@ -25,7 +25,7 @@ var window = null; app.on('ready', function() { window = new BrowserWindow({width: 800, height: 600}); - window.loadUrl('https://github.com'); + window.loadURL('https://github.com'); }); ``` diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index aff5752ab5..917e067059 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -11,7 +11,7 @@ the [`BrowserWindow`](browser-window.md) object. An example of accessing the const BrowserWindow = require('electron').BrowserWindow; var win = new BrowserWindow({width: 800, height: 1500}); -win.loadUrl("http://github.com"); +win.loadURL("http://github.com"); var webContents = win.webContents; ``` @@ -32,7 +32,7 @@ Returns: * `event` Event * `errorCode` Integer * `errorDescription` String -* `validatedUrl` String +* `validatedURL` String This event is like `did-finish-load` but emitted when the load failed or was cancelled, e.g. `window.stop()` is invoked. @@ -61,8 +61,8 @@ Returns: * `event` Event * `status` Boolean -* `newUrl` String -* `originalUrl` String +* `newURL` String +* `originalURL` String * `httpResponseCode` Integer * `requestMethod` String * `referrer` String @@ -76,8 +76,8 @@ Emitted when details regarding a requested resource are available. Returns: * `event` Event -* `oldUrl` String -* `newUrl` String +* `oldURL` String +* `newURL` String * `isMainFrame` Boolean * `httpResponseCode` Integer * `requestMethod` String @@ -99,7 +99,7 @@ Emitted when the document in the given frame is loaded. Returns: * `event` Event -* `favicons` Array - Array of Urls +* `favicons` Array - Array of URLs Emitted when page receives favicon urls. @@ -133,7 +133,7 @@ Emitted when a user or the page wants to start navigation. It can happen when th `window.location` object is changed or a user clicks a link in the page. This event will not emit when the navigation is started programmatically with -APIs like `webContents.loadUrl` and `webContents.back`. +APIs like `webContents.loadURL` and `webContents.back`. Calling `event.preventDefault()` will prevent the navigation. @@ -198,7 +198,7 @@ Returns the `session` object used by this webContents. See [session documentation](session.md) for this object's methods. -### `webContents.loadUrl(url[, options])` +### `webContents.loadURL(url[, options])` * `url` URL * `options` Object (optional), properties: @@ -209,15 +209,15 @@ See [session documentation](session.md) for this object's methods. Loads the `url` in the window, the `url` must contain the protocol prefix, e.g. the `http://` or `file://`. -### `webContents.getUrl()` +### `webContents.getURL()` Returns URL of the current web page. ```javascript 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(); ``` ### `webContents.getTitle()` @@ -447,7 +447,7 @@ const BrowserWindow = require('electron').BrowserWindow; const fs = require('fs'); var win = new BrowserWindow({width: 800, height: 600}); -win.loadUrl("http://github.com"); +win.loadURL("http://github.com"); win.webContents.on("did-finish-load", function() { // Use default printing options @@ -524,7 +524,7 @@ An example of sending messages from the main process to the renderer process: var window = null; app.on('ready', function() { window = new BrowserWindow({width: 800, height: 600}); - window.loadUrl('file://' + __dirname + '/index.html'); + window.loadURL('file://' + __dirname + '/index.html'); window.webContents.on('did-finish-load', function() { window.webContents.send('ping', 'whoooooooh!'); }); @@ -660,7 +660,7 @@ when the DevTools has been closed. Returns true if the process of saving page has been initiated successfully. ```javascript -win.loadUrl('https://github.com'); +win.loadURL('https://github.com'); win.webContents.on('did-finish-load', function() { win.webContents.savePage('/tmp/test.html', 'HTMLComplete', function(error) { diff --git a/docs/api/web-frame.md b/docs/api/web-frame.md index c9cfb48f34..38c5e30db4 100644 --- a/docs/api/web-frame.md +++ b/docs/api/web-frame.md @@ -66,7 +66,7 @@ webFrame.setSpellCheckProvider("en-US", true, { }); ``` -### `webFrame.registerUrlSchemeAsSecure(scheme)` +### `webFrame.registerURLSchemeAsSecure(scheme)` * `scheme` String @@ -76,14 +76,14 @@ Secure schemes do not trigger mixed content warnings. For example, `https` and `data` are secure schemes because they cannot be corrupted by active network attackers. -### `webFrame.registerUrlSchemeAsBypassingCsp(scheme)` +### `webFrame.registerURLSchemeAsBypassingCSP(scheme)` * `scheme` String Resources will be loaded from this `scheme` regardless of the current page's Content Security Policy. -### `webFrame.registerUrlSchemeAsPrivileged(scheme)` +### `webFrame.registerURLSchemeAsPrivileged(scheme)` * `scheme` String diff --git a/docs/api/web-view-tag.md b/docs/api/web-view-tag.md index a12ec44713..25b0e39946 100644 --- a/docs/api/web-view-tag.md +++ b/docs/api/web-view-tag.md @@ -170,7 +170,7 @@ webview.addEventListener("dom-ready", function() { }); ``` -### `.getUrl()` +### `.getURL()` Returns URL of guest page. @@ -402,7 +402,7 @@ Returns: * `errorCode` Integer * `errorDescription` String -* `validatedUrl` String +* `validatedURL` String This event is like `did-finish-load`, but fired when the load failed or was cancelled, e.g. `window.stop()` is invoked. @@ -428,8 +428,8 @@ Corresponds to the points in time when the spinner of the tab stops spinning. Returns: * `status` Boolean -* `newUrl` String -* `originalUrl` String +* `newURL` String +* `originalURL` String * `httpResponseCode` Integer * `requestMethod` String * `referrer` String @@ -442,8 +442,8 @@ Fired when details regarding a requested resource is available. Returns: -* `oldUrl` String -* `newUrl` String +* `oldURL` String +* `newURL` String * `isMainFrame` Boolean Fired when a redirect was received while requesting a resource. @@ -466,7 +466,7 @@ url. Returns: -* `favicons` Array - Array of Urls. +* `favicons` Array - Array of URLs. Fired when page receives favicon urls. diff --git a/docs/tutorial/application-packaging.md b/docs/tutorial/application-packaging.md index 7c1ea773e2..45973e49ea 100644 --- a/docs/tutorial/application-packaging.md +++ b/docs/tutorial/application-packaging.md @@ -73,7 +73,7 @@ You can also display a web page in an `asar` archive with `BrowserWindow`: ```javascript const BrowserWindow = require('electron').BrowserWindow; 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'); ``` ### Web API diff --git a/docs/tutorial/online-offline-events.md b/docs/tutorial/online-offline-events.md index 6e031282b5..d143118e01 100644 --- a/docs/tutorial/online-offline-events.md +++ b/docs/tutorial/online-offline-events.md @@ -13,7 +13,7 @@ const BrowserWindow = electron.BrowserWindow; var onlineStatusWindow; app.on('ready', function() { onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false }); - onlineStatusWindow.loadUrl('file://' + __dirname + '/online-status.html'); + onlineStatusWindow.loadURL('file://' + __dirname + '/online-status.html'); }); ``` @@ -54,7 +54,7 @@ const BrowserWindow = electron.BrowserWindow; var onlineStatusWindow; app.on('ready', function() { onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false }); - onlineStatusWindow.loadUrl('file://' + __dirname + '/online-status.html'); + onlineStatusWindow.loadURL('file://' + __dirname + '/online-status.html'); }); ipcMain.on('online-status-changed', function(event, status) { diff --git a/docs/tutorial/quick-start.md b/docs/tutorial/quick-start.md index 7c55340f75..4c61413436 100644 --- a/docs/tutorial/quick-start.md +++ b/docs/tutorial/quick-start.md @@ -105,7 +105,7 @@ app.on('ready', function() { mainWindow = new BrowserWindow({width: 800, height: 600}); // and load the index.html of the app. - mainWindow.loadUrl('file://' + __dirname + '/index.html'); + mainWindow.loadURL('file://' + __dirname + '/index.html'); // Open the DevTools. mainWindow.webContents.openDevTools(); diff --git a/docs/tutorial/using-pepper-flash-plugin.md b/docs/tutorial/using-pepper-flash-plugin.md index 4cbbb519f4..a9918b220a 100644 --- a/docs/tutorial/using-pepper-flash-plugin.md +++ b/docs/tutorial/using-pepper-flash-plugin.md @@ -36,7 +36,7 @@ app.on('ready', function() { 'plugins': true } }); - mainWindow.loadUrl('file://' + __dirname + '/index.html'); + mainWindow.loadURL('file://' + __dirname + '/index.html'); // Something else }); ``` diff --git a/spec/api-browser-window-spec.coffee b/spec/api-browser-window-spec.coffee index 055cd8ed34..00437ae412 100644 --- a/spec/api-browser-window-spec.coffee +++ b/spec/api-browser-window-spec.coffee @@ -31,14 +31,14 @@ describe 'browser-window module', -> fs.unlinkSync(test) assert.equal String(content), 'unload' done() - w.loadUrl 'file://' + path.join(fixtures, 'api', 'unload.html') + w.loadURL 'file://' + path.join(fixtures, 'api', 'unload.html') it 'should emit beforeunload handler', (done) -> w.on 'onbeforeunload', -> done() w.webContents.on 'did-finish-load', -> w.close() - w.loadUrl 'file://' + path.join(fixtures, 'api', 'beforeunload-false.html') + w.loadURL 'file://' + path.join(fixtures, 'api', 'beforeunload-false.html') describe 'window.close()', -> it 'should emit unload handler', (done) -> @@ -48,23 +48,23 @@ describe 'browser-window module', -> fs.unlinkSync(test) assert.equal String(content), 'close' done() - w.loadUrl 'file://' + path.join(fixtures, 'api', 'close.html') + w.loadURL 'file://' + path.join(fixtures, 'api', 'close.html') it 'should emit beforeunload handler', (done) -> w.on 'onbeforeunload', -> done() - w.loadUrl 'file://' + path.join(fixtures, 'api', 'close-beforeunload-false.html') + w.loadURL 'file://' + path.join(fixtures, 'api', 'close-beforeunload-false.html') - describe 'BrowserWindow.loadUrl(url)', -> + describe 'BrowserWindow.loadURL(url)', -> it 'should emit did-start-loading event', (done) -> w.webContents.on 'did-start-loading', -> done() - w.loadUrl 'about:blank' + w.loadURL 'about:blank' it 'should emit did-fail-load event', (done) -> w.webContents.on 'did-fail-load', -> done() - w.loadUrl 'file://a.txt' + w.loadURL 'file://a.txt' describe 'BrowserWindow.show()', -> it 'should focus on window', -> @@ -214,7 +214,7 @@ describe 'browser-window module', -> show: false webPreferences: preload: preload - w.loadUrl 'file://' + path.join(fixtures, 'api', 'preload.html') + w.loadURL 'file://' + path.join(fixtures, 'api', 'preload.html') describe '"node-integration" option', -> it 'disables node integration when specified to false', (done) -> @@ -228,28 +228,28 @@ describe 'browser-window module', -> webPreferences: preload: preload nodeIntegration: false - w.loadUrl 'file://' + path.join(fixtures, 'api', 'blank.html') + w.loadURL 'file://' + path.join(fixtures, 'api', 'blank.html') describe 'beforeunload handler', -> it 'returning true would not prevent close', (done) -> w.on 'closed', -> done() - w.loadUrl 'file://' + path.join(fixtures, 'api', 'close-beforeunload-true.html') + w.loadURL 'file://' + path.join(fixtures, 'api', 'close-beforeunload-true.html') it 'returning non-empty string would not prevent close', (done) -> w.on 'closed', -> done() - w.loadUrl 'file://' + path.join(fixtures, 'api', 'close-beforeunload-string.html') + w.loadURL 'file://' + path.join(fixtures, 'api', 'close-beforeunload-string.html') it 'returning false would prevent close', (done) -> w.on 'onbeforeunload', -> done() - w.loadUrl 'file://' + path.join(fixtures, 'api', 'close-beforeunload-false.html') + w.loadURL 'file://' + path.join(fixtures, 'api', 'close-beforeunload-false.html') it 'returning empty string would prevent close', (done) -> w.on 'onbeforeunload', -> done() - w.loadUrl 'file://' + path.join(fixtures, 'api', 'close-beforeunload-empty-string.html') + w.loadURL 'file://' + path.join(fixtures, 'api', 'close-beforeunload-empty-string.html') describe 'new-window event', -> return if isCI and process.platform is 'darwin' @@ -259,7 +259,7 @@ describe 'browser-window module', -> assert.equal url, 'http://host/' assert.equal frameName, 'host' done() - w.loadUrl "file://#{fixtures}/pages/window-open.html" + w.loadURL "file://#{fixtures}/pages/window-open.html" it 'emits when link with target is called', (done) -> w.webContents.once 'new-window', (e, url, frameName) -> @@ -267,7 +267,7 @@ describe 'browser-window module', -> assert.equal url, 'http://host/' assert.equal frameName, 'target' done() - w.loadUrl "file://#{fixtures}/pages/target-name.html" + w.loadURL "file://#{fixtures}/pages/target-name.html" describe 'maximize event', -> return if isCI @@ -296,7 +296,7 @@ describe 'browser-window module', -> xdescribe 'beginFrameSubscription method', -> it 'subscribes frame updates', (done) -> - w.loadUrl "file://#{fixtures}/api/blank.html" + w.loadURL "file://#{fixtures}/api/blank.html" w.webContents.beginFrameSubscription (data) -> assert.notEqual data.length, 0 w.webContents.endFrameSubscription() @@ -321,4 +321,4 @@ describe 'browser-window module', -> fs.rmdirSync savePageDir done() - w.loadUrl "file://#{fixtures}/pages/save_page/index.html" + w.loadURL "file://#{fixtures}/pages/save_page/index.html" diff --git a/spec/api-clipboard-spec.coffee b/spec/api-clipboard-spec.coffee index b02eb855be..19da3fc75f 100644 --- a/spec/api-clipboard-spec.coffee +++ b/spec/api-clipboard-spec.coffee @@ -11,7 +11,7 @@ describe 'clipboard module', -> p = path.join fixtures, 'assets', 'logo.png' i = nativeImage.createFromPath p clipboard.writeImage p - assert.equal clipboard.readImage().toDataUrl(), i.toDataUrl() + assert.equal clipboard.readImage().toDataURL(), i.toDataURL() describe 'clipboard.readText()', -> it 'returns unicode string correctly', -> @@ -49,4 +49,4 @@ describe 'clipboard module', -> clipboard.write {text: "test", html: 'Hi', image: p} assert.equal clipboard.readText(), text assert.equal clipboard.readHtml(), markup - assert.equal clipboard.readImage().toDataUrl(), i.toDataUrl() + assert.equal clipboard.readImage().toDataURL(), i.toDataURL() diff --git a/spec/api-crash-reporter-spec.coffee b/spec/api-crash-reporter-spec.coffee index 281a1a77ae..676dbf9d69 100644 --- a/spec/api-crash-reporter-spec.coffee +++ b/spec/api-crash-reporter-spec.coffee @@ -55,5 +55,5 @@ describe 'crash-reporter module', -> pathname: path.join fixtures, 'api', 'crash.html' search: "?port=#{port}" if process.platform is 'darwin' - crashReporter.start {'submitUrl': 'http://127.0.0.1:' + port} - w.loadUrl url + crashReporter.start {'submitURL': 'http://127.0.0.1:' + port} + w.loadURL url diff --git a/spec/api-ipc-spec.coffee b/spec/api-ipc-spec.coffee index 1e6ee8f844..a8d2a65cde 100644 --- a/spec/api-ipc-spec.coffee +++ b/spec/api-ipc-spec.coffee @@ -86,7 +86,7 @@ describe 'ipc module', -> event.returnValue = null w.destroy() done() - w.loadUrl 'file://' + path.join(fixtures, 'api', 'send-sync-message.html') + w.loadURL 'file://' + path.join(fixtures, 'api', 'send-sync-message.html') describe 'remote listeners', -> it 'can be added and removed correctly', -> diff --git a/spec/api-session-spec.coffee b/spec/api-session-spec.coffee index f544dff4c3..bf91bdd6fc 100644 --- a/spec/api-session-spec.coffee +++ b/spec/api-session-spec.coffee @@ -23,7 +23,7 @@ describe 'session module', -> server.listen 0, '127.0.0.1', -> {port} = server.address() - w.loadUrl "#{url}:#{port}" + w.loadURL "#{url}:#{port}" w.webContents.on 'did-finish-load', -> w.webContents.session.cookies.get {url: url}, (error, list) -> return done(error) if error @@ -64,7 +64,7 @@ describe 'session module', -> ipcMain.removeAllListeners 'count' assert not count done() - w.loadUrl 'file://' + path.join(fixtures, 'api', 'localstorage.html') + w.loadURL 'file://' + path.join(fixtures, 'api', 'localstorage.html') w.webContents.on 'did-finish-load', -> options = origin: "file://", @@ -91,7 +91,7 @@ describe 'session module', -> downloadServer.listen 0, '127.0.0.1', -> {port} = downloadServer.address() ipcRenderer.sendSync 'set-download-option', false - w.loadUrl "#{url}:#{port}" + w.loadURL "#{url}:#{port}" ipcRenderer.once 'download-done', (event, state, url, mimeType, receivedBytes, totalBytes, disposition, filename) -> assert.equal state, 'completed' assert.equal filename, 'mock.pdf' @@ -108,7 +108,7 @@ describe 'session module', -> downloadServer.listen 0, '127.0.0.1', -> {port} = downloadServer.address() ipcRenderer.sendSync 'set-download-option', true - w.loadUrl "#{url}:#{port}/" + w.loadURL "#{url}:#{port}/" ipcRenderer.once 'download-done', (event, state, url, mimeType, receivedBytes, totalBytes, disposition, filename) -> assert.equal state, 'cancelled' assert.equal filename, 'mock.pdf' diff --git a/spec/asar-spec.coffee b/spec/asar-spec.coffee index f84fb05991..ad480a5825 100644 --- a/spec/asar-spec.coffee +++ b/spec/asar-spec.coffee @@ -453,7 +453,7 @@ describe 'asar package', -> ipcMain.once 'dirname', (event, dirname) -> assert.equal dirname, path.dirname(p) done() - w.loadUrl u + w.loadURL u it 'loads script tag in html', (done) -> after -> @@ -463,7 +463,7 @@ describe 'asar package', -> w = new BrowserWindow(show: false, width: 400, height: 400) p = path.resolve fixtures, 'asar', 'script.asar', 'index.html' u = url.format protocol: 'file', slashed: true, pathname: p - w.loadUrl u + w.loadURL u ipcMain.once 'ping', (event, message) -> assert.equal message, 'pong' done() diff --git a/spec/chromium-spec.coffee b/spec/chromium-spec.coffee index ebd7b36dc1..435f7bbbe3 100644 --- a/spec/chromium-spec.coffee +++ b/spec/chromium-spec.coffee @@ -43,7 +43,7 @@ describe 'chromium feature', -> w.webContents.on 'ipc-message', (event, args) -> assert.deepEqual args, ['hidden', true] done() - w.loadUrl url + w.loadURL url describe 'navigator.webkitGetUserMedia', -> it 'calls its callbacks', (done) -> @@ -96,7 +96,7 @@ describe 'chromium feature', -> w.webContents.on 'ipc-message', (event, args) -> assert.deepEqual args, ['opener', null] done() - w.loadUrl url + w.loadURL url it 'is not null for window opened by window.open', (done) -> listener = (event) -> diff --git a/spec/fixtures/api/crash.html b/spec/fixtures/api/crash.html index 3049484937..c1fb621426 100644 --- a/spec/fixtures/api/crash.html +++ b/spec/fixtures/api/crash.html @@ -6,7 +6,7 @@ var crashReporter = require('electron').crashReporter; crashReporter.start({ productName: 'Zombies', companyName: 'Umbrella Corporation', - submitUrl: 'http://127.0.0.1:' + port, + submitURL: 'http://127.0.0.1:' + port, autoSubmit: true, ignoreSystemCrashHandler: true, extra: { diff --git a/spec/static/main.js b/spec/static/main.js index e071474f9a..be3690cd9e 100644 --- a/spec/static/main.js +++ b/spec/static/main.js @@ -67,7 +67,7 @@ app.on('ready', function() { javascript: true // Test whether web-preferences crashes. }, }); - window.loadUrl('file://' + __dirname + '/index.html'); + window.loadURL('file://' + __dirname + '/index.html'); window.on('unresponsive', function() { var chosen = dialog.showMessageBox(window, { type: 'warning', @@ -88,7 +88,7 @@ app.on('ready', function() { item.on('done', function(e, state) { window.webContents.send('download-done', state, - item.getUrl(), + item.getURL(), item.getMimeType(), item.getReceivedBytes(), item.getTotalBytes(), From e8ffd24e4e12d33c739dc4c0953efe288699fd60 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 13 Nov 2015 16:41:33 +0800 Subject: [PATCH 25/31] Rename the "clicked" event to "click" in Tray --- atom/browser/api/atom_api_tray.cc | 8 ++++---- atom/browser/api/lib/browser-window.coffee | 2 +- atom/browser/api/lib/tray.coffee | 14 ++++++++++---- atom/common/api/lib/deprecate.coffee | 7 +++++-- docs/api/tray.md | 12 ++++++------ 5 files changed, 26 insertions(+), 17 deletions(-) diff --git a/atom/browser/api/atom_api_tray.cc b/atom/browser/api/atom_api_tray.cc index 0c24240f22..d3c5931ad6 100644 --- a/atom/browser/api/atom_api_tray.cc +++ b/atom/browser/api/atom_api_tray.cc @@ -44,21 +44,21 @@ mate::Wrappable* Tray::New(v8::Isolate* isolate, const gfx::Image& image) { void Tray::OnClicked(const gfx::Rect& bounds, int modifiers) { v8::Locker locker(isolate()); v8::HandleScope handle_scope(isolate()); - EmitCustomEvent("clicked", + EmitCustomEvent("click", ModifiersToObject(isolate(), modifiers), bounds); } void Tray::OnDoubleClicked(const gfx::Rect& bounds, int modifiers) { v8::Locker locker(isolate()); v8::HandleScope handle_scope(isolate()); - EmitCustomEvent("double-clicked", + EmitCustomEvent("double-click", ModifiersToObject(isolate(), modifiers), bounds); } void Tray::OnRightClicked(const gfx::Rect& bounds, int modifiers) { v8::Locker locker(isolate()); v8::HandleScope handle_scope(isolate()); - EmitCustomEvent("right-clicked", + EmitCustomEvent("right-click", ModifiersToObject(isolate(), modifiers), bounds); } @@ -67,7 +67,7 @@ void Tray::OnBalloonShow() { } void Tray::OnBalloonClicked() { - Emit("balloon-clicked"); + Emit("balloon-click"); } void Tray::OnBalloonClosed() { diff --git a/atom/browser/api/lib/browser-window.coffee b/atom/browser/api/lib/browser-window.coffee index 9947bc1a50..99921372f1 100644 --- a/atom/browser/api/lib/browser-window.coffee +++ b/atom/browser/api/lib/browser-window.coffee @@ -1,7 +1,7 @@ {app, ipcMain, deprecate} = require 'electron' {EventEmitter} = require 'events' -BrowserWindow = process.atomBinding('window').BrowserWindow +{BrowserWindow} = process.atomBinding 'window' BrowserWindow::__proto__ = EventEmitter.prototype BrowserWindow::_init = -> diff --git a/atom/browser/api/lib/tray.coffee b/atom/browser/api/lib/tray.coffee index 41cfc96d3f..db26ab5b7e 100644 --- a/atom/browser/api/lib/tray.coffee +++ b/atom/browser/api/lib/tray.coffee @@ -1,13 +1,19 @@ +{deprecate} = require 'electron' {EventEmitter} = require 'events' -{Tray} = process.atomBinding 'tray' +{Tray} = process.atomBinding 'tray' Tray::__proto__ = EventEmitter.prototype +Tray::_init = -> + # Deprecated. + deprecate.rename this, 'popContextMenu', 'popUpContextMenu' + deprecate.event this, 'clicked', 'click' + deprecate.event this, 'double-clicked', 'double-click' + deprecate.event this, 'right-clicked', 'right-click' + deprecate.event this, 'balloon-clicked', 'balloon-click' + Tray::setContextMenu = (menu) -> @_setContextMenu menu @menu = menu # Keep a strong reference of menu. -# Keep compatibility with old APIs. -Tray::popContextMenu = Tray::popUpContextMenu - module.exports = Tray diff --git a/atom/common/api/lib/deprecate.coffee b/atom/common/api/lib/deprecate.coffee index 070a9feb6a..1daf5e4714 100644 --- a/atom/common/api/lib/deprecate.coffee +++ b/atom/common/api/lib/deprecate.coffee @@ -42,12 +42,15 @@ deprecate.property = (object, property, method) -> # Deprecate an event. deprecate.event = (emitter, oldName, newName, fn) -> warned = false - emitter.on newName, -> + emitter.on newName, (args...) -> if @listenerCount(oldName) > 0 # there is listeners for old API. unless warned or process.noDeprecation warned = true deprecate.warn "'#{oldName}' event", "'#{newName}' event" - fn.apply this, arguments + if fn? + fn.apply this, arguments + else + @emit oldName, args... # Print deprecate warning. deprecate.warn = (oldName, newName) -> diff --git a/docs/api/tray.md b/docs/api/tray.md index ff4310308a..47936ab15e 100644 --- a/docs/api/tray.md +++ b/docs/api/tray.md @@ -31,10 +31,10 @@ __Platform limitations:__ * On Linux distributions that only have app indicator support, you have to install `libappindicator1` to make the tray icon work. * App indicator will only be shown when it has a context menu. -* When app indicator is used on Linux, the `clicked` event is ignored. +* When app indicator is used on Linux, the `click` event is ignored. If you want to keep exact same behaviors on all platforms, you should not -rely on the `clicked` event and always attach a context menu to the tray icon. +rely on the `click` event and always attach a context menu to the tray icon. ## Class: Tray @@ -53,7 +53,7 @@ The `Tray` module emits the following events: **Note:** Some events are only available on specific operating systems and are labeled as such. -### Event: 'clicked' +### Event: 'click' * `event` Event * `altKey` Boolean @@ -70,7 +70,7 @@ Emitted when the tray icon is clicked. __Note:__ The `bounds` payload is only implemented on OS X and Windows. -### Event: 'right-clicked' _OS X_ _Windows_ +### Event: 'right-click' _OS X_ _Windows_ * `event` Event * `altKey` Boolean @@ -85,7 +85,7 @@ __Note:__ The `bounds` payload is only implemented on OS X and Windows. Emitted when the tray icon is right clicked. -### Event: 'double-clicked' _OS X_ _Windows_ +### Event: 'double-click' _OS X_ _Windows_ * `event` Event * `altKey` Boolean @@ -104,7 +104,7 @@ Emitted when the tray icon is double clicked. Emitted when the tray balloon shows. -### Event: 'balloon-clicked' _Windows_ +### Event: 'balloon-click' _Windows_ Emitted when the tray balloon is clicked. From e76a7f7b7d662ebcd7d6a441e1dfc39118638775 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 13 Nov 2015 21:52:05 +0800 Subject: [PATCH 26/31] Fix typo, tray => Tray --- atom/browser/api/lib/exports/electron.coffee | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/atom/browser/api/lib/exports/electron.coffee b/atom/browser/api/lib/exports/electron.coffee index 6f70e6b38b..768224d957 100644 --- a/atom/browser/api/lib/exports/electron.coffee +++ b/atom/browser/api/lib/exports/electron.coffee @@ -45,7 +45,7 @@ Object.defineProperties module.exports, screen: enumerable: true get: -> require '../screen' - tray: + Tray: enumerable: true get: -> require '../tray' # The internal modules, invisible unless you know their names. From 9bf0a8647e86c10df4b21bfdca4168ca1c89235a Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 13 Nov 2015 21:52:27 +0800 Subject: [PATCH 27/31] Make it easier to use remote --- atom/renderer/api/lib/remote.coffee | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/atom/renderer/api/lib/remote.coffee b/atom/renderer/api/lib/remote.coffee index 09e7dcdcb5..a38d6ec0bf 100644 --- a/atom/renderer/api/lib/remote.coffee +++ b/atom/renderer/api/lib/remote.coffee @@ -134,6 +134,19 @@ ipcRenderer.on 'ATOM_RENDERER_CALLBACK', (event, id, args) -> ipcRenderer.on 'ATOM_RENDERER_RELEASE_CALLBACK', (event, id) -> callbacksRegistry.remove id +# List all built-in modules in browser process. +# NB(zcbenz): We should probably send an sync message to browser process to get +# them, but that would slow down the startup speed. +browserModules = + ['app', 'autoUpdater', 'BrowserWindow', 'contentTracing', 'dialog', + 'globalShortcut', 'ipcMain', 'Menu', 'MenuItem', 'powerMonitor', + 'powerSaveBlocker', 'protocol', 'Tray', 'clipboard', 'crashReporter', + 'nativeImage', 'screen', 'shell'] +# And add a helper receiver for each one. +for name in browserModules + do (name) -> + Object.defineProperty exports, name, get: -> exports.getBuiltin name + # Get remote module. # (Just like node's require, the modules are cached permanently, note that this # is safe leak since the object is not expected to get freed in browser) From 099278855c3067521a4c5f5988379f38ca4a6405 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 13 Nov 2015 21:54:56 +0800 Subject: [PATCH 28/31] Simplify how remote.require('electron') is optimized --- atom/browser/api/lib/exports/electron.coffee | 3 --- atom/browser/lib/rpc-server.coffee | 6 ------ atom/renderer/api/lib/remote.coffee | 12 +++--------- 3 files changed, 3 insertions(+), 18 deletions(-) diff --git a/atom/browser/api/lib/exports/electron.coffee b/atom/browser/api/lib/exports/electron.coffee index 768224d957..f0c3b87c98 100644 --- a/atom/browser/api/lib/exports/electron.coffee +++ b/atom/browser/api/lib/exports/electron.coffee @@ -1,9 +1,6 @@ # 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: diff --git a/atom/browser/lib/rpc-server.coffee b/atom/browser/lib/rpc-server.coffee index 5c67026deb..df6d4f1f94 100644 --- a/atom/browser/lib/rpc-server.coffee +++ b/atom/browser/lib/rpc-server.coffee @@ -18,10 +18,6 @@ valueToMeta = (sender, value, optimizeSimpleObject=false) -> meta.type = 'date' if value instanceof Date 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. if optimizeSimpleObject and meta.type is 'object' and v8Util.getHiddenValue value, 'simple' meta.type = 'value' @@ -49,8 +45,6 @@ valueToMeta = (sender, value, optimizeSimpleObject=false) -> meta.members = plainObjectToMeta value else if meta.type is 'date' meta.value = value.getTime() - else if meta.type is 'electronModule' - meta.members = (name for name of value) else meta.type = 'value' meta.value = value diff --git a/atom/renderer/api/lib/remote.coffee b/atom/renderer/api/lib/remote.coffee index a38d6ec0bf..e177ea4bb6 100644 --- a/atom/renderer/api/lib/remote.coffee +++ b/atom/renderer/api/lib/remote.coffee @@ -49,15 +49,6 @@ metaToValue = (meta) -> when 'date' then new Date(meta.value) when 'exception' 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 if meta.type is 'function' # A shadow class to represent the remote function object. @@ -157,6 +148,9 @@ exports.require = (module) -> meta = ipcRenderer.sendSync 'ATOM_BROWSER_REQUIRE', module moduleCache[module] = metaToValue meta +# Optimize require('electron'). +moduleCache.electron = exports + # Alias to remote.require('electron').xxx. builtinCache = {} exports.getBuiltin = (module) -> From b925ac00566b29b2410bf9f05a556a667db944f0 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 13 Nov 2015 22:15:16 +0800 Subject: [PATCH 29/31] Send sync message to get list of modules --- atom/browser/lib/rpc-server.coffee | 3 +++ atom/renderer/api/lib/remote.coffee | 8 +------- 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/atom/browser/lib/rpc-server.coffee b/atom/browser/lib/rpc-server.coffee index df6d4f1f94..6cbc5ffc1f 100644 --- a/atom/browser/lib/rpc-server.coffee +++ b/atom/browser/lib/rpc-server.coffee @@ -206,3 +206,6 @@ ipcMain.on 'ATOM_BROWSER_GUEST_WEB_CONTENTS', (event, guestInstanceId) -> event.returnValue = valueToMeta event.sender, guestViewManager.getGuest(guestInstanceId) catch e event.returnValue = exceptionToMeta e + +ipcMain.on 'ATOM_BROWSER_LIST_MODULES', (event) -> + event.returnValue = (name for name of electron) diff --git a/atom/renderer/api/lib/remote.coffee b/atom/renderer/api/lib/remote.coffee index e177ea4bb6..48cdd937fb 100644 --- a/atom/renderer/api/lib/remote.coffee +++ b/atom/renderer/api/lib/remote.coffee @@ -126,13 +126,7 @@ ipcRenderer.on 'ATOM_RENDERER_RELEASE_CALLBACK', (event, id) -> callbacksRegistry.remove id # List all built-in modules in browser process. -# NB(zcbenz): We should probably send an sync message to browser process to get -# them, but that would slow down the startup speed. -browserModules = - ['app', 'autoUpdater', 'BrowserWindow', 'contentTracing', 'dialog', - 'globalShortcut', 'ipcMain', 'Menu', 'MenuItem', 'powerMonitor', - 'powerSaveBlocker', 'protocol', 'Tray', 'clipboard', 'crashReporter', - 'nativeImage', 'screen', 'shell'] +browserModules = ipcRenderer.sendSync 'ATOM_BROWSER_LIST_MODULES' # And add a helper receiver for each one. for name in browserModules do (name) -> From 94e24abb998d73545b4a2eedf3872b5e13763d0f Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 13 Nov 2015 22:22:25 +0800 Subject: [PATCH 30/31] Use the new style remote module in Electron --- atom/common/api/lib/clipboard.coffee | 3 +-- atom/common/api/lib/crash-reporter.coffee | 6 +----- atom/renderer/api/lib/screen.coffee | 2 +- atom/renderer/lib/inspector.coffee | 4 ++-- atom/renderer/lib/override.coffee | 6 ++---- 5 files changed, 7 insertions(+), 14 deletions(-) diff --git a/atom/common/api/lib/clipboard.coffee b/atom/common/api/lib/clipboard.coffee index 0ea97d86ba..a3a6d555fe 100644 --- a/atom/common/api/lib/clipboard.coffee +++ b/atom/common/api/lib/clipboard.coffee @@ -1,6 +1,5 @@ if process.platform is 'linux' and process.type is 'renderer' - {remote} = require 'electron' # On Linux we could not access clipboard in renderer process. - module.exports = remote.getBuiltin 'clipboard' + module.exports = require('electron').remote.clipboard else module.exports = process.atomBinding 'clipboard' diff --git a/atom/common/api/lib/crash-reporter.coffee b/atom/common/api/lib/crash-reporter.coffee index 0713da99da..bd98ae2a42 100644 --- a/atom/common/api/lib/crash-reporter.coffee +++ b/atom/common/api/lib/crash-reporter.coffee @@ -16,11 +16,7 @@ class CrashReporter submitURL ?= options.submitUrl deprecate.warn 'submitUrl', 'submitURL' - {app} = - if process.type is 'browser' - electron - else - electron.remote.require 'electron' + {app} = if process.type is 'browser' then electron else electron.remote @productName ?= app.getName() companyName ?= 'GitHub, Inc' diff --git a/atom/renderer/api/lib/screen.coffee b/atom/renderer/api/lib/screen.coffee index b70aa55b57..9eecd49dc5 100644 --- a/atom/renderer/api/lib/screen.coffee +++ b/atom/renderer/api/lib/screen.coffee @@ -1 +1 @@ -module.exports = require('electron').remote.require('electron').screen +module.exports = require('electron').remote.screen diff --git a/atom/renderer/lib/inspector.coffee b/atom/renderer/lib/inspector.coffee index 34c6876fc2..d5ddfd72e4 100644 --- a/atom/renderer/lib/inspector.coffee +++ b/atom/renderer/lib/inspector.coffee @@ -33,7 +33,7 @@ convertToMenuTemplate = (items) -> createMenu = (x, y, items, document) -> {remote} = require 'electron' - {Menu} = remote.require 'electron' + {Menu} = remote menu = Menu.buildFromTemplate convertToMenuTemplate(items) # The menu is expected to show asynchronously. @@ -43,7 +43,7 @@ createMenu = (x, y, items, document) -> showFileChooserDialog = (callback) -> {remote} = require 'electron' - {dialog} = remote.require 'electron' + {dialog} = remote files = dialog.showOpenDialog {} callback pathToHtml5FileObject files[0] if files? diff --git a/atom/renderer/lib/override.coffee b/atom/renderer/lib/override.coffee index a3a2f9ac62..0b60ce0d66 100644 --- a/atom/renderer/lib/override.coffee +++ b/atom/renderer/lib/override.coffee @@ -67,19 +67,17 @@ window.open = (url, frameName='', features='') -> # Use the dialog API to implement alert(). window.alert = (message, title='') -> - dialog = remote.require 'dialog' buttons = ['OK'] message = message.toString() - dialog.showMessageBox remote.getCurrentWindow(), {message, title, buttons} + remote.dialog.showMessageBox remote.getCurrentWindow(), {message, title, buttons} # Alert should always return undefined. return # And the confirm(). window.confirm = (message, title='') -> - dialog = remote.require 'dialog' buttons = ['OK', 'Cancel'] cancelId = 1 - not dialog.showMessageBox remote.getCurrentWindow(), {message, title, buttons, cancelId} + not remote.dialog.showMessageBox remote.getCurrentWindow(), {message, title, buttons, cancelId} # But we do not support prompt(). window.prompt = -> From 5cacf79bc5ceb82a793b2cc3916f0a8ee4fc14ae Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 13 Nov 2015 22:34:00 +0800 Subject: [PATCH 31/31] docs: Document the new style of remote module --- docs/api/menu.md | 4 ++-- docs/api/remote.md | 11 ++++++++++- docs/api/synopsis.md | 2 +- docs/tutorial/devtools-extension.md | 2 +- 4 files changed, 14 insertions(+), 5 deletions(-) diff --git a/docs/api/menu.md b/docs/api/menu.md index c947f36d47..1d81968216 100644 --- a/docs/api/menu.md +++ b/docs/api/menu.md @@ -17,8 +17,8 @@ the user right clicks the page: diff --git a/docs/tutorial/devtools-extension.md b/docs/tutorial/devtools-extension.md index 258fb41947..7c7ea7d64a 100644 --- a/docs/tutorial/devtools-extension.md +++ b/docs/tutorial/devtools-extension.md @@ -24,7 +24,7 @@ Then you can load the extension in Electron by opening DevTools in any window, and running the following code in the DevTools console: ```javascript -const BrowserWindow = require('electron').remote.require('electron').BrowserWindow; +const BrowserWindow = require('electron').remote.BrowserWindow; BrowserWindow.addDevToolsExtension('/some-directory/react-devtools/shells/chrome'); ```