refactor: rename the atom directory to shell

This commit is contained in:
Samuel Attard 2019-06-19 13:43:10 -07:00 committed by Samuel Attard
parent 4575a4aae3
commit d7f07e8a80
631 changed files with 0 additions and 0 deletions

View file

@ -0,0 +1,203 @@
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include <string>
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/node_bindings.h"
#include "atom/common/node_includes.h"
#include "atom/common/promise_util.h"
#include "base/task/post_task.h"
#include "base/values.h"
#include "content/public/renderer/render_frame.h"
#include "electron/atom/common/api/api.mojom.h"
#include "native_mate/arguments.h"
#include "native_mate/dictionary.h"
#include "native_mate/handle.h"
#include "native_mate/object_template_builder.h"
#include "native_mate/wrappable.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "third_party/blink/public/web/web_local_frame.h"
using blink::WebLocalFrame;
using content::RenderFrame;
namespace {
RenderFrame* GetCurrentRenderFrame() {
WebLocalFrame* frame = WebLocalFrame::FrameForCurrentContext();
if (!frame)
return nullptr;
return RenderFrame::FromWebFrame(frame);
}
class IPCRenderer : public mate::Wrappable<IPCRenderer> {
public:
explicit IPCRenderer(v8::Isolate* isolate)
: task_runner_(base::CreateSingleThreadTaskRunnerWithTraits({})) {
Init(isolate);
RenderFrame* render_frame = GetCurrentRenderFrame();
DCHECK(render_frame);
// Bind the interface on the background runner. All accesses will be via
// the thread-safe pointer. This is to support our "fake-sync"
// MessageSync() hack; see the comment in IPCRenderer::SendSync.
atom::mojom::ElectronBrowserPtrInfo info;
render_frame->GetRemoteInterfaces()->GetInterface(mojo::MakeRequest(&info));
electron_browser_ptr_ = atom::mojom::ThreadSafeElectronBrowserPtr::Create(
std::move(info), task_runner_);
}
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "IPCRenderer"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.SetMethod("send", &IPCRenderer::Send)
.SetMethod("sendSync", &IPCRenderer::SendSync)
.SetMethod("sendTo", &IPCRenderer::SendTo)
.SetMethod("sendToHost", &IPCRenderer::SendToHost)
.SetMethod("invoke", &IPCRenderer::Invoke);
}
static mate::Handle<IPCRenderer> Create(v8::Isolate* isolate) {
return mate::CreateHandle(isolate, new IPCRenderer(isolate));
}
void Send(bool internal,
const std::string& channel,
const base::ListValue& arguments) {
electron_browser_ptr_->get()->Message(internal, channel, arguments.Clone());
}
v8::Local<v8::Promise> Invoke(mate::Arguments* args,
const std::string& channel,
const base::Value& arguments) {
atom::util::Promise p(args->isolate());
auto handle = p.GetHandle();
electron_browser_ptr_->get()->Invoke(
channel, arguments.Clone(),
base::BindOnce([](atom::util::Promise p,
base::Value result) { p.Resolve(result); },
std::move(p)));
return handle;
}
void SendTo(bool internal,
bool send_to_all,
int32_t web_contents_id,
const std::string& channel,
const base::ListValue& arguments) {
electron_browser_ptr_->get()->MessageTo(
internal, send_to_all, web_contents_id, channel, arguments.Clone());
}
void SendToHost(const std::string& channel,
const base::ListValue& arguments) {
electron_browser_ptr_->get()->MessageHost(channel, arguments.Clone());
}
base::Value SendSync(bool internal,
const std::string& channel,
const base::ListValue& arguments) {
// We aren't using a true synchronous mojo call here. We're calling an
// asynchronous method and blocking on the result. The reason we're doing
// this is a little complicated, so buckle up.
//
// Mojo has a concept of synchronous calls. However, synchronous calls are
// dangerous. In particular, it's quite possible for two processes to call
// synchronous methods on each other and cause a deadlock. Mojo has a
// mechanism to avoid this kind of deadlock: if a process is waiting on the
// result of a synchronous call, and it receives an incoming call for a
// synchronous method, it will process that request immediately, even
// though it's currently blocking. However, if it receives an incoming
// request for an _asynchronous_ method, that can't cause a deadlock, so it
// stashes the request on a queue to be processed once the synchronous
// thing it's waiting on returns.
//
// This behavior is useful for preventing deadlocks, but it is inconvenient
// here because it can result in messages being reordered. If the main
// process is awaiting the result of a synchronous call (which it does only
// very rarely, since it's bad to block the main process), and we send
// first an asynchronous message to the main process, followed by a
// synchronous message, then the main process will process the synchronous
// one first.
//
// It turns out, Electron has some dependency on message ordering,
// especially during window shutdown, and getting messages out of order can
// result in, for example, remote objects disappearing unexpectedly. To
// avoid these issues and guarantee consistent message ordering, we send
// all messages to the main process as asynchronous messages. This causes
// them to always be queued and processed in the same order they were
// received, even if they were received while the main process was waiting
// on a synchronous call.
//
// However, in the calling process, we still need to block on the result,
// because the caller is expecting a result synchronously. So we do a bit
// of a trick: we pass the Mojo handle over to a worker thread, send the
// asynchronous message from that thread, and then block on the result.
// It's important that we pass the handle over to the worker thread,
// because that allows Mojo to process incoming messages (most importantly,
// the response to our request) on that thread. If we didn't pass it to a
// worker thread, and instead sent the call from the main thread, we would
// never receive a response because Mojo wouldn't be able to run its
// message handling code, because the main thread would be tied up blocking
// on the WaitableEvent.
//
// Phew. If you got this far, here's a gold star: ⭐️
base::Value result;
// A task is posted to a worker thread to execute the request so that
// this thread may block on a waitable event. It is safe to pass raw
// pointers to |result| and |response_received_event| as this stack frame
// will survive until the request is complete.
base::WaitableEvent response_received_event;
task_runner_->PostTask(
FROM_HERE, base::BindOnce(&IPCRenderer::SendMessageSyncOnWorkerThread,
base::Unretained(this),
base::Unretained(&response_received_event),
base::Unretained(&result), internal, channel,
arguments.Clone()));
response_received_event.Wait();
return result;
}
private:
void SendMessageSyncOnWorkerThread(base::WaitableEvent* event,
base::Value* result,
bool internal,
const std::string& channel,
base::Value arguments) {
electron_browser_ptr_->get()->MessageSync(
internal, channel, std::move(arguments),
base::BindOnce(&IPCRenderer::ReturnSyncResponseToMainThread,
base::Unretained(event), base::Unretained(result)));
}
static void ReturnSyncResponseToMainThread(base::WaitableEvent* event,
base::Value* result,
base::Value response) {
*result = std::move(response);
event->Signal();
}
scoped_refptr<base::SequencedTaskRunner> task_runner_;
scoped_refptr<atom::mojom::ThreadSafeElectronBrowserPtr>
electron_browser_ptr_;
};
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
mate::Dictionary dict(context->GetIsolate(), exports);
dict.Set("ipc", IPCRenderer::Create(context->GetIsolate()));
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_renderer_ipc, Initialize)

View file

@ -0,0 +1,275 @@
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/renderer/api/atom_api_spell_check_client.h"
#include <map>
#include <set>
#include <unordered_set>
#include <utility>
#include <vector>
#include "atom/common/native_mate_converters/string16_converter.h"
#include "base/logging.h"
#include "base/numerics/safe_conversions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "components/spellcheck/renderer/spellcheck_worditerator.h"
#include "native_mate/converter.h"
#include "native_mate/dictionary.h"
#include "native_mate/function_template.h"
#include "third_party/blink/public/web/web_text_checking_completion.h"
#include "third_party/blink/public/web/web_text_checking_result.h"
#include "third_party/icu/source/common/unicode/uscript.h"
namespace atom {
namespace api {
namespace {
bool HasWordCharacters(const base::string16& text, int index) {
const base::char16* data = text.data();
int length = text.length();
while (index < length) {
uint32_t code = 0;
U16_NEXT(data, index, length, code);
UErrorCode error = U_ZERO_ERROR;
if (uscript_getScript(code, &error) != USCRIPT_COMMON)
return true;
}
return false;
}
struct Word {
blink::WebTextCheckingResult result;
base::string16 text;
std::vector<base::string16> contraction_words;
};
} // namespace
class SpellCheckClient::SpellcheckRequest {
public:
SpellcheckRequest(
const base::string16& text,
std::unique_ptr<blink::WebTextCheckingCompletion> completion)
: text_(text), completion_(std::move(completion)) {}
~SpellcheckRequest() {}
const base::string16& text() const { return text_; }
blink::WebTextCheckingCompletion* completion() { return completion_.get(); }
std::vector<Word>& wordlist() { return word_list_; }
private:
base::string16 text_; // Text to be checked in this task.
std::vector<Word> word_list_; // List of Words found in text
// The interface to send the misspelled ranges to WebKit.
std::unique_ptr<blink::WebTextCheckingCompletion> completion_;
DISALLOW_COPY_AND_ASSIGN(SpellcheckRequest);
};
SpellCheckClient::SpellCheckClient(const std::string& language,
v8::Isolate* isolate,
v8::Local<v8::Object> provider)
: pending_request_param_(nullptr),
isolate_(isolate),
context_(isolate, isolate->GetCurrentContext()),
provider_(isolate, provider) {
DCHECK(!context_.IsEmpty());
character_attributes_.SetDefaultLanguage(language);
// Persistent the method.
mate::Dictionary dict(isolate, provider);
dict.Get("spellCheck", &spell_check_);
}
SpellCheckClient::~SpellCheckClient() {
context_.Reset();
}
void SpellCheckClient::RequestCheckingOfText(
const blink::WebString& textToCheck,
std::unique_ptr<blink::WebTextCheckingCompletion> completionCallback) {
base::string16 text(textToCheck.Utf16());
// Ignore invalid requests.
if (text.empty() || !HasWordCharacters(text, 0)) {
completionCallback->DidCancelCheckingText();
return;
}
// Clean up the previous request before starting a new request.
if (pending_request_param_) {
pending_request_param_->completion()->DidCancelCheckingText();
}
pending_request_param_.reset(
new SpellcheckRequest(text, std::move(completionCallback)));
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(&SpellCheckClient::SpellCheckText, AsWeakPtr()));
}
bool SpellCheckClient::IsSpellCheckingEnabled() const {
return true;
}
void SpellCheckClient::ShowSpellingUI(bool show) {}
bool SpellCheckClient::IsShowingSpellingUI() {
return false;
}
void SpellCheckClient::UpdateSpellingUIWithMisspelledWord(
const blink::WebString& word) {}
void SpellCheckClient::SpellCheckText() {
const auto& text = pending_request_param_->text();
if (text.empty() || spell_check_.IsEmpty()) {
pending_request_param_->completion()->DidCancelCheckingText();
pending_request_param_ = nullptr;
return;
}
if (!text_iterator_.IsInitialized() &&
!text_iterator_.Initialize(&character_attributes_, true)) {
// We failed to initialize text_iterator_, return as spelled correctly.
VLOG(1) << "Failed to initialize SpellcheckWordIterator";
return;
}
if (!contraction_iterator_.IsInitialized() &&
!contraction_iterator_.Initialize(&character_attributes_, false)) {
// We failed to initialize the word iterator, return as spelled correctly.
VLOG(1) << "Failed to initialize contraction_iterator_";
return;
}
text_iterator_.SetText(text.c_str(), text.size());
SpellCheckScope scope(*this);
base::string16 word;
size_t word_start;
size_t word_length;
std::set<base::string16> words;
auto& word_list = pending_request_param_->wordlist();
Word word_entry;
for (;;) { // Run until end of text
const auto status =
text_iterator_.GetNextWord(&word, &word_start, &word_length);
if (status == SpellcheckWordIterator::IS_END_OF_TEXT)
break;
if (status == SpellcheckWordIterator::IS_SKIPPABLE)
continue;
word_entry.result.location = base::checked_cast<int>(word_start);
word_entry.result.length = base::checked_cast<int>(word_length);
word_entry.text = word;
word_entry.contraction_words.clear();
word_list.push_back(word_entry);
words.insert(word);
// If the given word is a concatenated word of two or more valid words
// (e.g. "hello:hello"), we should treat it as a valid word.
if (IsContraction(scope, word, &word_entry.contraction_words)) {
for (const auto& w : word_entry.contraction_words) {
words.insert(w);
}
}
}
// Send out all the words data to the spellchecker to check
SpellCheckWords(scope, words);
}
void SpellCheckClient::OnSpellCheckDone(
const std::vector<base::string16>& misspelled_words) {
std::vector<blink::WebTextCheckingResult> results;
std::unordered_set<base::string16> misspelled(misspelled_words.begin(),
misspelled_words.end());
auto& word_list = pending_request_param_->wordlist();
for (const auto& word : word_list) {
if (misspelled.find(word.text) != misspelled.end()) {
// If this is a contraction, iterate through parts and accept the word
// if none of them are misspelled
if (!word.contraction_words.empty()) {
auto all_correct = true;
for (const auto& contraction_word : word.contraction_words) {
if (misspelled.find(contraction_word) != misspelled.end()) {
all_correct = false;
break;
}
}
if (all_correct)
continue;
}
results.push_back(word.result);
}
}
pending_request_param_->completion()->DidFinishCheckingText(results);
pending_request_param_ = nullptr;
}
void SpellCheckClient::SpellCheckWords(const SpellCheckScope& scope,
const std::set<base::string16>& words) {
DCHECK(!scope.spell_check_.IsEmpty());
v8::Local<v8::FunctionTemplate> templ = mate::CreateFunctionTemplate(
isolate_,
base::BindRepeating(&SpellCheckClient::OnSpellCheckDone, AsWeakPtr()));
auto context = isolate_->GetCurrentContext();
v8::Local<v8::Value> args[] = {mate::ConvertToV8(isolate_, words),
templ->GetFunction(context).ToLocalChecked()};
// Call javascript with the words and the callback function
scope.spell_check_->Call(context, scope.provider_, 2, args).IsEmpty();
}
// Returns whether or not the given string is a contraction.
// This function is a fall-back when the SpellcheckWordIterator class
// returns a concatenated word which is not in the selected dictionary
// (e.g. "in'n'out") but each word is valid.
// Output variable contraction_words will contain individual
// words in the contraction.
bool SpellCheckClient::IsContraction(
const SpellCheckScope& scope,
const base::string16& contraction,
std::vector<base::string16>* contraction_words) {
DCHECK(contraction_iterator_.IsInitialized());
contraction_iterator_.SetText(contraction.c_str(), contraction.length());
base::string16 word;
size_t word_start;
size_t word_length;
for (auto status =
contraction_iterator_.GetNextWord(&word, &word_start, &word_length);
status != SpellcheckWordIterator::IS_END_OF_TEXT;
status = contraction_iterator_.GetNextWord(&word, &word_start,
&word_length)) {
if (status == SpellcheckWordIterator::IS_SKIPPABLE)
continue;
contraction_words->push_back(word);
}
return contraction_words->size() > 1;
}
SpellCheckClient::SpellCheckScope::SpellCheckScope(
const SpellCheckClient& client)
: handle_scope_(client.isolate_),
context_scope_(
v8::Local<v8::Context>::New(client.isolate_, client.context_)),
provider_(client.provider_.NewHandle()),
spell_check_(client.spell_check_.NewHandle()) {}
SpellCheckClient::SpellCheckScope::~SpellCheckScope() = default;
} // namespace api
} // namespace atom

