From 05031a38e51e47da3be8c46650cc2d48e1e539c6 Mon Sep 17 00:00:00 2001 From: John-Lin Date: Fri, 4 Sep 2015 15:42:57 +0800 Subject: [PATCH 01/27] Add api docs translations --- .../zh-TW/api/ipc-main-process.md | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 docs-translations/zh-TW/api/ipc-main-process.md diff --git a/docs-translations/zh-TW/api/ipc-main-process.md b/docs-translations/zh-TW/api/ipc-main-process.md new file mode 100644 index 00000000000..00e73efb4fc --- /dev/null +++ b/docs-translations/zh-TW/api/ipc-main-process.md @@ -0,0 +1,69 @@ +# ipc (主行程) + +當在主行程裡使用 `ipc` 模組,這個模組負責處理來自渲染行程(網頁)的非同步與同步訊息。 +來自渲染器的訊息將會被注入到這個模組裡。 + +## 傳送訊息 + +同樣的也可以透過主行程來傳送訊息到渲染行程,更多資訊請參考 [WebContents.send](browser-window.md#webcontentssendchannel-args) + +- 當傳送一個訊息, 事件名稱為 `channel` +- 回覆同步訊息,你需要設定 `event.returnValue` +- 送出一個非同步訊息回給發送端,你可以使用 `event.sender.send(...)` + +這裏是一個傳送和處理訊息的範例,在渲染行程與主行程之間: + +```javascript +// 在主行程裡 +var ipc = require('ipc'); +ipc.on('asynchronous-message', function(event, arg) { + console.log(arg); // 輸出 "ping" + event.sender.send('asynchronous-reply', 'pong'); +}); + +ipc.on('synchronous-message', function(event, arg) { + console.log(arg); // 輸出 "ping" + event.returnValue = 'pong'; +}); +``` + +```javascript +// 在渲染行程裡 (網頁). +var ipc = require('ipc'); +console.log(ipc.sendSync('synchronous-message', 'ping')); // 輸出 "pong" + +ipc.on('asynchronous-reply', function(arg) { + console.log(arg); // 輸出 "pong" +}); +ipc.send('asynchronous-message', 'ping'); +``` + +## 聆聽訊息 + +`ipc` 模組擁有下列幾個方法去聆聽事件: + +### `ipc.on(channel, callback)` + +* `channel` String - 事件名稱 +* `callback` Function + +當一個事件發生 `callback` 會帶著 `event` 物件和一個訊息 `arg` + +## IPC 事件 + +`event` 物件被傳入 `callback` 具有以下幾個方法: + +### `Event.returnValue` + +設定這個值可以回傳一個同步訊息 + +### `Event.sender` + +回傳 `WebContents` 可以送出訊息 + +### `Event.sender.send(channel[, arg1][, arg2][, ...])` + +* `channel` String - 事件名稱 +* `arg` (選用) + +此傳送訊息是非同步的訊息,至渲染行程,可以是一個一系列的參數 `arg` 可以是任何型態。 From 30c714a27f2edb4f54df64dbf06c106f2c8ae6d7 Mon Sep 17 00:00:00 2001 From: John-Lin Date: Fri, 4 Sep 2015 15:47:46 +0800 Subject: [PATCH 02/27] Fix typos in zh-TW README docs --- docs-translations/zh-TW/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs-translations/zh-TW/README.md b/docs-translations/zh-TW/README.md index 7c954034f21..cc75ba51c14 100644 --- a/docs-translations/zh-TW/README.md +++ b/docs-translations/zh-TW/README.md @@ -2,8 +2,8 @@ * [應用程式發布](tutorial/application-distribution.md) * [應用程式打包](tutorial/application-packaging.md) -* [使用原生模組](tutorial/using-native-node-modules.md) -* [Debug 主行程](tutorial/debugging-main-process.md) +* [使用原生 node 模組](tutorial/using-native-node-modules.md) +* [主行程 Debug](tutorial/debugging-main-process.md) * [使用 Selenium 和 WebDriver](tutorial/using-selenium-and-webdriver.md) * [DevTools 擴充](tutorial/devtools-extension.md) * [使用 Pepper Flash 套件](tutorial/using-pepper-flash-plugin.md) @@ -22,7 +22,7 @@ 客製的 DOM 元素: -* [`File`對象](api/file-object.md) +* [`File`物件](api/file-object.md) * [``物件](api/web-view-tag.md) * [`window.open`函數](api/window-open.md) From 67026cccc867db6a01765d385d484f2aa9814b77 Mon Sep 17 00:00:00 2001 From: John-Lin Date: Fri, 4 Sep 2015 16:06:15 +0800 Subject: [PATCH 03/27] Add api/shell.md docs zh-TW translations --- docs-translations/zh-TW/api/shell.md | 46 ++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 docs-translations/zh-TW/api/shell.md diff --git a/docs-translations/zh-TW/api/shell.md b/docs-translations/zh-TW/api/shell.md new file mode 100644 index 00000000000..3f3c9ae951c --- /dev/null +++ b/docs-translations/zh-TW/api/shell.md @@ -0,0 +1,46 @@ +# shell + +`shell` 模組提供一些整合桌面應用的功能。 + + +一個範例示範如何利用使用者的預設瀏覽器開啟 URL: + +```javascript +var shell = require('shell'); + +shell.openExternal('https://github.com'); +``` + +## Methods + +`shell` 模組有以下幾個方法: + +### `shell.showItemInFolder(fullPath)` + +* `fullPath` String + +顯示在檔案管理中指定的檔案,如果可以的話,選擇該檔案。 + +### `shell.openItem(fullPath)` + +* `fullPath` String + +打開指定的檔案,在桌面的預設方式。 +Open the given file in the desktop's default manner. + +### `shell.openExternal(url)` + +* `url` String + +打開一個指定的外部協定 URL 在桌面的預設方式。(舉例來說 mailto: URLs 會打開使用者的預設信箱) + + +### `shell.moveItemToTrash(fullPath)` + +* `fullPath` String + +移動指定檔案至垃圾桶,並會對這個操作回傳一個 boolean 狀態 + +### `shell.beep()` + +播放 beep 聲音。 From eb8ac2b5d8461bcfb6a1487fe5c57e68df12e882 Mon Sep 17 00:00:00 2001 From: Jonatas Freitas Date: Fri, 4 Sep 2015 11:42:37 -0300 Subject: [PATCH 04/27] Translate README.md to pt-BR --- docs-translations/pt-BR/README-pt-BR.md | 70 +++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 docs-translations/pt-BR/README-pt-BR.md diff --git a/docs-translations/pt-BR/README-pt-BR.md b/docs-translations/pt-BR/README-pt-BR.md new file mode 100644 index 00000000000..0c8f6fb52ba --- /dev/null +++ b/docs-translations/pt-BR/README-pt-BR.md @@ -0,0 +1,70 @@ +## Guias + +* [Distribuir Aplicação](../../docs/tutorial/application-distribution-pt-BR.md) +* [Empacotamento da aplicação](../../docs/tutorial/application-packaging-pt-BR.md) +* [Usando módulos nativos](../../docs/tutorial/using-native-node-modules-pt-BR.md) +* [Depuração do processo principal](../../docs/tutorial/debugging-main-process-pt-BR.md) +* [Usando Selenium e WebDriver](../../docs/tutorial/using-selenium-and-webdriver-pt-BR.md) +* [Extensão DevTools](../../docs/tutorial/devtools-extension-pt-BR.md) +* [Usando o plugin papper flash](../../docs/tutorial/using-pepper-flash-plugin-pt-BR.md) + +## Tutoriais + +* [Introdução](../../docs/tutorial/quick-start.md) +* [A integração com o ambiente de desenvolvimento](../../docs/tutorial/desktop-environment-integration.md) +* [Evento de detecção on-line/off-line](../../docs/tutorial/online-offline-events.md) + +## API - Referencias + +* [Sinopse](../../docs/api/synopsis.md) +* [Processos](../../docs/api/process.md) +* [Parâmetros CLI suportados (Chrome)](../../docs/api/chrome-command-line-switches.md) + +DOM elementos personalizados: + +* [Objeto `File`](../../docs/api/file-object.md) +* [Tag ``](../../docs/api/web-view-tag.md) +* [Função `window.open`](../../docs/api/window-open.md) + +Os principais módulos: + +* [app](../../docs/api/app.md) +* [auto-updater](../../docs/api/auto-updater.md) +* [browser-window](../../docs/api/browser-window.md) +* [content-tracing](../../docs/api/content-tracing.md) +* [dialog](../../docs/api/dialog.md) +* [global-shortcut](../../docs/api/global-shortcut.md) +* [ipc (main process)](../../docs/api/ipc-main-process.md) +* [menu](../../docs/api/menu.md) +* [menu-item](../../docs/api/menu-item.md) +* [power-monitor](../../docs/api/power-monitor.md) +* [power-save-blocker](../../docs/api/power-save-blocker.md) +* [protocol](../../docs/api/protocol.md) +* [session](../../docs/api/session.md) +* [webContents](../../docs/api/web-contents.md) +* [tray](../../docs/api/tray.md) + +Módulos do renderizador (web page): + +* [ipc (renderer)](../../docs/api/ipc-renderer.md) +* [remote](../../docs/api/remote.md) +* [web-frame](../../docs/api/web-frame.md) + +Módulos de ambos os processos: + +* [clipboard](../../docs/api/clipboard.md) +* [crash-reporter](../../docs/api/crash-reporter.md) +* [native-image](../../docs/api/native-image.md) +* [screen](../../docs/api/screen.md) +* [shell](../../docs/api/shell.md) + +## Desenvolvimento + +* [Estilo de código](../../docs/development/coding-style.md) +* [Estrutura de diretórios padrão](../../docs/development/source-code-directory-structure.md) +* [Diferenças técnicas do NW.js (antigo node-webkit)](../../docs/development/atom-shell-vs-node-webkit.md) +* [Visão geral do build](../../docs/development/build-system-overview.md) +* [Instrução de build (Mac)](../../docs/development/build-instructions-osx.md) +* [Instrução de build (Windows)](../../docs/development/build-instructions-windows.md) +* [Instrução de build (Linux)](../../docs/development/build-instructions-linux.md) +* [Configurando um symbol server no debugger](../../docs/development/setting-up-symbol-server.md) \ No newline at end of file From 26dea993dfd9dbecd3298b55d2607da3bae62732 Mon Sep 17 00:00:00 2001 From: Jonatas Freitas Date: Fri, 4 Sep 2015 11:52:27 -0300 Subject: [PATCH 05/27] Added pt-BR translation in README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 81196554495..68518052c01 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,7 @@ contains documents describing how to build and contribute to Electron. ## Documentation Translations +- [Brazilian Portuguese](https://github.com/atom/electron/tree/master/docs-translations/pt-BR) - [Korean](https://github.com/atom/electron/tree/master/docs-translations/ko) - [Japanese](https://github.com/atom/electron/tree/master/docs-translations/jp) - [Spanish](https://github.com/atom/electron/tree/master/docs-translations/es) From 5d6ac2296b45a20157136b5c96fbb7b83bb98f32 Mon Sep 17 00:00:00 2001 From: Jonatas Freitas Date: Fri, 4 Sep 2015 14:19:59 -0300 Subject: [PATCH 06/27] Translated styleguide. --- docs-translations/pt-BR/styleguide-pt-BR.md | 77 +++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 docs-translations/pt-BR/styleguide-pt-BR.md diff --git a/docs-translations/pt-BR/styleguide-pt-BR.md b/docs-translations/pt-BR/styleguide-pt-BR.md new file mode 100644 index 00000000000..817fa3c81e3 --- /dev/null +++ b/docs-translations/pt-BR/styleguide-pt-BR.md @@ -0,0 +1,77 @@ +# Styleguide do Electron + +Localize a seção apropriada para a sua tarefa: [Lendo a documentação do Electron](#) +ou [Escrevendo documentação para o Electron](#). + +## Escrevendo documentação para o Electron + +Estas são as formas que escrevemos a documentação do Electron. + +- No Máximo um `h1` por página. +- Usar `bash` ao invés de` cmd` em blocos de código (por causa do syntax highlighter). +- Títulos `h1` deve coincidir com o nome do objeto (i.e. `browser-window` → +`BrowserWindow`). +- Nomes de arquivos separados por hífen. +- Adicionar pelo menos uma descrição a cada frase. +- Métodos de cabeçalhos são envolto em `code`. +- Cabeçalhos de eventos são envolto em single 'quotation' marks. +- Não há listas com identação com mais de 2 níveis (por causa do markdown). +- Adicione títulos nas seções: Events, Class Methods e Instance Methods. +- Use 'will' ao invéis de 'would' ao descrever os resultados. +- Eventos e métodos são com cabeçalhos `h3`. +- Argumentos opcionais escritos como `function (required[, optional])`. +- Argumentos opcionais são indicados quando chamado na lista. +- Comprimento da linha é de 80 caracteres com colunas quebradas. +- Métodos específicos para uma plataforma são postos em itálico seguindo o cabeçalho do método. + - ```### `method(foo, bar)` _OS X_``` + +## Lendo a documentação do Electron + +Aqui estão algumas dicas de como entender a sintaxe da documentacão do Electron. + +### Métodos + +Um exemplo de [method](https://developer.mozilla.org/en-US/docs/Glossary/Method) +documentação: + +--- + +`methodName(required[, optional]))` + +* `require` String, **required** +* `optional` Integer + +--- + +O nome do método é seguido pelos seus argumentos. Argumentos opcionais são +simbolizada por colchetes que cercam o argumento opcional, bem como a vírgula +requerido se este argumento opcional segue outro argumento. + +Abaixo o método é para obter informações detalhadas sobre cada um dos argumentos. O tipo +de argumento é simbolizada por qualquer um dos tipos mais comuns: [`String`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String), [` Number`](https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number), [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript Referência/Global_Objects/Object), [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) +ou um tipo personalizado como o de Electron [`webContent`](api/web-content.md). + +### Eventos + +Um exemplo de [evento](https://developer.mozilla.org/en-US/docs/Web/API/Event) +documentação: + +--- + +Event: 'wake-up' + +Returns: + +* `time` String + +--- + +O evento é uma cadeia que é utilizada após um `.on` em um método listner. Se ela retorna +-lhe um valor e seu tipo é observado abaixo. Se você quiser um método para esctuar e responder +crie algo parecido com o exemplo abaixo: + +```javascript +Alarm.on('wake-up', function(time) { + console.log(time) +}) +``` \ No newline at end of file From f91a7e6d04f5568e630093debe8578fa7761f67d Mon Sep 17 00:00:00 2001 From: Jonatas Freitas Date: Fri, 4 Sep 2015 14:25:32 -0300 Subject: [PATCH 07/27] Fix README links. --- docs-translations/pt-BR/README-pt-BR.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/docs-translations/pt-BR/README-pt-BR.md b/docs-translations/pt-BR/README-pt-BR.md index 0c8f6fb52ba..111ab06a39b 100644 --- a/docs-translations/pt-BR/README-pt-BR.md +++ b/docs-translations/pt-BR/README-pt-BR.md @@ -1,12 +1,12 @@ ## Guias -* [Distribuir Aplicação](../../docs/tutorial/application-distribution-pt-BR.md) -* [Empacotamento da aplicação](../../docs/tutorial/application-packaging-pt-BR.md) -* [Usando módulos nativos](../../docs/tutorial/using-native-node-modules-pt-BR.md) -* [Depuração do processo principal](../../docs/tutorial/debugging-main-process-pt-BR.md) -* [Usando Selenium e WebDriver](../../docs/tutorial/using-selenium-and-webdriver-pt-BR.md) -* [Extensão DevTools](../../docs/tutorial/devtools-extension-pt-BR.md) -* [Usando o plugin papper flash](../../docs/tutorial/using-pepper-flash-plugin-pt-BR.md) +* [Distribuir Aplicação](../../docs/tutorial/application-distribution.md) +* [Empacotamento da aplicação](../../docs/tutorial/application-packaging.md) +* [Usando módulos nativos](../../docs/tutorial/using-native-node-modules.md) +* [Depuração do processo principal](../../docs/tutorial/debugging-main-process.md) +* [Usando Selenium e WebDriver](../../docs/tutorial/using-selenium-and-webdriver.md) +* [Extensão DevTools](../../docs/tutorial/devtools-extension.md) +* [Usando o plugin papper flash](../../docs/tutorial/using-pepper-flash-plugin.md) ## Tutoriais From 0577e911b387b0453c83b21f411e91b8e0df3f5e Mon Sep 17 00:00:00 2001 From: Eran Tiktin Date: Fri, 4 Sep 2015 23:24:42 +0300 Subject: [PATCH 08/27] Fix build failing on Windows build.py would fail on Windows due to a couple of changes made in #2459. This commit fixes those issues. --- atom/browser/atom_browser_main_parts.cc | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/atom/browser/atom_browser_main_parts.cc b/atom/browser/atom_browser_main_parts.cc index 4463115cfee..806c12b7eac 100644 --- a/atom/browser/atom_browser_main_parts.cc +++ b/atom/browser/atom_browser_main_parts.cc @@ -28,7 +28,8 @@ namespace atom { namespace { -const base::FilePath::CharType kStoragePartitionDirname[] = "Partitions"; +const base::FilePath::CharType kStoragePartitionDirname[] = + FILE_PATH_LITERAL("Partitions"); void GetStoragePartitionConfig(const GURL& partition, base::FilePath* partition_path, @@ -77,7 +78,7 @@ content::BrowserContext* AtomBrowserMainParts::GetBrowserContextForPartition( return browser_context_map_.get(id); scoped_ptr browser_context(CreateBrowserContext()); - browser_context->Initialize(partition_path.value(), in_memory); + browser_context->Initialize(partition_path.AsUTF8Unsafe(), in_memory); browser_context_map_.set(id, browser_context.Pass()); return browser_context_map_.get(id); } From dd871812b7b2e1c8411949326d149694bb451b61 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 5 Sep 2015 01:44:22 +0900 Subject: [PATCH 09/27] Add WebContentsPrefrences class --- atom/browser/api/atom_api_web_contents.cc | 11 +++++++-- atom/browser/api/atom_api_web_contents.h | 2 +- atom/browser/web_contents_preferences.cc | 25 +++++++++++++++++++ atom/browser/web_contents_preferences.h | 30 +++++++++++++++++++++++ filenames.gypi | 6 +++-- 5 files changed, 69 insertions(+), 5 deletions(-) create mode 100644 atom/browser/web_contents_preferences.cc create mode 100644 atom/browser/web_contents_preferences.h diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index 7cefe8e45e3..d724d1ea4c1 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -11,6 +11,7 @@ #include "atom/browser/atom_browser_context.h" #include "atom/browser/atom_browser_main_parts.h" #include "atom/browser/native_window.h" +#include "atom/browser/web_contents_preferences.h" #include "atom/browser/web_view_guest_delegate.h" #include "atom/common/api/api_messages.h" #include "atom/common/api/event_emitter_caller.h" @@ -153,7 +154,8 @@ WebContents::WebContents(content::WebContents* web_contents) web_contents->SetUserAgentOverride(GetBrowserContext()->GetUserAgent()); } -WebContents::WebContents(const mate::Dictionary& options) { +WebContents::WebContents(v8::Isolate* isolate, + const mate::Dictionary& options) { bool is_guest = false; options.Get("isGuest", &is_guest); @@ -185,6 +187,11 @@ WebContents::WebContents(const mate::Dictionary& options) { AttachAsUserData(web_contents); InitWithWebContents(web_contents); + // Save the preferences. + base::DictionaryValue web_preferences; + mate::ConvertFromV8(isolate, options.GetHandle(), &web_preferences); + new WebContentsPreferences(web_contents, std::move(web_preferences)); + web_contents->SetUserAgentOverride(GetBrowserContext()->GetUserAgent()); if (is_guest) { @@ -890,7 +897,7 @@ mate::Handle WebContents::CreateFrom( // static mate::Handle WebContents::Create( v8::Isolate* isolate, const mate::Dictionary& options) { - auto handle = mate::CreateHandle(isolate, new WebContents(options)); + auto handle = mate::CreateHandle(isolate, new WebContents(isolate, options)); g_wrap_web_contents.Run(handle.ToV8()); return handle; } diff --git a/atom/browser/api/atom_api_web_contents.h b/atom/browser/api/atom_api_web_contents.h index e75e88fd703..5ea62dabff6 100644 --- a/atom/browser/api/atom_api_web_contents.h +++ b/atom/browser/api/atom_api_web_contents.h @@ -116,7 +116,7 @@ class WebContents : public mate::TrackableObject, protected: explicit WebContents(content::WebContents* web_contents); - explicit WebContents(const mate::Dictionary& options); + WebContents(v8::Isolate* isolate, const mate::Dictionary& options); ~WebContents(); // mate::Wrappable: diff --git a/atom/browser/web_contents_preferences.cc b/atom/browser/web_contents_preferences.cc new file mode 100644 index 00000000000..8b956c1b41a --- /dev/null +++ b/atom/browser/web_contents_preferences.cc @@ -0,0 +1,25 @@ +// Copyright (c) 2015 GitHub, Inc. +// Use of this source code is governed by the MIT license that can be +// found in the LICENSE file. + +#include "atom/browser/web_contents_preferences.h" + +namespace atom { + +namespace { + +const char* kWebPreferencesKey = "WebContentsPreferences"; + +} // namespace + +WebContentsPreferences::WebContentsPreferences( + content::WebContents* web_contents, + base::DictionaryValue&& web_preferences) { + web_preferences_.Swap(&web_preferences); + web_contents->SetUserData(kWebPreferencesKey, this); +} + +WebContentsPreferences::~WebContentsPreferences() { +} + +} // namespace atom diff --git a/atom/browser/web_contents_preferences.h b/atom/browser/web_contents_preferences.h new file mode 100644 index 00000000000..bbbc4cf5e2e --- /dev/null +++ b/atom/browser/web_contents_preferences.h @@ -0,0 +1,30 @@ +// Copyright (c) 2015 GitHub, Inc. +// Use of this source code is governed by the MIT license that can be +// found in the LICENSE file. + +#ifndef ATOM_BROWSER_WEB_CONTENTS_PREFERENCES_H_ +#define ATOM_BROWSER_WEB_CONTENTS_PREFERENCES_H_ + +#include "base/values.h" +#include "content/public/browser/web_contents_user_data.h" + +namespace atom { + +class WebContentsPreferences + : public content::WebContentsUserData { + public: + WebContentsPreferences(content::WebContents* web_contents, + base::DictionaryValue&& web_preferences); + ~WebContentsPreferences() override; + + private: + friend class content::WebContentsUserData; + + base::DictionaryValue web_preferences_; + + DISALLOW_COPY_AND_ASSIGN(WebContentsPreferences); +}; + +} // namespace atom + +#endif // ATOM_BROWSER_WEB_CONTENTS_PREFERENCES_H_ diff --git a/filenames.gypi b/filenames.gypi index 2f97d01507e..b4d3bcb5e18 100644 --- a/filenames.gypi +++ b/filenames.gypi @@ -226,14 +226,16 @@ 'atom/browser/ui/x/window_state_watcher.h', 'atom/browser/ui/x/x_window_utils.cc', 'atom/browser/ui/x/x_window_utils.h', + 'atom/browser/web_contents_preferences.cc', + 'atom/browser/web_contents_preferences.h', + 'atom/browser/web_dialog_helper.cc', + 'atom/browser/web_dialog_helper.h', 'atom/browser/web_view_constants.cc', 'atom/browser/web_view_constants.h', 'atom/browser/web_view_guest_delegate.cc', 'atom/browser/web_view_guest_delegate.h', 'atom/browser/web_view_manager.cc', 'atom/browser/web_view_manager.h', - 'atom/browser/web_dialog_helper.cc', - 'atom/browser/web_dialog_helper.h', 'atom/browser/window_list.cc', 'atom/browser/window_list.h', 'atom/browser/window_list_observer.h', From 0e92a3e3333fc98a69170f7b202e78bc6b8895e7 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 5 Sep 2015 01:51:14 +0900 Subject: [PATCH 10/27] Use options['web-preferences'] to create WebContents --- atom/browser/api/atom_api_window.cc | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/atom/browser/api/atom_api_window.cc b/atom/browser/api/atom_api_window.cc index e6d16fe6fa5..c8c6437530e 100644 --- a/atom/browser/api/atom_api_window.cc +++ b/atom/browser/api/atom_api_window.cc @@ -13,6 +13,7 @@ #include "atom/common/native_mate_converters/gurl_converter.h" #include "atom/common/native_mate_converters/image_converter.h" #include "atom/common/native_mate_converters/string16_converter.h" +#include "atom/common/options_switches.h" #include "content/public/browser/render_process_host.h" #include "native_mate/constructor.h" #include "native_mate/dictionary.h" @@ -64,9 +65,12 @@ void OnCapturePageDone( Window::Window(v8::Isolate* isolate, const mate::Dictionary& options) { + // Use options['web-preferences'] to create WebContents. + mate::Dictionary web_preferences = mate::Dictionary::CreateEmpty(isolate); + options.Get(switches::kWebPreferences, &web_preferences); + // Creates the WebContents used by BrowserWindow. - mate::Dictionary web_contents_options(isolate, v8::Object::New(isolate)); - auto web_contents = WebContents::Create(isolate, web_contents_options); + auto web_contents = WebContents::Create(isolate, web_preferences); web_contents_.Reset(isolate, web_contents.ToV8()); api_web_contents_ = web_contents.get(); From 96771c7098fa66a29fd5422158d900883c7803f3 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 5 Sep 2015 01:52:29 +0900 Subject: [PATCH 11/27] NPAPI has been removed, remove related option --- atom/browser/native_window.cc | 9 --------- atom/browser/web_contents_preferences.cc | 7 +++++++ atom/browser/web_contents_preferences.h | 4 ++++ 3 files changed, 11 insertions(+), 9 deletions(-) diff --git a/atom/browser/native_window.cc b/atom/browser/native_window.cc index 96085846bca..b0b99081e3c 100644 --- a/atom/browser/native_window.cc +++ b/atom/browser/native_window.cc @@ -424,7 +424,6 @@ void NativeWindow::OverrideWebkitPrefs(content::WebPreferences* prefs) { return; bool b; - std::vector list; if (web_preferences_.Get("javascript", &b)) prefs->javascript_enabled = b; if (web_preferences_.Get("images", &b)) @@ -446,14 +445,6 @@ void NativeWindow::OverrideWebkitPrefs(content::WebPreferences* prefs) { prefs->allow_displaying_insecure_content = b; if (web_preferences_.Get("allow-running-insecure-content", &b)) prefs->allow_running_insecure_content = b; - if (web_preferences_.Get("extra-plugin-dirs", &list)) { - if (content::PluginService::GetInstance()->NPAPIPluginsSupported()) { - for (size_t i = 0; i < list.size(); ++i) - content::PluginService::GetInstance()->AddExtraPluginDir(list[i]); - } else { - LOG(WARNING) << "NPAPI plugins not supported on this platform"; - } - } } void NativeWindow::NotifyWindowClosed() { diff --git a/atom/browser/web_contents_preferences.cc b/atom/browser/web_contents_preferences.cc index 8b956c1b41a..fbd2c7661a7 100644 --- a/atom/browser/web_contents_preferences.cc +++ b/atom/browser/web_contents_preferences.cc @@ -22,4 +22,11 @@ WebContentsPreferences::WebContentsPreferences( WebContentsPreferences::~WebContentsPreferences() { } +// static +WebContentsPreferences* WebContentsPreferences::From( + content::WebContents* web_contents) { + return static_cast( + web_contents->GetUserData(kWebPreferencesKey)); +} + } // namespace atom diff --git a/atom/browser/web_contents_preferences.h b/atom/browser/web_contents_preferences.h index bbbc4cf5e2e..c4c50dc0707 100644 --- a/atom/browser/web_contents_preferences.h +++ b/atom/browser/web_contents_preferences.h @@ -10,9 +10,13 @@ namespace atom { +// Stores and applies the preferences of WebContents. class WebContentsPreferences : public content::WebContentsUserData { public: + // Get the preferences of |web_contents|. + static WebContentsPreferences* From(content::WebContents* web_contents); + WebContentsPreferences(content::WebContents* web_contents, base::DictionaryValue&& web_preferences); ~WebContentsPreferences() override; From 39975378bbc9943b7630910966fe78fc3efd5bf6 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 5 Sep 2015 02:04:09 +0900 Subject: [PATCH 12/27] Move AppendExtraCommandLineSwitches to WebContentsPreferences --- atom/browser/native_window.cc | 37 ------------------- atom/browser/web_contents_preferences.cc | 45 ++++++++++++++++++++++++ atom/browser/web_contents_preferences.h | 8 +++++ 3 files changed, 53 insertions(+), 37 deletions(-) diff --git a/atom/browser/native_window.cc b/atom/browser/native_window.cc index b0b99081e3c..51762d9c00a 100644 --- a/atom/browser/native_window.cc +++ b/atom/browser/native_window.cc @@ -43,10 +43,6 @@ #include "ui/gfx/screen.h" #include "ui/gl/gpu_switching_manager.h" -#if defined(OS_WIN) -#include "ui/gfx/switches.h" -#endif - using content::NavigationEntry; using content::RenderWidgetHostView; using content::RenderWidgetHost; @@ -57,17 +53,6 @@ namespace atom { namespace { -// Array of available web runtime features. -const char* kWebRuntimeFeatures[] = { - switches::kExperimentalFeatures, - switches::kExperimentalCanvasFeatures, - switches::kSubpixelFontScaling, - switches::kOverlayScrollbars, - switches::kOverlayFullscreenVideo, - switches::kSharedWorker, - switches::kPageVisibility, -}; - // Convert draggable regions in raw format to SkRegion format. Caller is // responsible for deleting the returned SkRegion instance. scoped_ptr DraggableRegionsToSkRegion( @@ -395,28 +380,6 @@ void NativeWindow::AppendExtraCommandLineSwitches( if (zoom_factor_ != 1.0) command_line->AppendSwitchASCII(switches::kZoomFactor, base::DoubleToString(zoom_factor_)); - - if (web_preferences_.IsEmpty()) - return; - - bool b; -#if defined(OS_WIN) - // Check if DirectWrite is disabled. - if (web_preferences_.Get(switches::kDirectWrite, &b) && !b) - command_line->AppendSwitch(::switches::kDisableDirectWrite); -#endif - - // Check if plugins are enabled. - if (web_preferences_.Get("plugins", &b) && b) - command_line->AppendSwitch(switches::kEnablePlugins); - - // 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_.Get(feature, &b)) - command_line->AppendSwitchASCII(feature, b ? "true" : "false"); - } } void NativeWindow::OverrideWebkitPrefs(content::WebPreferences* prefs) { diff --git a/atom/browser/web_contents_preferences.cc b/atom/browser/web_contents_preferences.cc index fbd2c7661a7..44525a8612e 100644 --- a/atom/browser/web_contents_preferences.cc +++ b/atom/browser/web_contents_preferences.cc @@ -4,12 +4,31 @@ #include "atom/browser/web_contents_preferences.h" +#include "atom/common/options_switches.h" +#include "base/command_line.h" + +#if defined(OS_WIN) +#include "ui/gfx/switches.h" +#endif + namespace atom { namespace { +// Pointer as WebContents's user data key. const char* kWebPreferencesKey = "WebContentsPreferences"; +// Array of available web runtime features. +const char* kWebRuntimeFeatures[] = { + switches::kExperimentalFeatures, + switches::kExperimentalCanvasFeatures, + switches::kSubpixelFontScaling, + switches::kOverlayScrollbars, + switches::kOverlayFullscreenVideo, + switches::kSharedWorker, + switches::kPageVisibility, +}; + } // namespace WebContentsPreferences::WebContentsPreferences( @@ -29,4 +48,30 @@ WebContentsPreferences* WebContentsPreferences::From( web_contents->GetUserData(kWebPreferencesKey)); } +// static +void WebContentsPreferences::AppendExtraCommandLineSwitches( + content::WebContents* web_contents, base::CommandLine* command_line) { + WebContentsPreferences* self = From(web_contents); + CHECK(self); + + bool b; +#if defined(OS_WIN) + // Check if DirectWrite is disabled. + if (self->web_preferences_.GetBoolean(switches::kDirectWrite, &b) && !b) + command_line->AppendSwitch(::switches::kDisableDirectWrite); +#endif + + // Check if plugins are enabled. + if (self->web_preferences_.GetBoolean("plugins", &b) && b) + command_line->AppendSwitch(switches::kEnablePlugins); + + // 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 (self->web_preferences_.GetBoolean(feature, &b)) + command_line->AppendSwitchASCII(feature, b ? "true" : "false"); + } +} + } // namespace atom diff --git a/atom/browser/web_contents_preferences.h b/atom/browser/web_contents_preferences.h index c4c50dc0707..4c606f779d4 100644 --- a/atom/browser/web_contents_preferences.h +++ b/atom/browser/web_contents_preferences.h @@ -8,6 +8,10 @@ #include "base/values.h" #include "content/public/browser/web_contents_user_data.h" +namespace base { +class CommandLine; +} + namespace atom { // Stores and applies the preferences of WebContents. @@ -17,6 +21,10 @@ class WebContentsPreferences // Get the preferences of |web_contents|. static WebContentsPreferences* From(content::WebContents* web_contents); + // Append command paramters appending to |web_contents|'s preferences. + static void AppendExtraCommandLineSwitches( + content::WebContents* web_contents, base::CommandLine* command_line); + WebContentsPreferences(content::WebContents* web_contents, base::DictionaryValue&& web_preferences); ~WebContentsPreferences() override; From 880dce950db1a1ff9e7d2ffd37eabaf8d6b69c18 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 5 Sep 2015 02:12:32 +0900 Subject: [PATCH 13/27] Move OverrideWebkitPrefs to WebContentsPreferences --- atom/browser/atom_browser_client.cc | 5 +++- atom/browser/native_window.cc | 30 ----------------------- atom/browser/native_window.h | 2 -- atom/browser/web_contents_preferences.cc | 31 ++++++++++++++++++++++++ atom/browser/web_contents_preferences.h | 10 +++++++- 5 files changed, 44 insertions(+), 34 deletions(-) diff --git a/atom/browser/atom_browser_client.cc b/atom/browser/atom_browser_client.cc index fad952d5336..ce333a58579 100644 --- a/atom/browser/atom_browser_client.cc +++ b/atom/browser/atom_browser_client.cc @@ -15,6 +15,7 @@ #include "atom/browser/atom_speech_recognition_manager_delegate.h" #include "atom/browser/browser.h" #include "atom/browser/native_window.h" +#include "atom/browser/web_contents_preferences.h" #include "atom/browser/web_view_manager.h" #include "atom/browser/web_view_constants.h" #include "atom/browser/window_list.h" @@ -169,7 +170,7 @@ void AtomBrowserClient::OverrideWebkitPrefs( NativeWindow* window = NativeWindow::FromWebContents(web_contents); if (window) - window->OverrideWebkitPrefs(prefs); + WebContentsPreferences::OverrideWebkitPrefs(web_contents, prefs); } std::string AtomBrowserClient::GetApplicationLocale() { @@ -231,6 +232,8 @@ void AtomBrowserClient::AppendExtraCommandLineSwitches( if (owner == OWNER_NATIVE_WINDOW) { window->AppendExtraCommandLineSwitches(command_line); + WebContentsPreferences::AppendExtraCommandLineSwitches( + window->web_contents(), command_line); } else if (owner == OWNER_GUEST_WEB_CONTENTS) { command_line->AppendSwitchASCII( switches::kGuestInstanceID, base::IntToString(info.guest_instance_id)); diff --git a/atom/browser/native_window.cc b/atom/browser/native_window.cc index 51762d9c00a..eb7f314fe88 100644 --- a/atom/browser/native_window.cc +++ b/atom/browser/native_window.cc @@ -31,8 +31,6 @@ #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/common/content_switches.h" -#include "content/public/common/renderer_preferences.h" -#include "content/public/common/web_preferences.h" #include "ipc/ipc_message_macros.h" #include "native_mate/dictionary.h" #include "ui/gfx/codec/png_codec.h" @@ -382,34 +380,6 @@ void NativeWindow::AppendExtraCommandLineSwitches( base::DoubleToString(zoom_factor_)); } -void NativeWindow::OverrideWebkitPrefs(content::WebPreferences* prefs) { - if (web_preferences_.IsEmpty()) - return; - - bool b; - if (web_preferences_.Get("javascript", &b)) - prefs->javascript_enabled = b; - if (web_preferences_.Get("images", &b)) - prefs->images_enabled = b; - if (web_preferences_.Get("java", &b)) - prefs->java_enabled = b; - if (web_preferences_.Get("text-areas-are-resizable", &b)) - prefs->text_areas_are_resizable = b; - if (web_preferences_.Get("webgl", &b)) - prefs->experimental_webgl_enabled = b; - if (web_preferences_.Get("webaudio", &b)) - prefs->webaudio_enabled = b; - if (web_preferences_.Get("web-security", &b)) { - prefs->web_security_enabled = b; - prefs->allow_displaying_insecure_content = !b; - prefs->allow_running_insecure_content = !b; - } - if (web_preferences_.Get("allow-displaying-insecure-content", &b)) - prefs->allow_displaying_insecure_content = b; - if (web_preferences_.Get("allow-running-insecure-content", &b)) - prefs->allow_running_insecure_content = b; -} - void NativeWindow::NotifyWindowClosed() { if (is_closed_) return; diff --git a/atom/browser/native_window.h b/atom/browser/native_window.h index 10889a5ccaf..4f074010ec4 100644 --- a/atom/browser/native_window.h +++ b/atom/browser/native_window.h @@ -35,7 +35,6 @@ class InspectableWebContents; namespace content { struct NativeWebKeyboardEvent; -struct WebPreferences; } namespace gfx { @@ -191,7 +190,6 @@ class NativeWindow : public content::WebContentsObserver, // Called when renderer process is going to be started. void AppendExtraCommandLineSwitches(base::CommandLine* command_line); - void OverrideWebkitPrefs(content::WebPreferences* prefs); // Public API used by platform-dependent delegates and observers to send UI // related notifications. diff --git a/atom/browser/web_contents_preferences.cc b/atom/browser/web_contents_preferences.cc index 44525a8612e..ad5e04fcdbf 100644 --- a/atom/browser/web_contents_preferences.cc +++ b/atom/browser/web_contents_preferences.cc @@ -6,6 +6,7 @@ #include "atom/common/options_switches.h" #include "base/command_line.h" +#include "content/public/common/web_preferences.h" #if defined(OS_WIN) #include "ui/gfx/switches.h" @@ -74,4 +75,34 @@ void WebContentsPreferences::AppendExtraCommandLineSwitches( } } +void WebContentsPreferences::OverrideWebkitPrefs( + content::WebContents* web_contents, content::WebPreferences* prefs) { + WebContentsPreferences* self = From(web_contents); + CHECK(self); + + bool b; + if (self->web_preferences_.GetBoolean("javascript", &b)) + prefs->javascript_enabled = b; + if (self->web_preferences_.GetBoolean("images", &b)) + prefs->images_enabled = b; + if (self->web_preferences_.GetBoolean("java", &b)) + prefs->java_enabled = b; + if (self->web_preferences_.GetBoolean("text-areas-are-resizable", &b)) + prefs->text_areas_are_resizable = b; + if (self->web_preferences_.GetBoolean("webgl", &b)) + prefs->experimental_webgl_enabled = b; + if (self->web_preferences_.GetBoolean("webaudio", &b)) + prefs->webaudio_enabled = b; + if (self->web_preferences_.GetBoolean("web-security", &b)) { + prefs->web_security_enabled = b; + prefs->allow_displaying_insecure_content = !b; + prefs->allow_running_insecure_content = !b; + } + if (self->web_preferences_.GetBoolean("allow-displaying-insecure-content", + &b)) + prefs->allow_displaying_insecure_content = b; + if (self->web_preferences_.GetBoolean("allow-running-insecure-content", &b)) + prefs->allow_running_insecure_content = b; +} + } // namespace atom diff --git a/atom/browser/web_contents_preferences.h b/atom/browser/web_contents_preferences.h index 4c606f779d4..a2a63415047 100644 --- a/atom/browser/web_contents_preferences.h +++ b/atom/browser/web_contents_preferences.h @@ -12,6 +12,10 @@ namespace base { class CommandLine; } +namespace content { +struct WebPreferences; +} + namespace atom { // Stores and applies the preferences of WebContents. @@ -21,10 +25,14 @@ class WebContentsPreferences // Get the preferences of |web_contents|. static WebContentsPreferences* From(content::WebContents* web_contents); - // Append command paramters appending to |web_contents|'s preferences. + // Append command paramters according to |web_contents|'s preferences. static void AppendExtraCommandLineSwitches( content::WebContents* web_contents, base::CommandLine* command_line); + // Modify the WebPreferences according to |web_contents|'s preferences. + static void OverrideWebkitPrefs( + content::WebContents* web_contents, content::WebPreferences* prefs); + WebContentsPreferences(content::WebContents* web_contents, base::DictionaryValue&& web_preferences); ~WebContentsPreferences() override; From 0b97d58a6f8f73d25097401e5cabec75222a6114 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 5 Sep 2015 02:33:13 +0900 Subject: [PATCH 14/27] Move a few options in NativeWindow to web-preferences --- atom/browser/api/atom_api_window.cc | 10 ++++++ atom/browser/atom_browser_client.cc | 2 +- atom/browser/native_window.cc | 40 ------------------------ atom/browser/native_window.h | 13 -------- atom/browser/web_contents_preferences.cc | 34 ++++++++++++++++++-- 5 files changed, 42 insertions(+), 57 deletions(-) diff --git a/atom/browser/api/atom_api_window.cc b/atom/browser/api/atom_api_window.cc index c8c6437530e..586cfdb2a78 100644 --- a/atom/browser/api/atom_api_window.cc +++ b/atom/browser/api/atom_api_window.cc @@ -69,6 +69,16 @@ Window::Window(v8::Isolate* isolate, const mate::Dictionary& options) { mate::Dictionary web_preferences = mate::Dictionary::CreateEmpty(isolate); options.Get(switches::kWebPreferences, &web_preferences); + // Be compatible with old options which are now in web_preferences. + std::string str; + double d; + if (options.Get(switches::kNodeIntegration, &str)) + web_preferences.Set(switches::kNodeIntegration, str); + if (options.Get(switches::kPreloadScript, &str)) + web_preferences.Set(switches::kPreloadScript, str); + if (options.Get(switches::kZoomFactor, &d)) + web_preferences.Set(switches::kZoomFactor, d); + // Creates the WebContents used by BrowserWindow. auto web_contents = WebContents::Create(isolate, web_preferences); web_contents_.Reset(isolate, web_contents.ToV8()); diff --git a/atom/browser/atom_browser_client.cc b/atom/browser/atom_browser_client.cc index ce333a58579..fa9c8fb4abe 100644 --- a/atom/browser/atom_browser_client.cc +++ b/atom/browser/atom_browser_client.cc @@ -39,6 +39,7 @@ #include "net/ssl/ssl_cert_request_info.h" #include "ppapi/host/ppapi_host.h" #include "ui/base/l10n/l10n_util.h" +#include "v8/include/v8.h" namespace atom { @@ -231,7 +232,6 @@ void AtomBrowserClient::AppendExtraCommandLineSwitches( ProcessOwner owner = GetProcessOwner(process_id, &window, &info); if (owner == OWNER_NATIVE_WINDOW) { - window->AppendExtraCommandLineSwitches(command_line); WebContentsPreferences::AppendExtraCommandLineSwitches( window->web_contents(), command_line); } else if (owner == OWNER_GUEST_WEB_CONTENTS) { diff --git a/atom/browser/native_window.cc b/atom/browser/native_window.cc index eb7f314fe88..997fe72c4ae 100644 --- a/atom/browser/native_window.cc +++ b/atom/browser/native_window.cc @@ -15,12 +15,10 @@ #include "atom/common/native_mate_converters/image_converter.h" #include "atom/common/native_mate_converters/file_path_converter.h" #include "atom/common/options_switches.h" -#include "base/command_line.h" #include "base/files/file_util.h" #include "base/json/json_writer.h" #include "base/prefs/pref_service.h" #include "base/message_loop/message_loop.h" -#include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "brightray/browser/inspectable_web_contents.h" #include "brightray/browser/inspectable_web_contents_view.h" @@ -77,9 +75,7 @@ NativeWindow::NativeWindow( transparent_(false), enable_larger_than_screen_(false), is_closed_(false), - node_integration_(true), has_dialog_attached_(false), - zoom_factor_(1.0), aspect_ratio_(0.0), inspectable_web_contents_(inspectable_web_contents), weak_factory_(this) { @@ -88,7 +84,6 @@ NativeWindow::NativeWindow( options.Get(switches::kFrame, &has_frame_); options.Get(switches::kTransparent, &transparent_); options.Get(switches::kEnableLargerThanScreen, &enable_larger_than_screen_); - options.Get(switches::kNodeIntegration, &node_integration_); // Tell the content module to initialize renderer widget with transparent // mode. @@ -97,25 +92,6 @@ NativeWindow::NativeWindow( // Read icon before window is created. options.Get(switches::kIcon, &icon_); - // The "preload" option must be absolute path. - if (options.Get(switches::kPreloadScript, &preload_script_) && - !preload_script_.IsAbsolute()) { - LOG(ERROR) << "Path of \"preload\" script must be absolute."; - preload_script_.clear(); - } - - // Be compatible with old API of "node-integration" option. - std::string old_string_token; - if (options.Get(switches::kNodeIntegration, &old_string_token) && - old_string_token != "disable") - node_integration_ = true; - - // Read the web preferences. - options.Get(switches::kWebPreferences, &web_preferences_); - - // Read the zoom factor before any navigation. - options.Get(switches::kZoomFactor, &zoom_factor_); - WindowList::AddWindow(this); } @@ -364,22 +340,6 @@ void NativeWindow::RendererResponsive(content::WebContents* source) { FOR_EACH_OBSERVER(NativeWindowObserver, observers_, OnRendererResponsive()); } -void NativeWindow::AppendExtraCommandLineSwitches( - base::CommandLine* command_line) { - // Append --node-integration to renderer process. - command_line->AppendSwitchASCII(switches::kNodeIntegration, - node_integration_ ? "true" : "false"); - - // Append --preload. - if (!preload_script_.empty()) - command_line->AppendSwitchPath(switches::kPreloadScript, preload_script_); - - // Append --zoom-factor. - if (zoom_factor_ != 1.0) - command_line->AppendSwitchASCII(switches::kZoomFactor, - base::DoubleToString(zoom_factor_)); -} - void NativeWindow::NotifyWindowClosed() { if (is_closed_) return; diff --git a/atom/browser/native_window.h b/atom/browser/native_window.h index 4f074010ec4..a10eda912e5 100644 --- a/atom/browser/native_window.h +++ b/atom/browser/native_window.h @@ -19,7 +19,6 @@ #include "content/public/browser/readback_types.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/browser/web_contents_user_data.h" -#include "native_mate/persistent_dictionary.h" #include "ui/gfx/image/image.h" #include "ui/gfx/image/image_skia.h" @@ -280,9 +279,6 @@ class NativeWindow : public content::WebContentsObserver, // The windows has been closed. bool is_closed_; - // Whether node integration is enabled. - bool node_integration_; - // There is a dialog that has been attached to window. bool has_dialog_attached_; @@ -290,15 +286,6 @@ class NativeWindow : public content::WebContentsObserver, // it should be cancelled when we can prove that the window is responsive. base::CancelableClosure window_unresposive_closure_; - // Web preferences. - mate::PersistentDictionary web_preferences_; - - // The script to load before page's JavaScript starts to run. - base::FilePath preload_script_; - - // Page's default zoom factor. - double zoom_factor_; - // Used to maintain the aspect ratio of a view which is inside of the // content view. double aspect_ratio_; diff --git a/atom/browser/web_contents_preferences.cc b/atom/browser/web_contents_preferences.cc index ad5e04fcdbf..a5bb6172f51 100644 --- a/atom/browser/web_contents_preferences.cc +++ b/atom/browser/web_contents_preferences.cc @@ -6,7 +6,9 @@ #include "atom/common/options_switches.h" #include "base/command_line.h" +#include "base/strings/string_number_conversions.h" #include "content/public/common/web_preferences.h" +#include "storage/common/fileapi/file_system_util.h" // IsAbsolute #if defined(OS_WIN) #include "ui/gfx/switches.h" @@ -54,25 +56,51 @@ void WebContentsPreferences::AppendExtraCommandLineSwitches( content::WebContents* web_contents, base::CommandLine* command_line) { WebContentsPreferences* self = From(web_contents); CHECK(self); + base::DictionaryValue& web_preferences = self->web_preferences_; bool b; #if defined(OS_WIN) // Check if DirectWrite is disabled. - if (self->web_preferences_.GetBoolean(switches::kDirectWrite, &b) && !b) + if (web_preferences.GetBoolean(switches::kDirectWrite, &b) && !b) command_line->AppendSwitch(::switches::kDisableDirectWrite); #endif // Check if plugins are enabled. - if (self->web_preferences_.GetBoolean("plugins", &b) && b) + if (web_preferences.GetBoolean("plugins", &b) && b) command_line->AppendSwitch(switches::kEnablePlugins); // 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 (self->web_preferences_.GetBoolean(feature, &b)) + if (web_preferences.GetBoolean(feature, &b)) command_line->AppendSwitchASCII(feature, b ? "true" : "false"); } + + // Check if we have node integration specified. + bool node_integration = true; + web_preferences.GetBoolean(switches::kNodeIntegration, &node_integration); + // Be compatible with old API of "node-integration" option. + std::string old_token; + if (web_preferences.GetString(switches::kNodeIntegration, &old_token) && + old_token != "disable") + node_integration = true; + command_line->AppendSwitchASCII(switches::kNodeIntegration, + node_integration ? "true" : "false"); + + // The preload script. + base::FilePath::StringType preload; + if (web_preferences.GetString(switches::kPreloadScript, &preload) && + !preload.empty() && + base::FilePath(preload).IsAbsolute()) + command_line->AppendSwitchNative(switches::kPreloadScript, preload); + + // The zoom factor. + double zoom_factor = 1.0; + if (web_preferences.GetDouble(switches::kZoomFactor, &zoom_factor) && + zoom_factor != 1.0) + command_line->AppendSwitchASCII(switches::kZoomFactor, + base::DoubleToString(zoom_factor)); } void WebContentsPreferences::OverrideWebkitPrefs( From b1afe538ee5e61b97d5340cbfcc8d920d2c14fd4 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 5 Sep 2015 10:57:39 +0900 Subject: [PATCH 15/27] Add undocumented "preload-url" option for web-preferences --- atom/browser/web_contents_preferences.cc | 19 ++++++++++++++----- atom/common/options_switches.cc | 3 +++ atom/common/options_switches.h | 1 + 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/atom/browser/web_contents_preferences.cc b/atom/browser/web_contents_preferences.cc index a5bb6172f51..269433e4d6b 100644 --- a/atom/browser/web_contents_preferences.cc +++ b/atom/browser/web_contents_preferences.cc @@ -8,7 +8,7 @@ #include "base/command_line.h" #include "base/strings/string_number_conversions.h" #include "content/public/common/web_preferences.h" -#include "storage/common/fileapi/file_system_util.h" // IsAbsolute +#include "net/base/filename_util.h" #if defined(OS_WIN) #include "ui/gfx/switches.h" @@ -90,10 +90,19 @@ void WebContentsPreferences::AppendExtraCommandLineSwitches( // The preload script. base::FilePath::StringType preload; - if (web_preferences.GetString(switches::kPreloadScript, &preload) && - !preload.empty() && - base::FilePath(preload).IsAbsolute()) - command_line->AppendSwitchNative(switches::kPreloadScript, preload); + if (web_preferences.GetString(switches::kPreloadScript, &preload)) { + if (base::FilePath(preload).IsAbsolute()) + command_line->AppendSwitchNative(switches::kPreloadScript, preload); + else + LOG(ERROR) << "preload script must have abosulute path."; + } else if (web_preferences.GetString(switches::kPreloadUrl, &preload)) { + // Translate to file path if there is "preload-url" option. + base::FilePath preload_path; + if (net::FileURLToFilePath(GURL(preload), &preload_path)) + command_line->AppendSwitchPath(switches::kPreloadScript, preload_path); + else + LOG(ERROR) << "preload url must be file:// protocol."; + } // The zoom factor. double zoom_factor = 1.0; diff --git a/atom/common/options_switches.cc b/atom/common/options_switches.cc index 8f457116ec3..ce5398e447f 100644 --- a/atom/common/options_switches.cc +++ b/atom/common/options_switches.cc @@ -75,6 +75,9 @@ const char kGuestInstanceID[] = "guest-instance-id"; // Script that will be loaded by guest WebContents before other scripts. const char kPreloadScript[] = "preload"; +// Like --preload, but the passed argument is an URL. +const char kPreloadUrl[] = "preload-url"; + // Whether the window should be transparent. const char kTransparent[] = "transparent"; diff --git a/atom/common/options_switches.h b/atom/common/options_switches.h index 2dd48ee32a1..c9298618bdf 100644 --- a/atom/common/options_switches.h +++ b/atom/common/options_switches.h @@ -41,6 +41,7 @@ extern const char kPpapiFlashPath[]; extern const char kPpapiFlashVersion[]; extern const char kGuestInstanceID[]; extern const char kPreloadScript[]; +extern const char kPreloadUrl[]; extern const char kTransparent[]; extern const char kType[]; extern const char kDisableAutoHideCursor[]; From 9c235509a6c6822d74cc38b575231b29a6ff2e1b Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 5 Sep 2015 11:43:30 +0900 Subject: [PATCH 16/27] Read guest view's info from WebContentsPreferences --- atom/browser/api/atom_api_web_view_manager.cc | 41 ++--------- atom/browser/atom_browser_client.cc | 68 +++---------------- atom/browser/atom_browser_context.cc | 2 +- atom/browser/lib/guest-view-manager.coffee | 14 ++-- atom/browser/web_contents_preferences.cc | 19 +++++- atom/browser/web_contents_preferences.h | 3 + atom/browser/web_view_manager.cc | 5 +- atom/browser/web_view_manager.h | 37 +--------- 8 files changed, 45 insertions(+), 144 deletions(-) diff --git a/atom/browser/api/atom_api_web_view_manager.cc b/atom/browser/api/atom_api_web_view_manager.cc index 221d0d7118b..83287ac8b2f 100644 --- a/atom/browser/api/atom_api_web_view_manager.cc +++ b/atom/browser/api/atom_api_web_view_manager.cc @@ -3,14 +3,12 @@ // found in the LICENSE file. #include "atom/browser/api/atom_api_web_contents.h" -#include "atom/browser/web_view_constants.h" +#include "atom/browser/web_contents_preferences.h" #include "atom/browser/web_view_manager.h" -#include "atom/common/native_mate_converters/gurl_converter.h" +#include "atom/common/native_mate_converters/value_converter.h" +#include "atom/common/node_includes.h" #include "content/public/browser/browser_context.h" #include "native_mate/dictionary.h" -#include "net/base/filename_util.h" - -#include "atom/common/node_includes.h" namespace mate { @@ -26,31 +24,6 @@ struct Converter { } }; -template<> -struct Converter { - static bool FromV8(v8::Isolate* isolate, v8::Local val, - atom::WebViewManager::WebViewInfo* out) { - Dictionary options; - if (!ConvertFromV8(isolate, val, &options)) - return false; - - GURL preload_url; - if (!options.Get(atom::web_view::kPreloadUrl, &preload_url)) - return false; - - if (!preload_url.is_empty() && - !net::FileURLToFilePath(preload_url, &(out->preload_script))) - return false; - - return options.Get(atom::web_view::kNodeIntegration, - &(out->node_integration)) && - options.Get(atom::web_view::kPlugins, &(out->plugins)) && - options.Get(atom::web_view::kPartitionId, &(out->partition_id)) && - options.Get(atom::web_view::kDisableWebSecurity, - &(out->disable_web_security)); - } -}; - } // namespace mate namespace { @@ -69,17 +42,13 @@ void AddGuest(int guest_instance_id, int element_instance_id, content::WebContents* embedder, content::WebContents* guest_web_contents, - atom::WebViewManager::WebViewInfo info) { + const base::DictionaryValue& options) { auto manager = GetWebViewManager(embedder); if (manager) manager->AddGuest(guest_instance_id, element_instance_id, embedder, guest_web_contents); - info.guest_instance_id = guest_instance_id; - info.embedder = embedder; - auto data = new atom::WebViewManager::WebViewInfoUserData(info); - guest_web_contents->SetUserData( - atom::web_view::kWebViewInfoKeyName, data); + atom::WebContentsPreferences::From(guest_web_contents)->Merge(options); } void RemoveGuest(content::WebContents* embedder, int guest_instance_id) { diff --git a/atom/browser/atom_browser_client.cc b/atom/browser/atom_browser_client.cc index fa9c8fb4abe..e45caceab01 100644 --- a/atom/browser/atom_browser_client.cc +++ b/atom/browser/atom_browser_client.cc @@ -16,8 +16,6 @@ #include "atom/browser/browser.h" #include "atom/browser/native_window.h" #include "atom/browser/web_contents_preferences.h" -#include "atom/browser/web_view_manager.h" -#include "atom/browser/web_view_constants.h" #include "atom/browser/window_list.h" #include "atom/common/options_switches.h" #include "base/command_line.h" @@ -56,37 +54,6 @@ bool g_suppress_renderer_process_restart = false; // Custom schemes to be registered to standard. std::string g_custom_schemes = ""; -// Find out the owner of the child process according to |process_id|. -enum ProcessOwner { - OWNER_NATIVE_WINDOW, - OWNER_GUEST_WEB_CONTENTS, - OWNER_NONE, // it might be devtools though. -}; - -ProcessOwner GetProcessOwner(int process_id, - NativeWindow** window, - WebViewManager::WebViewInfo* info) { - content::WebContents* web_contents = content::WebContents::FromRenderViewHost( - content::RenderViewHost::FromID(process_id, kDefaultRoutingID)); - if (!web_contents) - return OWNER_NONE; - - // First search for NativeWindow. - *window = NativeWindow::FromWebContents(web_contents); - if (*window) - return OWNER_NATIVE_WINDOW; - - // Then search for guest WebContents. - auto data = static_cast( - web_contents->GetUserData(web_view::kWebViewInfoKeyName)); - if (data) { - *info = data->web_view_info(); - return OWNER_GUEST_WEB_CONTENTS; - } - - return OWNER_NONE; -} - scoped_refptr ImportCertFromFile( const base::FilePath& path) { if (path.empty()) @@ -162,16 +129,7 @@ void AtomBrowserClient::OverrideWebkitPrefs( // Custom preferences of guest page. auto web_contents = content::WebContents::FromRenderViewHost(host); - auto info = static_cast( - web_contents->GetUserData(web_view::kWebViewInfoKeyName)); - if (info) { - prefs->web_security_enabled = !info->web_view_info().disable_web_security; - return; - } - - NativeWindow* window = NativeWindow::FromWebContents(web_contents); - if (window) - WebContentsPreferences::OverrideWebkitPrefs(web_contents, prefs); + WebContentsPreferences::OverrideWebkitPrefs(web_contents, prefs); } std::string AtomBrowserClient::GetApplicationLocale() { @@ -227,24 +185,14 @@ void AtomBrowserClient::AppendExtraCommandLineSwitches( if (ContainsKey(pending_processes_, process_id)) process_id = pending_processes_[process_id]; - NativeWindow* window; - WebViewManager::WebViewInfo info; - ProcessOwner owner = GetProcessOwner(process_id, &window, &info); + // Get the WebContents of the render process. + content::WebContents* web_contents = content::WebContents::FromRenderViewHost( + content::RenderViewHost::FromID(process_id, kDefaultRoutingID)); + if (!web_contents) + return; - if (owner == OWNER_NATIVE_WINDOW) { - WebContentsPreferences::AppendExtraCommandLineSwitches( - window->web_contents(), command_line); - } else if (owner == OWNER_GUEST_WEB_CONTENTS) { - command_line->AppendSwitchASCII( - switches::kGuestInstanceID, base::IntToString(info.guest_instance_id)); - command_line->AppendSwitchASCII( - switches::kNodeIntegration, info.node_integration ? "true" : "false"); - if (info.plugins) - command_line->AppendSwitch(switches::kEnablePlugins); - if (!info.preload_script.empty()) - command_line->AppendSwitchPath( - switches::kPreloadScript, info.preload_script); - } + WebContentsPreferences::AppendExtraCommandLineSwitches( + web_contents, command_line); } void AtomBrowserClient::DidCreatePpapiPlugin( diff --git a/atom/browser/atom_browser_context.cc b/atom/browser/atom_browser_context.cc index 583a6324a8f..43573b1c707 100644 --- a/atom/browser/atom_browser_context.cc +++ b/atom/browser/atom_browser_context.cc @@ -150,7 +150,7 @@ AtomBrowserContext::GetDownloadManagerDelegate() { content::BrowserPluginGuestManager* AtomBrowserContext::GetGuestManager() { if (!guest_manager_) - guest_manager_.reset(new WebViewManager(this)); + guest_manager_.reset(new WebViewManager); return guest_manager_.get(); } diff --git a/atom/browser/lib/guest-view-manager.coffee b/atom/browser/lib/guest-view-manager.coffee index 58127469908..961da8ad192 100644 --- a/atom/browser/lib/guest-view-manager.coffee +++ b/atom/browser/lib/guest-view-manager.coffee @@ -132,12 +132,14 @@ attachGuest = (embedder, elementInstanceId, guestInstanceId, params) -> return unless guestInstances[oldGuestInstanceId]? destroyGuest embedder, oldGuestInstanceId - webViewManager.addGuest guestInstanceId, elementInstanceId, embedder, guest, - nodeIntegration: params.nodeintegration - plugins: params.plugins - disableWebSecurity: params.disablewebsecurity - preloadUrl: params.preload ? '' - partitionId: getPartitionId(params.partition) + webPreferences = + 'guest-instance-id': guestInstanceId + 'node-integration': params.nodeintegration ? false + 'plugins': params.plugins + 'web-security': !params.disablewebsecurity + webPreferences['preload-url'] = params.preload if params.preload + webPreferences['partition'] = getPartitionId(params.partition) if params.partition + webViewManager.addGuest guestInstanceId, elementInstanceId, embedder, guest, webPreferences guest.attachParams = params embedderElementsMap[key] = guestInstanceId diff --git a/atom/browser/web_contents_preferences.cc b/atom/browser/web_contents_preferences.cc index 269433e4d6b..ab7a700cc28 100644 --- a/atom/browser/web_contents_preferences.cc +++ b/atom/browser/web_contents_preferences.cc @@ -44,6 +44,10 @@ WebContentsPreferences::WebContentsPreferences( WebContentsPreferences::~WebContentsPreferences() { } +void WebContentsPreferences::Merge(const base::DictionaryValue& extend) { + web_preferences_.MergeDictionary(&extend); +} + // static WebContentsPreferences* WebContentsPreferences::From( content::WebContents* web_contents) { @@ -55,7 +59,9 @@ WebContentsPreferences* WebContentsPreferences::From( void WebContentsPreferences::AppendExtraCommandLineSwitches( content::WebContents* web_contents, base::CommandLine* command_line) { WebContentsPreferences* self = From(web_contents); - CHECK(self); + if (!self) + return; + base::DictionaryValue& web_preferences = self->web_preferences_; bool b; @@ -110,12 +116,21 @@ void WebContentsPreferences::AppendExtraCommandLineSwitches( 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)) + command_line->AppendSwitchASCII(switches::kGuestInstanceID, + base::IntToString(guest_instance_id)); } +// static void WebContentsPreferences::OverrideWebkitPrefs( content::WebContents* web_contents, content::WebPreferences* prefs) { WebContentsPreferences* self = From(web_contents); - CHECK(self); + if (!self) + return; bool b; if (self->web_preferences_.GetBoolean("javascript", &b)) diff --git a/atom/browser/web_contents_preferences.h b/atom/browser/web_contents_preferences.h index a2a63415047..1053dd9c108 100644 --- a/atom/browser/web_contents_preferences.h +++ b/atom/browser/web_contents_preferences.h @@ -37,6 +37,9 @@ class WebContentsPreferences base::DictionaryValue&& web_preferences); ~WebContentsPreferences() override; + // $.extend(|web_preferences_|, |new_web_preferences|). + void Merge(const base::DictionaryValue& new_web_preferences); + private: friend class content::WebContentsUserData; diff --git a/atom/browser/web_view_manager.cc b/atom/browser/web_view_manager.cc index 9d0b9337599..d404c1a4368 100644 --- a/atom/browser/web_view_manager.cc +++ b/atom/browser/web_view_manager.cc @@ -5,13 +5,12 @@ #include "atom/browser/web_view_manager.h" #include "atom/browser/atom_browser_context.h" -#include "atom/browser/atom_browser_main_parts.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/web_contents.h" namespace atom { -WebViewManager::WebViewManager(content::BrowserContext* context) { +WebViewManager::WebViewManager() { } WebViewManager::~WebViewManager() { @@ -21,7 +20,6 @@ void WebViewManager::AddGuest(int guest_instance_id, int element_instance_id, content::WebContents* embedder, content::WebContents* web_contents) { - base::AutoLock auto_lock(lock_); web_contents_embedder_map_[guest_instance_id] = { web_contents, embedder }; // Map the element in embedder to guest. @@ -31,7 +29,6 @@ void WebViewManager::AddGuest(int guest_instance_id, } void WebViewManager::RemoveGuest(int guest_instance_id) { - base::AutoLock auto_lock(lock_); if (!ContainsKey(web_contents_embedder_map_, guest_instance_id)) return; diff --git a/atom/browser/web_view_manager.h b/atom/browser/web_view_manager.h index 20c04484972..ff9a8ecba2a 100644 --- a/atom/browser/web_view_manager.h +++ b/atom/browser/web_view_manager.h @@ -7,45 +7,14 @@ #include -#include "base/files/file_path.h" -#include "base/supports_user_data.h" -#include "base/synchronization/lock.h" #include "content/public/browser/browser_plugin_guest_manager.h" -#include "content/public/browser/site_instance.h" - -namespace content { -class BrowserContext; -class RenderProcessHost; -} namespace atom { class WebViewManager : public content::BrowserPluginGuestManager { public: - struct WebViewInfo { - int guest_instance_id; - content::WebContents* embedder; - bool node_integration; - bool plugins; - bool disable_web_security; - base::FilePath preload_script; - GURL partition_id; - }; - - class WebViewInfoUserData : public base::SupportsUserData::Data { - public: - explicit WebViewInfoUserData(WebViewInfo info) - : web_view_info_(info) {} - ~WebViewInfoUserData() override {} - - WebViewInfo& web_view_info() { return web_view_info_; } - - private: - WebViewInfo web_view_info_; - }; - - explicit WebViewManager(content::BrowserContext* context); - virtual ~WebViewManager(); + WebViewManager(); + ~WebViewManager() override; void AddGuest(int guest_instance_id, int element_instance_id, @@ -90,8 +59,6 @@ class WebViewManager : public content::BrowserPluginGuestManager { // (embedder_process_id, element_instance_id) => guest_instance_id std::map element_instance_id_to_guest_map_; - base::Lock lock_; - DISALLOW_COPY_AND_ASSIGN(WebViewManager); }; From f2bdca31b3f5ecf7303f2bd50a402551e1adb68e Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 5 Sep 2015 12:19:03 +0900 Subject: [PATCH 17/27] spec: webview test should avoid affecting each other --- spec/webview-spec.coffee | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/spec/webview-spec.coffee b/spec/webview-spec.coffee index fe281510b40..3eeacb0ad0e 100644 --- a/spec/webview-spec.coffee +++ b/spec/webview-spec.coffee @@ -160,7 +160,7 @@ describe ' tag', -> assert.equal e.message, 'undefined undefined undefined undefined' done() webview.src = "file://#{fixtures}/pages/c.html" - webview.partition = "test" + webview.partition = 'test1' document.body.appendChild webview it 'inserts node symbols when set', (done) -> @@ -169,7 +169,7 @@ describe ' tag', -> done() webview.setAttribute 'nodeintegration', 'on' webview.src = "file://#{fixtures}/pages/d.html" - webview.partition = "test" + webview.partition = 'test2' document.body.appendChild webview it 'isolates storage for different id', (done) -> @@ -180,7 +180,7 @@ describe ' tag', -> window.localStorage.setItem 'test', 'one' webview.addEventListener 'console-message', listener webview.src = "file://#{fixtures}/pages/partition/one.html" - webview.partition = "test" + webview.partition = 'test3' document.body.appendChild webview it 'uses current session storage when no id is provided', (done) -> From 3773f81fd5c21f1c7bca1a3eea1a9b452e716389 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 5 Sep 2015 19:47:44 +0800 Subject: [PATCH 18/27] Pass partition name instead of path to BrowserContext --- atom/browser/api/atom_api_web_contents.cc | 18 +++++++----- atom/browser/atom_browser_main_parts.cc | 34 ++++++---------------- atom/browser/atom_browser_main_parts.h | 2 +- atom/browser/lib/guest-view-manager.coffee | 27 ++++++----------- atom/browser/web_contents_preferences.cc | 6 ++-- atom/browser/web_contents_preferences.h | 2 +- vendor/brightray | 2 +- 7 files changed, 35 insertions(+), 56 deletions(-) diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index d724d1ea4c1..d8201973fd8 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -161,19 +161,21 @@ WebContents::WebContents(v8::Isolate* isolate, type_ = is_guest ? WEB_VIEW : BROWSER_WINDOW; + // TODO(zcbenz): Use host's BrowserContext when no partition is specified. content::BrowserContext* browser_context = AtomBrowserMainParts::Get()->browser_context(); content::WebContents* web_contents; if (is_guest) { - GURL guest_site; - options.Get("partition", &guest_site); - // use hosts' browser_context when no partition is specified. - if (!guest_site.query().empty()) { + std::string partition; + bool in_memory = false; + options.Get("partition", &partition); + options.Get("inMemory", &in_memory); + if (!partition.empty()) { browser_context = AtomBrowserMainParts::Get() - ->GetBrowserContextForPartition(guest_site); + ->GetBrowserContextForPartition(partition, in_memory); } - auto site_instance = - content::SiteInstance::CreateForURL(browser_context, guest_site); + content::SiteInstance* site_instance = content::SiteInstance::CreateForURL( + browser_context, GURL("chrome-guest://fake-host")); content::WebContents::CreateParams params(browser_context, site_instance); guest_delegate_.reset(new WebViewGuestDelegate); params.guest_delegate = guest_delegate_.get(); @@ -190,7 +192,7 @@ WebContents::WebContents(v8::Isolate* isolate, // Save the preferences. base::DictionaryValue web_preferences; mate::ConvertFromV8(isolate, options.GetHandle(), &web_preferences); - new WebContentsPreferences(web_contents, std::move(web_preferences)); + new WebContentsPreferences(web_contents, &web_preferences); web_contents->SetUserAgentOverride(GetBrowserContext()->GetUserAgent()); diff --git a/atom/browser/atom_browser_main_parts.cc b/atom/browser/atom_browser_main_parts.cc index 806c12b7eac..5fae6da14b2 100644 --- a/atom/browser/atom_browser_main_parts.cc +++ b/atom/browser/atom_browser_main_parts.cc @@ -26,24 +26,6 @@ namespace atom { -namespace { - -const base::FilePath::CharType kStoragePartitionDirname[] = - FILE_PATH_LITERAL("Partitions"); - -void GetStoragePartitionConfig(const GURL& partition, - base::FilePath* partition_path, - bool* in_memory, - std::string* id) { - *in_memory = (partition.path() != "/persist"); - net::UnescapeRule::Type flags = - net::UnescapeRule::SPACES | net::UnescapeRule::URL_SPECIAL_CHARS; - *id = net::UnescapeURLComponent(partition.query(), flags); - *partition_path = base::FilePath(kStoragePartitionDirname).AppendASCII(*id); -} - -} // namespace - // static AtomBrowserMainParts* AtomBrowserMainParts::self_ = NULL; @@ -69,18 +51,20 @@ AtomBrowserMainParts* AtomBrowserMainParts::Get() { } content::BrowserContext* AtomBrowserMainParts::GetBrowserContextForPartition( - const GURL& partition) { - std::string id; - bool in_memory; - base::FilePath partition_path; - GetStoragePartitionConfig(partition, &partition_path, &in_memory, &id); - if (browser_context_map_.contains(id)) - return browser_context_map_.get(id); + const std::string& partition, bool in_memory) { + if (browser_context_map_.contains(partition)) + return browser_context_map_.get(partition); scoped_ptr browser_context(CreateBrowserContext()); +<<<<<<< HEAD browser_context->Initialize(partition_path.AsUTF8Unsafe(), in_memory); browser_context_map_.set(id, browser_context.Pass()); return browser_context_map_.get(id); +======= + browser_context->Initialize(partition, in_memory); + browser_context_map_.set(partition, browser_context.Pass()); + return browser_context_map_.get(partition); +>>>>>>> Pass partition name instead of path to BrowserContext } void AtomBrowserMainParts::RegisterDestructionCallback( diff --git a/atom/browser/atom_browser_main_parts.h b/atom/browser/atom_browser_main_parts.h index d952f432882..b7b179cf806 100644 --- a/atom/browser/atom_browser_main_parts.h +++ b/atom/browser/atom_browser_main_parts.h @@ -35,7 +35,7 @@ class AtomBrowserMainParts : public brightray::BrowserMainParts { // Returns the BrowserContext associated with the partition. content::BrowserContext* GetBrowserContextForPartition( - const GURL& partition); + const std::string& partition, bool in_memory); // Register a callback that should be destroyed before JavaScript environment // gets destroyed. diff --git a/atom/browser/lib/guest-view-manager.coffee b/atom/browser/lib/guest-view-manager.coffee index 961da8ad192..c7ec439f96f 100644 --- a/atom/browser/lib/guest-view-manager.coffee +++ b/atom/browser/lib/guest-view-manager.coffee @@ -38,29 +38,21 @@ moveLastToFirst = (list) -> getNextInstanceId = (webContents) -> ++nextInstanceId -# Generate URL encoded partition id. -getPartitionId = (partition) -> - # Guest site url will be chrome-guest://fake-host/{persist}?{partitionId} - partitionId = "chrome-guest://fake-host/" - if partition - persist = partition.startsWith('persist:') - if persist - partition = partition.substring('persist:'.length) - partitionId += 'persist?' - else - # Just to differentiate from same persistant ID - partition += "_temp" - partitionId += '?' - partitionId += encodeURIComponent(partition) - return partitionId +# Parse the partition string. +parsePartition = (partition) -> + return ['', false] unless partition + if partition.startsWith 'persist:' + [partition.substr('persist:'.length), false] + else + [partition, true] # Create a new guest instance. createGuest = (embedder, params) -> webViewManager ?= process.atomBinding 'web_view_manager' id = getNextInstanceId embedder - partitionId = getPartitionId params.partition - guest = webContents.create {isGuest: true, partition: partitionId, embedder} + [partition, inMemory] = parsePartition params.partition + guest = webContents.create {isGuest: true, partition, inMemory, embedder} guestInstances[id] = {guest, embedder} # Destroy guest when the embedder is gone or navigated. @@ -138,7 +130,6 @@ attachGuest = (embedder, elementInstanceId, guestInstanceId, params) -> 'plugins': params.plugins 'web-security': !params.disablewebsecurity webPreferences['preload-url'] = params.preload if params.preload - webPreferences['partition'] = getPartitionId(params.partition) if params.partition webViewManager.addGuest guestInstanceId, elementInstanceId, embedder, guest, webPreferences guest.attachParams = params diff --git a/atom/browser/web_contents_preferences.cc b/atom/browser/web_contents_preferences.cc index ab7a700cc28..19ea826a5ff 100644 --- a/atom/browser/web_contents_preferences.cc +++ b/atom/browser/web_contents_preferences.cc @@ -4,6 +4,8 @@ #include "atom/browser/web_contents_preferences.h" +#include + #include "atom/common/options_switches.h" #include "base/command_line.h" #include "base/strings/string_number_conversions.h" @@ -36,8 +38,8 @@ const char* kWebRuntimeFeatures[] = { WebContentsPreferences::WebContentsPreferences( content::WebContents* web_contents, - base::DictionaryValue&& web_preferences) { - web_preferences_.Swap(&web_preferences); + base::DictionaryValue* web_preferences) { + web_preferences_.Swap(web_preferences); web_contents->SetUserData(kWebPreferencesKey, this); } diff --git a/atom/browser/web_contents_preferences.h b/atom/browser/web_contents_preferences.h index 1053dd9c108..310456725aa 100644 --- a/atom/browser/web_contents_preferences.h +++ b/atom/browser/web_contents_preferences.h @@ -34,7 +34,7 @@ class WebContentsPreferences content::WebContents* web_contents, content::WebPreferences* prefs); WebContentsPreferences(content::WebContents* web_contents, - base::DictionaryValue&& web_preferences); + base::DictionaryValue* web_preferences); ~WebContentsPreferences() override; // $.extend(|web_preferences_|, |new_web_preferences|). diff --git a/vendor/brightray b/vendor/brightray index 4d8f5d879d4..55bab304fd1 160000 --- a/vendor/brightray +++ b/vendor/brightray @@ -1 +1 @@ -Subproject commit 4d8f5d879d484db54895c3456ded3a3d3246415d +Subproject commit 55bab304fd1c92a79e636bca0313f7cbda000c06 From ba25bed45b60053090cae072ebc1a5e918eac7ab Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 5 Sep 2015 20:03:40 +0800 Subject: [PATCH 19/27] Store BrowserContext in ref-counted ptr --- atom/browser/atom_browser_main_parts.cc | 16 +++++----------- atom/browser/atom_browser_main_parts.h | 3 +-- vendor/brightray | 2 +- 3 files changed, 7 insertions(+), 14 deletions(-) diff --git a/atom/browser/atom_browser_main_parts.cc b/atom/browser/atom_browser_main_parts.cc index 5fae6da14b2..e614f9b6365 100644 --- a/atom/browser/atom_browser_main_parts.cc +++ b/atom/browser/atom_browser_main_parts.cc @@ -52,19 +52,13 @@ AtomBrowserMainParts* AtomBrowserMainParts::Get() { content::BrowserContext* AtomBrowserMainParts::GetBrowserContextForPartition( const std::string& partition, bool in_memory) { - if (browser_context_map_.contains(partition)) - return browser_context_map_.get(partition); + if (ContainsKey(browser_context_map_, partition)) + return browser_context_map_[partition].get(); - scoped_ptr browser_context(CreateBrowserContext()); -<<<<<<< HEAD - browser_context->Initialize(partition_path.AsUTF8Unsafe(), in_memory); - browser_context_map_.set(id, browser_context.Pass()); - return browser_context_map_.get(id); -======= + brightray::BrowserContext* browser_context = CreateBrowserContext(); browser_context->Initialize(partition, in_memory); - browser_context_map_.set(partition, browser_context.Pass()); - return browser_context_map_.get(partition); ->>>>>>> Pass partition name instead of path to BrowserContext + browser_context_map_[partition] = make_scoped_refptr(browser_context); + return browser_context; } void AtomBrowserMainParts::RegisterDestructionCallback( diff --git a/atom/browser/atom_browser_main_parts.h b/atom/browser/atom_browser_main_parts.h index b7b179cf806..de53f66788b 100644 --- a/atom/browser/atom_browser_main_parts.h +++ b/atom/browser/atom_browser_main_parts.h @@ -10,7 +10,6 @@ #include #include "base/callback.h" -#include "base/containers/scoped_ptr_hash_map.h" #include "base/timer/timer.h" #include "brightray/browser/browser_main_parts.h" #include "content/public/browser/browser_context.h" @@ -79,7 +78,7 @@ class AtomBrowserMainParts : public brightray::BrowserMainParts { std::list destruction_callbacks_; // partition_id => browser_context - base::ScopedPtrHashMap> + std::map> browser_context_map_; static AtomBrowserMainParts* self_; diff --git a/vendor/brightray b/vendor/brightray index 55bab304fd1..ca80107e3de 160000 --- a/vendor/brightray +++ b/vendor/brightray @@ -1 +1 @@ -Subproject commit 55bab304fd1c92a79e636bca0313f7cbda000c06 +Subproject commit ca80107e3dec28d5b49d64da9985525c3e2c4e84 From fafb28e41a59193c37d5282bf20a517c55ee9d6c Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 5 Sep 2015 20:54:36 +0800 Subject: [PATCH 20/27] Move management of browser context to BrowserContext --- atom/browser/api/atom_api_web_contents.cc | 6 ++---- atom/browser/atom_browser_context.cc | 16 ++++++++++++++-- atom/browser/atom_browser_context.h | 7 ++++--- atom/browser/atom_browser_main_parts.cc | 15 --------------- atom/browser/atom_browser_main_parts.h | 14 +------------- vendor/brightray | 2 +- 6 files changed, 22 insertions(+), 38 deletions(-) diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index d8201973fd8..e9165657011 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -170,10 +170,8 @@ WebContents::WebContents(v8::Isolate* isolate, bool in_memory = false; options.Get("partition", &partition); options.Get("inMemory", &in_memory); - if (!partition.empty()) { - browser_context = AtomBrowserMainParts::Get() - ->GetBrowserContextForPartition(partition, in_memory); - } + if (!partition.empty()) + browser_context = brightray::BrowserContext::From(partition, in_memory); content::SiteInstance* site_instance = content::SiteInstance::CreateForURL( browser_context, GURL("chrome-guest://fake-host")); content::WebContents::CreateParams params(browser_context, site_instance); diff --git a/atom/browser/atom_browser_context.cc b/atom/browser/atom_browser_context.cc index 43573b1c707..81973857b12 100644 --- a/atom/browser/atom_browser_context.cc +++ b/atom/browser/atom_browser_context.cc @@ -56,8 +56,10 @@ std::string RemoveWhitespace(const std::string& str) { } // namespace -AtomBrowserContext::AtomBrowserContext() - : job_factory_(new AtomURLRequestJobFactory) { +AtomBrowserContext::AtomBrowserContext(const std::string& partition, + bool in_memory) + : brightray::BrowserContext(partition, in_memory), + job_factory_(new AtomURLRequestJobFactory) { } AtomBrowserContext::~AtomBrowserContext() { @@ -162,3 +164,13 @@ void AtomBrowserContext::RegisterPrefs(PrefRegistrySimple* pref_registry) { } } // namespace atom + +namespace brightray { + +// static +BrowserContext* BrowserContext::Create(const std::string& partition, + bool in_memory) { + return new atom::AtomBrowserContext(partition, in_memory); +} + +} // namespace brightray diff --git a/atom/browser/atom_browser_context.h b/atom/browser/atom_browser_context.h index c1ff613b8c0..c99461ad9a8 100644 --- a/atom/browser/atom_browser_context.h +++ b/atom/browser/atom_browser_context.h @@ -17,8 +17,8 @@ class WebViewManager; class AtomBrowserContext : public brightray::BrowserContext { public: - AtomBrowserContext(); - virtual ~AtomBrowserContext(); + AtomBrowserContext(const std::string& partition, bool in_memory); + ~AtomBrowserContext() override; // brightray::URLRequestContextGetter::Delegate: std::string GetUserAgent() override; @@ -41,7 +41,8 @@ class AtomBrowserContext : public brightray::BrowserContext { scoped_ptr download_manager_delegate_; scoped_ptr guest_manager_; - AtomURLRequestJobFactory* job_factory_; // Weak reference. + // Managed by brightray::BrowserContext. + AtomURLRequestJobFactory* job_factory_; DISALLOW_COPY_AND_ASSIGN(AtomBrowserContext); }; diff --git a/atom/browser/atom_browser_main_parts.cc b/atom/browser/atom_browser_main_parts.cc index e614f9b6365..31a49046414 100644 --- a/atom/browser/atom_browser_main_parts.cc +++ b/atom/browser/atom_browser_main_parts.cc @@ -50,26 +50,11 @@ AtomBrowserMainParts* AtomBrowserMainParts::Get() { return self_; } -content::BrowserContext* AtomBrowserMainParts::GetBrowserContextForPartition( - const std::string& partition, bool in_memory) { - if (ContainsKey(browser_context_map_, partition)) - return browser_context_map_[partition].get(); - - brightray::BrowserContext* browser_context = CreateBrowserContext(); - browser_context->Initialize(partition, in_memory); - browser_context_map_[partition] = make_scoped_refptr(browser_context); - return browser_context; -} - void AtomBrowserMainParts::RegisterDestructionCallback( const base::Closure& callback) { destruction_callbacks_.push_back(callback); } -brightray::BrowserContext* AtomBrowserMainParts::CreateBrowserContext() { - return new AtomBrowserContext(); -} - void AtomBrowserMainParts::PostEarlyInitialization() { brightray::BrowserMainParts::PostEarlyInitialization(); diff --git a/atom/browser/atom_browser_main_parts.h b/atom/browser/atom_browser_main_parts.h index de53f66788b..59ff7c977c8 100644 --- a/atom/browser/atom_browser_main_parts.h +++ b/atom/browser/atom_browser_main_parts.h @@ -6,7 +6,6 @@ #define ATOM_BROWSER_ATOM_BROWSER_MAIN_PARTS_H_ #include -#include #include #include "base/callback.h" @@ -32,10 +31,6 @@ class AtomBrowserMainParts : public brightray::BrowserMainParts { static AtomBrowserMainParts* Get(); - // Returns the BrowserContext associated with the partition. - content::BrowserContext* GetBrowserContextForPartition( - const std::string& partition, bool in_memory); - // Register a callback that should be destroyed before JavaScript environment // gets destroyed. void RegisterDestructionCallback(const base::Closure& callback); @@ -43,10 +38,7 @@ class AtomBrowserMainParts : public brightray::BrowserMainParts { Browser* browser() { return browser_.get(); } protected: - // Implementations of brightray::BrowserMainParts. - brightray::BrowserContext* CreateBrowserContext() override; - - // Implementations of content::BrowserMainParts. + // content::BrowserMainParts: void PostEarlyInitialization() override; void PreMainMessageLoopRun() override; #if defined(OS_MACOSX) @@ -77,10 +69,6 @@ class AtomBrowserMainParts : public brightray::BrowserMainParts { // List of callbacks should be executed before destroying JS env. std::list destruction_callbacks_; - // partition_id => browser_context - std::map> - browser_context_map_; - static AtomBrowserMainParts* self_; DISALLOW_COPY_AND_ASSIGN(AtomBrowserMainParts); diff --git a/vendor/brightray b/vendor/brightray index ca80107e3de..b103a37d053 160000 --- a/vendor/brightray +++ b/vendor/brightray @@ -1 +1 @@ -Subproject commit ca80107e3dec28d5b49d64da9985525c3e2c4e84 +Subproject commit b103a37d05335766421f4228fcb392cc57f8ea67 From 0b1a3f3ef3b02bd76f411eef775913242d2ff3fb Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 5 Sep 2015 22:39:48 +0800 Subject: [PATCH 21/27] Manage the life of BrowserContext in Session --- atom/browser/api/atom_api_session.cc | 20 ++++++++---- atom/browser/api/atom_api_session.h | 8 +++-- atom/browser/api/atom_api_web_contents.cc | 37 ++++++++++++----------- atom/browser/atom_browser_context.cc | 6 ++-- vendor/brightray | 2 +- 5 files changed, 44 insertions(+), 29 deletions(-) diff --git a/atom/browser/api/atom_api_session.cc b/atom/browser/api/atom_api_session.cc index 3ca15ab871f..db9d89c3dd6 100644 --- a/atom/browser/api/atom_api_session.cc +++ b/atom/browser/api/atom_api_session.cc @@ -241,7 +241,7 @@ Session::Session(AtomBrowserContext* browser_context) Session::~Session() { auto download_manager = - content::BrowserContext::GetDownloadManager(browser_context_); + content::BrowserContext::GetDownloadManager(browser_context()); download_manager->RemoveObserver(this); } @@ -258,7 +258,7 @@ void Session::OnDownloadCreated(content::DownloadManager* manager, } void Session::ResolveProxy(const GURL& url, ResolveProxyCallback callback) { - new ResolveProxyHelper(browser_context_, url, callback); + new ResolveProxyHelper(browser_context(), url, callback); } void Session::ClearCache(const net::CompletionCallback& callback) { @@ -279,7 +279,7 @@ void Session::ClearStorageData(mate::Arguments* args) { } auto storage_partition = - content::BrowserContext::GetStoragePartition(browser_context_, nullptr); + content::BrowserContext::GetStoragePartition(browser_context(), nullptr); storage_partition->ClearData( options.storage_types, options.quota_types, options.origin, content::StoragePartition::OriginMatcherFunction(), @@ -300,7 +300,7 @@ void Session::SetDownloadPath(const base::FilePath& path) { v8::Local Session::Cookies(v8::Isolate* isolate) { if (cookies_.IsEmpty()) { - auto handle = atom::api::Cookies::Create(isolate, browser_context_); + auto handle = atom::api::Cookies::Create(isolate, browser_context()); cookies_.Reset(isolate, handle.ToV8()); } return v8::Local::New(isolate, cookies_); @@ -319,8 +319,7 @@ mate::ObjectTemplateBuilder Session::GetObjectTemplateBuilder( // static mate::Handle Session::CreateFrom( - v8::Isolate* isolate, - AtomBrowserContext* browser_context) { + v8::Isolate* isolate, AtomBrowserContext* browser_context) { auto existing = TrackableObject::FromWrappedClass(isolate, browser_context); if (existing) return mate::CreateHandle(isolate, static_cast(existing)); @@ -330,6 +329,14 @@ mate::Handle Session::CreateFrom( return handle; } +// static +mate::Handle Session::FromPartition( + v8::Isolate* isolate, const std::string& partition, bool in_memory) { + auto browser_context = brightray::BrowserContext::From(partition, in_memory); + return CreateFrom(isolate, + static_cast(browser_context.get())); +} + void SetWrapSession(const WrapSessionCallback& callback) { g_wrap_session = callback; } @@ -348,6 +355,7 @@ void Initialize(v8::Local exports, v8::Local unused, v8::Local context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); mate::Dictionary dict(isolate, exports); + dict.SetMethod("fromPartition", &atom::api::Session::FromPartition); dict.SetMethod("_setWrapSession", &atom::api::SetWrapSession); dict.SetMethod("_clearWrapSession", &atom::api::ClearWrapSession); } diff --git a/atom/browser/api/atom_api_session.h b/atom/browser/api/atom_api_session.h index c06348974ff..d9799861401 100644 --- a/atom/browser/api/atom_api_session.h +++ b/atom/browser/api/atom_api_session.h @@ -37,7 +37,11 @@ class Session: public mate::TrackableObject, static mate::Handle CreateFrom( v8::Isolate* isolate, AtomBrowserContext* browser_context); - AtomBrowserContext* browser_context() const { return browser_context_; } + // Gets the Session of |partition| and |in_memory|. + static mate::Handle FromPartition( + v8::Isolate* isolate, const std::string& partition, bool in_memory); + + AtomBrowserContext* browser_context() const { return browser_context_.get(); } protected: explicit Session(AtomBrowserContext* browser_context); @@ -61,7 +65,7 @@ class Session: public mate::TrackableObject, v8::Global cookies_; - AtomBrowserContext* browser_context_; // weak ref + scoped_refptr browser_context_; DISALLOW_COPY_AND_ASSIGN(Session); }; diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index e9165657011..77fbf9f1de8 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -156,30 +156,36 @@ WebContents::WebContents(content::WebContents* web_contents) WebContents::WebContents(v8::Isolate* isolate, const mate::Dictionary& options) { + // Whether it is a guest WebContents. bool is_guest = false; options.Get("isGuest", &is_guest); - type_ = is_guest ? WEB_VIEW : BROWSER_WINDOW; - // TODO(zcbenz): Use host's BrowserContext when no partition is specified. - content::BrowserContext* browser_context = - AtomBrowserMainParts::Get()->browser_context(); + // Obtain the session. + std::string partition; + mate::Handle session; + if (options.Get("session", &session)) { + } else if (options.Get("partition", &partition)) { + bool in_memory = true; + options.Get("inMemory", &in_memory); + session = Session::FromPartition(isolate, partition, in_memory); + } else { + // Use the default session if not specified. + session = Session::FromPartition(isolate, "", false); + } + session_.Reset(isolate, session.ToV8()); + content::WebContents* web_contents; if (is_guest) { - std::string partition; - bool in_memory = false; - options.Get("partition", &partition); - options.Get("inMemory", &in_memory); - if (!partition.empty()) - browser_context = brightray::BrowserContext::From(partition, in_memory); content::SiteInstance* site_instance = content::SiteInstance::CreateForURL( - browser_context, GURL("chrome-guest://fake-host")); - content::WebContents::CreateParams params(browser_context, site_instance); + session->browser_context(), GURL("chrome-guest://fake-host")); + content::WebContents::CreateParams params( + session->browser_context(), site_instance); guest_delegate_.reset(new WebViewGuestDelegate); params.guest_delegate = guest_delegate_.get(); web_contents = content::WebContents::Create(params); } else { - content::WebContents::CreateParams params(browser_context); + content::WebContents::CreateParams params(session->browser_context()); web_contents = content::WebContents::Create(params); } @@ -496,6 +502,7 @@ void WebContents::NavigationEntryCommitted( } void WebContents::Destroy() { + session_.Reset(); if (type_ == WEB_VIEW && managed_web_contents()) { // When force destroying the "destroyed" event is not emitted. WebContentsDestroyed(); @@ -658,10 +665,6 @@ void WebContents::InspectServiceWorker() { } v8::Local WebContents::Session(v8::Isolate* isolate) { - if (session_.IsEmpty()) { - auto handle = Session::CreateFrom(isolate, GetBrowserContext()); - session_.Reset(isolate, handle.ToV8()); - } return v8::Local::New(isolate, session_); } diff --git a/atom/browser/atom_browser_context.cc b/atom/browser/atom_browser_context.cc index 81973857b12..d1ef09e70ff 100644 --- a/atom/browser/atom_browser_context.cc +++ b/atom/browser/atom_browser_context.cc @@ -168,9 +168,9 @@ void AtomBrowserContext::RegisterPrefs(PrefRegistrySimple* pref_registry) { namespace brightray { // static -BrowserContext* BrowserContext::Create(const std::string& partition, - bool in_memory) { - return new atom::AtomBrowserContext(partition, in_memory); +scoped_refptr BrowserContext::Create( + const std::string& partition, bool in_memory) { + return make_scoped_refptr(new atom::AtomBrowserContext(partition, in_memory)); } } // namespace brightray diff --git a/vendor/brightray b/vendor/brightray index b103a37d053..251521cb8c5 160000 --- a/vendor/brightray +++ b/vendor/brightray @@ -1 +1 @@ -Subproject commit b103a37d05335766421f4228fcb392cc57f8ea67 +Subproject commit 251521cb8c51670dbd08ab9fd2dd45e249cbb596 From 2454dccde0bfbbd436e00dd0caa5afa0a427af6f Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 5 Sep 2015 23:22:38 +0800 Subject: [PATCH 22/27] docs: preload, node-integration, zoom-factor have been moved --- docs/api/browser-window.md | 28 +++++++++++++++++----------- docs/api/web-view-tag.md | 18 +++++++++--------- 2 files changed, 26 insertions(+), 20 deletions(-) diff --git a/docs/api/browser-window.md b/docs/api/browser-window.md index e9d2c7f6feb..3e19b5bfabf 100644 --- a/docs/api/browser-window.md +++ b/docs/api/browser-window.md @@ -48,8 +48,6 @@ Properties `width` and `height` are required. * `fullscreen` Boolean - Whether the window should show in fullscreen. When set to `false` the fullscreen button will also be hidden on OS X. * `skip-taskbar` Boolean - Whether to show the window in taskbar. -* `zoom-factor` Number - The default zoom factor of the page, `3.0` represents -`300%`. * `kiosk` Boolean - The kiosk mode. * `title` String - Default window title. * `icon` [NativeImage](native-image.md) - The window icon, when omitted on @@ -57,8 +55,6 @@ Properties `width` and `height` are required. * `show` Boolean - Whether window should be shown when created. * `frame` Boolean - Specify `false` to create a [Frameless Window](frameless-window.md). -* `node-integration` Boolean - Whether node integration is enabled. Default - is `true`. * `accept-first-mouse` Boolean - Whether the web view accepts a single mouse-down event that simultaneously activates the window. * `disable-auto-hide-cursor` Boolean - Whether to hide cursor when typing. @@ -68,10 +64,6 @@ Properties `width` and `height` are required. than screen. * `dark-theme` Boolean - Forces using dark theme for the window, only works on some GTK+3 desktop environments. -* `preload` String - Specifies a script that will be loaded before other - scripts run in the window. This script will always have access to node APIs - no matter whether node integration is turned on for the window, and the path - of `preload` script has to be absolute path. * `transparent` Boolean - Makes the window [transparent](frameless-window.md). * `type` String - Specifies the type of the window, possible types are `desktop`, `dock`, `toolbar`, `splash`, `notification`. This only works on @@ -79,11 +71,25 @@ Properties `width` and `height` are required. * `standard-window` Boolean - Uses the OS X's standard window instead of the textured window. Defaults to `true`. * `web-preferences` Object - Settings of web page's features, properties: + * `node-integration` Boolean - Whether node integration is enabled. Default + is `true`. + * `preload` String - Specifies a script that will be loaded before other + scripts run in the page. This script will always have access to node APIs + no matter whether node integration is turned on for the page, and the path + of `preload` script has to be absolute path. + * `partition` String - Sets the session used by the page. If `partition` + starts with `persist:`, the page will use a persistent session available to + all pages in the app with the same `partition`. if there is no `persist:` + prefix, the page will use an in-memory session. By assigning the same + `partition`, multiple pages can share the same session. If the `partition` + is unset then default session of the app will be used. + * `zoom-factor` Number - The default zoom factor of the page, `3.0` represents + `300%`. * `javascript` Boolean * `web-security` Boolean - When setting `false`, it will disable the - same-origin policy (Usually using testing websites by people), and set `allow_displaying_insecure_content` - and `allow_running_insecure_content` to `true` if these two options are not - set by user. + same-origin policy (Usually using testing websites by people), and set + `allow_displaying_insecure_content` and `allow_running_insecure_content` to + `true` if these two options are not set by user. * `allow-displaying-insecure-content` Boolean - Allow an https page to display content like images from http URLs. * `allow-running-insecure-content` Boolean - Allow a https page to run diff --git a/docs/api/web-view-tag.md b/docs/api/web-view-tag.md index c1b1f705e95..85039070216 100644 --- a/docs/api/web-view-tag.md +++ b/docs/api/web-view-tag.md @@ -138,16 +138,16 @@ If "on", the guest page will have web security disabled. ``` -Sets the storage partition used by the `webview`. If the storage partition ID starts with `persist:`, -the `webview` will use a persistent storage partition available to all `webview` in the app with -the same storage partition ID. if there is no `persist:` prefix, the `webview` will -use an in-memory storage partition. By assigning the same partition ID, multiple `webview` -can share the same storage partition. If the storage partition ID is unset then default storage -of the app will be used. +Sets the session used by the page. If `partition` starts with `persist:`, the +page will use a persistent session available to all pages in the app with the +same `partition`. if there is no `persist:` prefix, the page will use an +in-memory session. By assigning the same `partition`, multiple pages can share +the same session. If the `partition` is unset then default session of the app +will be used. -This value can only be modified before the first navigation, since the storage partition of an active -renderer process cannot change. Subsequent attempts to modify the value will fail with a -DOM exception. +This value can only be modified before the first navigation, since the session +of an active renderer process cannot change. Subsequent attempts to modify the +value will fail with a DOM exception. ## Methods From 5eb0bedbbca8b9062d11ea412230ee5ab19db4d3 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sun, 6 Sep 2015 09:22:32 +0800 Subject: [PATCH 23/27] Parse partition in webContents.create --- atom/browser/api/atom_api_web_contents.cc | 7 +++++-- atom/browser/lib/guest-view-manager.coffee | 11 +---------- 2 files changed, 6 insertions(+), 12 deletions(-) diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index 77fbf9f1de8..d22f7aab61f 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -165,9 +165,12 @@ WebContents::WebContents(v8::Isolate* isolate, std::string partition; mate::Handle session; if (options.Get("session", &session)) { - } else if (options.Get("partition", &partition)) { + } else if (options.Get("partition", &partition) && !partition.empty()) { bool in_memory = true; - options.Get("inMemory", &in_memory); + if (base::StartsWith(partition, "persist:", base::CompareCase::SENSITIVE)) { + in_memory = false; + partition = partition.substr(8); + } session = Session::FromPartition(isolate, partition, in_memory); } else { // Use the default session if not specified. diff --git a/atom/browser/lib/guest-view-manager.coffee b/atom/browser/lib/guest-view-manager.coffee index c7ec439f96f..1c05b65b2dc 100644 --- a/atom/browser/lib/guest-view-manager.coffee +++ b/atom/browser/lib/guest-view-manager.coffee @@ -38,21 +38,12 @@ moveLastToFirst = (list) -> getNextInstanceId = (webContents) -> ++nextInstanceId -# Parse the partition string. -parsePartition = (partition) -> - return ['', false] unless partition - if partition.startsWith 'persist:' - [partition.substr('persist:'.length), false] - else - [partition, true] - # Create a new guest instance. createGuest = (embedder, params) -> webViewManager ?= process.atomBinding 'web_view_manager' id = getNextInstanceId embedder - [partition, inMemory] = parsePartition params.partition - guest = webContents.create {isGuest: true, partition, inMemory, embedder} + guest = webContents.create {isGuest: true, partition: params.partition, embedder} guestInstances[id] = {guest, embedder} # Destroy guest when the embedder is gone or navigated. From e2bd1abce635f39ef8dc20b73afdaca01130761a Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sun, 6 Sep 2015 10:30:59 +0800 Subject: [PATCH 24/27] Make sure BrowserContext is destroyed on exit --- atom/browser/api/atom_api_session.cc | 20 ++++++++++++++------ atom/browser/api/atom_api_session.h | 7 ++++++- atom/browser/api/atom_api_web_contents.h | 4 +++- atom/browser/api/atom_api_window.cc | 5 ++++- atom/browser/api/atom_api_window.h | 4 +++- atom/browser/api/trackable_object.cc | 9 ++++++--- atom/browser/api/trackable_object.h | 12 ++++++++++-- vendor/brightray | 2 +- 8 files changed, 47 insertions(+), 16 deletions(-) diff --git a/atom/browser/api/atom_api_session.cc b/atom/browser/api/atom_api_session.cc index db9d89c3dd6..7d31626c141 100644 --- a/atom/browser/api/atom_api_session.cc +++ b/atom/browser/api/atom_api_session.cc @@ -233,16 +233,16 @@ void SetProxyInIO(net::URLRequestContextGetter* getter, Session::Session(AtomBrowserContext* browser_context) : browser_context_(browser_context) { AttachAsUserData(browser_context); + // Observe DownloadManger to get download notifications. - auto download_manager = - content::BrowserContext::GetDownloadManager(browser_context); - download_manager->AddObserver(this); + content::BrowserContext::GetDownloadManager(browser_context)-> + AddObserver(this); } Session::~Session() { - auto download_manager = - content::BrowserContext::GetDownloadManager(browser_context()); - download_manager->RemoveObserver(this); + content::BrowserContext::GetDownloadManager(browser_context())-> + RemoveObserver(this); + Destroy(); } void Session::OnDownloadCreated(content::DownloadManager* manager, @@ -257,6 +257,14 @@ void Session::OnDownloadCreated(content::DownloadManager* manager, } } +bool Session::IsDestroyed() const { + return !browser_context_; +} + +void Session::Destroy() { + browser_context_ = nullptr; +} + void Session::ResolveProxy(const GURL& url, ResolveProxyCallback callback) { new ResolveProxyHelper(browser_context(), url, callback); } diff --git a/atom/browser/api/atom_api_session.h b/atom/browser/api/atom_api_session.h index d9799861401..14406e57af5 100644 --- a/atom/browser/api/atom_api_session.h +++ b/atom/browser/api/atom_api_session.h @@ -51,11 +51,15 @@ class Session: public mate::TrackableObject, void OnDownloadCreated(content::DownloadManager* manager, content::DownloadItem* item) override; - // mate::Wrappable implementations: + // mate::Wrappable: mate::ObjectTemplateBuilder GetObjectTemplateBuilder( v8::Isolate* isolate) override; + bool IsDestroyed() const override; private: + // mate::TrackableObject: + void Destroy() override; + void ResolveProxy(const GURL& url, ResolveProxyCallback callback); void ClearCache(const net::CompletionCallback& callback); void ClearStorageData(mate::Arguments* args); @@ -63,6 +67,7 @@ class Session: public mate::TrackableObject, void SetDownloadPath(const base::FilePath& path); v8::Local Cookies(v8::Isolate* isolate); + // Cached object for cookies API. v8::Global cookies_; scoped_refptr browser_context_; diff --git a/atom/browser/api/atom_api_web_contents.h b/atom/browser/api/atom_api_web_contents.h index 5ea62dabff6..e2e405b7385 100644 --- a/atom/browser/api/atom_api_web_contents.h +++ b/atom/browser/api/atom_api_web_contents.h @@ -48,7 +48,9 @@ class WebContents : public mate::TrackableObject, static mate::Handle Create( v8::Isolate* isolate, const mate::Dictionary& options); - void Destroy(); + // mate::TrackableObject: + void Destroy() override; + bool IsAlive() const; int GetID() const; bool Equal(const WebContents* web_contents) const; diff --git a/atom/browser/api/atom_api_window.cc b/atom/browser/api/atom_api_window.cc index 586cfdb2a78..e171fa7698f 100644 --- a/atom/browser/api/atom_api_window.cc +++ b/atom/browser/api/atom_api_window.cc @@ -221,7 +221,10 @@ bool Window::IsDestroyed() const { } void Window::Destroy() { - window_->CloseContents(nullptr); + if (window_) { + window_->CloseContents(nullptr); + window_.reset(); + } } void Window::Close() { diff --git a/atom/browser/api/atom_api_window.h b/atom/browser/api/atom_api_window.h index de2f093ea3e..4384e03a249 100644 --- a/atom/browser/api/atom_api_window.h +++ b/atom/browser/api/atom_api_window.h @@ -78,8 +78,10 @@ class Window : public mate::TrackableObject, bool IsDestroyed() const override; private: + // mate::TrackableObject: + void Destroy() override; + // APIs for NativeWindow. - void Destroy(); void Close(); bool IsClosed(); void Focus(); diff --git a/atom/browser/api/trackable_object.cc b/atom/browser/api/trackable_object.cc index ae9fa44230a..50bfa59e6a7 100644 --- a/atom/browser/api/trackable_object.cc +++ b/atom/browser/api/trackable_object.cc @@ -29,7 +29,9 @@ class IDUserData : public base::SupportsUserData::Data { } // namespace TrackableObjectBase::TrackableObjectBase() - : weak_map_id_(0), wrapped_(nullptr) { + : weak_map_id_(0), wrapped_(nullptr), weak_factory_(this) { + RegisterDestructionCallback( + base::Bind(&TrackableObjectBase::Destroy, weak_factory_.GetWeakPtr())); } TrackableObjectBase::~TrackableObjectBase() { @@ -61,8 +63,9 @@ int32_t TrackableObjectBase::GetIDFromWrappedClass(base::SupportsUserData* w) { } // static -void TrackableObjectBase::RegisterDestructionCallback(void (*c)()) { - atom::AtomBrowserMainParts::Get()->RegisterDestructionCallback(base::Bind(c)); +void TrackableObjectBase::RegisterDestructionCallback( + const base::Closure& closure) { + atom::AtomBrowserMainParts::Get()->RegisterDestructionCallback(closure); } } // namespace mate diff --git a/atom/browser/api/trackable_object.h b/atom/browser/api/trackable_object.h index 656904cc45d..8ff7d1c0404 100644 --- a/atom/browser/api/trackable_object.h +++ b/atom/browser/api/trackable_object.h @@ -9,7 +9,9 @@ #include "atom/browser/api/event_emitter.h" #include "atom/common/id_weak_map.h" +#include "base/bind.h" #include "base/memory/scoped_ptr.h" +#include "base/memory/weak_ptr.h" namespace base { class SupportsUserData; @@ -28,6 +30,9 @@ class TrackableObjectBase : public mate::EventEmitter { // Wrap TrackableObject into a class that SupportsUserData. void AttachAsUserData(base::SupportsUserData* wrapped); + // Subclasses should implement this to destroy their native types. + virtual void Destroy() = 0; + protected: ~TrackableObjectBase() override; @@ -39,12 +44,14 @@ class TrackableObjectBase : public mate::EventEmitter { // Register a callback that should be destroyed before JavaScript environment // gets destroyed. - static void RegisterDestructionCallback(void (*callback)()); + static void RegisterDestructionCallback(const base::Closure& closure); int32_t weak_map_id_; base::SupportsUserData* wrapped_; private: + base::WeakPtrFactory weak_factory_; + DISALLOW_COPY_AND_ASSIGN(TrackableObjectBase); }; @@ -85,7 +92,8 @@ class TrackableObject : public TrackableObjectBase { } TrackableObject() { - RegisterDestructionCallback(&TrackableObject::ReleaseAllWeakReferences); + RegisterDestructionCallback( + base::Bind(&TrackableObject::ReleaseAllWeakReferences)); } // Removes this instance from the weak map. diff --git a/vendor/brightray b/vendor/brightray index 251521cb8c5..8d64120b51b 160000 --- a/vendor/brightray +++ b/vendor/brightray @@ -1 +1 @@ -Subproject commit 251521cb8c51670dbd08ab9fd2dd45e249cbb596 +Subproject commit 8d64120b51b48be46eaa419957b965c0ccfc6c8f From 512f89910df7352f6709578e8f6a143041cf6f9f Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sun, 6 Sep 2015 11:07:38 +0800 Subject: [PATCH 25/27] docs: No more extra-plugin-dirs --- docs/api/browser-window.md | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/docs/api/browser-window.md b/docs/api/browser-window.md index 3e19b5bfabf..d74e999379b 100644 --- a/docs/api/browser-window.md +++ b/docs/api/browser-window.md @@ -99,13 +99,7 @@ Properties `width` and `height` are required. * `text-areas-are-resizable` Boolean * `webgl` Boolean * `webaudio` Boolean - * `plugins` Boolean - Whether plugins should be enabled, currently only - `NPAPI` plugins are supported. - * `extra-plugin-dirs` Array - Array of paths that would be searched for - plugins. Note that if you want to add a directory under your app, you - should use `__dirname` or `process.resourcesPath` to join the paths to - make them absolute, using relative paths would make Electron search - under current working directory. + * `plugins` Boolean - Whether plugins should be enabled. * `experimental-features` Boolean * `experimental-canvas-features` Boolean * `subpixel-font-scaling` Boolean From 342e0c6cf716d6009eca0ba4da303acf6d18b59f Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sun, 6 Sep 2015 11:13:41 +0800 Subject: [PATCH 26/27] Remove dead code --- atom/browser/native_window.h | 7 ------- 1 file changed, 7 deletions(-) diff --git a/atom/browser/native_window.h b/atom/browser/native_window.h index a10eda912e5..b89e2b58e6e 100644 --- a/atom/browser/native_window.h +++ b/atom/browser/native_window.h @@ -24,10 +24,6 @@ class SkRegion; -namespace base { -class CommandLine; -} - namespace brightray { class InspectableWebContents; } @@ -187,9 +183,6 @@ class NativeWindow : public content::WebContentsObserver, content::WebContents*, const content::NativeWebKeyboardEvent& event) {} - // Called when renderer process is going to be started. - void AppendExtraCommandLineSwitches(base::CommandLine* command_line); - // Public API used by platform-dependent delegates and observers to send UI // related notifications. void NotifyWindowClosed(); From 4537d88a580f5768b7c64c6b96d4a99a60c99f74 Mon Sep 17 00:00:00 2001 From: Dick Choi Date: Sun, 6 Sep 2015 12:36:27 +0900 Subject: [PATCH 27/27] fix typo Code block should be ended `` --- docs-translations/ko/api/content-tracing.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs-translations/ko/api/content-tracing.md b/docs-translations/ko/api/content-tracing.md index f6010d156f6..6c8133823a9 100644 --- a/docs-translations/ko/api/content-tracing.md +++ b/docs-translations/ko/api/content-tracing.md @@ -15,7 +15,7 @@ contentTracing.startRecording('*', contentTracing.DEFAULT_OPTIONS, function() { }); }, 5000); }); -`` +``` ## Methods