View file

@ -0,0 +1,114 @@
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_RENDERER_API_ATOM_API_SPELL_CHECK_CLIENT_H_
#define ATOM_RENDERER_API_ATOM_API_SPELL_CHECK_CLIENT_H_
#include <memory>
#include <set>
#include <string>
#include <vector>
#include "base/callback.h"
#include "base/memory/weak_ptr.h"
#include "components/spellcheck/renderer/spellcheck_worditerator.h"
#include "native_mate/scoped_persistent.h"
#include "third_party/blink/public/platform/web_spell_check_panel_host_client.h"
#include "third_party/blink/public/platform/web_vector.h"
#include "third_party/blink/public/web/web_text_check_client.h"
namespace blink {
struct WebTextCheckingResult;
class WebTextCheckingCompletion;
} // namespace blink
namespace atom {
namespace api {
class SpellCheckClient : public blink::WebSpellCheckPanelHostClient,
public blink::WebTextCheckClient,
public base::SupportsWeakPtr<SpellCheckClient> {
public:
SpellCheckClient(const std::string& language,
v8::Isolate* isolate,
v8::Local<v8::Object> provider);
~SpellCheckClient() override;
private:
class SpellcheckRequest;
// blink::WebTextCheckClient:
void RequestCheckingOfText(const blink::WebString& textToCheck,
std::unique_ptr<blink::WebTextCheckingCompletion>
completionCallback) override;
bool IsSpellCheckingEnabled() const override;
// blink::WebSpellCheckPanelHostClient:
void ShowSpellingUI(bool show) override;
bool IsShowingSpellingUI() override;
void UpdateSpellingUIWithMisspelledWord(
const blink::WebString& word) override;
struct SpellCheckScope {
v8::HandleScope handle_scope_;
v8::Context::Scope context_scope_;
v8::Local<v8::Object> provider_;
v8::Local<v8::Function> spell_check_;
explicit SpellCheckScope(const SpellCheckClient& client);
~SpellCheckScope();
};
// Run through the word iterator and send out requests
// to the JS API for checking spellings of words in the current
// request.
void SpellCheckText();
// Call JavaScript to check spelling a word.
// The javascript function will callback OnSpellCheckDone
// with the results of all the misspelled words.
void SpellCheckWords(const SpellCheckScope& scope,
const std::set<base::string16>& words);
// Returns whether or not the given word is a contraction of valid words
// (e.g. "word:word").
// Output variable contraction_words will contain individual
// words in the contraction.
bool IsContraction(const SpellCheckScope& scope,
const base::string16& word,
std::vector<base::string16>* contraction_words);
// Callback for the JS API which returns the list of misspelled words.
void OnSpellCheckDone(const std::vector<base::string16>& misspelled_words);
// Represents character attributes used for filtering out characters which
// are not supported by this SpellCheck object.
SpellcheckCharAttribute character_attributes_;
// Represents word iterators used in this spellchecker. The |text_iterator_|
// splits text provided by WebKit into words, contractions, or concatenated
// words. The |contraction_iterator_| splits a concatenated word extracted by
// |text_iterator_| into word components so we can treat a concatenated word
// consisting only of correct words as a correct word.
SpellcheckWordIterator text_iterator_;
SpellcheckWordIterator contraction_iterator_;
// The parameters of a pending background-spellchecking request.
// (When WebKit sends two or more requests, we cancel the previous
// requests so we do not have to use vectors.)
std::unique_ptr<SpellcheckRequest> pending_request_param_;
v8::Isolate* isolate_;
v8::Persistent<v8::Context> context_;
mate::ScopedPersistent<v8::Object> provider_;
mate::ScopedPersistent<v8::Function> spell_check_;
DISALLOW_COPY_AND_ASSIGN(SpellCheckClient);
};
} // namespace api
} // namespace atom
#endif // ATOM_RENDERER_API_ATOM_API_SPELL_CHECK_CLIENT_H_

View file

@ -0,0 +1,580 @@
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "atom/common/api/api.mojom.h"
#include "atom/common/api/event_emitter_caller.h"
#include "atom/common/native_mate_converters/blink_converter.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/gfx_converter.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/node_includes.h"
#include "atom/common/promise_util.h"
#include "atom/renderer/api/atom_api_spell_check_client.h"
#include "base/memory/memory_pressure_listener.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_frame_observer.h"
#include "content/public/renderer/render_frame_visitor.h"
#include "content/public/renderer/render_view.h"
#include "native_mate/dictionary.h"
#include "native_mate/object_template_builder.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "third_party/blink/public/platform/web_cache.h"
#include "third_party/blink/public/platform/web_isolated_world_info.h"
#include "third_party/blink/public/web/web_custom_element.h"
#include "third_party/blink/public/web/web_document.h"
#include "third_party/blink/public/web/web_element.h"
#include "third_party/blink/public/web/web_frame_widget.h"
#include "third_party/blink/public/web/web_ime_text_span.h"
#include "third_party/blink/public/web/web_input_method_controller.h"
#include "third_party/blink/public/web/web_local_frame.h"
#include "third_party/blink/public/web/web_script_execution_callback.h"
#include "third_party/blink/public/web/web_script_source.h"
#include "third_party/blink/public/web/web_view.h"
#include "url/url_util.h"
namespace mate {
template <>
struct Converter<blink::WebLocalFrame::ScriptExecutionType> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
blink::WebLocalFrame::ScriptExecutionType* out) {
std::string execution_type;
if (!ConvertFromV8(isolate, val, &execution_type))
return false;
if (execution_type == "asynchronous") {
*out = blink::WebLocalFrame::kAsynchronous;
} else if (execution_type == "asynchronousBlockingOnload") {
*out = blink::WebLocalFrame::kAsynchronousBlockingOnload;
} else if (execution_type == "synchronous") {
*out = blink::WebLocalFrame::kSynchronous;
} else {
return false;
}
return true;
}
};
} // namespace mate
namespace atom {
namespace api {
namespace {
content::RenderFrame* GetRenderFrame(v8::Local<v8::Value> value) {
v8::Local<v8::Context> context =
v8::Local<v8::Object>::Cast(value)->CreationContext();
if (context.IsEmpty())
return nullptr;
blink::WebLocalFrame* frame = blink::WebLocalFrame::FrameForContext(context);
if (!frame)
return nullptr;
return content::RenderFrame::FromWebFrame(frame);
}
class RenderFrameStatus : public content::RenderFrameObserver {
public:
explicit RenderFrameStatus(content::RenderFrame* render_frame)
: content::RenderFrameObserver(render_frame) {}
~RenderFrameStatus() final {}
bool is_ok() { return render_frame() != nullptr; }
// RenderFrameObserver implementation.
void OnDestruct() final {}
};
class ScriptExecutionCallback : public blink::WebScriptExecutionCallback {
public:
explicit ScriptExecutionCallback(atom::util::Promise promise)
: promise_(std::move(promise)) {}
~ScriptExecutionCallback() override {}
void Completed(
const blink::WebVector<v8::Local<v8::Value>>& result) override {
if (!result.empty()) {
if (!result[0].IsEmpty()) {
// Right now only single results per frame is supported.
promise_.Resolve(result[0]);
} else {
promise_.RejectWithErrorMessage(
"Script failed to execute, this normally means an error "
"was thrown. Check the renderer console for the error.");
}
} else {
promise_.RejectWithErrorMessage(
"WebFrame was removed before script could run. This normally means "
"the underlying frame was destroyed");
}
delete this;
}
private:
atom::util::Promise promise_;
DISALLOW_COPY_AND_ASSIGN(ScriptExecutionCallback);
};
class FrameSetSpellChecker : public content::RenderFrameVisitor {
public:
FrameSetSpellChecker(SpellCheckClient* spell_check_client,
content::RenderFrame* main_frame)
: spell_check_client_(spell_check_client), main_frame_(main_frame) {
content::RenderFrame::ForEach(this);
main_frame->GetWebFrame()->SetSpellCheckPanelHostClient(spell_check_client);
}
bool Visit(content::RenderFrame* render_frame) override {
auto* view = render_frame->GetRenderView();
if (view->GetMainRenderFrame() == main_frame_ ||
(render_frame->IsMainFrame() && render_frame == main_frame_)) {
render_frame->GetWebFrame()->SetTextCheckClient(spell_check_client_);
}
return true;
}
private:
SpellCheckClient* spell_check_client_;
content::RenderFrame* main_frame_;
DISALLOW_COPY_AND_ASSIGN(FrameSetSpellChecker);
};
class SpellCheckerHolder : public content::RenderFrameObserver {
public:
// Find existing holder for the |render_frame|.
static SpellCheckerHolder* FromRenderFrame(
content::RenderFrame* render_frame) {
for (auto* holder : instances_) {
if (holder->render_frame() == render_frame)
return holder;
}
return nullptr;
}
SpellCheckerHolder(content::RenderFrame* render_frame,
std::unique_ptr<SpellCheckClient> spell_check_client)
: content::RenderFrameObserver(render_frame),
spell_check_client_(std::move(spell_check_client)) {
DCHECK(!FromRenderFrame(render_frame));
instances_.insert(this);
}
~SpellCheckerHolder() final { instances_.erase(this); }
void UnsetAndDestroy() {
FrameSetSpellChecker set_spell_checker(nullptr, render_frame());
delete this;
}
// RenderFrameObserver implementation.
void OnDestruct() final {
// Since we delete this in WillReleaseScriptContext, this method is unlikely
// to be called, but override anyway since I'm not sure if there are some
// corner cases.
//
// Note that while there are two "delete this", it is totally fine as the
// observer unsubscribes automatically in destructor and the other one won't
// be called.
//
// Also note that we should not call UnsetAndDestroy here, as the render
// frame is going to be destroyed.
delete this;
}
void WillReleaseScriptContext(v8::Local<v8::Context> context,
int world_id) final {
// Unset spell checker when the script context is going to be released, as
// the spell check implementation lives there.
UnsetAndDestroy();
}
private:
static std::set<SpellCheckerHolder*> instances_;
std::unique_ptr<SpellCheckClient> spell_check_client_;
};
} // namespace
// static
std::set<SpellCheckerHolder*> SpellCheckerHolder::instances_;
void SetName(v8::Local<v8::Value> window, const std::string& name) {
GetRenderFrame(window)->GetWebFrame()->SetName(
blink::WebString::FromUTF8(name));
}
void SetZoomLevel(v8::Local<v8::Value> window, double level) {
content::RenderFrame* render_frame = GetRenderFrame(window);
mojom::ElectronBrowserPtr browser_ptr;
render_frame->GetRemoteInterfaces()->GetInterface(
mojo::MakeRequest(&browser_ptr));
browser_ptr->SetTemporaryZoomLevel(level);
}
double GetZoomLevel(v8::Local<v8::Value> window) {
double result = 0.0;
content::RenderFrame* render_frame = GetRenderFrame(window);
mojom::ElectronBrowserPtr browser_ptr;
render_frame->GetRemoteInterfaces()->GetInterface(
mojo::MakeRequest(&browser_ptr));
browser_ptr->DoGetZoomLevel(&result);
return result;
}
void SetZoomFactor(v8::Local<v8::Value> window, double factor) {
SetZoomLevel(window, blink::WebView::ZoomFactorToZoomLevel(factor));
}
double GetZoomFactor(v8::Local<v8::Value> window) {
return blink::WebView::ZoomLevelToZoomFactor(GetZoomLevel(window));
}
void SetVisualZoomLevelLimits(v8::Local<v8::Value> window,
double min_level,
double max_level) {
blink::WebFrame* web_frame = GetRenderFrame(window)->GetWebFrame();
web_frame->View()->SetDefaultPageScaleLimits(min_level, max_level);
web_frame->View()->SetIgnoreViewportTagScaleLimits(true);
}
void SetLayoutZoomLevelLimits(v8::Local<v8::Value> window,
double min_level,
double max_level) {
blink::WebFrame* web_frame = GetRenderFrame(window)->GetWebFrame();
web_frame->View()->ZoomLimitsChanged(min_level, max_level);
}
void AllowGuestViewElementDefinition(v8::Isolate* isolate,
v8::Local<v8::Value> window,
v8::Local<v8::Object> context,
v8::Local<v8::Function> register_cb) {
v8::HandleScope handle_scope(isolate);
v8::Context::Scope context_scope(context->CreationContext());
blink::WebCustomElement::EmbedderNamesAllowedScope embedder_names_scope;
GetRenderFrame(context)->GetWebFrame()->RequestExecuteV8Function(
context->CreationContext(), register_cb, v8::Null(isolate), 0, nullptr,
nullptr);
}
int GetWebFrameId(v8::Local<v8::Value> window,
v8::Local<v8::Value> content_window) {
// Get the WebLocalFrame before (possibly) executing any user-space JS while
// getting the |params|. We track the status of the RenderFrame via an
// observer in case it is deleted during user code execution.
content::RenderFrame* render_frame = GetRenderFrame(content_window);
RenderFrameStatus render_frame_status(render_frame);
if (!render_frame_status.is_ok())
return -1;
blink::WebLocalFrame* frame = render_frame->GetWebFrame();
// Parent must exist.
blink::WebFrame* parent_frame = frame->Parent();
DCHECK(parent_frame);
DCHECK(parent_frame->IsWebLocalFrame());
return render_frame->GetRoutingID();
}
void SetSpellCheckProvider(mate::Arguments* args,
v8::Local<v8::Value> window,
const std::string& language,
v8::Local<v8::Object> provider) {
auto context = args->isolate()->GetCurrentContext();
if (!provider->Has(context, mate::StringToV8(args->isolate(), "spellCheck"))
.ToChecked()) {
args->ThrowError("\"spellCheck\" has to be defined");
return;
}
// Remove the old client.
content::RenderFrame* render_frame = GetRenderFrame(window);
auto* existing = SpellCheckerHolder::FromRenderFrame(render_frame);
if (existing)
existing->UnsetAndDestroy();
// Set spellchecker for all live frames in the same process or
// in the sandbox mode for all live sub frames to this WebFrame.
auto spell_check_client =
std::make_unique<SpellCheckClient>(language, args->isolate(), provider);
FrameSetSpellChecker spell_checker(spell_check_client.get(), render_frame);
// Attach the spell checker to RenderFrame.
new SpellCheckerHolder(render_frame, std::move(spell_check_client));
}
void InsertText(v8::Local<v8::Value> window, const std::string& text) {
blink::WebFrame* web_frame = GetRenderFrame(window)->GetWebFrame();
if (web_frame->IsWebLocalFrame()) {
web_frame->ToWebLocalFrame()
->FrameWidget()
->GetActiveWebInputMethodController()
->CommitText(blink::WebString::FromUTF8(text),
blink::WebVector<blink::WebImeTextSpan>(),
blink::WebRange(), 0);
}
}
base::string16 InsertCSS(v8::Local<v8::Value> window, const std::string& css) {
blink::WebFrame* web_frame = GetRenderFrame(window)->GetWebFrame();
if (web_frame->IsWebLocalFrame()) {
return web_frame->ToWebLocalFrame()
->GetDocument()
.InsertStyleSheet(blink::WebString::FromUTF8(css))
.Utf16();
}
return base::string16();
}
void RemoveInsertedCSS(v8::Local<v8::Value> window, const base::string16& key) {
blink::WebFrame* web_frame = GetRenderFrame(window)->GetWebFrame();
if (web_frame->IsWebLocalFrame()) {
web_frame->ToWebLocalFrame()->GetDocument().RemoveInsertedStyleSheet(
blink::WebString::FromUTF16(key));
}
}
v8::Local<v8::Promise> ExecuteJavaScript(mate::Arguments* args,
v8::Local<v8::Value> window,
const base::string16& code) {
v8::Isolate* isolate = args->isolate();
util::Promise promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
bool has_user_gesture = false;
args->GetNext(&has_user_gesture);
GetRenderFrame(window)->GetWebFrame()->RequestExecuteScriptAndReturnValue(
blink::WebScriptSource(blink::WebString::FromUTF16(code)),
has_user_gesture, new ScriptExecutionCallback(std::move(promise)));
return handle;
}
v8::Local<v8::Promise> ExecuteJavaScriptInIsolatedWorld(
mate::Arguments* args,
v8::Local<v8::Value> window,
int world_id,
const std::vector<mate::Dictionary>& scripts) {
v8::Isolate* isolate = args->isolate();
util::Promise promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
std::vector<blink::WebScriptSource> sources;
for (const auto& script : scripts) {
base::string16 code;
base::string16 url;
int start_line = 1;
script.Get("url", &url);
script.Get("startLine", &start_line);
if (!script.Get("code", &code)) {
promise.RejectWithErrorMessage("Invalid 'code'");
return handle;
}
sources.emplace_back(
blink::WebScriptSource(blink::WebString::FromUTF16(code),
blink::WebURL(GURL(url)), start_line));
}
bool has_user_gesture = false;
args->GetNext(&has_user_gesture);
blink::WebLocalFrame::ScriptExecutionType scriptExecutionType =
blink::WebLocalFrame::kSynchronous;
args->GetNext(&scriptExecutionType);
// Debugging tip: if you see a crash stack trace beginning from this call,
// then it is very likely that some exception happened when executing the
// "content_script/init.js" script.
GetRenderFrame(window)->GetWebFrame()->RequestExecuteScriptInIsolatedWorld(
world_id, &sources.front(), sources.size(), has_user_gesture,
scriptExecutionType, new ScriptExecutionCallback(std::move(promise)));
return handle;
}
void SetIsolatedWorldInfo(v8::Local<v8::Value> window,
int world_id,
const mate::Dictionary& options,
mate::Arguments* args) {
std::string origin_url, security_policy, name;
options.Get("securityOrigin", &origin_url);
options.Get("csp", &security_policy);
options.Get("name", &name);
if (!security_policy.empty() && origin_url.empty()) {
args->ThrowError(
"If csp is specified, securityOrigin should also be specified");
return;
}
blink::WebIsolatedWorldInfo info;
info.security_origin = blink::WebSecurityOrigin::CreateFromString(
blink::WebString::FromUTF8(origin_url));
info.content_security_policy = blink::WebString::FromUTF8(security_policy);
info.human_readable_name = blink::WebString::FromUTF8(name);
GetRenderFrame(window)->GetWebFrame()->SetIsolatedWorldInfo(world_id, info);
}
blink::WebCache::ResourceTypeStats GetResourceUsage(v8::Isolate* isolate) {
blink::WebCache::ResourceTypeStats stats;
blink::WebCache::GetResourceTypeStats(&stats);
return stats;
}
void ClearCache(v8::Isolate* isolate) {
isolate->IdleNotificationDeadline(0.5);
blink::WebCache::Clear();
base::MemoryPressureListener::NotifyMemoryPressure(
base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL);
}
v8::Local<v8::Value> FindFrameByRoutingId(v8::Isolate* isolate,
v8::Local<v8::Value> window,
int routing_id) {
content::RenderFrame* render_frame =
content::RenderFrame::FromRoutingID(routing_id);
if (render_frame)
return render_frame->GetWebFrame()->MainWorldScriptContext()->Global();
else
return v8::Null(isolate);
}
v8::Local<v8::Value> GetOpener(v8::Isolate* isolate,
v8::Local<v8::Value> window) {
blink::WebFrame* frame = GetRenderFrame(window)->GetWebFrame()->Opener();
if (frame && frame->IsWebLocalFrame())
return frame->ToWebLocalFrame()->MainWorldScriptContext()->Global();
else
return v8::Null(isolate);
}
// Don't name it as GetParent, Windows has API with same name.
v8::Local<v8::Value> GetFrameParent(v8::Isolate* isolate,
v8::Local<v8::Value> window) {
blink::WebFrame* frame = GetRenderFrame(window)->GetWebFrame()->Parent();
if (frame && frame->IsWebLocalFrame())
return frame->ToWebLocalFrame()->MainWorldScriptContext()->Global();
else
return v8::Null(isolate);
}
v8::Local<v8::Value> GetTop(v8::Isolate* isolate, v8::Local<v8::Value> window) {
blink::WebFrame* frame = GetRenderFrame(window)->GetWebFrame()->Top();
if (frame && frame->IsWebLocalFrame())
return frame->ToWebLocalFrame()->MainWorldScriptContext()->Global();
else
return v8::Null(isolate);
}
v8::Local<v8::Value> GetFirstChild(v8::Isolate* isolate,
v8::Local<v8::Value> window) {
blink::WebFrame* frame = GetRenderFrame(window)->GetWebFrame()->FirstChild();
if (frame && frame->IsWebLocalFrame())
return frame->ToWebLocalFrame()->MainWorldScriptContext()->Global();
else
return v8::Null(isolate);
}
v8::Local<v8::Value> GetNextSibling(v8::Isolate* isolate,
v8::Local<v8::Value> window) {
blink::WebFrame* frame = GetRenderFrame(window)->GetWebFrame()->NextSibling();
if (frame && frame->IsWebLocalFrame())
return frame->ToWebLocalFrame()->MainWorldScriptContext()->Global();
else
return v8::Null(isolate);
}
v8::Local<v8::Value> GetFrameForSelector(v8::Isolate* isolate,
v8::Local<v8::Value> window,
const std::string& selector) {
blink::WebElement element =
GetRenderFrame(window)->GetWebFrame()->GetDocument().QuerySelector(
blink::WebString::FromUTF8(selector));
if (element.IsNull()) // not found
return v8::Null(isolate);
blink::WebFrame* frame = blink::WebFrame::FromFrameOwnerElement(element);
if (frame && frame->IsWebLocalFrame())
return frame->ToWebLocalFrame()->MainWorldScriptContext()->Global();
else
return v8::Null(isolate);
}
v8::Local<v8::Value> FindFrameByName(v8::Isolate* isolate,
v8::Local<v8::Value> window,
const std::string& name) {
blink::WebFrame* frame =
GetRenderFrame(window)->GetWebFrame()->FindFrameByName(
blink::WebString::FromUTF8(name));
if (frame && frame->IsWebLocalFrame())
return frame->ToWebLocalFrame()->MainWorldScriptContext()->Global();
else
return v8::Null(isolate);
}
int GetRoutingId(v8::Local<v8::Value> window) {
return GetRenderFrame(window)->GetRoutingID();
}
} // namespace api
} // namespace atom
namespace {
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
using namespace atom::api; // NOLINT(build/namespaces)
v8::Isolate* isolate = context->GetIsolate();
mate::Dictionary dict(isolate, exports);
dict.SetMethod("setName", &SetName);
dict.SetMethod("setZoomLevel", &SetZoomLevel);
dict.SetMethod("getZoomLevel", &GetZoomLevel);
dict.SetMethod("setZoomFactor", &SetZoomFactor);
dict.SetMethod("getZoomFactor", &GetZoomFactor);
dict.SetMethod("setVisualZoomLevelLimits", &SetVisualZoomLevelLimits);
dict.SetMethod("setLayoutZoomLevelLimits", &SetLayoutZoomLevelLimits);
dict.SetMethod("allowGuestViewElementDefinition",
&AllowGuestViewElementDefinition);
dict.SetMethod("getWebFrameId", &GetWebFrameId);
dict.SetMethod("setSpellCheckProvider", &SetSpellCheckProvider);
dict.SetMethod("insertText", &InsertText);
dict.SetMethod("insertCSS", &InsertCSS);
dict.SetMethod("removeInsertedCSS", &RemoveInsertedCSS);
dict.SetMethod("executeJavaScript", &ExecuteJavaScript);
dict.SetMethod("executeJavaScriptInIsolatedWorld",
&ExecuteJavaScriptInIsolatedWorld);
dict.SetMethod("setIsolatedWorldInfo", &SetIsolatedWorldInfo);
dict.SetMethod("getResourceUsage", &GetResourceUsage);
dict.SetMethod("clearCache", &ClearCache);
dict.SetMethod("_findFrameByRoutingId", &FindFrameByRoutingId);
dict.SetMethod("_getFrameForSelector", &GetFrameForSelector);
dict.SetMethod("_findFrameByName", &FindFrameByName);
dict.SetMethod("_getOpener", &GetOpener);
dict.SetMethod("_getParent", &GetFrameParent);
dict.SetMethod("_getTop", &GetTop);
dict.SetMethod("_getFirstChild", &GetFirstChild);
dict.SetMethod("_getNextSibling", &GetNextSibling);
dict.SetMethod("_getRoutingId", &GetRoutingId);
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_renderer_web_frame, Initialize)

View file

@ -0,0 +1,230 @@
// Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/renderer/atom_autofill_agent.h"
#include <utility>
#include <vector>
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_view.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "third_party/blink/public/platform/web_keyboard_event.h"
#include "third_party/blink/public/platform/web_string.h"
#include "third_party/blink/public/web/web_document.h"
#include "third_party/blink/public/web/web_local_frame.h"
#include "third_party/blink/public/web/web_option_element.h"
#include "third_party/blink/public/web/web_user_gesture_indicator.h"
#include "ui/events/keycodes/keyboard_codes.h"
#include "ui/gfx/geometry/rect_f.h"
namespace atom {
namespace {
const size_t kMaxDataLength = 1024;
const size_t kMaxListSize = 512;
void GetDataListSuggestions(const blink::WebInputElement& element,
std::vector<base::string16>* values,
std::vector<base::string16>* labels) {
for (const auto& option : element.FilteredDataListOptions()) {
values->push_back(option.Value().Utf16());
if (option.Value() != option.Label())
labels->push_back(option.Label().Utf16());
else
labels->push_back(base::string16());
}
}
void TrimStringVectorForIPC(std::vector<base::string16>* strings) {
// Limit the size of the vector.
if (strings->size() > kMaxListSize)
strings->resize(kMaxListSize);
// Limit the size of the strings in the vector.
for (size_t i = 0; i < strings->size(); ++i) {
if ((*strings)[i].length() > kMaxDataLength)
(*strings)[i].resize(kMaxDataLength);
}
}
} // namespace
AutofillAgent::AutofillAgent(content::RenderFrame* frame,
blink::AssociatedInterfaceRegistry* registry)
: content::RenderFrameObserver(frame),
binding_(this),
weak_ptr_factory_(this) {
render_frame()->GetWebFrame()->SetAutofillClient(this);
registry->AddInterface(
base::Bind(&AutofillAgent::BindRequest, base::Unretained(this)));
}
AutofillAgent::~AutofillAgent() = default;
void AutofillAgent::BindRequest(
mojom::ElectronAutofillAgentAssociatedRequest request) {
binding_.Bind(std::move(request));
}
void AutofillAgent::OnDestruct() {
delete this;
}
void AutofillAgent::DidChangeScrollOffset() {
HidePopup();
}
void AutofillAgent::FocusedElementChanged(const blink::WebElement&) {
focused_node_was_last_clicked_ = false;
was_focused_before_now_ = false;
HidePopup();
}
void AutofillAgent::TextFieldDidEndEditing(const blink::WebInputElement&) {
HidePopup();
}
void AutofillAgent::TextFieldDidChange(
const blink::WebFormControlElement& element) {
if (!IsUserGesture() && !render_frame()->IsPasting())
return;
weak_ptr_factory_.InvalidateWeakPtrs();
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(&AutofillAgent::TextFieldDidChangeImpl,
weak_ptr_factory_.GetWeakPtr(), element));
}
void AutofillAgent::TextFieldDidChangeImpl(
const blink::WebFormControlElement& element) {
ShowSuggestionsOptions options;
options.requires_caret_at_end = true;
ShowSuggestions(element, options);
}
void AutofillAgent::TextFieldDidReceiveKeyDown(
const blink::WebInputElement& element,
const blink::WebKeyboardEvent& event) {
if (event.windows_key_code == ui::VKEY_DOWN ||
event.windows_key_code == ui::VKEY_UP) {
ShowSuggestionsOptions options;
options.autofill_on_empty_values = true;
options.requires_caret_at_end = true;
ShowSuggestions(element, options);
}
}
void AutofillAgent::OpenTextDataListChooser(
const blink::WebInputElement& element) {
ShowSuggestionsOptions options;
options.autofill_on_empty_values = true;
ShowSuggestions(element, options);
}
void AutofillAgent::DataListOptionsChanged(
const blink::WebInputElement& element) {
if (!element.Focused())
return;
ShowSuggestionsOptions options;
options.requires_caret_at_end = true;
ShowSuggestions(element, options);
}
AutofillAgent::ShowSuggestionsOptions::ShowSuggestionsOptions()
: autofill_on_empty_values(false), requires_caret_at_end(false) {}
void AutofillAgent::ShowSuggestions(const blink::WebFormControlElement& element,
const ShowSuggestionsOptions& options) {
if (!element.IsEnabled() || element.IsReadOnly())
return;
const blink::WebInputElement* input_element = ToWebInputElement(&element);
if (input_element) {
if (!input_element->IsTextField())
return;
}
blink::WebString value = element.EditingValue();
if (value.length() > kMaxDataLength ||
(!options.autofill_on_empty_values && value.IsEmpty()) ||
(options.requires_caret_at_end &&
(element.SelectionStart() != element.SelectionEnd() ||
element.SelectionEnd() != static_cast<int>(value.length())))) {
HidePopup();
return;
}
std::vector<base::string16> data_list_values;
std::vector<base::string16> data_list_labels;
if (input_element) {
GetDataListSuggestions(*input_element, &data_list_values,
&data_list_labels);
TrimStringVectorForIPC(&data_list_values);
TrimStringVectorForIPC(&data_list_labels);
}
ShowPopup(element, data_list_values, data_list_labels);
}
void AutofillAgent::DidReceiveLeftMouseDownOrGestureTapInNode(
const blink::WebNode& node) {
focused_node_was_last_clicked_ = !node.IsNull() && node.Focused();
}
void AutofillAgent::DidCompleteFocusChangeInFrame() {
DoFocusChangeComplete();
}
bool AutofillAgent::IsUserGesture() const {
return blink::WebUserGestureIndicator::IsProcessingUserGesture(
render_frame()->GetWebFrame());
}
void AutofillAgent::HidePopup() {
GetElectronBrowser()->HideAutofillPopup();
}
void AutofillAgent::ShowPopup(const blink::WebFormControlElement& element,
const std::vector<base::string16>& values,
const std::vector<base::string16>& labels) {
gfx::RectF bounds =
render_frame()->GetRenderView()->ElementBoundsInWindow(element);
GetElectronBrowser()->ShowAutofillPopup(bounds, values, labels);
}
void AutofillAgent::AcceptDataListSuggestion(const base::string16& suggestion) {
auto element = render_frame()->GetWebFrame()->GetDocument().FocusedElement();
if (element.IsFormControlElement()) {
ToWebInputElement(&element)->SetAutofillValue(
blink::WebString::FromUTF16(suggestion));
}
}
void AutofillAgent::DoFocusChangeComplete() {
auto element = render_frame()->GetWebFrame()->GetDocument().FocusedElement();
if (element.IsNull() || !element.IsFormControlElement())
return;
if (focused_node_was_last_clicked_ && was_focused_before_now_) {
ShowSuggestionsOptions options;
options.autofill_on_empty_values = true;
auto* input_element = ToWebInputElement(&element);
if (input_element)
ShowSuggestions(*input_element, options);
}
was_focused_before_now_ = true;
focused_node_was_last_clicked_ = false;
}
const mojom::ElectronBrowserPtr& AutofillAgent::GetElectronBrowser() {
if (!browser_ptr_) {
render_frame()->GetRemoteInterfaces()->GetInterface(
mojo::MakeRequest(&browser_ptr_));
}
return browser_ptr_;
}
} // namespace atom

View file

@ -0,0 +1,90 @@
// Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_RENDERER_ATOM_AUTOFILL_AGENT_H_
#define ATOM_RENDERER_ATOM_AUTOFILL_AGENT_H_
#include <vector>
#include "atom/common/api/api.mojom.h"
#include "base/memory/weak_ptr.h"
#include "content/public/renderer/render_frame_observer.h"
#include "mojo/public/cpp/bindings/associated_binding.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h"
#include "third_party/blink/public/web/web_autofill_client.h"
#include "third_party/blink/public/web/web_element.h"
#include "third_party/blink/public/web/web_form_control_element.h"
#include "third_party/blink/public/web/web_input_element.h"
namespace atom {
class AutofillAgent : public content::RenderFrameObserver,
public blink::WebAutofillClient,
public mojom::ElectronAutofillAgent {
public:
explicit AutofillAgent(content::RenderFrame* frame,
blink::AssociatedInterfaceRegistry* registry);
~AutofillAgent() override;
void BindRequest(mojom::ElectronAutofillAgentAssociatedRequest request);
// content::RenderFrameObserver:
void OnDestruct() override;
void DidChangeScrollOffset() override;
void FocusedElementChanged(const blink::WebElement&) override;
void DidCompleteFocusChangeInFrame() override;
void DidReceiveLeftMouseDownOrGestureTapInNode(
const blink::WebNode&) override;
private:
struct ShowSuggestionsOptions {
ShowSuggestionsOptions();
bool autofill_on_empty_values;
bool requires_caret_at_end;
};
// blink::WebAutofillClient:
void TextFieldDidEndEditing(const blink::WebInputElement&) override;
void TextFieldDidChange(const blink::WebFormControlElement&) override;
void TextFieldDidChangeImpl(const blink::WebFormControlElement&);
void TextFieldDidReceiveKeyDown(const blink::WebInputElement&,
const blink::WebKeyboardEvent&) override;
void OpenTextDataListChooser(const blink::WebInputElement&) override;
void DataListOptionsChanged(const blink::WebInputElement&) override;
// mojom::ElectronAutofillAgent
void AcceptDataListSuggestion(const base::string16& suggestion) override;
bool IsUserGesture() const;
void HidePopup();
void ShowPopup(const blink::WebFormControlElement&,
const std::vector<base::string16>&,
const std::vector<base::string16>&);
void ShowSuggestions(const blink::WebFormControlElement& element,
const ShowSuggestionsOptions& options);
void DoFocusChangeComplete();
const mojom::ElectronBrowserPtr& GetElectronBrowser();
mojom::ElectronBrowserPtr browser_ptr_;
// True when the last click was on the focused node.
bool focused_node_was_last_clicked_ = false;
// This is set to false when the focus changes, then set back to true soon
// afterwards. This helps track whether an event happened after a node was
// already focused, or if it caused the focus to change.
bool was_focused_before_now_ = false;
mojo::AssociatedBinding<mojom::ElectronAutofillAgent> binding_;
base::WeakPtrFactory<AutofillAgent> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(AutofillAgent);
};
} // namespace atom
#endif // ATOM_RENDERER_ATOM_AUTOFILL_AGENT_H_

View file

@ -0,0 +1,159 @@
// Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/renderer/atom_render_frame_observer.h"
#include <string>
#include <utility>
#include <vector>
#include "atom/common/api/event_emitter_caller.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/node_includes.h"
#include "atom/common/options_switches.h"
#include "base/command_line.h"
#include "base/strings/string_number_conversions.h"
#include "base/trace_event/trace_event.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_view.h"
#include "electron/atom/common/api/api.mojom.h"
#include "ipc/ipc_message_macros.h"
#include "native_mate/dictionary.h"
#include "net/base/net_module.h"
#include "net/grit/net_resources.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "third_party/blink/public/platform/web_isolated_world_info.h"
#include "third_party/blink/public/web/blink.h"
#include "third_party/blink/public/web/web_document.h"
#include "third_party/blink/public/web/web_draggable_region.h"
#include "third_party/blink/public/web/web_element.h"
#include "third_party/blink/public/web/web_local_frame.h"
#include "third_party/blink/public/web/web_script_source.h"
#include "ui/base/resource/resource_bundle.h"
namespace atom {
namespace {
base::StringPiece NetResourceProvider(int key) {
if (key == IDR_DIR_HEADER_HTML) {
base::StringPiece html_data =
ui::ResourceBundle::GetSharedInstance().GetRawDataResource(
IDR_DIR_HEADER_HTML);
return html_data;
}
return base::StringPiece();
}
} // namespace
AtomRenderFrameObserver::AtomRenderFrameObserver(
content::RenderFrame* frame,
RendererClientBase* renderer_client)
: content::RenderFrameObserver(frame),
render_frame_(frame),
renderer_client_(renderer_client) {
// Initialise resource for directory listing.
net::NetModule::SetResourceProvider(NetResourceProvider);
}
void AtomRenderFrameObserver::DidClearWindowObject() {
renderer_client_->DidClearWindowObject(render_frame_);
}
void AtomRenderFrameObserver::DidCreateScriptContext(
v8::Handle<v8::Context> context,
int world_id) {
if (ShouldNotifyClient(world_id))
renderer_client_->DidCreateScriptContext(context, render_frame_);
bool use_context_isolation = renderer_client_->isolated_world();
bool is_main_world = IsMainWorld(world_id);
bool is_main_frame = render_frame_->IsMainFrame();
bool is_not_opened = !render_frame_->GetWebFrame()->Opener();
bool allow_node_in_sub_frames =
base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kNodeIntegrationInSubFrames);
bool should_create_isolated_context =
use_context_isolation && is_main_world &&
(is_main_frame || allow_node_in_sub_frames) && is_not_opened;
if (should_create_isolated_context) {
CreateIsolatedWorldContext();
renderer_client_->SetupMainWorldOverrides(context, render_frame_);
}
if (world_id >= World::ISOLATED_WORLD_EXTENSIONS &&
world_id <= World::ISOLATED_WORLD_EXTENSIONS_END) {
renderer_client_->SetupExtensionWorldOverrides(context, render_frame_,
world_id);
}
}
void AtomRenderFrameObserver::DraggableRegionsChanged() {
blink::WebVector<blink::WebDraggableRegion> webregions =
render_frame_->GetWebFrame()->GetDocument().DraggableRegions();
std::vector<mojom::DraggableRegionPtr> regions;
for (auto& webregion : webregions) {
auto region = mojom::DraggableRegion::New();
render_frame_->GetRenderView()->ConvertViewportToWindowViaWidget(
&webregion.bounds);
region->bounds = webregion.bounds;
region->draggable = webregion.draggable;
regions.push_back(std::move(region));
}
mojom::ElectronBrowserPtr browser_ptr;
render_frame_->GetRemoteInterfaces()->GetInterface(
mojo::MakeRequest(&browser_ptr));
browser_ptr->UpdateDraggableRegions(std::move(regions));
}
void AtomRenderFrameObserver::WillReleaseScriptContext(
v8::Local<v8::Context> context,
int world_id) {
if (ShouldNotifyClient(world_id))
renderer_client_->WillReleaseScriptContext(context, render_frame_);
}
void AtomRenderFrameObserver::OnDestruct() {
delete this;
}
void AtomRenderFrameObserver::CreateIsolatedWorldContext() {
auto* frame = render_frame_->GetWebFrame();
blink::WebIsolatedWorldInfo info;
// This maps to the name shown in the context combo box in the Console tab
// of the dev tools.
info.human_readable_name =
blink::WebString::FromUTF8("Electron Isolated Context");
// Setup document's origin policy in isolated world
info.security_origin = frame->GetDocument().GetSecurityOrigin();
frame->SetIsolatedWorldInfo(World::ISOLATED_WORLD, info);
// Create initial script context in isolated world
blink::WebScriptSource source("void 0");
frame->ExecuteScriptInIsolatedWorld(World::ISOLATED_WORLD, source);
}
bool AtomRenderFrameObserver::IsMainWorld(int world_id) {
return world_id == World::MAIN_WORLD;
}
bool AtomRenderFrameObserver::IsIsolatedWorld(int world_id) {
return world_id == World::ISOLATED_WORLD;
}
bool AtomRenderFrameObserver::ShouldNotifyClient(int world_id) {
bool allow_node_in_sub_frames =
base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kNodeIntegrationInSubFrames);
if (renderer_client_->isolated_world() &&
(render_frame_->IsMainFrame() || allow_node_in_sub_frames))
return IsIsolatedWorld(world_id);
else
return IsMainWorld(world_id);
}
} // namespace atom

View file

@ -0,0 +1,71 @@
// Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_RENDERER_ATOM_RENDER_FRAME_OBSERVER_H_
#define ATOM_RENDERER_ATOM_RENDER_FRAME_OBSERVER_H_
#include <string>
#include "atom/renderer/renderer_client_base.h"
#include "base/strings/string16.h"
#include "content/public/renderer/render_frame_observer.h"
#include "ipc/ipc_platform_file.h"
#include "third_party/blink/public/platform/web_isolated_world_ids.h"
#include "third_party/blink/public/web/web_local_frame.h"
namespace base {
class ListValue;
}
namespace atom {
enum World {
MAIN_WORLD = 0,
// Use a high number far away from 0 to not collide with any other world
// IDs created internally by Chrome.
ISOLATED_WORLD = 999,
// Numbers for isolated worlds for extensions are set in
// lib/renderer/content-script-injector.ts, and are greater than or equal to
// this number, up to ISOLATED_WORLD_EXTENSIONS_END.
ISOLATED_WORLD_EXTENSIONS = 1 << 20,
// Last valid isolated world ID.
ISOLATED_WORLD_EXTENSIONS_END =
blink::IsolatedWorldId::kEmbedderWorldIdLimit - 1
};
// Helper class to forward the messages to the client.
class AtomRenderFrameObserver : public content::RenderFrameObserver {
public:
AtomRenderFrameObserver(content::RenderFrame* frame,
RendererClientBase* renderer_client);
// content::RenderFrameObserver:
void DidClearWindowObject() override;
void DidCreateScriptContext(v8::Handle<v8::Context> context,
int world_id) override;
void DraggableRegionsChanged() override;
void WillReleaseScriptContext(v8::Local<v8::Context> context,
int world_id) override;
void OnDestruct() override;
private:
bool ShouldNotifyClient(int world_id);
void CreateIsolatedWorldContext();
bool IsMainWorld(int world_id);
bool IsIsolatedWorld(int world_id);
void OnTakeHeapSnapshot(IPC::PlatformFileForTransit file_handle,
const std::string& channel);
content::RenderFrame* render_frame_;
RendererClientBase* renderer_client_;
DISALLOW_COPY_AND_ASSIGN(AtomRenderFrameObserver);
};
} // namespace atom
#endif // ATOM_RENDERER_ATOM_RENDER_FRAME_OBSERVER_H_

View file

@ -0,0 +1,248 @@
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/renderer/atom_renderer_client.h"
#include <string>
#include <vector>
#include "atom/common/api/electron_bindings.h"
#include "atom/common/api/event_emitter_caller.h"
#include "atom/common/asar/asar_util.h"
#include "atom/common/node_bindings.h"
#include "atom/common/node_includes.h"
#include "atom/common/options_switches.h"
#include "atom/renderer/atom_render_frame_observer.h"
#include "atom/renderer/web_worker_observer.h"
#include "base/command_line.h"
#include "content/public/renderer/render_frame.h"
#include "native_mate/dictionary.h"
#include "third_party/blink/public/web/web_document.h"
#include "third_party/blink/public/web/web_local_frame.h"
#include "third_party/electron_node/src/node_native_module.h"
namespace atom {
namespace {
bool IsDevToolsExtension(content::RenderFrame* render_frame) {
return static_cast<GURL>(render_frame->GetWebFrame()->GetDocument().Url())
.SchemeIs("chrome-extension");
}
} // namespace
AtomRendererClient::AtomRendererClient()
: node_bindings_(
NodeBindings::Create(NodeBindings::BrowserEnvironment::RENDERER)),
electron_bindings_(new ElectronBindings(uv_default_loop())) {}
AtomRendererClient::~AtomRendererClient() {
asar::ClearArchives();
}
void AtomRendererClient::RenderFrameCreated(
content::RenderFrame* render_frame) {
new AtomRenderFrameObserver(render_frame, this);
RendererClientBase::RenderFrameCreated(render_frame);
}
void AtomRendererClient::RunScriptsAtDocumentStart(
content::RenderFrame* render_frame) {
// Inform the document start pharse.
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
node::Environment* env = GetEnvironment(render_frame);
if (env)
mate::EmitEvent(env->isolate(), env->process_object(), "document-start");
}
void AtomRendererClient::RunScriptsAtDocumentEnd(
content::RenderFrame* render_frame) {
// Inform the document end pharse.
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
node::Environment* env = GetEnvironment(render_frame);
if (env)
mate::EmitEvent(env->isolate(), env->process_object(), "document-end");
}
void AtomRendererClient::DidCreateScriptContext(
v8::Handle<v8::Context> context,
content::RenderFrame* render_frame) {
RendererClientBase::DidCreateScriptContext(context, render_frame);
// TODO(zcbenz): Do not create Node environment if node integration is not
// enabled.
// Do not load node if we're aren't a main frame or a devtools extension
// unless node support has been explicitly enabled for sub frames
bool is_main_frame =
render_frame->IsMainFrame() && !render_frame->GetWebFrame()->Opener();
bool is_devtools = IsDevToolsExtension(render_frame);
bool allow_node_in_subframes =
base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kNodeIntegrationInSubFrames);
bool should_load_node =
is_main_frame || is_devtools || allow_node_in_subframes;
if (!should_load_node) {
return;
}
injected_frames_.insert(render_frame);
// If this is the first environment we are creating, prepare the node
// bindings.
if (!node_integration_initialized_) {
node_integration_initialized_ = true;
node_bindings_->Initialize();
node_bindings_->PrepareMessageLoop();
}
// Setup node tracing controller.
if (!node::tracing::TraceEventHelper::GetAgent())
node::tracing::TraceEventHelper::SetAgent(node::CreateAgent());
// Setup node environment for each window.
node::Environment* env = node_bindings_->CreateEnvironment(context);
auto* command_line = base::CommandLine::ForCurrentProcess();
// If we have disabled the site instance overrides we should prevent loading
// any non-context aware native module
if (command_line->HasSwitch(switches::kDisableElectronSiteInstanceOverrides))
env->ForceOnlyContextAwareNativeModules();
env->WarnNonContextAwareNativeModules();
environments_.insert(env);
// Add Electron extended APIs.
electron_bindings_->BindTo(env->isolate(), env->process_object());
AddRenderBindings(env->isolate(), env->process_object());
mate::Dictionary process_dict(env->isolate(), env->process_object());
process_dict.SetReadOnly("isMainFrame", render_frame->IsMainFrame());
// Load everything.
node_bindings_->LoadEnvironment(env);
if (node_bindings_->uv_env() == nullptr) {
// Make uv loop being wrapped by window context.
node_bindings_->set_uv_env(env);
// Give the node loop a run to make sure everything is ready.
node_bindings_->RunMessageLoop();
}
}
void AtomRendererClient::WillReleaseScriptContext(
v8::Handle<v8::Context> context,
content::RenderFrame* render_frame) {
if (injected_frames_.find(render_frame) == injected_frames_.end())
return;
injected_frames_.erase(render_frame);
node::Environment* env = node::Environment::GetCurrent(context);
if (environments_.find(env) == environments_.end())
return;
environments_.erase(env);
mate::EmitEvent(env->isolate(), env->process_object(), "exit");
// The main frame may be replaced.
if (env == node_bindings_->uv_env())
node_bindings_->set_uv_env(nullptr);
// Destroy the node environment. We only do this if node support has been
// enabled for sub-frames to avoid a change-of-behavior / introduce crashes
// for existing users.
// We also do this if we have disable electron site instance overrides to
// avoid memory leaks
auto* command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kNodeIntegrationInSubFrames) ||
command_line->HasSwitch(switches::kDisableElectronSiteInstanceOverrides))
node::FreeEnvironment(env);
// ElectronBindings is tracking node environments.
electron_bindings_->EnvironmentDestroyed(env);
}
bool AtomRendererClient::ShouldFork(blink::WebLocalFrame* frame,
const GURL& url,
const std::string& http_method,
bool is_initial_navigation,
bool is_server_redirect) {
// Handle all the navigations and reloads in browser.
// FIXME We only support GET here because http method will be ignored when
// the OpenURLFromTab is triggered, which means form posting would not work,
// we should solve this by patching Chromium in future.
return http_method == "GET";
}
void AtomRendererClient::DidInitializeWorkerContextOnWorkerThread(
v8::Local<v8::Context> context) {
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kNodeIntegrationInWorker)) {
WebWorkerObserver::GetCurrent()->ContextCreated(context);
}
}
void AtomRendererClient::WillDestroyWorkerContextOnWorkerThread(
v8::Local<v8::Context> context) {
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kNodeIntegrationInWorker)) {
WebWorkerObserver::GetCurrent()->ContextWillDestroy(context);
}
}
void AtomRendererClient::SetupMainWorldOverrides(
v8::Handle<v8::Context> context,
content::RenderFrame* render_frame) {
// Setup window overrides in the main world context
// Wrap the bundle into a function that receives the isolatedWorld as
// an argument.
auto* isolate = context->GetIsolate();
std::vector<v8::Local<v8::String>> isolated_bundle_params = {
node::FIXED_ONE_BYTE_STRING(isolate, "nodeProcess"),
node::FIXED_ONE_BYTE_STRING(isolate, "isolatedWorld")};
std::vector<v8::Local<v8::Value>> isolated_bundle_args = {
GetEnvironment(render_frame)->process_object(),
GetContext(render_frame->GetWebFrame(), isolate)->Global()};
node::per_process::native_module_loader.CompileAndCall(
context, "electron/js2c/isolated_bundle", &isolated_bundle_params,
&isolated_bundle_args, nullptr);
}
void AtomRendererClient::SetupExtensionWorldOverrides(
v8::Handle<v8::Context> context,
content::RenderFrame* render_frame,
int world_id) {
auto* isolate = context->GetIsolate();
std::vector<v8::Local<v8::String>> isolated_bundle_params = {
node::FIXED_ONE_BYTE_STRING(isolate, "nodeProcess"),
node::FIXED_ONE_BYTE_STRING(isolate, "isolatedWorld"),
node::FIXED_ONE_BYTE_STRING(isolate, "worldId")};
std::vector<v8::Local<v8::Value>> isolated_bundle_args = {
GetEnvironment(render_frame)->process_object(),
GetContext(render_frame->GetWebFrame(), isolate)->Global(),
v8::Integer::New(isolate, world_id)};
node::per_process::native_module_loader.CompileAndCall(
context, "electron/js2c/content_script_bundle", &isolated_bundle_params,
&isolated_bundle_args, nullptr);
}
node::Environment* AtomRendererClient::GetEnvironment(
content::RenderFrame* render_frame) const {
if (injected_frames_.find(render_frame) == injected_frames_.end())
return nullptr;
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
auto context =
GetContext(render_frame->GetWebFrame(), v8::Isolate::GetCurrent());
node::Environment* env = node::Environment::GetCurrent(context);
if (environments_.find(env) == environments_.end())
return nullptr;
return env;
}
} // namespace atom

View file

@ -0,0 +1,78 @@
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_RENDERER_ATOM_RENDERER_CLIENT_H_
#define ATOM_RENDERER_ATOM_RENDERER_CLIENT_H_
#include <memory>
#include <set>
#include <string>
#include <vector>
#include "atom/renderer/renderer_client_base.h"
namespace node {
class Environment;
} // namespace node
namespace atom {
class ElectronBindings;
class NodeBindings;
class AtomRendererClient : public RendererClientBase {
public:
AtomRendererClient();
~AtomRendererClient() override;
// atom::RendererClientBase:
void DidCreateScriptContext(v8::Handle<v8::Context> context,
content::RenderFrame* render_frame) override;
void WillReleaseScriptContext(v8::Handle<v8::Context> context,
content::RenderFrame* render_frame) override;
void SetupMainWorldOverrides(v8::Handle<v8::Context> context,
content::RenderFrame* render_frame) override;
void SetupExtensionWorldOverrides(v8::Handle<v8::Context> context,
content::RenderFrame* render_frame,
int world_id) override;
private:
// content::ContentRendererClient:
void RenderFrameCreated(content::RenderFrame*) override;
void RunScriptsAtDocumentStart(content::RenderFrame* render_frame) override;
void RunScriptsAtDocumentEnd(content::RenderFrame* render_frame) override;
bool ShouldFork(blink::WebLocalFrame* frame,
const GURL& url,
const std::string& http_method,
bool is_initial_navigation,
bool is_server_redirect) override;
void DidInitializeWorkerContextOnWorkerThread(
v8::Local<v8::Context> context) override;
void WillDestroyWorkerContextOnWorkerThread(
v8::Local<v8::Context> context) override;
node::Environment* GetEnvironment(content::RenderFrame* frame) const;
// Whether the node integration has been initialized.
bool node_integration_initialized_ = false;
std::unique_ptr<NodeBindings> node_bindings_;
std::unique_ptr<ElectronBindings> electron_bindings_;
// The node::Environment::GetCurrent API does not return nullptr when it
// is called for a context without node::Environment, so we have to keep
// a book of the environments created.
std::set<node::Environment*> environments_;
// Getting main script context from web frame would lazily initializes
// its script context. Doing so in a web page without scripts would trigger
// assertion, so we have to keep a book of injected web frames.
std::set<content::RenderFrame*> injected_frames_;
DISALLOW_COPY_AND_ASSIGN(AtomRendererClient);
};
} // namespace atom
#endif // ATOM_RENDERER_ATOM_RENDERER_CLIENT_H_

View file

@ -0,0 +1,299 @@
// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/renderer/atom_sandboxed_renderer_client.h"
#include "atom/common/api/electron_bindings.h"
#include "atom/common/application_info.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/node_bindings.h"
#include "atom/common/node_includes.h"
#include "atom/common/options_switches.h"
#include "atom/renderer/atom_render_frame_observer.h"
#include "base/base_paths.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/path_service.h"
#include "base/process/process_handle.h"
#include "content/public/renderer/render_frame.h"
#include "gin/converter.h"
#include "native_mate/dictionary.h"
#include "third_party/blink/public/web/blink.h"
#include "third_party/blink/public/web/web_document.h"
#include "third_party/electron_node/src/node_binding.h"
#include "third_party/electron_node/src/node_native_module.h"
namespace atom {
namespace {
const char kLifecycleKey[] = "lifecycle";
const char kModuleCacheKey[] = "native-module-cache";
bool IsDevTools(content::RenderFrame* render_frame) {
return render_frame->GetWebFrame()->GetDocument().Url().ProtocolIs(
"devtools");
}
bool IsDevToolsExtension(content::RenderFrame* render_frame) {
return render_frame->GetWebFrame()->GetDocument().Url().ProtocolIs(
"chrome-extension");
}
v8::Local<v8::Object> GetModuleCache(v8::Isolate* isolate) {
auto context = isolate->GetCurrentContext();
mate::Dictionary global(isolate, context->Global());
v8::Local<v8::Value> cache;
if (!global.GetHidden(kModuleCacheKey, &cache)) {
cache = v8::Object::New(isolate);
global.SetHidden(kModuleCacheKey, cache);
}
return cache->ToObject(context).ToLocalChecked();
}
// adapted from node.cc
v8::Local<v8::Value> GetBinding(v8::Isolate* isolate,
v8::Local<v8::String> key,
mate::Arguments* margs) {
v8::Local<v8::Object> exports;
std::string module_key = gin::V8ToString(isolate, key);
mate::Dictionary cache(isolate, GetModuleCache(isolate));
if (cache.Get(module_key.c_str(), &exports)) {
return exports;
}
auto* mod = node::binding::get_linked_module(module_key.c_str());
if (!mod) {
char errmsg[1024];
snprintf(errmsg, sizeof(errmsg), "No such module: %s", module_key.c_str());
margs->ThrowError(errmsg);
return exports;
}
exports = v8::Object::New(isolate);
DCHECK_EQ(mod->nm_register_func, nullptr);
DCHECK_NE(mod->nm_context_register_func, nullptr);
mod->nm_context_register_func(exports, v8::Null(isolate),
isolate->GetCurrentContext(), mod->nm_priv);
cache.Set(module_key.c_str(), exports);
return exports;
}
v8::Local<v8::Value> CreatePreloadScript(v8::Isolate* isolate,
v8::Local<v8::String> preloadSrc) {
return RendererClientBase::RunScript(isolate->GetCurrentContext(),
preloadSrc);
}
void InvokeHiddenCallback(v8::Handle<v8::Context> context,
const std::string& hidden_key,
const std::string& callback_name) {
auto* isolate = context->GetIsolate();
auto binding_key = mate::ConvertToV8(isolate, hidden_key)
->ToString(context)
.ToLocalChecked();
auto private_binding_key = v8::Private::ForApi(isolate, binding_key);
auto global_object = context->Global();
v8::Local<v8::Value> value;
if (!global_object->GetPrivate(context, private_binding_key).ToLocal(&value))
return;
if (value.IsEmpty() || !value->IsObject())
return;
auto binding = value->ToObject(context).ToLocalChecked();
auto callback_key = mate::ConvertToV8(isolate, callback_name)
->ToString(context)
.ToLocalChecked();
auto callback_value = binding->Get(context, callback_key).ToLocalChecked();
DCHECK(callback_value->IsFunction()); // set by sandboxed_renderer/init.js
auto callback = v8::Handle<v8::Function>::Cast(callback_value);
ignore_result(callback->Call(context, binding, 0, nullptr));
}
} // namespace
AtomSandboxedRendererClient::AtomSandboxedRendererClient() {
// Explicitly register electron's builtin modules.
NodeBindings::RegisterBuiltinModules();
metrics_ = base::ProcessMetrics::CreateCurrentProcessMetrics();
}
AtomSandboxedRendererClient::~AtomSandboxedRendererClient() {}
void AtomSandboxedRendererClient::InitializeBindings(
v8::Local<v8::Object> binding,
v8::Local<v8::Context> context,
bool is_main_frame) {
auto* isolate = context->GetIsolate();
mate::Dictionary b(isolate, binding);
b.SetMethod("get", GetBinding);
b.SetMethod("createPreloadScript", CreatePreloadScript);
mate::Dictionary process = mate::Dictionary::CreateEmpty(isolate);
b.Set("process", process);
ElectronBindings::BindProcess(isolate, &process, metrics_.get());
process.Set("argv", base::CommandLine::ForCurrentProcess()->argv());
process.SetReadOnly("pid", base::GetCurrentProcId());
process.SetReadOnly("sandboxed", true);
process.SetReadOnly("type", "renderer");
process.SetReadOnly("isMainFrame", is_main_frame);
// Pass in CLI flags needed to setup the renderer
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kGuestInstanceID))
b.Set(options::kGuestInstanceID,
command_line->GetSwitchValueASCII(switches::kGuestInstanceID));
}
void AtomSandboxedRendererClient::RenderFrameCreated(
content::RenderFrame* render_frame) {
new AtomRenderFrameObserver(render_frame, this);
RendererClientBase::RenderFrameCreated(render_frame);
}
void AtomSandboxedRendererClient::RenderViewCreated(
content::RenderView* render_view) {
RendererClientBase::RenderViewCreated(render_view);
}
void AtomSandboxedRendererClient::RunScriptsAtDocumentStart(
content::RenderFrame* render_frame) {
if (injected_frames_.find(render_frame) == injected_frames_.end())
return;
auto* isolate = blink::MainThreadIsolate();
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Context> context =
GetContext(render_frame->GetWebFrame(), isolate);
v8::Context::Scope context_scope(context);
InvokeHiddenCallback(context, kLifecycleKey, "onDocumentStart");
}
void AtomSandboxedRendererClient::RunScriptsAtDocumentEnd(
content::RenderFrame* render_frame) {
if (injected_frames_.find(render_frame) == injected_frames_.end())
return;
auto* isolate = blink::MainThreadIsolate();
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Context> context =
GetContext(render_frame->GetWebFrame(), isolate);
v8::Context::Scope context_scope(context);
InvokeHiddenCallback(context, kLifecycleKey, "onDocumentEnd");
}
void AtomSandboxedRendererClient::DidCreateScriptContext(
v8::Handle<v8::Context> context,
content::RenderFrame* render_frame) {
RendererClientBase::DidCreateScriptContext(context, render_frame);
// Only allow preload for the main frame or
// For devtools we still want to run the preload_bundle script
// Or when nodeSupport is explicitly enabled in sub frames
bool is_main_frame = render_frame->IsMainFrame();
bool is_devtools =
IsDevTools(render_frame) || IsDevToolsExtension(render_frame);
bool allow_node_in_sub_frames =
base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kNodeIntegrationInSubFrames);
bool should_load_preload =
is_main_frame || is_devtools || allow_node_in_sub_frames;
if (!should_load_preload)
return;
injected_frames_.insert(render_frame);
// Wrap the bundle into a function that receives the binding object as
// argument.
auto* isolate = context->GetIsolate();
auto binding = v8::Object::New(isolate);
InitializeBindings(binding, context, render_frame->IsMainFrame());
AddRenderBindings(isolate, binding);
std::vector<v8::Local<v8::String>> sandbox_preload_bundle_params = {
node::FIXED_ONE_BYTE_STRING(isolate, "binding")};
std::vector<v8::Local<v8::Value>> sandbox_preload_bundle_args = {binding};
node::per_process::native_module_loader.CompileAndCall(
isolate->GetCurrentContext(), "electron/js2c/sandbox_bundle",
&sandbox_preload_bundle_params, &sandbox_preload_bundle_args, nullptr);
v8::HandleScope handle_scope(isolate);
v8::Context::Scope context_scope(context);
InvokeHiddenCallback(context, kLifecycleKey, "onLoaded");
}
void AtomSandboxedRendererClient::SetupMainWorldOverrides(
v8::Handle<v8::Context> context,
content::RenderFrame* render_frame) {
// Setup window overrides in the main world context
// Wrap the bundle into a function that receives the isolatedWorld as
// an argument.
auto* isolate = context->GetIsolate();
mate::Dictionary process = mate::Dictionary::CreateEmpty(isolate);
process.SetMethod("_linkedBinding", GetBinding);
std::vector<v8::Local<v8::String>> isolated_bundle_params = {
node::FIXED_ONE_BYTE_STRING(isolate, "nodeProcess"),
node::FIXED_ONE_BYTE_STRING(isolate, "isolatedWorld")};
std::vector<v8::Local<v8::Value>> isolated_bundle_args = {
process.GetHandle(),
GetContext(render_frame->GetWebFrame(), isolate)->Global()};
node::per_process::native_module_loader.CompileAndCall(
context, "electron/js2c/isolated_bundle", &isolated_bundle_params,
&isolated_bundle_args, nullptr);
}
void AtomSandboxedRendererClient::SetupExtensionWorldOverrides(
v8::Handle<v8::Context> context,
content::RenderFrame* render_frame,
int world_id) {
auto* isolate = context->GetIsolate();
mate::Dictionary process = mate::Dictionary::CreateEmpty(isolate);
process.SetMethod("_linkedBinding", GetBinding);
std::vector<v8::Local<v8::String>> isolated_bundle_params = {
node::FIXED_ONE_BYTE_STRING(isolate, "nodeProcess"),
node::FIXED_ONE_BYTE_STRING(isolate, "isolatedWorld"),
node::FIXED_ONE_BYTE_STRING(isolate, "worldId")};
std::vector<v8::Local<v8::Value>> isolated_bundle_args = {
process.GetHandle(),
GetContext(render_frame->GetWebFrame(), isolate)->Global(),
v8::Integer::New(isolate, world_id)};
node::per_process::native_module_loader.CompileAndCall(
context, "electron/js2c/content_script_bundle", &isolated_bundle_params,
&isolated_bundle_args, nullptr);
}
void AtomSandboxedRendererClient::WillReleaseScriptContext(
v8::Handle<v8::Context> context,
content::RenderFrame* render_frame) {
if (injected_frames_.find(render_frame) == injected_frames_.end())
return;
injected_frames_.erase(render_frame);
auto* isolate = context->GetIsolate();
v8::HandleScope handle_scope(isolate);
v8::Context::Scope context_scope(context);
InvokeHiddenCallback(context, kLifecycleKey, "onExit");
}
} // namespace atom

View file

@ -0,0 +1,54 @@
// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_RENDERER_ATOM_SANDBOXED_RENDERER_CLIENT_H_
#define ATOM_RENDERER_ATOM_SANDBOXED_RENDERER_CLIENT_H_
#include <memory>
#include <set>
#include <string>
#include <vector>
#include "atom/renderer/renderer_client_base.h"
#include "base/process/process_metrics.h"
namespace atom {
class AtomSandboxedRendererClient : public RendererClientBase {
public:
AtomSandboxedRendererClient();
~AtomSandboxedRendererClient() override;
void InitializeBindings(v8::Local<v8::Object> binding,
v8::Local<v8::Context> context,
bool is_main_frame);
// atom::RendererClientBase:
void DidCreateScriptContext(v8::Handle<v8::Context> context,
content::RenderFrame* render_frame) override;
void WillReleaseScriptContext(v8::Handle<v8::Context> context,
content::RenderFrame* render_frame) override;
void SetupMainWorldOverrides(v8::Handle<v8::Context> context,
content::RenderFrame* render_frame) override;
void SetupExtensionWorldOverrides(v8::Handle<v8::Context> context,
content::RenderFrame* render_frame,
int world_id) override;
// content::ContentRendererClient:
void RenderFrameCreated(content::RenderFrame*) override;
void RenderViewCreated(content::RenderView*) override;
void RunScriptsAtDocumentStart(content::RenderFrame* render_frame) override;
void RunScriptsAtDocumentEnd(content::RenderFrame* render_frame) override;
private:
std::unique_ptr<base::ProcessMetrics> metrics_;
// Getting main script context from web frame would lazily initializes
// its script context. Doing so in a web page without scripts would trigger
// assertion, so we have to keep a book of injected web frames.
std::set<content::RenderFrame*> injected_frames_;
DISALLOW_COPY_AND_ASSIGN(AtomSandboxedRendererClient);
};
} // namespace atom
#endif // ATOM_RENDERER_ATOM_SANDBOXED_RENDERER_CLIENT_H_

View file

@ -0,0 +1,60 @@
// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/renderer/content_settings_observer.h"
#include "content/public/renderer/render_frame.h"
#include "third_party/blink/public/platform/url_conversion.h"
#include "third_party/blink/public/platform/web_security_origin.h"
#include "third_party/blink/public/web/web_local_frame.h"
namespace atom {
ContentSettingsObserver::ContentSettingsObserver(
content::RenderFrame* render_frame)
: content::RenderFrameObserver(render_frame) {
render_frame->GetWebFrame()->SetContentSettingsClient(this);
}
ContentSettingsObserver::~ContentSettingsObserver() {}
bool ContentSettingsObserver::AllowDatabase() {
blink::WebFrame* frame = render_frame()->GetWebFrame();
if (frame->GetSecurityOrigin().IsUnique() ||
frame->Top()->GetSecurityOrigin().IsUnique())
return false;
auto origin = blink::WebStringToGURL(frame->GetSecurityOrigin().ToString());
if (!origin.IsStandard())
return false;
return true;
}
bool ContentSettingsObserver::AllowStorage(bool local) {
blink::WebFrame* frame = render_frame()->GetWebFrame();
if (frame->GetSecurityOrigin().IsUnique() ||
frame->Top()->GetSecurityOrigin().IsUnique())
return false;
auto origin = blink::WebStringToGURL(frame->GetSecurityOrigin().ToString());
if (!origin.IsStandard())
return false;
return true;
}
bool ContentSettingsObserver::AllowIndexedDB(
const blink::WebSecurityOrigin& security_origin) {
blink::WebFrame* frame = render_frame()->GetWebFrame();
if (frame->GetSecurityOrigin().IsUnique() ||
frame->Top()->GetSecurityOrigin().IsUnique())
return false;
auto origin = blink::WebStringToGURL(frame->GetSecurityOrigin().ToString());
if (!origin.IsStandard())
return false;
return true;
}
void ContentSettingsObserver::OnDestruct() {
delete this;
}
} // namespace atom

View file

@ -0,0 +1,34 @@
// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_RENDERER_CONTENT_SETTINGS_OBSERVER_H_
#define ATOM_RENDERER_CONTENT_SETTINGS_OBSERVER_H_
#include "base/compiler_specific.h"
#include "content/public/renderer/render_frame_observer.h"
#include "third_party/blink/public/platform/web_content_settings_client.h"
namespace atom {
class ContentSettingsObserver : public content::RenderFrameObserver,
public blink::WebContentSettingsClient {
public:
explicit ContentSettingsObserver(content::RenderFrame* render_frame);
~ContentSettingsObserver() override;
// blink::WebContentSettingsClient implementation.
bool AllowDatabase() override;
bool AllowStorage(bool local) override;
bool AllowIndexedDB(const blink::WebSecurityOrigin& security_origin) override;
private:
// content::RenderFrameObserver implementation.
void OnDestruct() override;
DISALLOW_COPY_AND_ASSIGN(ContentSettingsObserver);
};
} // namespace atom
#endif // ATOM_RENDERER_CONTENT_SETTINGS_OBSERVER_H_

View file

@ -0,0 +1,179 @@
// Copyright (c) 2019 Slack Technologies, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "electron/atom/renderer/electron_api_service_impl.h"
#include <memory>
#include <utility>
#include <vector>
#include "atom/common/atom_constants.h"
#include "atom/common/heap_snapshot.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "base/environment.h"
#include "base/macros.h"
#include "base/threading/thread_restrictions.h"
#include "electron/atom/common/api/event_emitter_caller.h"
#include "electron/atom/common/node_includes.h"
#include "electron/atom/common/options_switches.h"
#include "electron/atom/renderer/atom_render_frame_observer.h"
#include "electron/atom/renderer/renderer_client_base.h"
#include "mojo/public/cpp/system/platform_handle.h"
#include "native_mate/dictionary.h"
#include "third_party/blink/public/web/blink.h"
#include "third_party/blink/public/web/web_local_frame.h"
namespace atom {
namespace {
const char kIpcKey[] = "ipcNative";
// Gets the private object under kIpcKey
v8::Local<v8::Object> GetIpcObject(v8::Local<v8::Context> context) {
auto* isolate = context->GetIsolate();
auto binding_key =
mate::ConvertToV8(isolate, kIpcKey)->ToString(context).ToLocalChecked();
auto private_binding_key = v8::Private::ForApi(isolate, binding_key);
auto global_object = context->Global();
auto value =
global_object->GetPrivate(context, private_binding_key).ToLocalChecked();
DCHECK(!value.IsEmpty() && value->IsObject());
return value->ToObject(context).ToLocalChecked();
}
void InvokeIpcCallback(v8::Local<v8::Context> context,
const std::string& callback_name,
std::vector<v8::Local<v8::Value>> args) {
TRACE_EVENT0("devtools.timeline", "FunctionCall");
auto* isolate = context->GetIsolate();
auto ipcNative = GetIpcObject(context);
// Only set up the node::CallbackScope if there's a node environment.
// Sandboxed renderers don't have a node environment.
node::Environment* env = node::Environment::GetCurrent(context);
std::unique_ptr<node::CallbackScope> callback_scope;
if (env) {
callback_scope.reset(new node::CallbackScope(isolate, ipcNative, {0, 0}));
}
auto callback_key = mate::ConvertToV8(isolate, callback_name)
->ToString(context)
.ToLocalChecked();
auto callback_value = ipcNative->Get(context, callback_key).ToLocalChecked();
DCHECK(callback_value->IsFunction()); // set by init.ts
auto callback = v8::Local<v8::Function>::Cast(callback_value);
ignore_result(callback->Call(context, ipcNative, args.size(), args.data()));
}
void EmitIPCEvent(v8::Local<v8::Context> context,
bool internal,
const std::string& channel,
const std::vector<base::Value>& args,
int32_t sender_id) {
auto* isolate = context->GetIsolate();
v8::HandleScope handle_scope(isolate);
v8::Context::Scope context_scope(context);
v8::MicrotasksScope script_scope(isolate,
v8::MicrotasksScope::kRunMicrotasks);
std::vector<v8::Local<v8::Value>> argv = {
mate::ConvertToV8(isolate, internal), mate::ConvertToV8(isolate, channel),
mate::ConvertToV8(isolate, args), mate::ConvertToV8(isolate, sender_id)};
InvokeIpcCallback(context, "onMessage", argv);
}
} // namespace
ElectronApiServiceImpl::~ElectronApiServiceImpl() = default;
ElectronApiServiceImpl::ElectronApiServiceImpl(
content::RenderFrame* render_frame,
RendererClientBase* renderer_client,
mojom::ElectronRendererAssociatedRequest request)
: content::RenderFrameObserver(render_frame),
binding_(this),
render_frame_(render_frame),
renderer_client_(renderer_client) {
binding_.Bind(std::move(request));
binding_.set_connection_error_handler(base::BindOnce(
&ElectronApiServiceImpl::OnDestruct, base::Unretained(this)));
}
// static
void ElectronApiServiceImpl::CreateMojoService(
content::RenderFrame* render_frame,
RendererClientBase* renderer_client,
mojom::ElectronRendererAssociatedRequest request) {
DCHECK(render_frame);
// Owns itself. Will be deleted when the render frame is destroyed.
new ElectronApiServiceImpl(render_frame, renderer_client, std::move(request));
}
void ElectronApiServiceImpl::OnDestruct() {
delete this;
}
void ElectronApiServiceImpl::Message(bool internal,
bool send_to_all,
const std::string& channel,
base::Value arguments,
int32_t sender_id) {
blink::WebLocalFrame* frame = render_frame_->GetWebFrame();
if (!frame)
return;
v8::Isolate* isolate = blink::MainThreadIsolate();
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Context> context = renderer_client_->GetContext(frame, isolate);
EmitIPCEvent(context, internal, channel, arguments.GetList(), sender_id);
// Also send the message to all sub-frames.
// TODO(MarshallOfSound): Completely move this logic to the main process
if (send_to_all) {
for (blink::WebFrame* child = frame->FirstChild(); child;
child = child->NextSibling())
if (child->IsWebLocalFrame()) {
v8::Local<v8::Context> child_context =
renderer_client_->GetContext(child->ToWebLocalFrame(), isolate);
EmitIPCEvent(child_context, internal, channel, arguments.GetList(),
sender_id);
}
}
}
void ElectronApiServiceImpl::UpdateCrashpadPipeName(
const std::string& pipe_name) {
#if defined(OS_WIN)
std::unique_ptr<base::Environment> env(base::Environment::Create());
env->SetVar(kCrashpadPipeName, pipe_name);
#endif
}
void ElectronApiServiceImpl::TakeHeapSnapshot(
mojo::ScopedHandle file,
TakeHeapSnapshotCallback callback) {
base::ThreadRestrictions::ScopedAllowIO allow_io;
base::PlatformFile platform_file;
if (mojo::UnwrapPlatformFile(std::move(file), &platform_file) !=
MOJO_RESULT_OK) {
LOG(ERROR) << "Unable to get the file handle from mojo.";
std::move(callback).Run(false);
return;
}
base::File base_file(platform_file);
bool success = atom::TakeHeapSnapshot(blink::MainThreadIsolate(), &base_file);
std::move(callback).Run(success);
}
} // namespace atom

View file

@ -0,0 +1,55 @@
// Copyright (c) 2019 Slack Technologies, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_RENDERER_ELECTRON_API_SERVICE_IMPL_H_
#define ATOM_RENDERER_ELECTRON_API_SERVICE_IMPL_H_
#include <string>
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_frame_observer.h"
#include "electron/atom/common/api/api.mojom.h"
#include "mojo/public/cpp/bindings/associated_binding.h"
namespace atom {
class RendererClientBase;
class ElectronApiServiceImpl : public mojom::ElectronRenderer,
public content::RenderFrameObserver {
public:
static void CreateMojoService(
content::RenderFrame* render_frame,
RendererClientBase* renderer_client,
mojom::ElectronRendererAssociatedRequest request);
void Message(bool internal,
bool send_to_all,
const std::string& channel,
base::Value arguments,
int32_t sender_id) override;
void UpdateCrashpadPipeName(const std::string& pipe_name) override;
void TakeHeapSnapshot(mojo::ScopedHandle file,
TakeHeapSnapshotCallback callback) override;
private:
~ElectronApiServiceImpl() override;
ElectronApiServiceImpl(content::RenderFrame* render_frame,
RendererClientBase* renderer_client,
mojom::ElectronRendererAssociatedRequest request);
// RenderFrameObserver implementation.
void OnDestruct() override;
mojo::AssociatedBinding<mojom::ElectronRenderer> binding_;
content::RenderFrame* render_frame_;
RendererClientBase* renderer_client_;
DISALLOW_COPY_AND_ASSIGN(ElectronApiServiceImpl);
};
} // namespace atom
#endif // ATOM_RENDERER_ELECTRON_API_SERVICE_IMPL_H_

View file

@ -0,0 +1,64 @@
// 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/renderer/guest_view_container.h"
#include <map>
#include <utility>
#include "base/bind.h"
#include "base/lazy_instance.h"
#include "base/threading/thread_task_runner_handle.h"
#include "ui/gfx/geometry/size.h"
namespace atom {
namespace {
using GuestViewContainerMap = std::map<int, GuestViewContainer*>;
static base::LazyInstance<GuestViewContainerMap>::DestructorAtExit
g_guest_view_container_map = LAZY_INSTANCE_INITIALIZER;
} // namespace
GuestViewContainer::GuestViewContainer(content::RenderFrame* render_frame)
: weak_ptr_factory_(this) {}
GuestViewContainer::~GuestViewContainer() {
if (element_instance_id_ > 0)
g_guest_view_container_map.Get().erase(element_instance_id_);
}
// static
GuestViewContainer* GuestViewContainer::FromID(int element_instance_id) {
GuestViewContainerMap* guest_view_containers =
g_guest_view_container_map.Pointer();
auto it = guest_view_containers->find(element_instance_id);
return it == guest_view_containers->end() ? nullptr : it->second;
}
void GuestViewContainer::RegisterElementResizeCallback(
const ResizeCallback& callback) {
element_resize_callback_ = callback;
}
void GuestViewContainer::SetElementInstanceID(int element_instance_id) {
element_instance_id_ = element_instance_id;
g_guest_view_container_map.Get().insert(
std::make_pair(element_instance_id, this));
}
void GuestViewContainer::DidResizeElement(const gfx::Size& new_size) {
if (element_resize_callback_.is_null())
return;
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(element_resize_callback_, new_size));
}
base::WeakPtr<content::BrowserPluginDelegate> GuestViewContainer::GetWeakPtr() {
return weak_ptr_factory_.GetWeakPtr();
}
} // namespace atom

View file

@ -0,0 +1,46 @@
// 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_RENDERER_GUEST_VIEW_CONTAINER_H_
#define ATOM_RENDERER_GUEST_VIEW_CONTAINER_H_
#include "base/callback.h"
#include "content/public/renderer/browser_plugin_delegate.h"
#include "content/public/renderer/render_frame.h"
namespace gfx {
class Size;
}
namespace atom {
class GuestViewContainer : public content::BrowserPluginDelegate {
public:
typedef base::Callback<void(const gfx::Size&)> ResizeCallback;
explicit GuestViewContainer(content::RenderFrame* render_frame);
~GuestViewContainer() override;
static GuestViewContainer* FromID(int element_instance_id);
void RegisterElementResizeCallback(const ResizeCallback& callback);
// content::BrowserPluginDelegate:
void SetElementInstanceID(int element_instance_id) final;
void DidResizeElement(const gfx::Size& new_size) final;
base::WeakPtr<BrowserPluginDelegate> GetWeakPtr() final;
private:
int element_instance_id_;
ResizeCallback element_resize_callback_;
base::WeakPtrFactory<GuestViewContainer> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(GuestViewContainer);
};
} // namespace atom
#endif // ATOM_RENDERER_GUEST_VIEW_CONTAINER_H_

View file

@ -0,0 +1,37 @@
// Copyright (c) 2018 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/renderer/printing/print_render_frame_helper_delegate.h"
#include "content/public/renderer/render_frame.h"
#include "third_party/blink/public/web/web_element.h"
#include "third_party/blink/public/web/web_local_frame.h"
namespace atom {
PrintRenderFrameHelperDelegate::PrintRenderFrameHelperDelegate() = default;
PrintRenderFrameHelperDelegate::~PrintRenderFrameHelperDelegate() = default;
bool PrintRenderFrameHelperDelegate::CancelPrerender(
content::RenderFrame* render_frame) {
return false;
}
// Return the PDF object element if |frame| is the out of process PDF extension.
blink::WebElement PrintRenderFrameHelperDelegate::GetPdfElement(
blink::WebLocalFrame* frame) {
return blink::WebElement();
}
bool PrintRenderFrameHelperDelegate::IsPrintPreviewEnabled() {
return false;
}
bool PrintRenderFrameHelperDelegate::OverridePrint(
blink::WebLocalFrame* frame) {
return false;
}
} // namespace atom

View file

@ -0,0 +1,31 @@
// Copyright (c) 2018 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_RENDERER_PRINTING_PRINT_RENDER_FRAME_HELPER_DELEGATE_H_
#define ATOM_RENDERER_PRINTING_PRINT_RENDER_FRAME_HELPER_DELEGATE_H_
#include "base/macros.h"
#include "components/printing/renderer/print_render_frame_helper.h"
namespace atom {
class PrintRenderFrameHelperDelegate
: public printing::PrintRenderFrameHelper::Delegate {
public:
PrintRenderFrameHelperDelegate();
~PrintRenderFrameHelperDelegate() override;
private:
// printing::PrintRenderFrameHelper::Delegate:
bool CancelPrerender(content::RenderFrame* render_frame) override;
blink::WebElement GetPdfElement(blink::WebLocalFrame* frame) override;
bool IsPrintPreviewEnabled() override;
bool OverridePrint(blink::WebLocalFrame* frame) override;
DISALLOW_COPY_AND_ASSIGN(PrintRenderFrameHelperDelegate);
};
} // namespace atom
#endif // ATOM_RENDERER_PRINTING_PRINT_RENDER_FRAME_HELPER_DELEGATE_H_

View file

@ -0,0 +1,322 @@
// Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/renderer/renderer_client_base.h"
#include <memory>
#include <string>
#include <vector>
#include "atom/common/color_util.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/options_switches.h"
#include "atom/renderer/atom_autofill_agent.h"
#include "atom/renderer/atom_render_frame_observer.h"
#include "atom/renderer/content_settings_observer.h"
#include "atom/renderer/electron_api_service_impl.h"
#include "base/command_line.h"
#include "base/strings/string_split.h"
#include "base/strings/stringprintf.h"
#include "content/common/buildflags.h"
#include "content/public/common/content_constants.h"
#include "content/public/common/content_switches.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_view.h"
#include "electron/buildflags/buildflags.h"
#include "native_mate/dictionary.h"
#include "printing/buildflags/buildflags.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h"
#include "third_party/blink/public/web/blink.h"
#include "third_party/blink/public/web/web_custom_element.h" // NOLINT(build/include_alpha)
#include "third_party/blink/public/web/web_frame_widget.h"
#include "third_party/blink/public/web/web_plugin_params.h"
#include "third_party/blink/public/web/web_script_source.h"
#include "third_party/blink/public/web/web_security_policy.h"
#include "third_party/blink/public/web/web_view.h"
#include "third_party/blink/renderer/platform/weborigin/scheme_registry.h" // nogncheck
#if defined(OS_MACOSX)
#include "base/strings/sys_string_conversions.h"
#endif
#if defined(OS_WIN)
#include <shlobj.h>
#endif
#if BUILDFLAG(ENABLE_PDF_VIEWER)
#include "atom/common/atom_constants.h"
#endif // BUILDFLAG(ENABLE_PDF_VIEWER)
#if BUILDFLAG(ENABLE_PEPPER_FLASH)
#include "chrome/renderer/pepper/pepper_helper.h"
#endif // BUILDFLAG(ENABLE_PEPPER_FLASH)
#if BUILDFLAG(ENABLE_TTS)
#include "chrome/renderer/tts_dispatcher.h"
#endif // BUILDFLAG(ENABLE_TTS)
#if BUILDFLAG(ENABLE_PRINTING)
#include "atom/renderer/printing/print_render_frame_helper_delegate.h"
#include "components/printing/renderer/print_render_frame_helper.h"
#include "printing/print_settings.h"
#endif // BUILDFLAG(ENABLE_PRINTING)
namespace atom {
namespace {
std::vector<std::string> ParseSchemesCLISwitch(base::CommandLine* command_line,
const char* switch_name) {
std::string custom_schemes = command_line->GetSwitchValueASCII(switch_name);
return base::SplitString(custom_schemes, ",", base::TRIM_WHITESPACE,
base::SPLIT_WANT_NONEMPTY);
}
void SetHiddenValue(v8::Handle<v8::Context> context,
const base::StringPiece& key,
v8::Local<v8::Value> value) {
v8::Isolate* isolate = context->GetIsolate();
v8::Local<v8::Private> privateKey =
v8::Private::ForApi(isolate, mate::StringToV8(isolate, key));
context->Global()->SetPrivate(context, privateKey, value);
}
} // namespace
RendererClientBase::RendererClientBase() {
auto* command_line = base::CommandLine::ForCurrentProcess();
// Parse --standard-schemes=scheme1,scheme2
std::vector<std::string> standard_schemes_list =
ParseSchemesCLISwitch(command_line, switches::kStandardSchemes);
for (const std::string& scheme : standard_schemes_list)
url::AddStandardScheme(scheme.c_str(), url::SCHEME_WITH_HOST);
isolated_world_ = base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kContextIsolation);
// We rely on the unique process host id which is notified to the
// renderer process via command line switch from the content layer,
// if this switch is removed from the content layer for some reason,
// we should define our own.
DCHECK(command_line->HasSwitch(::switches::kRendererClientId));
renderer_client_id_ =
command_line->GetSwitchValueASCII(::switches::kRendererClientId);
}
RendererClientBase::~RendererClientBase() {}
void RendererClientBase::DidCreateScriptContext(
v8::Handle<v8::Context> context,
content::RenderFrame* render_frame) {
// global.setHidden("contextId", `${processHostId}-${++next_context_id_}`)
auto context_id = base::StringPrintf(
"%s-%" PRId64, renderer_client_id_.c_str(), ++next_context_id_);
v8::Isolate* isolate = context->GetIsolate();
SetHiddenValue(context, "contextId", mate::ConvertToV8(isolate, context_id));
auto* command_line = base::CommandLine::ForCurrentProcess();
bool enableRemoteModule =
!command_line->HasSwitch(switches::kDisableRemoteModule);
SetHiddenValue(context, "enableRemoteModule",
mate::ConvertToV8(isolate, enableRemoteModule));
}
void RendererClientBase::AddRenderBindings(
v8::Isolate* isolate,
v8::Local<v8::Object> binding_object) {
mate::Dictionary dict(isolate, binding_object);
}
void RendererClientBase::RenderThreadStarted() {
auto* command_line = base::CommandLine::ForCurrentProcess();
#if BUILDFLAG(USE_EXTERNAL_POPUP_MENU)
// On macOS, popup menus are rendered by the main process by default.
// This causes problems in OSR, since when the popup is rendered separately,
// it won't be captured in the rendered image.
if (command_line->HasSwitch(options::kOffscreen)) {
blink::WebView::SetUseExternalPopupMenus(false);
}
#endif
blink::WebCustomElement::AddEmbedderCustomElementName("webview");
blink::WebCustomElement::AddEmbedderCustomElementName("browserplugin");
WTF::String extension_scheme("chrome-extension");
// Extension resources are HTTP-like and safe to expose to the fetch API. The
// rules for the fetch API are consistent with XHR.
blink::SchemeRegistry::RegisterURLSchemeAsSupportingFetchAPI(
extension_scheme);
// Extension resources, when loaded as the top-level document, should bypass
// Blink's strict first-party origin checks.
blink::SchemeRegistry::RegisterURLSchemeAsFirstPartyWhenTopLevel(
extension_scheme);
// In Chrome we should set extension's origins to match the pages they can
// work on, but in Electron currently we just let extensions do anything.
blink::SchemeRegistry::RegisterURLSchemeAsSecure(extension_scheme);
blink::SchemeRegistry::RegisterURLSchemeAsBypassingContentSecurityPolicy(
extension_scheme);
// Parse --secure-schemes=scheme1,scheme2
std::vector<std::string> secure_schemes_list =
ParseSchemesCLISwitch(command_line, switches::kSecureSchemes);
for (const std::string& scheme : secure_schemes_list)
blink::SchemeRegistry::RegisterURLSchemeAsSecure(
WTF::String::FromUTF8(scheme.data(), scheme.length()));
std::vector<std::string> fetch_enabled_schemes =
ParseSchemesCLISwitch(command_line, switches::kFetchSchemes);
for (const std::string& scheme : fetch_enabled_schemes) {
blink::WebSecurityPolicy::RegisterURLSchemeAsSupportingFetchAPI(
blink::WebString::FromASCII(scheme));
}
std::vector<std::string> service_worker_schemes =
ParseSchemesCLISwitch(command_line, switches::kServiceWorkerSchemes);
for (const std::string& scheme : service_worker_schemes)
blink::WebSecurityPolicy::RegisterURLSchemeAsAllowingServiceWorkers(
blink::WebString::FromASCII(scheme));
std::vector<std::string> csp_bypassing_schemes =
ParseSchemesCLISwitch(command_line, switches::kBypassCSPSchemes);
for (const std::string& scheme : csp_bypassing_schemes)
blink::SchemeRegistry::RegisterURLSchemeAsBypassingContentSecurityPolicy(
WTF::String::FromUTF8(scheme.data(), scheme.length()));
// Allow file scheme to handle service worker by default.
// FIXME(zcbenz): Can this be moved elsewhere?
blink::WebSecurityPolicy::RegisterURLSchemeAsAllowingServiceWorkers("file");
blink::SchemeRegistry::RegisterURLSchemeAsSupportingFetchAPI("file");
#if defined(OS_WIN)
// Set ApplicationUserModelID in renderer process.
base::string16 app_id =
command_line->GetSwitchValueNative(switches::kAppUserModelId);
if (!app_id.empty()) {
SetCurrentProcessExplicitAppUserModelID(app_id.c_str());
}
#endif
}
void RendererClientBase::RenderFrameCreated(
content::RenderFrame* render_frame) {
#if defined(TOOLKIT_VIEWS)
new AutofillAgent(render_frame,
render_frame->GetAssociatedInterfaceRegistry());
#endif
#if BUILDFLAG(ENABLE_PEPPER_FLASH)
new PepperHelper(render_frame);
#endif
new ContentSettingsObserver(render_frame);
#if BUILDFLAG(ENABLE_PRINTING)
new printing::PrintRenderFrameHelper(
render_frame, std::make_unique<atom::PrintRenderFrameHelperDelegate>());
#endif
// TODO(nornagon): it might be possible for an IPC message sent to this
// service to trigger v8 context creation before the page has begun loading.
// However, it's unclear whether such a timing is possible to trigger, and we
// don't have any test to confirm it. Add a test that confirms that a
// main->renderer IPC can't cause the preload script to be executed twice. If
// it is possible to trigger the preload script before the document is ready
// through this interface, we should delay adding it to the registry until
// the document is ready.
render_frame->GetAssociatedInterfaceRegistry()->AddInterface(
base::BindRepeating(&ElectronApiServiceImpl::CreateMojoService,
render_frame, this));
#if BUILDFLAG(ENABLE_PDF_VIEWER)
// Allow access to file scheme from pdf viewer.
blink::WebSecurityPolicy::AddOriginAccessWhitelistEntry(
GURL(kPdfViewerUIOrigin), "file", "", true);
#endif // BUILDFLAG(ENABLE_PDF_VIEWER)
content::RenderView* render_view = render_frame->GetRenderView();
if (render_frame->IsMainFrame() && render_view) {
blink::WebView* webview = render_view->GetWebView();
if (webview) {
base::CommandLine* cmd = base::CommandLine::ForCurrentProcess();
if (cmd->HasSwitch(switches::kGuestInstanceID)) { // webview.
webview->SetBaseBackgroundColor(SK_ColorTRANSPARENT);
} else { // normal window.
std::string name = cmd->GetSwitchValueASCII(switches::kBackgroundColor);
SkColor color =
name.empty() ? SK_ColorTRANSPARENT : ParseHexColor(name);
webview->SetBaseBackgroundColor(color);
}
}
}
}
void RendererClientBase::DidClearWindowObject(
content::RenderFrame* render_frame) {
// Make sure every page will get a script context created.
render_frame->GetWebFrame()->ExecuteScript(blink::WebScriptSource("void 0"));
}
std::unique_ptr<blink::WebSpeechSynthesizer>
RendererClientBase::OverrideSpeechSynthesizer(
blink::WebSpeechSynthesizerClient* client) {
#if BUILDFLAG(ENABLE_TTS)
return std::make_unique<TtsDispatcher>(client);
#else
return nullptr;
#endif
}
bool RendererClientBase::OverrideCreatePlugin(
content::RenderFrame* render_frame,
const blink::WebPluginParams& params,
blink::WebPlugin** plugin) {
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (params.mime_type.Utf8() == content::kBrowserPluginMimeType ||
#if BUILDFLAG(ENABLE_PDF_VIEWER)
params.mime_type.Utf8() == kPdfPluginMimeType ||
#endif // BUILDFLAG(ENABLE_PDF_VIEWER)
command_line->HasSwitch(switches::kEnablePlugins))
return false;
*plugin = nullptr;
return true;
}
void RendererClientBase::AddSupportedKeySystems(
std::vector<std::unique_ptr<::media::KeySystemProperties>>* key_systems) {
#if defined(WIDEVINE_CDM_AVAILABLE)
key_systems_provider_.AddSupportedKeySystems(key_systems);
#endif
}
bool RendererClientBase::IsKeySystemsUpdateNeeded() {
#if defined(WIDEVINE_CDM_AVAILABLE)
return key_systems_provider_.IsKeySystemsUpdateNeeded();
#else
return false;
#endif
}
void RendererClientBase::DidSetUserAgent(const std::string& user_agent) {
#if BUILDFLAG(ENABLE_PRINTING)
printing::SetAgent(user_agent);
#endif
}
v8::Local<v8::Context> RendererClientBase::GetContext(
blink::WebLocalFrame* frame,
v8::Isolate* isolate) const {
if (isolated_world())
return frame->WorldScriptContext(isolate, World::ISOLATED_WORLD);
else
return frame->MainWorldScriptContext();
}
v8::Local<v8::Value> RendererClientBase::RunScript(
v8::Local<v8::Context> context,
v8::Local<v8::String> source) {
auto maybe_script = v8::Script::Compile(context, source);
v8::Local<v8::Script> script;
if (!maybe_script.ToLocal(&script))
return v8::Local<v8::Value>();
return script->Run(context).ToLocalChecked();
}
} // namespace atom

View file

@ -0,0 +1,78 @@
// Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_RENDERER_RENDERER_CLIENT_BASE_H_
#define ATOM_RENDERER_RENDERER_CLIENT_BASE_H_
#include <memory>
#include <string>
#include <vector>
#include "content/public/renderer/content_renderer_client.h"
#include "third_party/blink/public/web/web_local_frame.h"
// In SHARED_INTERMEDIATE_DIR.
#include "widevine_cdm_version.h" // NOLINT(build/include)
#if defined(WIDEVINE_CDM_AVAILABLE)
#include "chrome/renderer/media/chrome_key_systems_provider.h" // nogncheck
#endif
namespace atom {
class RendererClientBase : public content::ContentRendererClient {
public:
RendererClientBase();
~RendererClientBase() override;
virtual void DidCreateScriptContext(v8::Handle<v8::Context> context,
content::RenderFrame* render_frame);
virtual void WillReleaseScriptContext(v8::Handle<v8::Context> context,
content::RenderFrame* render_frame) = 0;
virtual void DidClearWindowObject(content::RenderFrame* render_frame);
virtual void SetupMainWorldOverrides(v8::Handle<v8::Context> context,
content::RenderFrame* render_frame) = 0;
virtual void SetupExtensionWorldOverrides(v8::Handle<v8::Context> context,
content::RenderFrame* render_frame,
int world_id) = 0;
bool isolated_world() const { return isolated_world_; }
// Get the context that the Electron API is running in.
v8::Local<v8::Context> GetContext(blink::WebLocalFrame* frame,
v8::Isolate* isolate) const;
// Executes a given v8 Script
static v8::Local<v8::Value> RunScript(v8::Local<v8::Context> context,
v8::Local<v8::String> source);
protected:
void AddRenderBindings(v8::Isolate* isolate,
v8::Local<v8::Object> binding_object);
// content::ContentRendererClient:
void RenderThreadStarted() override;
void RenderFrameCreated(content::RenderFrame*) override;
std::unique_ptr<blink::WebSpeechSynthesizer> OverrideSpeechSynthesizer(
blink::WebSpeechSynthesizerClient* client) override;
bool OverrideCreatePlugin(content::RenderFrame* render_frame,
const blink::WebPluginParams& params,
blink::WebPlugin** plugin) override;
void AddSupportedKeySystems(
std::vector<std::unique_ptr<::media::KeySystemProperties>>* key_systems)
override;
bool IsKeySystemsUpdateNeeded() override;
void DidSetUserAgent(const std::string& user_agent) override;
private:
#if defined(WIDEVINE_CDM_AVAILABLE)
ChromeKeySystemsProvider key_systems_provider_;
#endif
bool isolated_world_;
std::string renderer_client_id_;
// An increasing ID used for indentifying an V8 context in this process.
int64_t next_context_id_ = 0;
};
} // namespace atom
#endif // ATOM_RENDERER_RENDERER_CLIENT_BASE_H_

View file

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleIdentifier</key>
<string>${ELECTRON_BUNDLE_ID}</string>
<key>CFBundleName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>LSUIElement</key>
<true/>
<key>NSSupportsAutomaticGraphicsSwitching</key>
<true/>
</dict>
</plist>

View file

@ -0,0 +1,74 @@
// Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/renderer/web_worker_observer.h"
#include "atom/common/api/electron_bindings.h"
#include "atom/common/api/event_emitter_caller.h"
#include "atom/common/asar/asar_util.h"
#include "atom/common/node_bindings.h"
#include "atom/common/node_includes.h"
#include "base/lazy_instance.h"
#include "base/threading/thread_local.h"
namespace atom {
namespace {
static base::LazyInstance<
base::ThreadLocalPointer<WebWorkerObserver>>::DestructorAtExit lazy_tls =
LAZY_INSTANCE_INITIALIZER;
} // namespace
// static
WebWorkerObserver* WebWorkerObserver::GetCurrent() {
WebWorkerObserver* self = lazy_tls.Pointer()->Get();
return self ? self : new WebWorkerObserver;
}
WebWorkerObserver::WebWorkerObserver()
: node_bindings_(
NodeBindings::Create(NodeBindings::BrowserEnvironment::WORKER)),
electron_bindings_(new ElectronBindings(node_bindings_->uv_loop())) {
lazy_tls.Pointer()->Set(this);
}
WebWorkerObserver::~WebWorkerObserver() {
lazy_tls.Pointer()->Set(nullptr);
node::FreeEnvironment(node_bindings_->uv_env());
asar::ClearArchives();
}
void WebWorkerObserver::ContextCreated(v8::Local<v8::Context> context) {
v8::Context::Scope context_scope(context);
// Start the embed thread.
node_bindings_->PrepareMessageLoop();
// Setup node environment for each window.
node::Environment* env = node_bindings_->CreateEnvironment(context);
// Add Electron extended APIs.
electron_bindings_->BindTo(env->isolate(), env->process_object());
// Load everything.
node_bindings_->LoadEnvironment(env);
// Make uv loop being wrapped by window context.
node_bindings_->set_uv_env(env);
// Give the node loop a run to make sure everything is ready.
node_bindings_->RunMessageLoop();
}
void WebWorkerObserver::ContextWillDestroy(v8::Local<v8::Context> context) {
node::Environment* env = node::Environment::GetCurrent(context);
if (env)
mate::EmitEvent(env->isolate(), env->process_object(), "exit");
delete this;
}
} // namespace atom

View file

@ -0,0 +1,39 @@
// Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_RENDERER_WEB_WORKER_OBSERVER_H_
#define ATOM_RENDERER_WEB_WORKER_OBSERVER_H_
#include <memory>
#include "base/macros.h"
#include "v8/include/v8.h"
namespace atom {
class ElectronBindings;
class NodeBindings;
// Watches for WebWorker and insert node integration to it.
class WebWorkerObserver {
public:
// Returns the WebWorkerObserver for current worker thread.
static WebWorkerObserver* GetCurrent();
void ContextCreated(v8::Local<v8::Context> context);
void ContextWillDestroy(v8::Local<v8::Context> context);
private:
WebWorkerObserver();
~WebWorkerObserver();
std::unique_ptr<NodeBindings> node_bindings_;
std::unique_ptr<ElectronBindings> electron_bindings_;
DISALLOW_COPY_AND_ASSIGN(WebWorkerObserver);
};
} // namespace atom
#endif // ATOM_RENDERER_WEB_WORKER_OBSERVER_H_