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

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,249 @@
// 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_BROWSER_API_ATOM_API_APP_H_
#define ATOM_BROWSER_API_ATOM_API_APP_H_
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "atom/browser/api/event_emitter.h"
#include "atom/browser/api/process_metric.h"
#include "atom/browser/atom_browser_client.h"
#include "atom/browser/browser.h"
#include "atom/browser/browser_observer.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/promise_util.h"
#include "base/task/cancelable_task_tracker.h"
#include "chrome/browser/icon_manager.h"
#include "chrome/browser/process_singleton.h"
#include "content/public/browser/browser_child_process_observer.h"
#include "content/public/browser/gpu_data_manager_observer.h"
#include "content/public/browser/render_process_host.h"
#include "native_mate/dictionary.h"
#include "native_mate/handle.h"
#include "net/base/completion_once_callback.h"
#include "net/base/completion_repeating_callback.h"
#include "net/ssl/client_cert_identity.h"
#if defined(USE_NSS_CERTS)
#include "chrome/browser/certificate_manager_model.h"
#endif
namespace base {
class FilePath;
}
namespace mate {
class Arguments;
} // namespace mate
namespace atom {
#if defined(OS_WIN)
enum class JumpListResult : int;
#endif
namespace api {
class App : public AtomBrowserClient::Delegate,
public mate::EventEmitter<App>,
public BrowserObserver,
public content::GpuDataManagerObserver,
public content::BrowserChildProcessObserver {
public:
using FileIconCallback =
base::RepeatingCallback<void(v8::Local<v8::Value>, const gfx::Image&)>;
static mate::Handle<App> Create(v8::Isolate* isolate);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
#if defined(USE_NSS_CERTS)
void OnCertificateManagerModelCreated(
std::unique_ptr<base::DictionaryValue> options,
net::CompletionOnceCallback callback,
std::unique_ptr<CertificateManagerModel> model);
#endif
base::FilePath GetAppPath() const;
void RenderProcessReady(content::RenderProcessHost* host);
void RenderProcessDisconnected(base::ProcessId host_pid);
void PreMainMessageLoopRun();
protected:
explicit App(v8::Isolate* isolate);
~App() override;
// BrowserObserver:
void OnBeforeQuit(bool* prevent_default) override;
void OnWillQuit(bool* prevent_default) override;
void OnWindowAllClosed() override;
void OnQuit() override;
void OnOpenFile(bool* prevent_default, const std::string& file_path) override;
void OnOpenURL(const std::string& url) override;
void OnActivate(bool has_visible_windows) override;
void OnWillFinishLaunching() override;
void OnFinishLaunching(const base::DictionaryValue& launch_info) override;
void OnLogin(scoped_refptr<LoginHandler> login_handler,
const base::DictionaryValue& request_details) override;
void OnAccessibilitySupportChanged() override;
void OnPreMainMessageLoopRun() override;
#if defined(OS_MACOSX)
void OnWillContinueUserActivity(bool* prevent_default,
const std::string& type) override;
void OnDidFailToContinueUserActivity(const std::string& type,
const std::string& error) override;
void OnContinueUserActivity(bool* prevent_default,
const std::string& type,
const base::DictionaryValue& user_info) override;
void OnUserActivityWasContinued(
const std::string& type,
const base::DictionaryValue& user_info) override;
void OnUpdateUserActivityState(
bool* prevent_default,
const std::string& type,
const base::DictionaryValue& user_info) override;
void OnNewWindowForTab() override;
#endif
// content::ContentBrowserClient:
void AllowCertificateError(
content::WebContents* web_contents,
int cert_error,
const net::SSLInfo& ssl_info,
const GURL& request_url,
bool is_main_frame_request,
bool strict_enforcement,
bool expired_previous_decision,
const base::RepeatingCallback<
void(content::CertificateRequestResultType)>& callback) override;
void SelectClientCertificate(
content::WebContents* web_contents,
net::SSLCertRequestInfo* cert_request_info,
net::ClientCertIdentityList client_certs,
std::unique_ptr<content::ClientCertificateDelegate> delegate) override;
bool CanCreateWindow(content::RenderFrameHost* opener,
const GURL& opener_url,
const GURL& opener_top_level_frame_url,
const url::Origin& source_origin,
content::mojom::WindowContainerType container_type,
const GURL& target_url,
const content::Referrer& referrer,
const std::string& frame_name,
WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& features,
const std::vector<std::string>& additional_features,
const scoped_refptr<network::ResourceRequestBody>& body,
bool user_gesture,
bool opener_suppressed,
bool* no_javascript_access) override;
// content::GpuDataManagerObserver:
void OnGpuInfoUpdate() override;
void OnGpuProcessCrashed(base::TerminationStatus status) override;
// content::BrowserChildProcessObserver:
void BrowserChildProcessLaunchedAndConnected(
const content::ChildProcessData& data) override;
void BrowserChildProcessHostDisconnected(
const content::ChildProcessData& data) override;
void BrowserChildProcessCrashed(
const content::ChildProcessData& data,
const content::ChildProcessTerminationInfo& info) override;
void BrowserChildProcessKilled(
const content::ChildProcessData& data,
const content::ChildProcessTerminationInfo& info) override;
private:
void SetAppPath(const base::FilePath& app_path);
void ChildProcessLaunched(int process_type, base::ProcessHandle handle);
void ChildProcessDisconnected(base::ProcessId pid);
void SetAppLogsPath(mate::Arguments* args);
// Get/Set the pre-defined path in PathService.
base::FilePath GetPath(mate::Arguments* args, const std::string& name);
void SetPath(mate::Arguments* args,
const std::string& name,
const base::FilePath& path);
void SetDesktopName(const std::string& desktop_name);
std::string GetLocale();
std::string GetLocaleCountryCode();
void OnSecondInstance(const base::CommandLine::StringVector& cmd,
const base::FilePath& cwd);
bool HasSingleInstanceLock() const;
bool RequestSingleInstanceLock();
void ReleaseSingleInstanceLock();
bool Relaunch(mate::Arguments* args);
void DisableHardwareAcceleration(mate::Arguments* args);
void DisableDomainBlockingFor3DAPIs(mate::Arguments* args);
bool IsAccessibilitySupportEnabled();
void SetAccessibilitySupportEnabled(bool enabled, mate::Arguments* args);
Browser::LoginItemSettings GetLoginItemSettings(mate::Arguments* args);
#if defined(USE_NSS_CERTS)
void ImportCertificate(const base::DictionaryValue& options,
net::CompletionRepeatingCallback callback);
#endif
v8::Local<v8::Promise> GetFileIcon(const base::FilePath& path,
mate::Arguments* args);
std::vector<mate::Dictionary> GetAppMetrics(v8::Isolate* isolate);
v8::Local<v8::Value> GetGPUFeatureStatus(v8::Isolate* isolate);
v8::Local<v8::Promise> GetGPUInfo(v8::Isolate* isolate,
const std::string& info_type);
void EnableSandbox(mate::Arguments* args);
void SetUserAgentFallback(const std::string& user_agent);
std::string GetUserAgentFallback();
void SetBrowserClientCanUseCustomSiteInstance(bool should_disable);
bool CanBrowserClientUseCustomSiteInstance();
#if defined(OS_MACOSX)
bool MoveToApplicationsFolder(mate::Arguments* args);
bool IsInApplicationsFolder();
v8::Local<v8::Value> GetDockAPI(v8::Isolate* isolate);
v8::Global<v8::Value> dock_;
#endif
#if defined(MAS_BUILD)
base::RepeatingCallback<void()> StartAccessingSecurityScopedResource(
mate::Arguments* args);
#endif
#if defined(OS_WIN)
// Get the current Jump List settings.
v8::Local<v8::Value> GetJumpListSettings();
// Set or remove a custom Jump List for the application.
JumpListResult SetJumpList(v8::Local<v8::Value> val, mate::Arguments* args);
#endif // defined(OS_WIN)
std::unique_ptr<ProcessSingleton> process_singleton_;
#if defined(USE_NSS_CERTS)
std::unique_ptr<CertificateManagerModel> certificate_manager_model_;
#endif
// Tracks tasks requesting file icons.
base::CancelableTaskTracker cancelable_task_tracker_;
base::FilePath app_path_;
using ProcessMetricMap =
std::unordered_map<base::ProcessId, std::unique_ptr<atom::ProcessMetric>>;
ProcessMetricMap app_metrics_;
DISALLOW_COPY_AND_ASSIGN(App);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_APP_H_

View file

@ -0,0 +1,38 @@
// Copyright (c) 2019 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/api/atom_api_app.h"
#include "atom/browser/atom_paths.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
#include "base/path_service.h"
#import <Cocoa/Cocoa.h>
namespace atom {
namespace api {
void App::SetAppLogsPath(mate::Arguments* args) {
base::FilePath custom_path;
if (args->GetNext(&custom_path)) {
if (!custom_path.IsAbsolute()) {
args->ThrowError("Path must be absolute");
return;
}
base::PathService::Override(DIR_APP_LOGS, custom_path);
} else {
NSString* bundle_name =
[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
NSString* logs_path =
[NSString stringWithFormat:@"Library/Logs/%@", bundle_name];
NSString* library_path =
[NSHomeDirectory() stringByAppendingPathComponent:logs_path];
base::PathService::Override(DIR_APP_LOGS,
base::FilePath([library_path UTF8String]));
}
}
} // namespace api
} // namespace atom

View file

@ -0,0 +1,66 @@
// 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/browser/api/atom_api_app.h"
#include <string>
#import <Cocoa/Cocoa.h>
#include "base/strings/sys_string_conversions.h"
namespace atom {
namespace api {
// Callback passed to js which will stop accessing the given bookmark.
void OnStopAccessingSecurityScopedResource(NSURL* bookmarkUrl) {
[bookmarkUrl stopAccessingSecurityScopedResource];
[bookmarkUrl release];
}
// Get base64 encoded NSData, create a bookmark for it and start accessing it.
base::RepeatingCallback<void()> App::StartAccessingSecurityScopedResource(
mate::Arguments* args) {
std::string data;
args->GetNext(&data);
NSString* base64str = base::SysUTF8ToNSString(data);
NSData* bookmarkData = [[NSData alloc] initWithBase64EncodedString:base64str
options:0];
// Create bookmarkUrl from NSData.
BOOL isStale = false;
NSError* error = nil;
NSURL* bookmarkUrl =
[NSURL URLByResolvingBookmarkData:bookmarkData
options:NSURLBookmarkResolutionWithSecurityScope
relativeToURL:nil
bookmarkDataIsStale:&isStale
error:&error];
if (error != nil) {
NSString* err =
[NSString stringWithFormat:@"NSError: %@ %@", error, [error userInfo]];
args->ThrowError(base::SysNSStringToUTF8(err));
}
if (isStale) {
args->ThrowError("bookmarkDataIsStale - try recreating the bookmark");
}
if (error == nil && isStale == false) {
[bookmarkUrl startAccessingSecurityScopedResource];
}
// Stop the NSURL from being GC'd.
[bookmarkUrl retain];
// Return a js callback which will close the bookmark.
return base::BindRepeating(&OnStopAccessingSecurityScopedResource,
bookmarkUrl);
}
} // namespace api
} // namespace atom

View file

@ -0,0 +1,164 @@
// 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/browser/api/atom_api_auto_updater.h"
#include "atom/browser/browser.h"
#include "atom/browser/native_window.h"
#include "atom/browser/window_list.h"
#include "atom/common/api/event_emitter_caller.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/node_includes.h"
#include "base/time/time.h"
#include "native_mate/dictionary.h"
#include "native_mate/object_template_builder.h"
namespace mate {
template <>
struct Converter<base::Time> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
const base::Time& val) {
v8::MaybeLocal<v8::Value> date =
v8::Date::New(isolate->GetCurrentContext(), val.ToJsTime());
if (date.IsEmpty())
return v8::Null(isolate);
else
return date.ToLocalChecked();
}
};
} // namespace mate
namespace atom {
namespace api {
AutoUpdater::AutoUpdater(v8::Isolate* isolate) {
auto_updater::AutoUpdater::SetDelegate(this);
Init(isolate);
}
AutoUpdater::~AutoUpdater() {
auto_updater::AutoUpdater::SetDelegate(nullptr);
}
void AutoUpdater::OnError(const std::string& message) {
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
auto error = v8::Exception::Error(mate::StringToV8(isolate(), message));
mate::EmitEvent(
isolate(), GetWrapper(), "error",
error->ToObject(isolate()->GetCurrentContext()).ToLocalChecked(),
// Message is also emitted to keep compatibility with old code.
message);
}
void AutoUpdater::OnError(const std::string& message,
const int code,
const std::string& domain) {
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
auto error = v8::Exception::Error(mate::StringToV8(isolate(), message));
auto errorObject =
error->ToObject(isolate()->GetCurrentContext()).ToLocalChecked();
auto context = isolate()->GetCurrentContext();
// add two new params for better error handling
errorObject
->Set(context, mate::StringToV8(isolate(), "code"),
v8::Integer::New(isolate(), code))
.Check();
errorObject
->Set(context, mate::StringToV8(isolate(), "domain"),
mate::StringToV8(isolate(), domain))
.Check();
mate::EmitEvent(isolate(), GetWrapper(), "error", errorObject, message);
}
void AutoUpdater::OnCheckingForUpdate() {
Emit("checking-for-update");
}
void AutoUpdater::OnUpdateAvailable() {
Emit("update-available");
}
void AutoUpdater::OnUpdateNotAvailable() {
Emit("update-not-available");
}
void AutoUpdater::OnUpdateDownloaded(const std::string& release_notes,
const std::string& release_name,
const base::Time& release_date,
const std::string& url) {
Emit("update-downloaded", release_notes, release_name, release_date, url,
// Keep compatibility with old APIs.
base::BindRepeating(&AutoUpdater::QuitAndInstall,
base::Unretained(this)));
}
void AutoUpdater::OnWindowAllClosed() {
QuitAndInstall();
}
void AutoUpdater::SetFeedURL(mate::Arguments* args) {
auto_updater::AutoUpdater::SetFeedURL(args);
}
void AutoUpdater::QuitAndInstall() {
Emit("before-quit-for-update");
// If we don't have any window then quitAndInstall immediately.
if (WindowList::IsEmpty()) {
auto_updater::AutoUpdater::QuitAndInstall();
return;
}
// Otherwise do the restart after all windows have been closed.
WindowList::AddObserver(this);
WindowList::CloseAllWindows();
}
// static
mate::Handle<AutoUpdater> AutoUpdater::Create(v8::Isolate* isolate) {
return mate::CreateHandle(isolate, new AutoUpdater(isolate));
}
// static
void AutoUpdater::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "AutoUpdater"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.SetMethod("checkForUpdates", &auto_updater::AutoUpdater::CheckForUpdates)
.SetMethod("getFeedURL", &auto_updater::AutoUpdater::GetFeedURL)
.SetMethod("setFeedURL", &AutoUpdater::SetFeedURL)
.SetMethod("quitAndInstall", &AutoUpdater::QuitAndInstall);
}
} // namespace api
} // namespace atom
namespace {
using atom::api::AutoUpdater;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
mate::Dictionary dict(isolate, exports);
dict.Set("autoUpdater", AutoUpdater::Create(isolate));
dict.Set("AutoUpdater", AutoUpdater::GetConstructor(isolate)
->GetFunction(context)
.ToLocalChecked());
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_browser_auto_updater, Initialize)

View file

@ -0,0 +1,61 @@
// 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_BROWSER_API_ATOM_API_AUTO_UPDATER_H_
#define ATOM_BROWSER_API_ATOM_API_AUTO_UPDATER_H_
#include <string>
#include "atom/browser/api/event_emitter.h"
#include "atom/browser/auto_updater.h"
#include "atom/browser/window_list_observer.h"
#include "native_mate/arguments.h"
#include "native_mate/handle.h"
namespace atom {
namespace api {
class AutoUpdater : public mate::EventEmitter<AutoUpdater>,
public auto_updater::Delegate,
public WindowListObserver {
public:
static mate::Handle<AutoUpdater> Create(v8::Isolate* isolate);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
protected:
explicit AutoUpdater(v8::Isolate* isolate);
~AutoUpdater() override;
// Delegate implementations.
void OnError(const std::string& error) override;
void OnError(const std::string& message,
const int code,
const std::string& domain) override;
void OnCheckingForUpdate() override;
void OnUpdateAvailable() override;
void OnUpdateNotAvailable() override;
void OnUpdateDownloaded(const std::string& release_notes,
const std::string& release_name,
const base::Time& release_date,
const std::string& update_url) override;
// WindowListObserver:
void OnWindowAllClosed() override;
private:
std::string GetFeedURL();
void SetFeedURL(mate::Arguments* args);
void QuitAndInstall();
DISALLOW_COPY_AND_ASSIGN(AutoUpdater);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_AUTO_UPDATER_H_

View file

@ -0,0 +1,183 @@
// 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/browser/api/atom_api_browser_view.h"
#include "atom/browser/api/atom_api_web_contents.h"
#include "atom/browser/browser.h"
#include "atom/browser/native_browser_view.h"
#include "atom/common/color_util.h"
#include "atom/common/native_mate_converters/gfx_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/node_includes.h"
#include "atom/common/options_switches.h"
#include "native_mate/constructor.h"
#include "native_mate/dictionary.h"
#include "ui/gfx/geometry/rect.h"
namespace mate {
template <>
struct Converter<atom::AutoResizeFlags> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
atom::AutoResizeFlags* auto_resize_flags) {
mate::Dictionary params;
if (!ConvertFromV8(isolate, val, &params)) {
return false;
}
uint8_t flags = 0;
bool width = false;
if (params.Get("width", &width) && width) {
flags |= atom::kAutoResizeWidth;
}
bool height = false;
if (params.Get("height", &height) && height) {
flags |= atom::kAutoResizeHeight;
}
bool horizontal = false;
if (params.Get("horizontal", &horizontal) && horizontal) {
flags |= atom::kAutoResizeHorizontal;
}
bool vertical = false;
if (params.Get("vertical", &vertical) && vertical) {
flags |= atom::kAutoResizeVertical;
}
*auto_resize_flags = static_cast<atom::AutoResizeFlags>(flags);
return true;
}
};
} // namespace mate
namespace atom {
namespace api {
BrowserView::BrowserView(v8::Isolate* isolate,
v8::Local<v8::Object> wrapper,
const mate::Dictionary& options) {
Init(isolate, wrapper, options);
}
void BrowserView::Init(v8::Isolate* isolate,
v8::Local<v8::Object> wrapper,
const mate::Dictionary& options) {
mate::Dictionary web_preferences = mate::Dictionary::CreateEmpty(isolate);
options.Get(options::kWebPreferences, &web_preferences);
web_preferences.Set("type", "browserView");
mate::Handle<class WebContents> web_contents =
WebContents::Create(isolate, web_preferences);
web_contents_.Reset(isolate, web_contents.ToV8());
api_web_contents_ = web_contents.get();
Observe(web_contents->web_contents());
view_.reset(
NativeBrowserView::Create(api_web_contents_->managed_web_contents()));
InitWith(isolate, wrapper);
}
BrowserView::~BrowserView() {
if (api_web_contents_) { // destroy() is called
// Destroy WebContents asynchronously unless app is shutting down,
// because destroy() might be called inside WebContents's event handler.
api_web_contents_->DestroyWebContents(!Browser::Get()->is_shutting_down());
}
}
void BrowserView::WebContentsDestroyed() {
api_web_contents_ = nullptr;
web_contents_.Reset();
}
// static
mate::WrappableBase* BrowserView::New(mate::Arguments* args) {
if (!Browser::Get()->is_ready()) {
args->ThrowError("Cannot create BrowserView before app is ready");
return nullptr;
}
if (args->Length() > 1) {
args->ThrowError("Too many arguments");
return nullptr;
}
mate::Dictionary options;
if (!(args->Length() == 1 && args->GetNext(&options))) {
options = mate::Dictionary::CreateEmpty(args->isolate());
}
return new BrowserView(args->isolate(), args->GetThis(), options);
}
int32_t BrowserView::ID() const {
return weak_map_id();
}
void BrowserView::SetAutoResize(AutoResizeFlags flags) {
view_->SetAutoResizeFlags(flags);
}
void BrowserView::SetBounds(const gfx::Rect& bounds) {
view_->SetBounds(bounds);
}
void BrowserView::SetBackgroundColor(const std::string& color_name) {
view_->SetBackgroundColor(ParseHexColor(color_name));
}
v8::Local<v8::Value> BrowserView::GetWebContents() {
if (web_contents_.IsEmpty()) {
return v8::Null(isolate());
}
return v8::Local<v8::Value>::New(isolate(), web_contents_);
}
// static
void BrowserView::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "BrowserView"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.MakeDestroyable()
.SetMethod("setAutoResize", &BrowserView::SetAutoResize)
.SetMethod("setBounds", &BrowserView::SetBounds)
.SetMethod("setBackgroundColor", &BrowserView::SetBackgroundColor)
.SetProperty("webContents", &BrowserView::GetWebContents)
.SetProperty("id", &BrowserView::ID);
}
} // namespace api
} // namespace atom
namespace {
using atom::api::BrowserView;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
BrowserView::SetConstructor(isolate, base::BindRepeating(&BrowserView::New));
mate::Dictionary browser_view(isolate, BrowserView::GetConstructor(isolate)
->GetFunction(context)
.ToLocalChecked());
browser_view.SetMethod("fromId",
&mate::TrackableObject<BrowserView>::FromWeakMapID);
browser_view.SetMethod("getAllViews",
&mate::TrackableObject<BrowserView>::GetAll);
mate::Dictionary dict(isolate, exports);
dict.Set("BrowserView", browser_view);
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_browser_browser_view, Initialize)

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_BROWSER_API_ATOM_API_BROWSER_VIEW_H_
#define ATOM_BROWSER_API_ATOM_API_BROWSER_VIEW_H_
#include <memory>
#include <string>
#include "atom/browser/api/trackable_object.h"
#include "atom/browser/native_browser_view.h"
#include "content/public/browser/web_contents_observer.h"
#include "native_mate/handle.h"
namespace gfx {
class Rect;
}
namespace mate {
class Arguments;
class Dictionary;
} // namespace mate
namespace atom {
class NativeBrowserView;
namespace api {
class WebContents;
class BrowserView : public mate::TrackableObject<BrowserView>,
public content::WebContentsObserver {
public:
static mate::WrappableBase* New(mate::Arguments* args);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
WebContents* web_contents() const { return api_web_contents_; }
NativeBrowserView* view() const { return view_.get(); }
int32_t ID() const;
protected:
BrowserView(v8::Isolate* isolate,
v8::Local<v8::Object> wrapper,
const mate::Dictionary& options);
~BrowserView() override;
// content::WebContentsObserver:
void WebContentsDestroyed() override;
private:
void Init(v8::Isolate* isolate,
v8::Local<v8::Object> wrapper,
const mate::Dictionary& options);
void SetAutoResize(AutoResizeFlags flags);
void SetBounds(const gfx::Rect& bounds);
void SetBackgroundColor(const std::string& color_name);
v8::Local<v8::Value> GetWebContents();
v8::Global<v8::Value> web_contents_;
class WebContents* api_web_contents_ = nullptr;
std::unique_ptr<NativeBrowserView> view_;
DISALLOW_COPY_AND_ASSIGN(BrowserView);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_BROWSER_VIEW_H_

View file

@ -0,0 +1,479 @@
// 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/browser/api/atom_api_browser_window.h"
#include <memory>
#include "atom/browser/browser.h"
#include "atom/browser/unresponsive_suppressor.h"
#include "atom/browser/web_contents_preferences.h"
#include "atom/browser/window_list.h"
#include "atom/common/api/constructor.h"
#include "atom/common/color_util.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/node_includes.h"
#include "atom/common/options_switches.h"
#include "base/threading/thread_task_runner_handle.h"
#include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck
#include "content/browser/renderer_host/render_widget_host_owner_delegate.h" // nogncheck
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "gin/converter.h"
#include "native_mate/dictionary.h"
#include "ui/gl/gpu_switching_manager.h"
namespace atom {
namespace api {
BrowserWindow::BrowserWindow(v8::Isolate* isolate,
v8::Local<v8::Object> wrapper,
const mate::Dictionary& options)
: TopLevelWindow(isolate, options), weak_factory_(this) {
mate::Handle<class WebContents> web_contents;
// Use options.webPreferences in WebContents.
mate::Dictionary web_preferences = mate::Dictionary::CreateEmpty(isolate);
options.Get(options::kWebPreferences, &web_preferences);
// Copy the backgroundColor to webContents.
v8::Local<v8::Value> value;
if (options.Get(options::kBackgroundColor, &value))
web_preferences.Set(options::kBackgroundColor, value);
v8::Local<v8::Value> transparent;
if (options.Get("transparent", &transparent))
web_preferences.Set("transparent", transparent);
if (options.Get("webContents", &web_contents) && !web_contents.IsEmpty()) {
// Set webPreferences from options if using an existing webContents.
// These preferences will be used when the webContent launches new
// render processes.
auto* existing_preferences =
WebContentsPreferences::From(web_contents->web_contents());
base::DictionaryValue web_preferences_dict;
if (mate::ConvertFromV8(isolate, web_preferences.GetHandle(),
&web_preferences_dict)) {
existing_preferences->Clear();
existing_preferences->Merge(web_preferences_dict);
}
} else {
// Creates the WebContents used by BrowserWindow.
web_contents = WebContents::Create(isolate, web_preferences);
}
web_contents_.Reset(isolate, web_contents.ToV8());
api_web_contents_ = web_contents->GetWeakPtr();
api_web_contents_->AddObserver(this);
Observe(api_web_contents_->web_contents());
// Keep a copy of the options for later use.
mate::Dictionary(isolate, web_contents->GetWrapper())
.Set("browserWindowOptions", options);
// Associate with BrowserWindow.
web_contents->SetOwnerWindow(window());
auto* host = web_contents->web_contents()->GetRenderViewHost();
if (host)
host->GetWidget()->AddInputEventObserver(this);
InitWith(isolate, wrapper);
#if defined(OS_MACOSX)
if (!window()->has_frame())
OverrideNSWindowContentView(web_contents->managed_web_contents());
#endif
// Init window after everything has been setup.
window()->InitFromOptions(options);
}
BrowserWindow::~BrowserWindow() {
// FIXME This is a hack rather than a proper fix preventing shutdown crashes.
if (api_web_contents_)
api_web_contents_->RemoveObserver(this);
// Note that the OnWindowClosed will not be called after the destructor runs,
// since the window object is managed by the TopLevelWindow class.
if (web_contents())
Cleanup();
}
void BrowserWindow::OnInputEvent(const blink::WebInputEvent& event) {
switch (event.GetType()) {
case blink::WebInputEvent::kGestureScrollBegin:
case blink::WebInputEvent::kGestureScrollUpdate:
case blink::WebInputEvent::kGestureScrollEnd:
Emit("scroll-touch-edge");
break;
default:
break;
}
}
void BrowserWindow::RenderViewHostChanged(content::RenderViewHost* old_host,
content::RenderViewHost* new_host) {
if (old_host)
old_host->GetWidget()->RemoveInputEventObserver(this);
if (new_host)
new_host->GetWidget()->AddInputEventObserver(this);
}
void BrowserWindow::RenderViewCreated(
content::RenderViewHost* render_view_host) {
if (!window()->transparent())
return;
content::RenderWidgetHostImpl* impl = content::RenderWidgetHostImpl::FromID(
render_view_host->GetProcess()->GetID(),
render_view_host->GetRoutingID());
if (impl)
impl->owner_delegate()->SetBackgroundOpaque(false);
}
void BrowserWindow::DidFirstVisuallyNonEmptyPaint() {
if (window()->IsVisible())
return;
// When there is a non-empty first paint, resize the RenderWidget to force
// Chromium to draw.
auto* const view = web_contents()->GetRenderWidgetHostView();
view->Show();
view->SetSize(window()->GetContentSize());
// Emit the ReadyToShow event in next tick in case of pending drawing work.
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(
[](base::WeakPtr<BrowserWindow> self) {
if (self)
self->Emit("ready-to-show");
},
GetWeakPtr()));
}
void BrowserWindow::BeforeUnloadDialogCancelled() {
WindowList::WindowCloseCancelled(window());
// Cancel unresponsive event when window close is cancelled.
window_unresponsive_closure_.Cancel();
}
void BrowserWindow::OnRendererUnresponsive(content::RenderProcessHost*) {
// Schedule the unresponsive shortly later, since we may receive the
// responsive event soon. This could happen after the whole application had
// blocked for a while.
// Also notice that when closing this event would be ignored because we have
// explicitly started a close timeout counter. This is on purpose because we
// don't want the unresponsive event to be sent too early when user is closing
// the window.
ScheduleUnresponsiveEvent(50);
}
void BrowserWindow::OnCloseContents() {
// On some machines it may happen that the window gets destroyed for twice,
// checking web_contents() can effectively guard against that.
// https://github.com/electron/electron/issues/16202.
//
// TODO(zcbenz): We should find out the root cause and improve the closing
// procedure of BrowserWindow.
if (!web_contents())
return;
// Close all child windows before closing current window.
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
for (v8::Local<v8::Value> value : child_windows_.Values(isolate())) {
mate::Handle<BrowserWindow> child;
if (mate::ConvertFromV8(isolate(), value, &child) && !child.IsEmpty())
child->window()->CloseImmediately();
}
// When the web contents is gone, close the window immediately, but the
// memory will not be freed until you call delete.
// In this way, it would be safe to manage windows via smart pointers. If you
// want to free memory when the window is closed, you can do deleting by
// overriding the OnWindowClosed method in the observer.
window()->CloseImmediately();
// Do not sent "unresponsive" event after window is closed.
window_unresponsive_closure_.Cancel();
}
void BrowserWindow::OnRendererResponsive() {
window_unresponsive_closure_.Cancel();
Emit("responsive");
}
void BrowserWindow::OnDraggableRegionsUpdated(
const std::vector<mojom::DraggableRegionPtr>& regions) {
UpdateDraggableRegions(regions);
}
void BrowserWindow::RequestPreferredWidth(int* width) {
*width = web_contents()->GetPreferredSize().width();
}
void BrowserWindow::OnCloseButtonClicked(bool* prevent_default) {
// When user tries to close the window by clicking the close button, we do
// not close the window immediately, instead we try to close the web page
// first, and when the web page is closed the window will also be closed.
*prevent_default = true;
// Assume the window is not responding if it doesn't cancel the close and is
// not closed in 5s, in this way we can quickly show the unresponsive
// dialog when the window is busy executing some script withouth waiting for
// the unresponsive timeout.
if (window_unresponsive_closure_.IsCancelled())
ScheduleUnresponsiveEvent(5000);
if (!web_contents())
// Already closed by renderer
return;
if (web_contents()->NeedToFireBeforeUnload())
web_contents()->DispatchBeforeUnload(false /* auto_cancel */);
else
web_contents()->Close();
}
void BrowserWindow::OnWindowClosed() {
Cleanup();
TopLevelWindow::OnWindowClosed();
}
void BrowserWindow::OnWindowBlur() {
web_contents()->StoreFocus();
#if defined(OS_MACOSX)
auto* rwhv = web_contents()->GetRenderWidgetHostView();
if (rwhv)
rwhv->SetActive(false);
#endif
TopLevelWindow::OnWindowBlur();
}
void BrowserWindow::OnWindowFocus() {
web_contents()->RestoreFocus();
#if defined(OS_MACOSX)
auto* rwhv = web_contents()->GetRenderWidgetHostView();
if (rwhv)
rwhv->SetActive(true);
#else
if (!api_web_contents_->IsDevToolsOpened())
web_contents()->Focus();
#endif
TopLevelWindow::OnWindowFocus();
}
void BrowserWindow::OnWindowResize() {
#if defined(OS_MACOSX)
if (!draggable_regions_.empty())
UpdateDraggableRegions(draggable_regions_);
#endif
TopLevelWindow::OnWindowResize();
}
void BrowserWindow::OnWindowLeaveFullScreen() {
TopLevelWindow::OnWindowLeaveFullScreen();
#if defined(OS_MACOSX)
if (web_contents()->IsFullscreenForCurrentTab())
web_contents()->ExitFullscreen(true);
#endif
}
void BrowserWindow::Focus() {
if (api_web_contents_->IsOffScreen())
FocusOnWebView();
else
TopLevelWindow::Focus();
}
void BrowserWindow::Blur() {
if (api_web_contents_->IsOffScreen())
BlurWebView();
else
TopLevelWindow::Blur();
}
void BrowserWindow::SetBackgroundColor(const std::string& color_name) {
TopLevelWindow::SetBackgroundColor(color_name);
auto* view = web_contents()->GetRenderWidgetHostView();
if (view)
view->SetBackgroundColor(ParseHexColor(color_name));
}
void BrowserWindow::SetBrowserView(v8::Local<v8::Value> value) {
TopLevelWindow::ResetBrowserViews();
TopLevelWindow::AddBrowserView(value);
#if defined(OS_MACOSX)
UpdateDraggableRegions(draggable_regions_);
#endif
}
void BrowserWindow::AddBrowserView(v8::Local<v8::Value> value) {
TopLevelWindow::AddBrowserView(value);
#if defined(OS_MACOSX)
UpdateDraggableRegions(draggable_regions_);
#endif
}
void BrowserWindow::RemoveBrowserView(v8::Local<v8::Value> value) {
TopLevelWindow::RemoveBrowserView(value);
#if defined(OS_MACOSX)
UpdateDraggableRegions(draggable_regions_);
#endif
}
void BrowserWindow::ResetBrowserViews() {
TopLevelWindow::ResetBrowserViews();
#if defined(OS_MACOSX)
UpdateDraggableRegions(draggable_regions_);
#endif
}
void BrowserWindow::SetVibrancy(v8::Isolate* isolate,
v8::Local<v8::Value> value) {
std::string type = gin::V8ToString(isolate, value);
auto* render_view_host = web_contents()->GetRenderViewHost();
if (render_view_host) {
auto* impl = content::RenderWidgetHostImpl::FromID(
render_view_host->GetProcess()->GetID(),
render_view_host->GetRoutingID());
if (impl)
impl->owner_delegate()->SetBackgroundOpaque(
type.empty() ? !window_->transparent() : false);
}
TopLevelWindow::SetVibrancy(isolate, value);
}
void BrowserWindow::FocusOnWebView() {
web_contents()->GetRenderViewHost()->GetWidget()->Focus();
}
void BrowserWindow::BlurWebView() {
web_contents()->GetRenderViewHost()->GetWidget()->Blur();
}
bool BrowserWindow::IsWebViewFocused() {
auto* host_view = web_contents()->GetRenderViewHost()->GetWidget()->GetView();
return host_view && host_view->HasFocus();
}
v8::Local<v8::Value> BrowserWindow::GetWebContents(v8::Isolate* isolate) {
if (web_contents_.IsEmpty())
return v8::Null(isolate);
return v8::Local<v8::Value>::New(isolate, web_contents_);
}
// Convert draggable regions in raw format to SkRegion format.
std::unique_ptr<SkRegion> BrowserWindow::DraggableRegionsToSkRegion(
const std::vector<mojom::DraggableRegionPtr>& regions) {
auto sk_region = std::make_unique<SkRegion>();
for (const auto& region : regions) {
sk_region->op(
region->bounds.x(), region->bounds.y(), region->bounds.right(),
region->bounds.bottom(),
region->draggable ? SkRegion::kUnion_Op : SkRegion::kDifference_Op);
}
return sk_region;
}
void BrowserWindow::ScheduleUnresponsiveEvent(int ms) {
if (!window_unresponsive_closure_.IsCancelled())
return;
window_unresponsive_closure_.Reset(base::BindRepeating(
&BrowserWindow::NotifyWindowUnresponsive, GetWeakPtr()));
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE, window_unresponsive_closure_.callback(),
base::TimeDelta::FromMilliseconds(ms));
}
void BrowserWindow::NotifyWindowUnresponsive() {
window_unresponsive_closure_.Cancel();
if (!window_->IsClosed() && window_->IsEnabled() &&
!IsUnresponsiveEventSuppressed()) {
Emit("unresponsive");
}
}
void BrowserWindow::Cleanup() {
auto* host = web_contents()->GetRenderViewHost();
if (host)
host->GetWidget()->RemoveInputEventObserver(this);
// Destroy WebContents asynchronously unless app is shutting down,
// because destroy() might be called inside WebContents's event handler.
api_web_contents_->DestroyWebContents(!Browser::Get()->is_shutting_down());
Observe(nullptr);
}
// static
mate::WrappableBase* BrowserWindow::New(mate::Arguments* args) {
if (!Browser::Get()->is_ready()) {
args->ThrowError("Cannot create BrowserWindow before app is ready");
return nullptr;
}
if (args->Length() > 1) {
args->ThrowError();
return nullptr;
}
mate::Dictionary options;
if (!(args->Length() == 1 && args->GetNext(&options))) {
options = mate::Dictionary::CreateEmpty(args->isolate());
}
return new BrowserWindow(args->isolate(), args->GetThis(), options);
}
// static
void BrowserWindow::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "BrowserWindow"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.SetMethod("focusOnWebView", &BrowserWindow::FocusOnWebView)
.SetMethod("blurWebView", &BrowserWindow::BlurWebView)
.SetMethod("isWebViewFocused", &BrowserWindow::IsWebViewFocused)
.SetProperty("webContents", &BrowserWindow::GetWebContents);
}
// static
v8::Local<v8::Value> BrowserWindow::From(v8::Isolate* isolate,
NativeWindow* native_window) {
auto* existing = TrackableObject::FromWrappedClass(isolate, native_window);
if (existing)
return existing->GetWrapper();
else
return v8::Null(isolate);
}
} // namespace api
} // namespace atom
namespace {
using atom::api::BrowserWindow;
using atom::api::TopLevelWindow;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
mate::Dictionary dict(isolate, exports);
dict.Set("BrowserWindow",
mate::CreateConstructor<BrowserWindow>(
isolate, base::BindRepeating(&BrowserWindow::New)));
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_browser_window, Initialize)

View file

@ -0,0 +1,130 @@
// 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_BROWSER_API_ATOM_API_BROWSER_WINDOW_H_
#define ATOM_BROWSER_API_ATOM_API_BROWSER_WINDOW_H_
#include <memory>
#include <string>
#include <vector>
#include "atom/browser/api/atom_api_top_level_window.h"
#include "atom/browser/api/atom_api_web_contents.h"
#include "base/cancelable_callback.h"
namespace atom {
namespace api {
class BrowserWindow : public TopLevelWindow,
public content::RenderWidgetHost::InputEventObserver,
public content::WebContentsObserver,
public ExtendedWebContentsObserver {
public:
static mate::WrappableBase* New(mate::Arguments* args);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
// Returns the BrowserWindow object from |native_window|.
static v8::Local<v8::Value> From(v8::Isolate* isolate,
NativeWindow* native_window);
base::WeakPtr<BrowserWindow> GetWeakPtr() {
return weak_factory_.GetWeakPtr();
}
protected:
BrowserWindow(v8::Isolate* isolate,
v8::Local<v8::Object> wrapper,
const mate::Dictionary& options);
~BrowserWindow() override;
// content::RenderWidgetHost::InputEventObserver:
void OnInputEvent(const blink::WebInputEvent& event) override;
// content::WebContentsObserver:
void RenderViewHostChanged(content::RenderViewHost* old_host,
content::RenderViewHost* new_host) override;
void RenderViewCreated(content::RenderViewHost* render_view_host) override;
void DidFirstVisuallyNonEmptyPaint() override;
void BeforeUnloadDialogCancelled() override;
void OnRendererUnresponsive(content::RenderProcessHost*) override;
// ExtendedWebContentsObserver:
void OnCloseContents() override;
void OnRendererResponsive() override;
void OnDraggableRegionsUpdated(
const std::vector<mojom::DraggableRegionPtr>& regions) override;
// NativeWindowObserver:
void RequestPreferredWidth(int* width) override;
void OnCloseButtonClicked(bool* prevent_default) override;
// TopLevelWindow:
void OnWindowClosed() override;
void OnWindowBlur() override;
void OnWindowFocus() override;
void OnWindowResize() override;
void OnWindowLeaveFullScreen() override;
void Focus() override;
void Blur() override;
void SetBackgroundColor(const std::string& color_name) override;
void SetBrowserView(v8::Local<v8::Value> value) override;
void AddBrowserView(v8::Local<v8::Value> value) override;
void RemoveBrowserView(v8::Local<v8::Value> value) override;
void ResetBrowserViews() override;
void SetVibrancy(v8::Isolate* isolate, v8::Local<v8::Value> value) override;
// BrowserWindow APIs.
void FocusOnWebView();
void BlurWebView();
bool IsWebViewFocused();
v8::Local<v8::Value> GetWebContents(v8::Isolate* isolate);
private:
#if defined(OS_MACOSX)
void OverrideNSWindowContentView(InspectableWebContents* iwc);
#endif
// Helpers.
// Called when the window needs to update its draggable region.
void UpdateDraggableRegions(
const std::vector<mojom::DraggableRegionPtr>& regions);
// Convert draggable regions in raw format to SkRegion format.
std::unique_ptr<SkRegion> DraggableRegionsToSkRegion(
const std::vector<mojom::DraggableRegionPtr>& regions);
// Schedule a notification unresponsive event.
void ScheduleUnresponsiveEvent(int ms);
// Dispatch unresponsive event to observers.
void NotifyWindowUnresponsive();
// Cleanup our WebContents observers.
void Cleanup();
// Closure that would be called when window is unresponsive when closing,
// it should be cancelled when we can prove that the window is responsive.
base::CancelableClosure window_unresponsive_closure_;
#if defined(OS_MACOSX)
std::vector<mojom::DraggableRegionPtr> draggable_regions_;
#endif
v8::Global<v8::Value> web_contents_;
base::WeakPtr<api::WebContents> api_web_contents_;
base::WeakPtrFactory<BrowserWindow> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(BrowserWindow);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_BROWSER_WINDOW_H_

View file

@ -0,0 +1,140 @@
// 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/browser/api/atom_api_browser_window.h"
#include <memory>
#include <vector>
#import <Cocoa/Cocoa.h>
#include "atom/browser/native_browser_view.h"
#include "atom/browser/native_window_mac.h"
#include "atom/browser/ui/inspectable_web_contents_view.h"
#include "base/mac/scoped_nsobject.h"
@interface NSView (WebContentsView)
- (void)setMouseDownCanMoveWindow:(BOOL)can_move;
@end
@interface ControlRegionView : NSView
@end
@implementation ControlRegionView
- (BOOL)mouseDownCanMoveWindow {
return NO;
}
- (NSView*)hitTest:(NSPoint)aPoint {
return nil;
}
@end
namespace atom {
namespace api {
namespace {
// Return a vector of non-draggable regions that fill a window of size
// |width| by |height|, but leave gaps where the window should be draggable.
std::vector<gfx::Rect> CalculateNonDraggableRegions(
std::unique_ptr<SkRegion> draggable,
int width,
int height) {
std::vector<gfx::Rect> result;
SkRegion non_draggable;
non_draggable.op(0, 0, width, height, SkRegion::kUnion_Op);
non_draggable.op(*draggable, SkRegion::kDifference_Op);
for (SkRegion::Iterator it(non_draggable); !it.done(); it.next()) {
result.push_back(gfx::SkIRectToRect(it.rect()));
}
return result;
}
} // namespace
void BrowserWindow::OverrideNSWindowContentView(InspectableWebContents* iwc) {
// Make NativeWindow use a NSView as content view.
static_cast<NativeWindowMac*>(window())->OverrideNSWindowContentView();
// Add webview to contentView.
NSView* webView = iwc->GetView()->GetNativeView().GetNativeNSView();
NSView* contentView =
[window()->GetNativeWindow().GetNativeNSWindow() contentView];
[webView setFrame:[contentView bounds]];
// ensure that buttons view is floated to top of view hierarchy
NSArray* subviews = [contentView subviews];
NSView* last = subviews.lastObject;
[contentView addSubview:webView positioned:NSWindowBelow relativeTo:last];
[contentView viewDidMoveToWindow];
}
void BrowserWindow::UpdateDraggableRegions(
const std::vector<mojom::DraggableRegionPtr>& regions) {
if (window_->has_frame())
return;
// All ControlRegionViews should be added as children of the WebContentsView,
// because WebContentsView will be removed and re-added when entering and
// leaving fullscreen mode.
NSView* webView = web_contents()->GetNativeView().GetNativeNSView();
NSInteger webViewWidth = NSWidth([webView bounds]);
NSInteger webViewHeight = NSHeight([webView bounds]);
if ([webView respondsToSelector:@selector(setMouseDownCanMoveWindow:)]) {
[webView setMouseDownCanMoveWindow:YES];
}
// Remove all ControlRegionViews that are added last time.
// Note that [webView subviews] returns the view's mutable internal array and
// it should be copied to avoid mutating the original array while enumerating
// it.
base::scoped_nsobject<NSArray> subviews([[webView subviews] copy]);
for (NSView* subview in subviews.get())
if ([subview isKindOfClass:[ControlRegionView class]])
[subview removeFromSuperview];
// Draggable regions is implemented by having the whole web view draggable
// (mouseDownCanMoveWindow) and overlaying regions that are not draggable.
draggable_regions_.clear();
for (const auto& r : regions)
draggable_regions_.push_back(r.Clone());
std::vector<gfx::Rect> drag_exclude_rects;
if (regions.empty()) {
drag_exclude_rects.push_back(gfx::Rect(0, 0, webViewWidth, webViewHeight));
} else {
drag_exclude_rects = CalculateNonDraggableRegions(
DraggableRegionsToSkRegion(regions), webViewWidth, webViewHeight);
}
auto browser_views = window_->browser_views();
for (NativeBrowserView* view : browser_views) {
view->UpdateDraggableRegions(drag_exclude_rects);
}
// Create and add a ControlRegionView for each region that needs to be
// excluded from the dragging.
for (const auto& rect : drag_exclude_rects) {
base::scoped_nsobject<NSView> controlRegion(
[[ControlRegionView alloc] initWithFrame:NSZeroRect]);
[controlRegion setFrame:NSMakeRect(rect.x(), webViewHeight - rect.bottom(),
rect.width(), rect.height())];
[webView addSubview:controlRegion];
}
// AppKit will not update its cache of mouseDownCanMoveWindow unless something
// changes. Previously we tried adding an NSView and removing it, but for some
// reason it required reposting the mouse-down event, and didn't always work.
// Calling the below seems to be an effective solution.
[[webView window] setMovableByWindowBackground:NO];
[[webView window] setMovableByWindowBackground:YES];
}
} // namespace api
} // namespace atom

View file

@ -0,0 +1,23 @@
// 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/browser/api/atom_api_browser_window.h"
#include "atom/browser/native_window_views.h"
namespace atom {
namespace api {
void BrowserWindow::UpdateDraggableRegions(
const std::vector<mojom::DraggableRegionPtr>& regions) {
if (window_->has_frame())
return;
static_cast<NativeWindowViews*>(window_.get())
->UpdateDraggableRegions(DraggableRegionsToSkRegion(regions));
}
} // namespace api
} // namespace atom

View file

@ -0,0 +1,162 @@
// 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 <set>
#include <string>
#include <utility>
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/node_includes.h"
#include "atom/common/promise_util.h"
#include "base/bind.h"
#include "base/files/file_util.h"
#include "base/optional.h"
#include "base/threading/thread_restrictions.h"
#include "content/public/browser/tracing_controller.h"
#include "native_mate/dictionary.h"
using content::TracingController;
namespace mate {
template <>
struct Converter<base::trace_event::TraceConfig> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
base::trace_event::TraceConfig* out) {
// (alexeykuzmin): A combination of "categoryFilter" and "traceOptions"
// has to be checked first because none of the fields
// in the `memory_dump_config` dict below are mandatory
// and we cannot check the config format.
Dictionary options;
if (ConvertFromV8(isolate, val, &options)) {
std::string category_filter, trace_options;
if (options.Get("categoryFilter", &category_filter) &&
options.Get("traceOptions", &trace_options)) {
*out = base::trace_event::TraceConfig(category_filter, trace_options);
return true;
}
}
base::DictionaryValue memory_dump_config;
if (ConvertFromV8(isolate, val, &memory_dump_config)) {
*out = base::trace_event::TraceConfig(memory_dump_config);
return true;
}
return false;
}
};
} // namespace mate
namespace {
using CompletionCallback = base::OnceCallback<void(const base::FilePath&)>;
base::Optional<base::FilePath> CreateTemporaryFileOnIO() {
base::FilePath temp_file_path;
if (!base::CreateTemporaryFile(&temp_file_path))
return base::nullopt;
return base::make_optional(std::move(temp_file_path));
}
void StopTracing(atom::util::Promise promise,
base::Optional<base::FilePath> file_path) {
if (file_path) {
auto endpoint = TracingController::CreateFileEndpoint(
*file_path, base::AdaptCallbackForRepeating(base::BindOnce(
&atom::util::Promise::ResolvePromise<base::FilePath>,
std::move(promise), *file_path)));
TracingController::GetInstance()->StopTracing(endpoint);
} else {
promise.RejectWithErrorMessage(
"Failed to create temporary file for trace data");
}
}
v8::Local<v8::Promise> StopRecording(mate::Arguments* args) {
atom::util::Promise promise(args->isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
base::FilePath path;
if (args->GetNext(&path) && !path.empty()) {
StopTracing(std::move(promise), base::make_optional(path));
} else {
// use a temporary file.
base::PostTaskWithTraitsAndReplyWithResult(
FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE},
base::BindOnce(CreateTemporaryFileOnIO),
base::BindOnce(StopTracing, std::move(promise)));
}
return handle;
}
v8::Local<v8::Promise> GetCategories(v8::Isolate* isolate) {
atom::util::Promise promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
// Note: This method always succeeds.
TracingController::GetInstance()->GetCategories(base::BindOnce(
atom::util::Promise::ResolvePromise<const std::set<std::string>&>,
std::move(promise)));
return handle;
}
v8::Local<v8::Promise> StartTracing(
v8::Isolate* isolate,
const base::trace_event::TraceConfig& trace_config) {
atom::util::Promise promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
if (!TracingController::GetInstance()->StartTracing(
trace_config, base::BindOnce(atom::util::Promise::ResolveEmptyPromise,
std::move(promise)))) {
// If StartTracing returns false, that means it didn't invoke its callback.
// Return an already-resolved promise and abandon the previous promise (it
// was std::move()d into the StartTracing callback and has been deleted by
// this point).
return atom::util::Promise::ResolvedPromise(isolate);
}
return handle;
}
void OnTraceBufferUsageAvailable(atom::util::Promise promise,
float percent_full,
size_t approximate_count) {
mate::Dictionary dict = mate::Dictionary::CreateEmpty(promise.isolate());
dict.Set("percentage", percent_full);
dict.Set("value", approximate_count);
promise.Resolve(dict.GetHandle());
}
v8::Local<v8::Promise> GetTraceBufferUsage(v8::Isolate* isolate) {
atom::util::Promise promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
// Note: This method always succeeds.
TracingController::GetInstance()->GetTraceBufferUsage(
base::BindOnce(&OnTraceBufferUsageAvailable, std::move(promise)));
return handle;
}
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.SetMethod("getCategories", &GetCategories);
dict.SetMethod("startRecording", &StartTracing);
dict.SetMethod("stopRecording", &StopRecording);
dict.SetMethod("getTraceBufferUsage", &GetTraceBufferUsage);
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_browser_content_tracing, Initialize)

View file

@ -0,0 +1,346 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/api/atom_api_cookies.h"
#include <memory>
#include <utility>
#include "atom/browser/atom_browser_context.h"
#include "atom/browser/cookie_change_notifier.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/gurl_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "base/time/time.h"
#include "base/values.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/storage_partition.h"
#include "gin/dictionary.h"
#include "gin/object_template_builder.h"
#include "net/cookies/canonical_cookie.h"
#include "net/cookies/cookie_store.h"
#include "net/cookies/cookie_util.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
using content::BrowserThread;
namespace gin {
template <>
struct Converter<net::CanonicalCookie> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
const net::CanonicalCookie& val) {
gin::Dictionary dict(isolate, v8::Object::New(isolate));
dict.Set("name", val.Name());
dict.Set("value", val.Value());
dict.Set("domain", val.Domain());
dict.Set("hostOnly", net::cookie_util::DomainIsHostOnly(val.Domain()));
dict.Set("path", val.Path());
dict.Set("secure", val.IsSecure());
dict.Set("httpOnly", val.IsHttpOnly());
dict.Set("session", !val.IsPersistent());
if (val.IsPersistent())
dict.Set("expirationDate", val.ExpiryDate().ToDoubleT());
return ConvertToV8(isolate, dict).As<v8::Object>();
}
};
template <>
struct Converter<network::mojom::CookieChangeCause> {
static v8::Local<v8::Value> ToV8(
v8::Isolate* isolate,
const network::mojom::CookieChangeCause& val) {
switch (val) {
case network::mojom::CookieChangeCause::INSERTED:
case network::mojom::CookieChangeCause::EXPLICIT:
return gin::StringToV8(isolate, "explicit");
case network::mojom::CookieChangeCause::OVERWRITE:
return gin::StringToV8(isolate, "overwrite");
case network::mojom::CookieChangeCause::EXPIRED:
return gin::StringToV8(isolate, "expired");
case network::mojom::CookieChangeCause::EVICTED:
return gin::StringToV8(isolate, "evicted");
case network::mojom::CookieChangeCause::EXPIRED_OVERWRITE:
return gin::StringToV8(isolate, "expired-overwrite");
default:
return gin::StringToV8(isolate, "unknown");
}
}
};
} // namespace gin
namespace atom {
namespace api {
namespace {
// Returns whether |domain| matches |filter|.
bool MatchesDomain(std::string filter, const std::string& domain) {
// Add a leading '.' character to the filter domain if it doesn't exist.
if (net::cookie_util::DomainIsHostOnly(filter))
filter.insert(0, ".");
std::string sub_domain(domain);
// Strip any leading '.' character from the input cookie domain.
if (!net::cookie_util::DomainIsHostOnly(sub_domain))
sub_domain = sub_domain.substr(1);
// Now check whether the domain argument is a subdomain of the filter domain.
for (sub_domain.insert(0, "."); sub_domain.length() >= filter.length();) {
if (sub_domain == filter)
return true;
const size_t next_dot = sub_domain.find('.', 1); // Skip over leading dot.
sub_domain.erase(0, next_dot);
}
return false;
}
// Returns whether |cookie| matches |filter|.
bool MatchesCookie(const base::Value& filter,
const net::CanonicalCookie& cookie) {
const std::string* str;
if ((str = filter.FindStringKey("name")) && *str != cookie.Name())
return false;
if ((str = filter.FindStringKey("path")) && *str != cookie.Path())
return false;
if ((str = filter.FindStringKey("domain")) &&
!MatchesDomain(*str, cookie.Domain()))
return false;
base::Optional<bool> secure_filter = filter.FindBoolKey("secure");
if (secure_filter && *secure_filter == cookie.IsSecure())
return false;
base::Optional<bool> session_filter = filter.FindBoolKey("session");
if (session_filter && *session_filter != !cookie.IsPersistent())
return false;
return true;
}
// Remove cookies from |list| not matching |filter|, and pass it to |callback|.
void FilterCookies(const base::Value& filter,
util::Promise promise,
const net::CookieList& list,
const net::CookieStatusList& excluded_list) {
net::CookieList result;
for (const auto& cookie : list) {
if (MatchesCookie(filter, cookie))
result.push_back(cookie);
}
promise.Resolve(gin::ConvertToV8(promise.isolate(), result));
}
std::string InclusionStatusToString(
net::CanonicalCookie::CookieInclusionStatus status) {
switch (status) {
case net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_HTTP_ONLY:
return "Failed to create httponly cookie";
case net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_SECURE_ONLY:
return "Cannot create a secure cookie from an insecure URL";
case net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_FAILURE_TO_STORE:
return "Failed to parse cookie";
case net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_INVALID_DOMAIN:
return "Failed to get cookie domain";
case net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_INVALID_PREFIX:
return "Failed because the cookie violated prefix rules.";
case net::CanonicalCookie::CookieInclusionStatus::
EXCLUDE_NONCOOKIEABLE_SCHEME:
return "Cannot set cookie for current scheme";
case net::CanonicalCookie::CookieInclusionStatus::INCLUDE:
return "";
default:
return "Setting cookie failed";
}
}
} // namespace
Cookies::Cookies(v8::Isolate* isolate, AtomBrowserContext* browser_context)
: browser_context_(browser_context) {
Init(isolate);
cookie_change_subscription_ =
browser_context_->cookie_change_notifier()->RegisterCookieChangeCallback(
base::BindRepeating(&Cookies::OnCookieChanged,
base::Unretained(this)));
}
Cookies::~Cookies() {}
v8::Local<v8::Promise> Cookies::Get(const base::DictionaryValue& filter) {
util::Promise promise(isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
std::string url_string;
filter.GetString("url", &url_string);
GURL url(url_string);
auto callback =
base::BindOnce(FilterCookies, filter.Clone(), std::move(promise));
auto* storage_partition = content::BrowserContext::GetDefaultStoragePartition(
browser_context_.get());
auto* manager = storage_partition->GetCookieManagerForBrowserProcess();
if (url.is_empty()) {
// GetAllCookies has a different callback signature than GetCookieList, but
// can be treated as the same, just returning no excluded cookies.
// |AddCookieStatusList| takes a |GetCookieListCallback| and returns a
// callback that calls the input callback with an empty excluded list.
manager->GetAllCookies(
net::cookie_util::AddCookieStatusList(std::move(callback)));
} else {
net::CookieOptions options;
options.set_include_httponly();
options.set_same_site_cookie_context(
net::CookieOptions::SameSiteCookieContext::SAME_SITE_STRICT);
options.set_do_not_update_access_time();
manager->GetCookieList(url, options, std::move(callback));
}
return handle;
}
v8::Local<v8::Promise> Cookies::Remove(const GURL& url,
const std::string& name) {
util::Promise promise(isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
auto cookie_deletion_filter = network::mojom::CookieDeletionFilter::New();
cookie_deletion_filter->url = url;
cookie_deletion_filter->cookie_name = name;
auto* storage_partition = content::BrowserContext::GetDefaultStoragePartition(
browser_context_.get());
auto* manager = storage_partition->GetCookieManagerForBrowserProcess();
manager->DeleteCookies(
std::move(cookie_deletion_filter),
base::BindOnce(
[](util::Promise promise, uint32_t num_deleted) {
util::Promise::ResolveEmptyPromise(std::move(promise));
},
std::move(promise)));
return handle;
}
v8::Local<v8::Promise> Cookies::Set(const base::DictionaryValue& details) {
util::Promise promise(isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
const std::string* url_string = details.FindStringKey("url");
const std::string* name = details.FindStringKey("name");
const std::string* value = details.FindStringKey("value");
const std::string* domain = details.FindStringKey("domain");
const std::string* path = details.FindStringKey("path");
bool secure = details.FindBoolKey("secure").value_or(false);
bool http_only = details.FindBoolKey("httpOnly").value_or(false);
base::Optional<double> creation_date = details.FindDoubleKey("creationDate");
base::Optional<double> expiration_date =
details.FindDoubleKey("expirationDate");
base::Optional<double> last_access_date =
details.FindDoubleKey("lastAccessDate");
base::Time creation_time = creation_date
? base::Time::FromDoubleT(*creation_date)
: base::Time::UnixEpoch();
base::Time expiration_time = expiration_date
? base::Time::FromDoubleT(*expiration_date)
: base::Time::UnixEpoch();
base::Time last_access_time = last_access_date
? base::Time::FromDoubleT(*last_access_date)
: base::Time::UnixEpoch();
GURL url(url_string ? *url_string : "");
if (!url.is_valid()) {
promise.RejectWithErrorMessage(InclusionStatusToString(
net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_INVALID_DOMAIN));
return handle;
}
if (!name || name->empty()) {
promise.RejectWithErrorMessage(InclusionStatusToString(
net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_FAILURE_TO_STORE));
return handle;
}
auto canonical_cookie = net::CanonicalCookie::CreateSanitizedCookie(
url, *name, value ? *value : "", domain ? *domain : "", path ? *path : "",
creation_time, expiration_time, last_access_time, secure, http_only,
net::CookieSameSite::NO_RESTRICTION, net::COOKIE_PRIORITY_DEFAULT);
if (!canonical_cookie || !canonical_cookie->IsCanonical()) {
promise.RejectWithErrorMessage(InclusionStatusToString(
net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_FAILURE_TO_STORE));
return handle;
}
net::CookieOptions options;
if (http_only) {
options.set_include_httponly();
}
auto* storage_partition = content::BrowserContext::GetDefaultStoragePartition(
browser_context_.get());
auto* manager = storage_partition->GetCookieManagerForBrowserProcess();
manager->SetCanonicalCookie(
*canonical_cookie, url.scheme(), options,
base::BindOnce(
[](util::Promise promise,
net::CanonicalCookie::CookieInclusionStatus status) {
auto errmsg = InclusionStatusToString(status);
if (errmsg.empty()) {
promise.Resolve();
} else {
promise.RejectWithErrorMessage(errmsg);
}
},
std::move(promise)));
return handle;
}
v8::Local<v8::Promise> Cookies::FlushStore() {
util::Promise promise(isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
auto* storage_partition = content::BrowserContext::GetDefaultStoragePartition(
browser_context_.get());
auto* manager = storage_partition->GetCookieManagerForBrowserProcess();
manager->FlushCookieStore(
base::BindOnce(util::Promise::ResolveEmptyPromise, std::move(promise)));
return handle;
}
void Cookies::OnCookieChanged(const CookieDetails* details) {
Emit("changed", gin::ConvertToV8(isolate(), *(details->cookie)),
gin::ConvertToV8(isolate(), details->cause),
gin::ConvertToV8(isolate(), details->removed));
}
// static
gin::Handle<Cookies> Cookies::Create(v8::Isolate* isolate,
AtomBrowserContext* browser_context) {
return gin::CreateHandle(isolate, new Cookies(isolate, browser_context));
}
// static
void Cookies::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(gin::StringToV8(isolate, "Cookies"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.SetMethod("get", &Cookies::Get)
.SetMethod("remove", &Cookies::Remove)
.SetMethod("set", &Cookies::Set)
.SetMethod("flushStore", &Cookies::FlushStore);
}
} // namespace api
} // namespace atom

View file

@ -0,0 +1,65 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_BROWSER_API_ATOM_API_COOKIES_H_
#define ATOM_BROWSER_API_ATOM_API_COOKIES_H_
#include <memory>
#include <string>
#include "atom/browser/api/trackable_object.h"
#include "atom/browser/net/cookie_details.h"
#include "atom/common/promise_util.h"
#include "base/callback_list.h"
#include "gin/handle.h"
#include "net/cookies/canonical_cookie.h"
namespace base {
class DictionaryValue;
}
namespace net {
class URLRequestContextGetter;
}
namespace atom {
class AtomBrowserContext;
namespace api {
class Cookies : public mate::TrackableObject<Cookies> {
public:
static gin::Handle<Cookies> Create(v8::Isolate* isolate,
AtomBrowserContext* browser_context);
// mate::TrackableObject:
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
protected:
Cookies(v8::Isolate* isolate, AtomBrowserContext* browser_context);
~Cookies() override;
v8::Local<v8::Promise> Get(const base::DictionaryValue& filter);
v8::Local<v8::Promise> Set(const base::DictionaryValue& details);
v8::Local<v8::Promise> Remove(const GURL& url, const std::string& name);
v8::Local<v8::Promise> FlushStore();
// CookieChangeNotifier subscription:
void OnCookieChanged(const CookieDetails*);
private:
std::unique_ptr<base::CallbackList<void(const CookieDetails*)>::Subscription>
cookie_change_subscription_;
scoped_refptr<AtomBrowserContext> browser_context_;
DISALLOW_COPY_AND_ASSIGN(Cookies);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_COOKIES_H_

View file

@ -0,0 +1,208 @@
// 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/browser/api/atom_api_debugger.h"
#include <memory>
#include <string>
#include <utility>
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/node_includes.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "content/public/browser/devtools_agent_host.h"
#include "content/public/browser/web_contents.h"
#include "native_mate/dictionary.h"
using content::DevToolsAgentHost;
namespace atom {
namespace api {
Debugger::Debugger(v8::Isolate* isolate, content::WebContents* web_contents)
: content::WebContentsObserver(web_contents), web_contents_(web_contents) {
Init(isolate);
}
Debugger::~Debugger() {}
void Debugger::AgentHostClosed(DevToolsAgentHost* agent_host) {
DCHECK(agent_host == agent_host_);
agent_host_ = nullptr;
ClearPendingRequests();
Emit("detach", "target closed");
}
void Debugger::DispatchProtocolMessage(DevToolsAgentHost* agent_host,
const std::string& message) {
DCHECK(agent_host == agent_host_);
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
std::unique_ptr<base::Value> parsed_message =
base::JSONReader::ReadDeprecated(message);
if (!parsed_message || !parsed_message->is_dict())
return;
base::DictionaryValue* dict =
static_cast<base::DictionaryValue*>(parsed_message.get());
int id;
if (!dict->GetInteger("id", &id)) {
std::string method;
if (!dict->GetString("method", &method))
return;
base::DictionaryValue* params_value = nullptr;
base::DictionaryValue params;
if (dict->GetDictionary("params", &params_value))
params.Swap(params_value);
Emit("message", method, params);
} else {
auto it = pending_requests_.find(id);
if (it == pending_requests_.end())
return;
atom::util::Promise promise = std::move(it->second);
pending_requests_.erase(it);
base::DictionaryValue* error = nullptr;
if (dict->GetDictionary("error", &error)) {
std::string message;
error->GetString("message", &message);
promise.RejectWithErrorMessage(message);
} else {
base::DictionaryValue* result_body = nullptr;
base::DictionaryValue result;
if (dict->GetDictionary("result", &result_body)) {
result.Swap(result_body);
}
promise.Resolve(result);
}
}
}
void Debugger::RenderFrameHostChanged(content::RenderFrameHost* old_rfh,
content::RenderFrameHost* new_rfh) {
if (agent_host_) {
agent_host_->DisconnectWebContents();
auto* web_contents = content::WebContents::FromRenderFrameHost(new_rfh);
agent_host_->ConnectWebContents(web_contents);
}
}
void Debugger::Attach(mate::Arguments* args) {
std::string protocol_version;
args->GetNext(&protocol_version);
if (agent_host_) {
args->ThrowError("Debugger is already attached to the target");
return;
}
if (!protocol_version.empty() &&
!DevToolsAgentHost::IsSupportedProtocolVersion(protocol_version)) {
args->ThrowError("Requested protocol version is not supported");
return;
}
agent_host_ = DevToolsAgentHost::GetOrCreateFor(web_contents_);
if (!agent_host_) {
args->ThrowError("No target available");
return;
}
agent_host_->AttachClient(this);
}
bool Debugger::IsAttached() {
return agent_host_ && agent_host_->IsAttached();
}
void Debugger::Detach() {
if (!agent_host_)
return;
agent_host_->DetachClient(this);
AgentHostClosed(agent_host_.get());
}
v8::Local<v8::Promise> Debugger::SendCommand(mate::Arguments* args) {
atom::util::Promise promise(isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
if (!agent_host_) {
promise.RejectWithErrorMessage("No target available");
return handle;
}
std::string method;
if (!args->GetNext(&method)) {
promise.RejectWithErrorMessage("Invalid method");
return handle;
}
base::DictionaryValue command_params;
args->GetNext(&command_params);
base::DictionaryValue request;
int request_id = ++previous_request_id_;
pending_requests_.emplace(request_id, std::move(promise));
request.SetInteger("id", request_id);
request.SetString("method", method);
if (!command_params.empty())
request.Set("params",
base::Value::ToUniquePtrValue(command_params.Clone()));
std::string json_args;
base::JSONWriter::Write(request, &json_args);
agent_host_->DispatchProtocolMessage(this, json_args);
return handle;
}
void Debugger::ClearPendingRequests() {
for (auto& it : pending_requests_)
it.second.RejectWithErrorMessage("target closed while handling command");
}
// static
mate::Handle<Debugger> Debugger::Create(v8::Isolate* isolate,
content::WebContents* web_contents) {
return mate::CreateHandle(isolate, new Debugger(isolate, web_contents));
}
// static
void Debugger::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "Debugger"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.SetMethod("attach", &Debugger::Attach)
.SetMethod("isAttached", &Debugger::IsAttached)
.SetMethod("detach", &Debugger::Detach)
.SetMethod("sendCommand", &Debugger::SendCommand);
}
} // namespace api
} // namespace atom
namespace {
using atom::api::Debugger;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
mate::Dictionary(isolate, exports)
.Set("Debugger", Debugger::GetConstructor(isolate)
->GetFunction(context)
.ToLocalChecked());
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_browser_debugger, Initialize)

View file

@ -0,0 +1,78 @@
// 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_BROWSER_API_ATOM_API_DEBUGGER_H_
#define ATOM_BROWSER_API_ATOM_API_DEBUGGER_H_
#include <map>
#include <string>
#include "atom/browser/api/trackable_object.h"
#include "atom/common/promise_util.h"
#include "base/callback.h"
#include "base/values.h"
#include "content/public/browser/devtools_agent_host_client.h"
#include "content/public/browser/web_contents_observer.h"
#include "native_mate/handle.h"
namespace content {
class DevToolsAgentHost;
class WebContents;
} // namespace content
namespace mate {
class Arguments;
}
namespace atom {
namespace api {
class Debugger : public mate::TrackableObject<Debugger>,
public content::DevToolsAgentHostClient,
public content::WebContentsObserver {
public:
static mate::Handle<Debugger> Create(v8::Isolate* isolate,
content::WebContents* web_contents);
// mate::TrackableObject:
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
protected:
Debugger(v8::Isolate* isolate, content::WebContents* web_contents);
~Debugger() override;
// content::DevToolsAgentHostClient:
void AgentHostClosed(content::DevToolsAgentHost* agent_host) override;
void DispatchProtocolMessage(content::DevToolsAgentHost* agent_host,
const std::string& message) override;
// content::WebContentsObserver:
void RenderFrameHostChanged(content::RenderFrameHost* old_rfh,
content::RenderFrameHost* new_rfh) override;
private:
using PendingRequestMap = std::map<int, atom::util::Promise>;
void Attach(mate::Arguments* args);
bool IsAttached();
void Detach();
v8::Local<v8::Promise> SendCommand(mate::Arguments* args);
void ClearPendingRequests();
content::WebContents* web_contents_; // Weak Reference.
scoped_refptr<content::DevToolsAgentHost> agent_host_;
PendingRequestMap pending_requests_;
int previous_request_id_ = 0;
DISALLOW_COPY_AND_ASSIGN(Debugger);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_DEBUGGER_H_

View file

@ -0,0 +1,234 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/api/atom_api_desktop_capturer.h"
#include <memory>
#include <utility>
#include <vector>
#include "atom/common/api/atom_api_native_image.h"
#include "atom/common/native_mate_converters/gfx_converter.h"
#include "atom/common/node_includes.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_restrictions.h"
#include "chrome/browser/media/webrtc/desktop_media_list.h"
#include "chrome/browser/media/webrtc/window_icon_util.h"
#include "content/public/browser/desktop_capture.h"
#include "native_mate/dictionary.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_capture_options.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_capturer.h"
#if defined(OS_WIN)
#include "third_party/webrtc/modules/desktop_capture/win/dxgi_duplicator_controller.h"
#include "third_party/webrtc/modules/desktop_capture/win/screen_capturer_win_directx.h"
#include "ui/display/win/display_info.h"
#endif // defined(OS_WIN)
namespace mate {
template <>
struct Converter<atom::api::DesktopCapturer::Source> {
static v8::Local<v8::Value> ToV8(
v8::Isolate* isolate,
const atom::api::DesktopCapturer::Source& source) {
mate::Dictionary dict(isolate, v8::Object::New(isolate));
content::DesktopMediaID id = source.media_list_source.id;
dict.Set("name", base::UTF16ToUTF8(source.media_list_source.name));
dict.Set("id", id.ToString());
dict.Set("thumbnail",
atom::api::NativeImage::Create(
isolate, gfx::Image(source.media_list_source.thumbnail)));
dict.Set("display_id", source.display_id);
if (source.fetch_icon) {
dict.Set(
"appIcon",
atom::api::NativeImage::Create(
isolate, gfx::Image(GetWindowIcon(source.media_list_source.id))));
}
return ConvertToV8(isolate, dict);
}
};
} // namespace mate
namespace atom {
namespace api {
DesktopCapturer::DesktopCapturer(v8::Isolate* isolate) {
Init(isolate);
}
DesktopCapturer::~DesktopCapturer() {}
void DesktopCapturer::StartHandling(bool capture_window,
bool capture_screen,
const gfx::Size& thumbnail_size,
bool fetch_window_icons) {
fetch_window_icons_ = fetch_window_icons;
#if defined(OS_WIN)
if (content::desktop_capture::CreateDesktopCaptureOptions()
.allow_directx_capturer()) {
// DxgiDuplicatorController should be alive in this scope according to
// screen_capturer_win.cc.
auto duplicator = webrtc::DxgiDuplicatorController::Instance();
using_directx_capturer_ = webrtc::ScreenCapturerWinDirectx::IsSupported();
}
#endif // defined(OS_WIN)
// clear any existing captured sources.
captured_sources_.clear();
// Start listening for captured sources.
capture_window_ = capture_window;
capture_screen_ = capture_screen;
{
// Initialize the source list.
// Apply the new thumbnail size and restart capture.
if (capture_window) {
window_capturer_.reset(new NativeDesktopMediaList(
content::DesktopMediaID::TYPE_WINDOW,
content::desktop_capture::CreateWindowCapturer()));
window_capturer_->SetThumbnailSize(thumbnail_size);
window_capturer_->AddObserver(this);
window_capturer_->StartUpdating();
}
if (capture_screen) {
screen_capturer_.reset(new NativeDesktopMediaList(
content::DesktopMediaID::TYPE_SCREEN,
content::desktop_capture::CreateScreenCapturer()));
screen_capturer_->SetThumbnailSize(thumbnail_size);
screen_capturer_->AddObserver(this);
screen_capturer_->StartUpdating();
}
}
}
void DesktopCapturer::OnSourceAdded(DesktopMediaList* list, int index) {}
void DesktopCapturer::OnSourceRemoved(DesktopMediaList* list, int index) {}
void DesktopCapturer::OnSourceMoved(DesktopMediaList* list,
int old_index,
int new_index) {}
void DesktopCapturer::OnSourceNameChanged(DesktopMediaList* list, int index) {}
void DesktopCapturer::OnSourceThumbnailChanged(DesktopMediaList* list,
int index) {}
void DesktopCapturer::OnSourceUnchanged(DesktopMediaList* list) {
UpdateSourcesList(list);
}
bool DesktopCapturer::ShouldScheduleNextRefresh(DesktopMediaList* list) {
UpdateSourcesList(list);
return false;
}
void DesktopCapturer::UpdateSourcesList(DesktopMediaList* list) {
if (capture_window_ &&
list->GetMediaListType() == content::DesktopMediaID::TYPE_WINDOW) {
capture_window_ = false;
const auto& media_list_sources = list->GetSources();
std::vector<DesktopCapturer::Source> window_sources;
window_sources.reserve(media_list_sources.size());
for (const auto& media_list_source : media_list_sources) {
window_sources.emplace_back(DesktopCapturer::Source{
media_list_source, std::string(), fetch_window_icons_});
}
std::move(window_sources.begin(), window_sources.end(),
std::back_inserter(captured_sources_));
}
if (capture_screen_ &&
list->GetMediaListType() == content::DesktopMediaID::TYPE_SCREEN) {
capture_screen_ = false;
const auto& media_list_sources = list->GetSources();
std::vector<DesktopCapturer::Source> screen_sources;
screen_sources.reserve(media_list_sources.size());
for (const auto& media_list_source : media_list_sources) {
screen_sources.emplace_back(
DesktopCapturer::Source{media_list_source, std::string()});
}
#if defined(OS_WIN)
// Gather the same unique screen IDs used by the electron.screen API in
// order to provide an association between it and
// desktopCapturer/getUserMedia. This is only required when using the
// DirectX capturer, otherwise the IDs across the APIs already match.
if (using_directx_capturer_) {
std::vector<std::string> device_names;
// Crucially, this list of device names will be in the same order as
// |media_list_sources|.
if (!webrtc::DxgiDuplicatorController::Instance()->GetDeviceNames(
&device_names)) {
Emit("error", "Failed to get sources.");
return;
}
int device_name_index = 0;
for (auto& source : screen_sources) {
const auto& device_name = device_names[device_name_index++];
std::wstring wide_device_name;
base::UTF8ToWide(device_name.c_str(), device_name.size(),
&wide_device_name);
const int64_t device_id =
display::win::DisplayInfo::DeviceIdFromDeviceName(
wide_device_name.c_str());
source.display_id = base::NumberToString(device_id);
}
}
#elif defined(OS_MACOSX)
// On Mac, the IDs across the APIs match.
for (auto& source : screen_sources) {
source.display_id = base::NumberToString(source.media_list_source.id.id);
}
#endif // defined(OS_WIN)
// TODO(ajmacd): Add Linux support. The IDs across APIs differ but Chrome
// only supports capturing the entire desktop on Linux. Revisit this if
// individual screen support is added.
std::move(screen_sources.begin(), screen_sources.end(),
std::back_inserter(captured_sources_));
}
if (!capture_window_ && !capture_screen_)
Emit("finished", captured_sources_, fetch_window_icons_);
}
// static
mate::Handle<DesktopCapturer> DesktopCapturer::Create(v8::Isolate* isolate) {
return mate::CreateHandle(isolate, new DesktopCapturer(isolate));
}
// static
void DesktopCapturer::BuildPrototype(
v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "DesktopCapturer"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.SetMethod("startHandling", &DesktopCapturer::StartHandling);
}
} // namespace api
} // namespace atom
namespace {
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
mate::Dictionary dict(isolate, exports);
dict.SetMethod("createDesktopCapturer", &atom::api::DesktopCapturer::Create);
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_browser_desktop_capturer, Initialize)

View file

@ -0,0 +1,78 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_BROWSER_API_ATOM_API_DESKTOP_CAPTURER_H_
#define ATOM_BROWSER_API_ATOM_API_DESKTOP_CAPTURER_H_
#include <memory>
#include <string>
#include <vector>
#include "atom/browser/api/trackable_object.h"
#include "chrome/browser/media/webrtc/desktop_media_list_observer.h"
#include "chrome/browser/media/webrtc/native_desktop_media_list.h"
#include "native_mate/handle.h"
namespace atom {
namespace api {
class DesktopCapturer : public mate::TrackableObject<DesktopCapturer>,
public DesktopMediaListObserver {
public:
struct Source {
DesktopMediaList::Source media_list_source;
// Will be an empty string if not available.
std::string display_id;
// Whether or not this source should provide an icon.
bool fetch_icon = false;
};
static mate::Handle<DesktopCapturer> Create(v8::Isolate* isolate);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
void StartHandling(bool capture_window,
bool capture_screen,
const gfx::Size& thumbnail_size,
bool fetch_window_icons);
protected:
explicit DesktopCapturer(v8::Isolate* isolate);
~DesktopCapturer() override;
// DesktopMediaListObserver overrides.
void OnSourceAdded(DesktopMediaList* list, int index) override;
void OnSourceRemoved(DesktopMediaList* list, int index) override;
void OnSourceMoved(DesktopMediaList* list,
int old_index,
int new_index) override;
void OnSourceNameChanged(DesktopMediaList* list, int index) override;
void OnSourceThumbnailChanged(DesktopMediaList* list, int index) override;
void OnSourceUnchanged(DesktopMediaList* list) override;
bool ShouldScheduleNextRefresh(DesktopMediaList* list) override;
private:
void UpdateSourcesList(DesktopMediaList* list);
std::unique_ptr<DesktopMediaList> window_capturer_;
std::unique_ptr<DesktopMediaList> screen_capturer_;
std::vector<DesktopCapturer::Source> captured_sources_;
bool capture_window_ = false;
bool capture_screen_ = false;
bool fetch_window_icons_ = false;
#if defined(OS_WIN)
bool using_directx_capturer_ = false;
#endif // defined(OS_WIN)
DISALLOW_COPY_AND_ASSIGN(DesktopCapturer);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_DESKTOP_CAPTURER_H_

View file

@ -0,0 +1,106 @@
// 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 <utility>
#include <vector>
#include "atom/browser/api/atom_api_browser_window.h"
#include "atom/browser/native_window.h"
#include "atom/browser/ui/certificate_trust.h"
#include "atom/browser/ui/file_dialog.h"
#include "atom/browser/ui/message_box.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/file_dialog_converter.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
#include "atom/common/native_mate_converters/image_converter.h"
#include "atom/common/native_mate_converters/message_box_converter.h"
#include "atom/common/native_mate_converters/net_converter.h"
#include "atom/common/node_includes.h"
#include "atom/common/promise_util.h"
#include "native_mate/dictionary.h"
namespace {
int ShowMessageBoxSync(const atom::MessageBoxSettings& settings) {
return atom::ShowMessageBoxSync(settings);
}
void ResolvePromiseObject(atom::util::Promise promise,
int result,
bool checkbox_checked) {
mate::Dictionary dict = mate::Dictionary::CreateEmpty(promise.isolate());
dict.Set("response", result);
dict.Set("checkboxChecked", checkbox_checked);
promise.Resolve(dict.GetHandle());
}
v8::Local<v8::Promise> ShowMessageBox(const atom::MessageBoxSettings& settings,
mate::Arguments* args) {
v8::Isolate* isolate = args->isolate();
atom::util::Promise promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
atom::ShowMessageBox(
settings, base::BindOnce(&ResolvePromiseObject, std::move(promise)));
return handle;
}
void ShowOpenDialogSync(const file_dialog::DialogSettings& settings,
mate::Arguments* args) {
std::vector<base::FilePath> paths;
if (file_dialog::ShowOpenDialogSync(settings, &paths))
args->Return(paths);
}
v8::Local<v8::Promise> ShowOpenDialog(
const file_dialog::DialogSettings& settings,
mate::Arguments* args) {
atom::util::Promise promise(args->isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
file_dialog::ShowOpenDialog(settings, std::move(promise));
return handle;
}
void ShowSaveDialogSync(const file_dialog::DialogSettings& settings,
mate::Arguments* args) {
base::FilePath path;
if (file_dialog::ShowSaveDialogSync(settings, &path))
args->Return(path);
}
v8::Local<v8::Promise> ShowSaveDialog(
const file_dialog::DialogSettings& settings,
mate::Arguments* args) {
atom::util::Promise promise(args->isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
file_dialog::ShowSaveDialog(settings, std::move(promise));
return handle;
}
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.SetMethod("showMessageBoxSync", &ShowMessageBoxSync);
dict.SetMethod("showMessageBox", &ShowMessageBox);
dict.SetMethod("showErrorBox", &atom::ShowErrorBox);
dict.SetMethod("showOpenDialogSync", &ShowOpenDialogSync);
dict.SetMethod("showOpenDialog", &ShowOpenDialog);
dict.SetMethod("showSaveDialogSync", &ShowSaveDialogSync);
dict.SetMethod("showSaveDialog", &ShowSaveDialog);
#if defined(OS_MACOSX) || defined(OS_WIN)
dict.SetMethod("showCertificateTrustDialog",
&certificate_trust::ShowCertificateTrust);
#endif
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_browser_dialog, Initialize)

View file

@ -0,0 +1,253 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/api/atom_api_download_item.h"
#include <map>
#include "atom/browser/atom_browser_main_parts.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/file_dialog_converter.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
#include "atom/common/native_mate_converters/gurl_converter.h"
#include "atom/common/node_includes.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "native_mate/dictionary.h"
#include "net/base/filename_util.h"
namespace mate {
template <>
struct Converter<download::DownloadItem::DownloadState> {
static v8::Local<v8::Value> ToV8(
v8::Isolate* isolate,
download::DownloadItem::DownloadState state) {
std::string download_state;
switch (state) {
case download::DownloadItem::IN_PROGRESS:
download_state = "progressing";
break;
case download::DownloadItem::COMPLETE:
download_state = "completed";
break;
case download::DownloadItem::CANCELLED:
download_state = "cancelled";
break;
case download::DownloadItem::INTERRUPTED:
download_state = "interrupted";
break;
default:
break;
}
return ConvertToV8(isolate, download_state);
}
};
} // namespace mate
namespace atom {
namespace api {
namespace {
std::map<uint32_t, v8::Global<v8::Object>> g_download_item_objects;
} // namespace
DownloadItem::DownloadItem(v8::Isolate* isolate,
download::DownloadItem* download_item)
: download_item_(download_item) {
download_item_->AddObserver(this);
Init(isolate);
AttachAsUserData(download_item);
}
DownloadItem::~DownloadItem() {
if (download_item_) {
// Destroyed by either garbage collection or destroy().
download_item_->RemoveObserver(this);
download_item_->Remove();
}
// Remove from the global map.
g_download_item_objects.erase(weak_map_id());
}
void DownloadItem::OnDownloadUpdated(download::DownloadItem* item) {
if (download_item_->IsDone()) {
Emit("done", item->GetState());
// Destroy the item once item is downloaded.
base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
GetDestroyClosure());
} else {
Emit("updated", item->GetState());
}
}
void DownloadItem::OnDownloadDestroyed(download::DownloadItem* download_item) {
download_item_ = nullptr;
// Destroy the native class immediately when downloadItem is destroyed.
delete this;
}
void DownloadItem::Pause() {
download_item_->Pause();
}
bool DownloadItem::IsPaused() const {
return download_item_->IsPaused();
}
void DownloadItem::Resume() {
download_item_->Resume(true /* user_gesture */);
}
bool DownloadItem::CanResume() const {
return download_item_->CanResume();
}
void DownloadItem::Cancel() {
download_item_->Cancel(true);
}
int64_t DownloadItem::GetReceivedBytes() const {
return download_item_->GetReceivedBytes();
}
int64_t DownloadItem::GetTotalBytes() const {
return download_item_->GetTotalBytes();
}
std::string DownloadItem::GetMimeType() const {
return download_item_->GetMimeType();
}
bool DownloadItem::HasUserGesture() const {
return download_item_->HasUserGesture();
}
std::string DownloadItem::GetFilename() const {
return base::UTF16ToUTF8(
net::GenerateFileName(GetURL(), GetContentDisposition(), std::string(),
download_item_->GetSuggestedFilename(),
GetMimeType(), "download")
.LossyDisplayName());
}
std::string DownloadItem::GetContentDisposition() const {
return download_item_->GetContentDisposition();
}
const GURL& DownloadItem::GetURL() const {
return download_item_->GetURL();
}
const std::vector<GURL>& DownloadItem::GetURLChain() const {
return download_item_->GetUrlChain();
}
download::DownloadItem::DownloadState DownloadItem::GetState() const {
return download_item_->GetState();
}
bool DownloadItem::IsDone() const {
return download_item_->IsDone();
}
void DownloadItem::SetSavePath(const base::FilePath& path) {
save_path_ = path;
}
base::FilePath DownloadItem::GetSavePath() const {
return save_path_;
}
file_dialog::DialogSettings DownloadItem::GetSaveDialogOptions() const {
return dialog_options_;
}
void DownloadItem::SetSaveDialogOptions(
const file_dialog::DialogSettings& options) {
dialog_options_ = options;
}
std::string DownloadItem::GetLastModifiedTime() const {
return download_item_->GetLastModifiedTime();
}
std::string DownloadItem::GetETag() const {
return download_item_->GetETag();
}
double DownloadItem::GetStartTime() const {
return download_item_->GetStartTime().ToDoubleT();
}
// static
void DownloadItem::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "DownloadItem"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.MakeDestroyable()
.SetMethod("pause", &DownloadItem::Pause)
.SetMethod("isPaused", &DownloadItem::IsPaused)
.SetMethod("resume", &DownloadItem::Resume)
.SetMethod("canResume", &DownloadItem::CanResume)
.SetMethod("cancel", &DownloadItem::Cancel)
.SetMethod("getReceivedBytes", &DownloadItem::GetReceivedBytes)
.SetMethod("getTotalBytes", &DownloadItem::GetTotalBytes)
.SetMethod("getMimeType", &DownloadItem::GetMimeType)
.SetMethod("hasUserGesture", &DownloadItem::HasUserGesture)
.SetMethod("getFilename", &DownloadItem::GetFilename)
.SetMethod("getContentDisposition", &DownloadItem::GetContentDisposition)
.SetMethod("getURL", &DownloadItem::GetURL)
.SetMethod("getURLChain", &DownloadItem::GetURLChain)
.SetMethod("getState", &DownloadItem::GetState)
.SetMethod("isDone", &DownloadItem::IsDone)
.SetMethod("setSavePath", &DownloadItem::SetSavePath)
.SetMethod("getSavePath", &DownloadItem::GetSavePath)
.SetMethod("setSaveDialogOptions", &DownloadItem::SetSaveDialogOptions)
.SetMethod("getSaveDialogOptions", &DownloadItem::GetSaveDialogOptions)
.SetMethod("getLastModifiedTime", &DownloadItem::GetLastModifiedTime)
.SetMethod("getETag", &DownloadItem::GetETag)
.SetMethod("getStartTime", &DownloadItem::GetStartTime);
}
// static
mate::Handle<DownloadItem> DownloadItem::Create(v8::Isolate* isolate,
download::DownloadItem* item) {
auto* existing = TrackableObject::FromWrappedClass(isolate, item);
if (existing)
return mate::CreateHandle(isolate, static_cast<DownloadItem*>(existing));
auto handle = mate::CreateHandle(isolate, new DownloadItem(isolate, item));
// Reference this object in case it got garbage collected.
g_download_item_objects[handle->weak_map_id()] =
v8::Global<v8::Object>(isolate, handle.ToV8());
return handle;
}
} // namespace api
} // namespace atom
namespace {
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
mate::Dictionary(isolate, exports)
.Set("DownloadItem", atom::api::DownloadItem::GetConstructor(isolate)
->GetFunction(context)
.ToLocalChecked());
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_browser_download_item, Initialize)

View file

@ -0,0 +1,74 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_BROWSER_API_ATOM_API_DOWNLOAD_ITEM_H_
#define ATOM_BROWSER_API_ATOM_API_DOWNLOAD_ITEM_H_
#include <string>
#include <vector>
#include "atom/browser/api/trackable_object.h"
#include "atom/browser/ui/file_dialog.h"
#include "base/files/file_path.h"
#include "components/download/public/common/download_item.h"
#include "native_mate/handle.h"
#include "url/gurl.h"
namespace atom {
namespace api {
class DownloadItem : public mate::TrackableObject<DownloadItem>,
public download::DownloadItem::Observer {
public:
static mate::Handle<DownloadItem> Create(v8::Isolate* isolate,
download::DownloadItem* item);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
void Pause();
bool IsPaused() const;
void Resume();
bool CanResume() const;
void Cancel();
int64_t GetReceivedBytes() const;
int64_t GetTotalBytes() const;
std::string GetMimeType() const;
bool HasUserGesture() const;
std::string GetFilename() const;
std::string GetContentDisposition() const;
const GURL& GetURL() const;
const std::vector<GURL>& GetURLChain() const;
download::DownloadItem::DownloadState GetState() const;
bool IsDone() const;
void SetSavePath(const base::FilePath& path);
base::FilePath GetSavePath() const;
file_dialog::DialogSettings GetSaveDialogOptions() const;
void SetSaveDialogOptions(const file_dialog::DialogSettings& options);
std::string GetLastModifiedTime() const;
std::string GetETag() const;
double GetStartTime() const;
protected:
DownloadItem(v8::Isolate* isolate, download::DownloadItem* download_item);
~DownloadItem() override;
// Override download::DownloadItem::Observer methods
void OnDownloadUpdated(download::DownloadItem* download) override;
void OnDownloadDestroyed(download::DownloadItem* download) override;
private:
base::FilePath save_path_;
file_dialog::DialogSettings dialog_options_;
download::DownloadItem* download_item_;
DISALLOW_COPY_AND_ASSIGN(DownloadItem);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_DOWNLOAD_ITEM_H_

View file

@ -0,0 +1,26 @@
// 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/browser/api/event_emitter.h"
#include "atom/common/node_includes.h"
#include "native_mate/dictionary.h"
namespace {
v8::Local<v8::Object> CreateWithSender(v8::Isolate* isolate,
v8::Local<v8::Object> sender) {
return mate::internal::CreateJSEvent(isolate, sender, nullptr, base::nullopt);
}
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.SetMethod("createWithSender", &CreateWithSender);
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_browser_event, Initialize)

View file

@ -0,0 +1,168 @@
// 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/browser/api/atom_api_global_shortcut.h"
#include <string>
#include <vector>
#include "atom/browser/api/atom_api_system_preferences.h"
#include "atom/common/native_mate_converters/accelerator_converter.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/node_includes.h"
#include "base/stl_util.h"
#include "base/strings/utf_string_conversions.h"
#include "native_mate/dictionary.h"
#if defined(OS_MACOSX)
#include "base/mac/mac_util.h"
#endif
using extensions::GlobalShortcutListener;
namespace {
#if defined(OS_MACOSX)
bool RegisteringMediaKeyForUntrustedClient(const ui::Accelerator& accelerator) {
if (base::mac::IsAtLeastOS10_14()) {
constexpr ui::KeyboardCode mediaKeys[] = {
ui::VKEY_MEDIA_PLAY_PAUSE, ui::VKEY_MEDIA_NEXT_TRACK,
ui::VKEY_MEDIA_PREV_TRACK, ui::VKEY_MEDIA_STOP};
if (std::find(std::begin(mediaKeys), std::end(mediaKeys),
accelerator.key_code()) != std::end(mediaKeys)) {
bool trusted =
atom::api::SystemPreferences::IsTrustedAccessibilityClient(false);
if (!trusted)
return true;
}
}
return false;
}
#endif
} // namespace
namespace atom {
namespace api {
GlobalShortcut::GlobalShortcut(v8::Isolate* isolate) {
Init(isolate);
}
GlobalShortcut::~GlobalShortcut() {
UnregisterAll();
}
void GlobalShortcut::OnKeyPressed(const ui::Accelerator& accelerator) {
if (accelerator_callback_map_.find(accelerator) ==
accelerator_callback_map_.end()) {
// This should never occur, because if it does, GlobalGlobalShortcutListener
// notifies us with wrong accelerator.
NOTREACHED();
return;
}
accelerator_callback_map_[accelerator].Run();
}
bool GlobalShortcut::RegisterAll(
const std::vector<ui::Accelerator>& accelerators,
const base::Closure& callback) {
std::vector<ui::Accelerator> registered;
for (auto& accelerator : accelerators) {
#if defined(OS_MACOSX)
if (RegisteringMediaKeyForUntrustedClient(accelerator))
return false;
GlobalShortcutListener* listener = GlobalShortcutListener::GetInstance();
if (!listener->RegisterAccelerator(accelerator, this)) {
// unregister all shortcuts if any failed
UnregisterSome(registered);
return false;
}
#endif
registered.push_back(accelerator);
accelerator_callback_map_[accelerator] = callback;
}
return true;
}
bool GlobalShortcut::Register(const ui::Accelerator& accelerator,
const base::Closure& callback) {
#if defined(OS_MACOSX)
if (RegisteringMediaKeyForUntrustedClient(accelerator))
return false;
#endif
if (!GlobalShortcutListener::GetInstance()->RegisterAccelerator(accelerator,
this)) {
return false;
}
accelerator_callback_map_[accelerator] = callback;
return true;
}
void GlobalShortcut::Unregister(const ui::Accelerator& accelerator) {
if (!ContainsKey(accelerator_callback_map_, accelerator))
return;
accelerator_callback_map_.erase(accelerator);
GlobalShortcutListener::GetInstance()->UnregisterAccelerator(accelerator,
this);
}
void GlobalShortcut::UnregisterSome(
const std::vector<ui::Accelerator>& accelerators) {
for (auto& accelerator : accelerators) {
Unregister(accelerator);
}
}
bool GlobalShortcut::IsRegistered(const ui::Accelerator& accelerator) {
return ContainsKey(accelerator_callback_map_, accelerator);
}
void GlobalShortcut::UnregisterAll() {
accelerator_callback_map_.clear();
GlobalShortcutListener::GetInstance()->UnregisterAccelerators(this);
}
// static
mate::Handle<GlobalShortcut> GlobalShortcut::Create(v8::Isolate* isolate) {
return mate::CreateHandle(isolate, new GlobalShortcut(isolate));
}
// static
void GlobalShortcut::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "GlobalShortcut"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.SetMethod("registerAll", &GlobalShortcut::RegisterAll)
.SetMethod("register", &GlobalShortcut::Register)
.SetMethod("isRegistered", &GlobalShortcut::IsRegistered)
.SetMethod("unregister", &GlobalShortcut::Unregister)
.SetMethod("unregisterAll", &GlobalShortcut::UnregisterAll);
}
} // namespace api
} // namespace atom
namespace {
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
mate::Dictionary dict(isolate, exports);
dict.Set("globalShortcut", atom::api::GlobalShortcut::Create(isolate));
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_browser_global_shortcut, Initialize)

View file

@ -0,0 +1,58 @@
// 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_BROWSER_API_ATOM_API_GLOBAL_SHORTCUT_H_
#define ATOM_BROWSER_API_ATOM_API_GLOBAL_SHORTCUT_H_
#include <map>
#include <string>
#include <vector>
#include "atom/browser/api/trackable_object.h"
#include "base/callback.h"
#include "chrome/browser/extensions/global_shortcut_listener.h"
#include "native_mate/handle.h"
#include "ui/base/accelerators/accelerator.h"
namespace atom {
namespace api {
class GlobalShortcut : public extensions::GlobalShortcutListener::Observer,
public mate::TrackableObject<GlobalShortcut> {
public:
static mate::Handle<GlobalShortcut> Create(v8::Isolate* isolate);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
protected:
explicit GlobalShortcut(v8::Isolate* isolate);
~GlobalShortcut() override;
private:
typedef std::map<ui::Accelerator, base::Closure> AcceleratorCallbackMap;
bool RegisterAll(const std::vector<ui::Accelerator>& accelerators,
const base::Closure& callback);
bool Register(const ui::Accelerator& accelerator,
const base::Closure& callback);
bool IsRegistered(const ui::Accelerator& accelerator);
void Unregister(const ui::Accelerator& accelerator);
void UnregisterSome(const std::vector<ui::Accelerator>& accelerators);
void UnregisterAll();
// GlobalShortcutListener::Observer implementation.
void OnKeyPressed(const ui::Accelerator& accelerator) override;
AcceleratorCallbackMap accelerator_callback_map_;
DISALLOW_COPY_AND_ASSIGN(GlobalShortcut);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_GLOBAL_SHORTCUT_H_

View file

@ -0,0 +1,166 @@
// Copyright (c) 2017 Amaplex Software, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/api/atom_api_in_app_purchase.h"
#include <string>
#include <utility>
#include <vector>
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/node_includes.h"
#include "native_mate/dictionary.h"
namespace mate {
template <>
struct Converter<in_app_purchase::Payment> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
const in_app_purchase::Payment& payment) {
mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
dict.SetHidden("simple", true);
dict.Set("productIdentifier", payment.productIdentifier);
dict.Set("quantity", payment.quantity);
return dict.GetHandle();
}
};
template <>
struct Converter<in_app_purchase::Transaction> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
const in_app_purchase::Transaction& val) {
mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
dict.SetHidden("simple", true);
dict.Set("transactionIdentifier", val.transactionIdentifier);
dict.Set("transactionDate", val.transactionDate);
dict.Set("originalTransactionIdentifier",
val.originalTransactionIdentifier);
dict.Set("transactionState", val.transactionState);
dict.Set("errorCode", val.errorCode);
dict.Set("errorMessage", val.errorMessage);
dict.Set("payment", val.payment);
return dict.GetHandle();
}
};
template <>
struct Converter<in_app_purchase::Product> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
const in_app_purchase::Product& val) {
mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
dict.SetHidden("simple", true);
dict.Set("productIdentifier", val.productIdentifier);
dict.Set("localizedDescription", val.localizedDescription);
dict.Set("localizedTitle", val.localizedTitle);
dict.Set("contentVersion", val.localizedTitle);
dict.Set("contentLengths", val.contentLengths);
// Pricing Information
dict.Set("price", val.price);
dict.Set("formattedPrice", val.formattedPrice);
// Downloadable Content Information
dict.Set("isDownloadable", val.isDownloadable);
return dict.GetHandle();
}
};
} // namespace mate
namespace atom {
namespace api {
#if defined(OS_MACOSX)
// static
mate::Handle<InAppPurchase> InAppPurchase::Create(v8::Isolate* isolate) {
return mate::CreateHandle(isolate, new InAppPurchase(isolate));
}
// static
void InAppPurchase::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "InAppPurchase"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.SetMethod("canMakePayments", &in_app_purchase::CanMakePayments)
.SetMethod("getReceiptURL", &in_app_purchase::GetReceiptURL)
.SetMethod("purchaseProduct", &InAppPurchase::PurchaseProduct)
.SetMethod("finishAllTransactions",
&in_app_purchase::FinishAllTransactions)
.SetMethod("finishTransactionByDate",
&in_app_purchase::FinishTransactionByDate)
.SetMethod("getProducts", &InAppPurchase::GetProducts);
}
InAppPurchase::InAppPurchase(v8::Isolate* isolate) {
Init(isolate);
}
InAppPurchase::~InAppPurchase() {}
v8::Local<v8::Promise> InAppPurchase::PurchaseProduct(
const std::string& product_id,
mate::Arguments* args) {
v8::Isolate* isolate = args->isolate();
atom::util::Promise promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
int quantity = 1;
args->GetNext(&quantity);
in_app_purchase::PurchaseProduct(
product_id, quantity,
base::BindOnce(atom::util::Promise::ResolvePromise<bool>,
std::move(promise)));
return handle;
}
v8::Local<v8::Promise> InAppPurchase::GetProducts(
const std::vector<std::string>& productIDs,
mate::Arguments* args) {
v8::Isolate* isolate = args->isolate();
atom::util::Promise promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
in_app_purchase::GetProducts(
productIDs, base::BindOnce(atom::util::Promise::ResolvePromise<
std::vector<in_app_purchase::Product>>,
std::move(promise)));
return handle;
}
void InAppPurchase::OnTransactionsUpdated(
const std::vector<in_app_purchase::Transaction>& transactions) {
Emit("transactions-updated", transactions);
}
#endif
} // namespace api
} // namespace atom
namespace {
using atom::api::InAppPurchase;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
#if defined(OS_MACOSX)
v8::Isolate* isolate = context->GetIsolate();
mate::Dictionary dict(isolate, exports);
dict.Set("inAppPurchase", InAppPurchase::Create(isolate));
dict.Set("InAppPurchase", InAppPurchase::GetConstructor(isolate)
->GetFunction(context)
.ToLocalChecked());
#endif
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_browser_in_app_purchase, Initialize)

View file

@ -0,0 +1,52 @@
// Copyright (c) 2017 Amaplex Software, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_BROWSER_API_ATOM_API_IN_APP_PURCHASE_H_
#define ATOM_BROWSER_API_ATOM_API_IN_APP_PURCHASE_H_
#include <string>
#include <vector>
#include "atom/browser/api/event_emitter.h"
#include "atom/browser/mac/in_app_purchase.h"
#include "atom/browser/mac/in_app_purchase_observer.h"
#include "atom/browser/mac/in_app_purchase_product.h"
#include "atom/common/promise_util.h"
#include "native_mate/handle.h"
namespace atom {
namespace api {
class InAppPurchase : public mate::EventEmitter<InAppPurchase>,
public in_app_purchase::TransactionObserver {
public:
static mate::Handle<InAppPurchase> Create(v8::Isolate* isolate);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
protected:
explicit InAppPurchase(v8::Isolate* isolate);
~InAppPurchase() override;
v8::Local<v8::Promise> PurchaseProduct(const std::string& product_id,
mate::Arguments* args);
v8::Local<v8::Promise> GetProducts(const std::vector<std::string>& productIDs,
mate::Arguments* args);
// TransactionObserver:
void OnTransactionsUpdated(
const std::vector<in_app_purchase::Transaction>& transactions) override;
private:
DISALLOW_COPY_AND_ASSIGN(InAppPurchase);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_IN_APP_PURCHASE_H_

View file

@ -0,0 +1,259 @@
// 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/browser/api/atom_api_menu.h"
#include "atom/browser/native_window.h"
#include "atom/common/native_mate_converters/accelerator_converter.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/image_converter.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/node_includes.h"
#include "native_mate/constructor.h"
#include "native_mate/dictionary.h"
#include "native_mate/object_template_builder.h"
namespace atom {
namespace api {
Menu::Menu(v8::Isolate* isolate, v8::Local<v8::Object> wrapper)
: model_(new AtomMenuModel(this)) {
InitWith(isolate, wrapper);
model_->AddObserver(this);
}
Menu::~Menu() {
if (model_) {
model_->RemoveObserver(this);
}
}
void Menu::AfterInit(v8::Isolate* isolate) {
mate::Dictionary wrappable(isolate, GetWrapper());
mate::Dictionary delegate;
if (!wrappable.Get("delegate", &delegate))
return;
delegate.Get("isCommandIdChecked", &is_checked_);
delegate.Get("isCommandIdEnabled", &is_enabled_);
delegate.Get("isCommandIdVisible", &is_visible_);
delegate.Get("shouldCommandIdWorkWhenHidden", &works_when_hidden_);
delegate.Get("getAcceleratorForCommandId", &get_accelerator_);
delegate.Get("shouldRegisterAcceleratorForCommandId",
&should_register_accelerator_);
delegate.Get("executeCommand", &execute_command_);
delegate.Get("menuWillShow", &menu_will_show_);
}
bool Menu::IsCommandIdChecked(int command_id) const {
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
return is_checked_.Run(GetWrapper(), command_id);
}
bool Menu::IsCommandIdEnabled(int command_id) const {
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
return is_enabled_.Run(GetWrapper(), command_id);
}
bool Menu::IsCommandIdVisible(int command_id) const {
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
return is_visible_.Run(GetWrapper(), command_id);
}
bool Menu::ShouldCommandIdWorkWhenHidden(int command_id) const {
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
return works_when_hidden_.Run(GetWrapper(), command_id);
}
bool Menu::GetAcceleratorForCommandIdWithParams(
int command_id,
bool use_default_accelerator,
ui::Accelerator* accelerator) const {
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
v8::Local<v8::Value> val =
get_accelerator_.Run(GetWrapper(), command_id, use_default_accelerator);
return mate::ConvertFromV8(isolate(), val, accelerator);
}
bool Menu::ShouldRegisterAcceleratorForCommandId(int command_id) const {
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
return should_register_accelerator_.Run(GetWrapper(), command_id);
}
void Menu::ExecuteCommand(int command_id, int flags) {
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
execute_command_.Run(GetWrapper(),
mate::internal::CreateEventFromFlags(isolate(), flags),
command_id);
}
void Menu::OnMenuWillShow(ui::SimpleMenuModel* source) {
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
menu_will_show_.Run(GetWrapper());
}
void Menu::InsertItemAt(int index,
int command_id,
const base::string16& label) {
model_->InsertItemAt(index, command_id, label);
}
void Menu::InsertSeparatorAt(int index) {
model_->InsertSeparatorAt(index, ui::NORMAL_SEPARATOR);
}
void Menu::InsertCheckItemAt(int index,
int command_id,
const base::string16& label) {
model_->InsertCheckItemAt(index, command_id, label);
}
void Menu::InsertRadioItemAt(int index,
int command_id,
const base::string16& label,
int group_id) {
model_->InsertRadioItemAt(index, command_id, label, group_id);
}
void Menu::InsertSubMenuAt(int index,
int command_id,
const base::string16& label,
Menu* menu) {
menu->parent_ = this;
model_->InsertSubMenuAt(index, command_id, label, menu->model_.get());
}
void Menu::SetIcon(int index, const gfx::Image& image) {
model_->SetIcon(index, image);
}
void Menu::SetSublabel(int index, const base::string16& sublabel) {
model_->SetSublabel(index, sublabel);
}
void Menu::SetRole(int index, const base::string16& role) {
model_->SetRole(index, role);
}
void Menu::Clear() {
model_->Clear();
}
int Menu::GetIndexOfCommandId(int command_id) {
return model_->GetIndexOfCommandId(command_id);
}
int Menu::GetItemCount() const {
return model_->GetItemCount();
}
int Menu::GetCommandIdAt(int index) const {
return model_->GetCommandIdAt(index);
}
base::string16 Menu::GetLabelAt(int index) const {
return model_->GetLabelAt(index);
}
base::string16 Menu::GetSublabelAt(int index) const {
return model_->GetSublabelAt(index);
}
base::string16 Menu::GetAcceleratorTextAt(int index) const {
ui::Accelerator accelerator;
model_->GetAcceleratorAtWithParams(index, true, &accelerator);
return accelerator.GetShortcutText();
}
bool Menu::IsItemCheckedAt(int index) const {
return model_->IsItemCheckedAt(index);
}
bool Menu::IsEnabledAt(int index) const {
return model_->IsEnabledAt(index);
}
bool Menu::IsVisibleAt(int index) const {
return model_->IsVisibleAt(index);
}
bool Menu::WorksWhenHiddenAt(int index) const {
return model_->WorksWhenHiddenAt(index);
}
void Menu::OnMenuWillClose() {
Emit("menu-will-close");
}
void Menu::OnMenuWillShow() {
Emit("menu-will-show");
}
// static
void Menu::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "Menu"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.MakeDestroyable()
.SetMethod("insertItem", &Menu::InsertItemAt)
.SetMethod("insertCheckItem", &Menu::InsertCheckItemAt)
.SetMethod("insertRadioItem", &Menu::InsertRadioItemAt)
.SetMethod("insertSeparator", &Menu::InsertSeparatorAt)
.SetMethod("insertSubMenu", &Menu::InsertSubMenuAt)
.SetMethod("setIcon", &Menu::SetIcon)
.SetMethod("setSublabel", &Menu::SetSublabel)
.SetMethod("setRole", &Menu::SetRole)
.SetMethod("clear", &Menu::Clear)
.SetMethod("getIndexOfCommandId", &Menu::GetIndexOfCommandId)
.SetMethod("getItemCount", &Menu::GetItemCount)
.SetMethod("getCommandIdAt", &Menu::GetCommandIdAt)
.SetMethod("getLabelAt", &Menu::GetLabelAt)
.SetMethod("getSublabelAt", &Menu::GetSublabelAt)
.SetMethod("getAcceleratorTextAt", &Menu::GetAcceleratorTextAt)
.SetMethod("isItemCheckedAt", &Menu::IsItemCheckedAt)
.SetMethod("isEnabledAt", &Menu::IsEnabledAt)
.SetMethod("worksWhenHiddenAt", &Menu::WorksWhenHiddenAt)
.SetMethod("isVisibleAt", &Menu::IsVisibleAt)
.SetMethod("popupAt", &Menu::PopupAt)
.SetMethod("closePopupAt", &Menu::ClosePopupAt);
}
} // namespace api
} // namespace atom
namespace {
using atom::api::Menu;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
Menu::SetConstructor(isolate, base::BindRepeating(&Menu::New));
mate::Dictionary dict(isolate, exports);
dict.Set(
"Menu",
Menu::GetConstructor(isolate)->GetFunction(context).ToLocalChecked());
#if defined(OS_MACOSX)
dict.SetMethod("setApplicationMenu", &Menu::SetApplicationMenu);
dict.SetMethod("sendActionToFirstResponder",
&Menu::SendActionToFirstResponder);
#endif
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_browser_menu, Initialize)

View file

@ -0,0 +1,145 @@
// 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_BROWSER_API_ATOM_API_MENU_H_
#define ATOM_BROWSER_API_ATOM_API_MENU_H_
#include <memory>
#include <string>
#include "atom/browser/api/atom_api_top_level_window.h"
#include "atom/browser/api/trackable_object.h"
#include "atom/browser/ui/atom_menu_model.h"
#include "base/callback.h"
namespace atom {
namespace api {
class Menu : public mate::TrackableObject<Menu>,
public AtomMenuModel::Delegate,
public AtomMenuModel::Observer {
public:
static mate::WrappableBase* New(mate::Arguments* args);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
#if defined(OS_MACOSX)
// Set the global menubar.
static void SetApplicationMenu(Menu* menu);
// Fake sending an action from the application menu.
static void SendActionToFirstResponder(const std::string& action);
#endif
AtomMenuModel* model() const { return model_.get(); }
protected:
Menu(v8::Isolate* isolate, v8::Local<v8::Object> wrapper);
~Menu() override;
// mate::Wrappable:
void AfterInit(v8::Isolate* isolate) override;
// ui::SimpleMenuModel::Delegate:
bool IsCommandIdChecked(int command_id) const override;
bool IsCommandIdEnabled(int command_id) const override;
bool IsCommandIdVisible(int command_id) const override;
bool ShouldCommandIdWorkWhenHidden(int command_id) const override;
bool GetAcceleratorForCommandIdWithParams(
int command_id,
bool use_default_accelerator,
ui::Accelerator* accelerator) const override;
bool ShouldRegisterAcceleratorForCommandId(int command_id) const override;
void ExecuteCommand(int command_id, int event_flags) override;
void OnMenuWillShow(ui::SimpleMenuModel* source) override;
virtual void PopupAt(TopLevelWindow* window,
int x,
int y,
int positioning_item,
const base::Closure& callback) = 0;
virtual void ClosePopupAt(int32_t window_id) = 0;
std::unique_ptr<AtomMenuModel> model_;
Menu* parent_ = nullptr;
// Observable:
void OnMenuWillClose() override;
void OnMenuWillShow() override;
private:
void InsertItemAt(int index, int command_id, const base::string16& label);
void InsertSeparatorAt(int index);
void InsertCheckItemAt(int index,
int command_id,
const base::string16& label);
void InsertRadioItemAt(int index,
int command_id,
const base::string16& label,
int group_id);
void InsertSubMenuAt(int index,
int command_id,
const base::string16& label,
Menu* menu);
void SetIcon(int index, const gfx::Image& image);
void SetSublabel(int index, const base::string16& sublabel);
void SetRole(int index, const base::string16& role);
void Clear();
int GetIndexOfCommandId(int command_id);
int GetItemCount() const;
int GetCommandIdAt(int index) const;
base::string16 GetLabelAt(int index) const;
base::string16 GetSublabelAt(int index) const;
base::string16 GetAcceleratorTextAt(int index) const;
bool IsItemCheckedAt(int index) const;
bool IsEnabledAt(int index) const;
bool IsVisibleAt(int index) const;
bool WorksWhenHiddenAt(int index) const;
// Stored delegate methods.
base::RepeatingCallback<bool(v8::Local<v8::Value>, int)> is_checked_;
base::RepeatingCallback<bool(v8::Local<v8::Value>, int)> is_enabled_;
base::RepeatingCallback<bool(v8::Local<v8::Value>, int)> is_visible_;
base::RepeatingCallback<bool(v8::Local<v8::Value>, int)> works_when_hidden_;
base::RepeatingCallback<v8::Local<v8::Value>(v8::Local<v8::Value>, int, bool)>
get_accelerator_;
base::RepeatingCallback<bool(v8::Local<v8::Value>, int)>
should_register_accelerator_;
base::RepeatingCallback<void(v8::Local<v8::Value>, v8::Local<v8::Value>, int)>
execute_command_;
base::RepeatingCallback<void(v8::Local<v8::Value>)> menu_will_show_;
DISALLOW_COPY_AND_ASSIGN(Menu);
};
} // namespace api
} // namespace atom
namespace mate {
template <>
struct Converter<atom::AtomMenuModel*> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
atom::AtomMenuModel** out) {
// null would be tranfered to NULL.
if (val->IsNull()) {
*out = nullptr;
return true;
}
atom::api::Menu* menu;
if (!Converter<atom::api::Menu*>::FromV8(isolate, val, &menu))
return false;
*out = menu->model();
return true;
}
};
} // namespace mate
#endif // ATOM_BROWSER_API_ATOM_API_MENU_H_

View file

@ -0,0 +1,58 @@
// 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_BROWSER_API_ATOM_API_MENU_MAC_H_
#define ATOM_BROWSER_API_ATOM_API_MENU_MAC_H_
#include "atom/browser/api/atom_api_menu.h"
#include <map>
#include <string>
#import "atom/browser/ui/cocoa/atom_menu_controller.h"
using base::scoped_nsobject;
namespace atom {
namespace api {
class MenuMac : public Menu {
protected:
MenuMac(v8::Isolate* isolate, v8::Local<v8::Object> wrapper);
~MenuMac() override;
void PopupAt(TopLevelWindow* window,
int x,
int y,
int positioning_item,
const base::Closure& callback) override;
void PopupOnUI(const base::WeakPtr<NativeWindow>& native_window,
int32_t window_id,
int x,
int y,
int positioning_item,
base::Closure callback);
void ClosePopupAt(int32_t window_id) override;
private:
friend class Menu;
void OnClosed(int32_t window_id, base::Closure callback);
scoped_nsobject<AtomMenuController> menu_controller_;
// window ID -> open context menu
std::map<int32_t, scoped_nsobject<AtomMenuController>> popup_controllers_;
base::WeakPtrFactory<MenuMac> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(MenuMac);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_MENU_MAC_H_

View file

@ -0,0 +1,175 @@
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#import "atom/browser/api/atom_api_menu_mac.h"
#include <string>
#include <utility>
#include "atom/browser/native_window.h"
#include "atom/browser/unresponsive_suppressor.h"
#include "atom/common/node_includes.h"
#include "base/mac/scoped_sending_event.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/sys_string_conversions.h"
#include "base/task/post_task.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/web_contents.h"
using content::BrowserThread;
namespace {
static scoped_nsobject<NSMenu> applicationMenu_;
} // namespace
namespace atom {
namespace api {
MenuMac::MenuMac(v8::Isolate* isolate, v8::Local<v8::Object> wrapper)
: Menu(isolate, wrapper), weak_factory_(this) {}
MenuMac::~MenuMac() = default;
void MenuMac::PopupAt(TopLevelWindow* window,
int x,
int y,
int positioning_item,
const base::Closure& callback) {
NativeWindow* native_window = window->window();
if (!native_window)
return;
auto popup =
base::BindOnce(&MenuMac::PopupOnUI, weak_factory_.GetWeakPtr(),
native_window->GetWeakPtr(), window->weak_map_id(), x, y,
positioning_item, callback);
base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, std::move(popup));
}
void MenuMac::PopupOnUI(const base::WeakPtr<NativeWindow>& native_window,
int32_t window_id,
int x,
int y,
int positioning_item,
base::Closure callback) {
if (!native_window)
return;
NSWindow* nswindow = native_window->GetNativeWindow().GetNativeNSWindow();
auto close_callback = base::BindRepeating(
&MenuMac::OnClosed, weak_factory_.GetWeakPtr(), window_id, callback);
popup_controllers_[window_id] = base::scoped_nsobject<AtomMenuController>(
[[AtomMenuController alloc] initWithModel:model()
useDefaultAccelerator:NO]);
NSMenu* menu = [popup_controllers_[window_id] menu];
NSView* view = [nswindow contentView];
// Which menu item to show.
NSMenuItem* item = nil;
if (positioning_item < [menu numberOfItems] && positioning_item >= 0)
item = [menu itemAtIndex:positioning_item];
// (-1, -1) means showing on mouse location.
NSPoint position;
if (x == -1 || y == -1) {
position = [view convertPoint:[nswindow mouseLocationOutsideOfEventStream]
fromView:nil];
} else {
position = NSMakePoint(x, [view frame].size.height - y);
}
// If no preferred item is specified, try to show all of the menu items.
if (!positioning_item) {
CGFloat windowBottom = CGRectGetMinY([view window].frame);
CGFloat lowestMenuPoint = windowBottom + position.y - [menu size].height;
CGFloat screenBottom = CGRectGetMinY([view window].screen.frame);
CGFloat distanceFromBottom = lowestMenuPoint - screenBottom;
if (distanceFromBottom < 0)
position.y = position.y - distanceFromBottom + 4;
}
// Place the menu left of cursor if it is overflowing off right of screen.
CGFloat windowLeft = CGRectGetMinX([view window].frame);
CGFloat rightmostMenuPoint = windowLeft + position.x + [menu size].width;
CGFloat screenRight = CGRectGetMaxX([view window].screen.frame);
if (rightmostMenuPoint > screenRight)
position.x = position.x - [menu size].width;
[popup_controllers_[window_id] setCloseCallback:close_callback];
// Make sure events can be pumped while the menu is up.
base::MessageLoopCurrent::ScopedNestableTaskAllower allow;
// One of the events that could be pumped is |window.close()|.
// User-initiated event-tracking loops protect against this by
// setting flags in -[CrApplication sendEvent:], but since
// web-content menus are initiated by IPC message the setup has to
// be done manually.
base::mac::ScopedSendingEvent sendingEventScoper;
// Don't emit unresponsive event when showing menu.
atom::UnresponsiveSuppressor suppressor;
[menu popUpMenuPositioningItem:item atLocation:position inView:view];
}
void MenuMac::ClosePopupAt(int32_t window_id) {
auto controller = popup_controllers_.find(window_id);
if (controller != popup_controllers_.end()) {
// Close the controller for the window.
[controller->second cancel];
} else if (window_id == -1) {
// Or just close all opened controllers.
for (auto it = popup_controllers_.begin();
it != popup_controllers_.end();) {
// The iterator is invalidated after the call.
[(it++)->second cancel];
}
}
}
void MenuMac::OnClosed(int32_t window_id, base::Closure callback) {
popup_controllers_.erase(window_id);
callback.Run();
}
// static
void Menu::SetApplicationMenu(Menu* base_menu) {
MenuMac* menu = static_cast<MenuMac*>(base_menu);
base::scoped_nsobject<AtomMenuController> menu_controller(
[[AtomMenuController alloc] initWithModel:menu->model_.get()
useDefaultAccelerator:YES]);
NSRunLoop* currentRunLoop = [NSRunLoop currentRunLoop];
[currentRunLoop cancelPerformSelector:@selector(setMainMenu:)
target:NSApp
argument:applicationMenu_];
applicationMenu_.reset([[menu_controller menu] retain]);
[[NSRunLoop currentRunLoop]
performSelector:@selector(setMainMenu:)
target:NSApp
argument:applicationMenu_
order:0
modes:[NSArray arrayWithObject:NSDefaultRunLoopMode]];
// Ensure the menu_controller_ is destroyed after main menu is set.
menu_controller.swap(menu->menu_controller_);
}
// static
void Menu::SendActionToFirstResponder(const std::string& action) {
SEL selector = NSSelectorFromString(base::SysUTF8ToNSString(action));
[NSApp sendAction:selector to:nil from:[NSApp mainMenu]];
}
// static
mate::WrappableBase* Menu::New(mate::Arguments* args) {
return new MenuMac(args->isolate(), args->GetThis());
}
} // namespace api
} // namespace atom

View file

@ -0,0 +1,84 @@
// 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/browser/api/atom_api_menu_views.h"
#include <memory>
#include "atom/browser/native_window_views.h"
#include "atom/browser/unresponsive_suppressor.h"
#include "ui/display/screen.h"
using views::MenuRunner;
namespace atom {
namespace api {
MenuViews::MenuViews(v8::Isolate* isolate, v8::Local<v8::Object> wrapper)
: Menu(isolate, wrapper), weak_factory_(this) {}
MenuViews::~MenuViews() = default;
void MenuViews::PopupAt(TopLevelWindow* window,
int x,
int y,
int positioning_item,
const base::Closure& callback) {
auto* native_window = static_cast<NativeWindowViews*>(window->window());
if (!native_window)
return;
// (-1, -1) means showing on mouse location.
gfx::Point location;
if (x == -1 || y == -1) {
location = display::Screen::GetScreen()->GetCursorScreenPoint();
} else {
gfx::Point origin = native_window->GetContentBounds().origin();
location = gfx::Point(origin.x() + x, origin.y() + y);
}
int flags = MenuRunner::CONTEXT_MENU | MenuRunner::HAS_MNEMONICS;
// Don't emit unresponsive event when showing menu.
atom::UnresponsiveSuppressor suppressor;
// Show the menu.
int32_t window_id = window->weak_map_id();
auto close_callback = base::BindRepeating(
&MenuViews::OnClosed, weak_factory_.GetWeakPtr(), window_id, callback);
menu_runners_[window_id] =
std::make_unique<MenuRunner>(model(), flags, close_callback);
menu_runners_[window_id]->RunMenuAt(
native_window->widget(), NULL, gfx::Rect(location, gfx::Size()),
views::MenuAnchorPosition::kTopLeft, ui::MENU_SOURCE_MOUSE);
}
void MenuViews::ClosePopupAt(int32_t window_id) {
auto runner = menu_runners_.find(window_id);
if (runner != menu_runners_.end()) {
// Close the runner for the window.
runner->second->Cancel();
} else if (window_id == -1) {
// Or just close all opened runners.
for (auto it = menu_runners_.begin(); it != menu_runners_.end();) {
// The iterator is invalidated after the call.
(it++)->second->Cancel();
}
}
}
void MenuViews::OnClosed(int32_t window_id, base::Closure callback) {
menu_runners_.erase(window_id);
callback.Run();
}
// static
mate::WrappableBase* Menu::New(mate::Arguments* args) {
return new MenuViews(args->isolate(), args->GetThis());
}
} // namespace api
} // namespace atom

View file

@ -0,0 +1,48 @@
// 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_BROWSER_API_ATOM_API_MENU_VIEWS_H_
#define ATOM_BROWSER_API_ATOM_API_MENU_VIEWS_H_
#include <map>
#include <memory>
#include "atom/browser/api/atom_api_menu.h"
#include "base/memory/weak_ptr.h"
#include "ui/display/screen.h"
#include "ui/views/controls/menu/menu_runner.h"
namespace atom {
namespace api {
class MenuViews : public Menu {
public:
MenuViews(v8::Isolate* isolate, v8::Local<v8::Object> wrapper);
~MenuViews() override;
protected:
void PopupAt(TopLevelWindow* window,
int x,
int y,
int positioning_item,
const base::Closure& callback) override;
void ClosePopupAt(int32_t window_id) override;
private:
void OnClosed(int32_t window_id, base::Closure callback);
// window ID -> open context menu
std::map<int32_t, std::unique_ptr<views::MenuRunner>> menu_runners_;
base::WeakPtrFactory<MenuViews> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(MenuViews);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_MENU_VIEWS_H_

View file

@ -0,0 +1,64 @@
// 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/browser/api/atom_api_net.h"
#include "atom/browser/api/atom_api_url_request.h"
#include "atom/common/node_includes.h"
#include "native_mate/dictionary.h"
namespace atom {
namespace api {
Net::Net(v8::Isolate* isolate) {
Init(isolate);
}
Net::~Net() {}
// static
v8::Local<v8::Value> Net::Create(v8::Isolate* isolate) {
return mate::CreateHandle(isolate, new Net(isolate)).ToV8();
}
// static
void Net::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "Net"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.SetProperty("URLRequest", &Net::URLRequest);
}
v8::Local<v8::Value> Net::URLRequest(v8::Isolate* isolate) {
return URLRequest::GetConstructor(isolate)
->GetFunction(isolate->GetCurrentContext())
.ToLocalChecked();
}
} // namespace api
} // namespace atom
namespace {
using atom::api::Net;
using atom::api::URLRequest;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
URLRequest::SetConstructor(isolate, base::BindRepeating(URLRequest::New));
mate::Dictionary dict(isolate, exports);
dict.Set("net", Net::Create(isolate));
dict.Set("Net",
Net::GetConstructor(isolate)->GetFunction(context).ToLocalChecked());
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_browser_net, Initialize)

View file

@ -0,0 +1,35 @@
// 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_BROWSER_API_ATOM_API_NET_H_
#define ATOM_BROWSER_API_ATOM_API_NET_H_
#include "atom/browser/api/event_emitter.h"
namespace atom {
namespace api {
class Net : public mate::EventEmitter<Net> {
public:
static v8::Local<v8::Value> Create(v8::Isolate* isolate);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
v8::Local<v8::Value> URLRequest(v8::Isolate* isolate);
protected:
explicit Net(v8::Isolate* isolate);
~Net() override;
private:
DISALLOW_COPY_AND_ASSIGN(Net);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_NET_H_

View file

@ -0,0 +1,190 @@
// 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/browser/api/atom_api_net_log.h"
#include <utility>
#include "atom/browser/atom_browser_context.h"
#include "atom/browser/net/system_network_context_manager.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
#include "atom/common/node_includes.h"
#include "base/command_line.h"
#include "chrome/browser/browser_process.h"
#include "components/net_log/chrome_net_log.h"
#include "content/public/browser/storage_partition.h"
#include "electron/electron_version.h"
#include "native_mate/dictionary.h"
#include "native_mate/handle.h"
#include "net/url_request/url_request_context_getter.h"
namespace atom {
namespace {
scoped_refptr<base::SequencedTaskRunner> CreateFileTaskRunner() {
// The tasks posted to this sequenced task runner do synchronous File I/O for
// checking paths and setting permissions on files.
//
// These operations can be skipped on shutdown since FileNetLogObserver's API
// doesn't require things to have completed until notified of completion.
return base::CreateSequencedTaskRunnerWithTraits(
{base::MayBlock(), base::TaskPriority::USER_VISIBLE,
base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN});
}
base::File OpenFileForWriting(base::FilePath path) {
return base::File(path,
base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE);
}
void ResolvePromiseWithNetError(util::Promise promise, int32_t error) {
if (error == net::OK) {
promise.Resolve();
} else {
promise.RejectWithErrorMessage(net::ErrorToString(error));
}
}
} // namespace
namespace api {
NetLog::NetLog(v8::Isolate* isolate, AtomBrowserContext* browser_context)
: browser_context_(browser_context), weak_ptr_factory_(this) {
Init(isolate);
file_task_runner_ = CreateFileTaskRunner();
}
NetLog::~NetLog() = default;
v8::Local<v8::Promise> NetLog::StartLogging(mate::Arguments* args) {
base::FilePath log_path;
if (!args->GetNext(&log_path) || log_path.empty()) {
args->ThrowError("The first parameter must be a valid string");
return v8::Local<v8::Promise>();
}
if (net_log_exporter_) {
args->ThrowError("There is already a net log running");
return v8::Local<v8::Promise>();
}
pending_start_promise_ = base::make_optional<util::Promise>(isolate());
v8::Local<v8::Promise> handle = pending_start_promise_->GetHandle();
auto command_line_string =
base::CommandLine::ForCurrentProcess()->GetCommandLineString();
auto channel_string = std::string("Electron " ELECTRON_VERSION);
base::Value custom_constants = base::Value::FromUniquePtrValue(
net_log::ChromeNetLog::GetPlatformConstants(command_line_string,
channel_string));
auto* network_context =
content::BrowserContext::GetDefaultStoragePartition(browser_context_)
->GetNetworkContext();
network_context->CreateNetLogExporter(mojo::MakeRequest(&net_log_exporter_));
net_log_exporter_.set_connection_error_handler(
base::BindOnce(&NetLog::OnConnectionError, base::Unretained(this)));
// TODO(deepak1556): Provide more flexibility to this module
// by allowing customizations on the capturing options.
auto capture_mode = net::NetLogCaptureMode::Default();
auto max_file_size = network::mojom::NetLogExporter::kUnlimitedFileSize;
base::PostTaskAndReplyWithResult(
file_task_runner_.get(), FROM_HERE,
base::BindOnce(OpenFileForWriting, log_path),
base::BindOnce(&NetLog::StartNetLogAfterCreateFile,
weak_ptr_factory_.GetWeakPtr(), capture_mode,
max_file_size, std::move(custom_constants)));
return handle;
}
void NetLog::StartNetLogAfterCreateFile(net::NetLogCaptureMode capture_mode,
uint64_t max_file_size,
base::Value custom_constants,
base::File output_file) {
if (!net_log_exporter_) {
// Theoretically the mojo pipe could have been closed by the time we get
// here via the connection error handler. If so, the promise has already
// been resolved.
return;
}
DCHECK(pending_start_promise_);
if (!output_file.IsValid()) {
std::move(*pending_start_promise_)
.RejectWithErrorMessage(
base::File::ErrorToString(output_file.error_details()));
net_log_exporter_.reset();
return;
}
net_log_exporter_->Start(
std::move(output_file), std::move(custom_constants), capture_mode,
max_file_size,
base::BindOnce(&NetLog::NetLogStarted, base::Unretained(this)));
}
void NetLog::NetLogStarted(int32_t error) {
DCHECK(pending_start_promise_);
ResolvePromiseWithNetError(std::move(*pending_start_promise_), error);
}
void NetLog::OnConnectionError() {
net_log_exporter_.reset();
if (pending_start_promise_) {
std::move(*pending_start_promise_)
.RejectWithErrorMessage("Failed to start net log exporter");
}
}
bool NetLog::IsCurrentlyLogging() const {
return !!net_log_exporter_;
}
v8::Local<v8::Promise> NetLog::StopLogging(mate::Arguments* args) {
util::Promise promise(isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
if (net_log_exporter_) {
// Move the net_log_exporter_ into the callback to ensure that the mojo
// pointer lives long enough to resolve the promise. Moving it into the
// callback will cause the instance variable to become empty.
net_log_exporter_->Stop(
base::Value(base::Value::Type::DICTIONARY),
base::BindOnce(
[](network::mojom::NetLogExporterPtr, util::Promise promise,
int32_t error) {
ResolvePromiseWithNetError(std::move(promise), error);
},
std::move(net_log_exporter_), std::move(promise)));
} else {
promise.RejectWithErrorMessage("No net log in progress");
}
return handle;
}
// static
mate::Handle<NetLog> NetLog::Create(v8::Isolate* isolate,
AtomBrowserContext* browser_context) {
return mate::CreateHandle(isolate, new NetLog(isolate, browser_context));
}
// static
void NetLog::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "NetLog"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.SetProperty("currentlyLogging", &NetLog::IsCurrentlyLogging)
.SetMethod("startLogging", &NetLog::StartLogging)
.SetMethod("stopLogging", &NetLog::StopLogging);
}
} // namespace api
} // namespace atom

View file

@ -0,0 +1,68 @@
// 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_BROWSER_API_ATOM_API_NET_LOG_H_
#define ATOM_BROWSER_API_ATOM_API_NET_LOG_H_
#include <list>
#include <memory>
#include <string>
#include "atom/browser/api/trackable_object.h"
#include "atom/common/promise_util.h"
#include "base/callback.h"
#include "base/optional.h"
#include "base/values.h"
#include "native_mate/handle.h"
#include "services/network/public/mojom/net_log.mojom.h"
namespace atom {
class AtomBrowserContext;
namespace api {
class NetLog : public mate::TrackableObject<NetLog> {
public:
static mate::Handle<NetLog> Create(v8::Isolate* isolate,
AtomBrowserContext* browser_context);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
v8::Local<v8::Promise> StartLogging(mate::Arguments* args);
v8::Local<v8::Promise> StopLogging(mate::Arguments* args);
bool IsCurrentlyLogging() const;
protected:
explicit NetLog(v8::Isolate* isolate, AtomBrowserContext* browser_context);
~NetLog() override;
void OnConnectionError();
void StartNetLogAfterCreateFile(net::NetLogCaptureMode capture_mode,
uint64_t max_file_size,
base::Value custom_constants,
base::File output_file);
void NetLogStarted(int32_t error);
private:
AtomBrowserContext* browser_context_;
network::mojom::NetLogExporterPtr net_log_exporter_;
base::Optional<util::Promise> pending_start_promise_;
scoped_refptr<base::TaskRunner> file_task_runner_;
base::WeakPtrFactory<NetLog> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(NetLog);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_NET_LOG_H_

View file

@ -0,0 +1,274 @@
// 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/browser/api/atom_api_notification.h"
#include "atom/browser/api/atom_api_menu.h"
#include "atom/browser/atom_browser_client.h"
#include "atom/browser/browser.h"
#include "atom/common/native_mate_converters/gfx_converter.h"
#include "atom/common/native_mate_converters/image_converter.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/node_includes.h"
#include "base/guid.h"
#include "base/strings/utf_string_conversions.h"
#include "native_mate/constructor.h"
#include "native_mate/dictionary.h"
#include "native_mate/object_template_builder.h"
#include "url/gurl.h"
namespace mate {
template <>
struct Converter<atom::NotificationAction> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
atom::NotificationAction* out) {
mate::Dictionary dict;
if (!ConvertFromV8(isolate, val, &dict))
return false;
if (!dict.Get("type", &(out->type))) {
return false;
}
dict.Get("text", &(out->text));
return true;
}
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
atom::NotificationAction val) {
mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
dict.Set("text", val.text);
dict.Set("type", val.type);
return dict.GetHandle();
}
};
} // namespace mate
namespace atom {
namespace api {
Notification::Notification(v8::Isolate* isolate,
v8::Local<v8::Object> wrapper,
mate::Arguments* args) {
InitWith(isolate, wrapper);
presenter_ = static_cast<AtomBrowserClient*>(AtomBrowserClient::Get())
->GetNotificationPresenter();
mate::Dictionary opts;
if (args->GetNext(&opts)) {
opts.Get("title", &title_);
opts.Get("subtitle", &subtitle_);
opts.Get("body", &body_);
has_icon_ = opts.Get("icon", &icon_);
if (has_icon_) {
opts.Get("icon", &icon_path_);
}
opts.Get("silent", &silent_);
opts.Get("replyPlaceholder", &reply_placeholder_);
opts.Get("hasReply", &has_reply_);
opts.Get("actions", &actions_);
opts.Get("sound", &sound_);
opts.Get("closeButtonText", &close_button_text_);
}
}
Notification::~Notification() {
if (notification_)
notification_->set_delegate(nullptr);
}
// static
mate::WrappableBase* Notification::New(mate::Arguments* args) {
if (!Browser::Get()->is_ready()) {
args->ThrowError("Cannot create Notification before app is ready");
return nullptr;
}
return new Notification(args->isolate(), args->GetThis(), args);
}
// Getters
base::string16 Notification::GetTitle() const {
return title_;
}
base::string16 Notification::GetSubtitle() const {
return subtitle_;
}
base::string16 Notification::GetBody() const {
return body_;
}
bool Notification::GetSilent() const {
return silent_;
}
bool Notification::GetHasReply() const {
return has_reply_;
}
base::string16 Notification::GetReplyPlaceholder() const {
return reply_placeholder_;
}
base::string16 Notification::GetSound() const {
return sound_;
}
std::vector<atom::NotificationAction> Notification::GetActions() const {
return actions_;
}
base::string16 Notification::GetCloseButtonText() const {
return close_button_text_;
}
// Setters
void Notification::SetTitle(const base::string16& new_title) {
title_ = new_title;
}
void Notification::SetSubtitle(const base::string16& new_subtitle) {
subtitle_ = new_subtitle;
}
void Notification::SetBody(const base::string16& new_body) {
body_ = new_body;
}
void Notification::SetSilent(bool new_silent) {
silent_ = new_silent;
}
void Notification::SetHasReply(bool new_has_reply) {
has_reply_ = new_has_reply;
}
void Notification::SetReplyPlaceholder(const base::string16& new_placeholder) {
reply_placeholder_ = new_placeholder;
}
void Notification::SetSound(const base::string16& new_sound) {
sound_ = new_sound;
}
void Notification::SetActions(
const std::vector<atom::NotificationAction>& actions) {
actions_ = actions;
}
void Notification::SetCloseButtonText(const base::string16& text) {
close_button_text_ = text;
}
void Notification::NotificationAction(int index) {
Emit("action", index);
}
void Notification::NotificationClick() {
Emit("click");
}
void Notification::NotificationReplied(const std::string& reply) {
Emit("reply", reply);
}
void Notification::NotificationDisplayed() {
Emit("show");
}
void Notification::NotificationDestroyed() {}
void Notification::NotificationClosed() {
Emit("close");
}
void Notification::Close() {
if (notification_) {
notification_->Dismiss();
notification_.reset();
}
}
// Showing notifications
void Notification::Show() {
Close();
if (presenter_) {
notification_ = presenter_->CreateNotification(this, base::GenerateGUID());
if (notification_) {
atom::NotificationOptions options;
options.title = title_;
options.subtitle = subtitle_;
options.msg = body_;
options.icon_url = GURL();
options.icon = icon_.AsBitmap();
options.silent = silent_;
options.has_reply = has_reply_;
options.reply_placeholder = reply_placeholder_;
options.actions = actions_;
options.sound = sound_;
options.close_button_text = close_button_text_;
notification_->Show(options);
}
}
}
bool Notification::IsSupported() {
return !!static_cast<AtomBrowserClient*>(AtomBrowserClient::Get())
->GetNotificationPresenter();
}
// static
void Notification::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "Notification"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.MakeDestroyable()
.SetMethod("show", &Notification::Show)
.SetMethod("close", &Notification::Close)
.SetProperty("title", &Notification::GetTitle, &Notification::SetTitle)
.SetProperty("subtitle", &Notification::GetSubtitle,
&Notification::SetSubtitle)
.SetProperty("body", &Notification::GetBody, &Notification::SetBody)
.SetProperty("silent", &Notification::GetSilent, &Notification::SetSilent)
.SetProperty("hasReply", &Notification::GetHasReply,
&Notification::SetHasReply)
.SetProperty("replyPlaceholder", &Notification::GetReplyPlaceholder,
&Notification::SetReplyPlaceholder)
.SetProperty("sound", &Notification::GetSound, &Notification::SetSound)
.SetProperty("actions", &Notification::GetActions,
&Notification::SetActions)
.SetProperty("closeButtonText", &Notification::GetCloseButtonText,
&Notification::SetCloseButtonText);
}
} // namespace api
} // namespace atom
namespace {
using atom::api::Notification;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
Notification::SetConstructor(isolate,
base::BindRepeating(&Notification::New));
mate::Dictionary dict(isolate, exports);
dict.Set("Notification", Notification::GetConstructor(isolate)
->GetFunction(context)
.ToLocalChecked());
dict.SetMethod("isSupported", &Notification::IsSupported);
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_common_notification, Initialize)

View file

@ -0,0 +1,97 @@
// 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_BROWSER_API_ATOM_API_NOTIFICATION_H_
#define ATOM_BROWSER_API_ATOM_API_NOTIFICATION_H_
#include <memory>
#include <string>
#include <vector>
#include "atom/browser/api/trackable_object.h"
#include "atom/browser/notifications/notification.h"
#include "atom/browser/notifications/notification_delegate.h"
#include "atom/browser/notifications/notification_presenter.h"
#include "base/strings/utf_string_conversions.h"
#include "native_mate/handle.h"
#include "ui/gfx/image/image.h"
namespace atom {
namespace api {
class Notification : public mate::TrackableObject<Notification>,
public NotificationDelegate {
public:
static mate::WrappableBase* New(mate::Arguments* args);
static bool IsSupported();
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
// NotificationDelegate:
void NotificationAction(int index) override;
void NotificationClick() override;
void NotificationReplied(const std::string& reply) override;
void NotificationDisplayed() override;
void NotificationDestroyed() override;
void NotificationClosed() override;
protected:
Notification(v8::Isolate* isolate,
v8::Local<v8::Object> wrapper,
mate::Arguments* args);
~Notification() override;
void Show();
void Close();
// Prop Getters
base::string16 GetTitle() const;
base::string16 GetSubtitle() const;
base::string16 GetBody() const;
bool GetSilent() const;
bool GetHasReply() const;
base::string16 GetReplyPlaceholder() const;
base::string16 GetSound() const;
std::vector<atom::NotificationAction> GetActions() const;
base::string16 GetCloseButtonText() const;
// Prop Setters
void SetTitle(const base::string16& new_title);
void SetSubtitle(const base::string16& new_subtitle);
void SetBody(const base::string16& new_body);
void SetSilent(bool new_silent);
void SetHasReply(bool new_has_reply);
void SetReplyPlaceholder(const base::string16& new_reply_placeholder);
void SetSound(const base::string16& sound);
void SetActions(const std::vector<atom::NotificationAction>& actions);
void SetCloseButtonText(const base::string16& text);
private:
base::string16 title_;
base::string16 subtitle_;
base::string16 body_;
gfx::Image icon_;
base::string16 icon_path_;
bool has_icon_ = false;
bool silent_ = false;
bool has_reply_ = false;
base::string16 reply_placeholder_;
base::string16 sound_;
std::vector<atom::NotificationAction> actions_;
base::string16 close_button_text_;
atom::NotificationPresenter* presenter_;
base::WeakPtr<atom::Notification> notification_;
DISALLOW_COPY_AND_ASSIGN(Notification);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_NOTIFICATION_H_

View file

@ -0,0 +1,152 @@
// 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/browser/api/atom_api_power_monitor.h"
#include "atom/browser/browser.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/node_includes.h"
#include "base/power_monitor/power_monitor.h"
#include "base/power_monitor/power_monitor_device_source.h"
#include "native_mate/dictionary.h"
namespace mate {
template <>
struct Converter<ui::IdleState> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
const ui::IdleState& in) {
switch (in) {
case ui::IDLE_STATE_ACTIVE:
return mate::StringToV8(isolate, "active");
case ui::IDLE_STATE_IDLE:
return mate::StringToV8(isolate, "idle");
case ui::IDLE_STATE_LOCKED:
return mate::StringToV8(isolate, "locked");
case ui::IDLE_STATE_UNKNOWN:
default:
return mate::StringToV8(isolate, "unknown");
}
}
};
} // namespace mate
namespace atom {
namespace api {
PowerMonitor::PowerMonitor(v8::Isolate* isolate) {
#if defined(OS_LINUX)
SetShutdownHandler(base::BindRepeating(&PowerMonitor::ShouldShutdown,
base::Unretained(this)));
#elif defined(OS_MACOSX)
Browser::Get()->SetShutdownHandler(base::BindRepeating(
&PowerMonitor::ShouldShutdown, base::Unretained(this)));
#endif
base::PowerMonitor::Get()->AddObserver(this);
Init(isolate);
#if defined(OS_MACOSX) || defined(OS_WIN)
InitPlatformSpecificMonitors();
#endif
}
PowerMonitor::~PowerMonitor() {
base::PowerMonitor::Get()->RemoveObserver(this);
}
bool PowerMonitor::ShouldShutdown() {
return !Emit("shutdown");
}
#if defined(OS_LINUX)
void PowerMonitor::BlockShutdown() {
PowerObserverLinux::BlockShutdown();
}
void PowerMonitor::UnblockShutdown() {
PowerObserverLinux::UnblockShutdown();
}
#endif
void PowerMonitor::OnPowerStateChange(bool on_battery_power) {
if (on_battery_power)
Emit("on-battery");
else
Emit("on-ac");
}
void PowerMonitor::OnSuspend() {
Emit("suspend");
}
void PowerMonitor::OnResume() {
Emit("resume");
}
ui::IdleState PowerMonitor::GetSystemIdleState(v8::Isolate* isolate,
int idle_threshold) {
if (idle_threshold > 0) {
return ui::CalculateIdleState(idle_threshold);
} else {
isolate->ThrowException(v8::Exception::TypeError(mate::StringToV8(
isolate, "Invalid idle threshold, must be greater than 0")));
return ui::IDLE_STATE_UNKNOWN;
}
}
int PowerMonitor::GetSystemIdleTime() {
return ui::CalculateIdleTime();
}
// static
v8::Local<v8::Value> PowerMonitor::Create(v8::Isolate* isolate) {
if (!Browser::Get()->is_ready()) {
isolate->ThrowException(v8::Exception::Error(
mate::StringToV8(isolate,
"The 'powerMonitor' module can't be used before the "
"app 'ready' event")));
return v8::Null(isolate);
}
return mate::CreateHandle(isolate, new PowerMonitor(isolate)).ToV8();
}
// static
void PowerMonitor::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "PowerMonitor"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.MakeDestroyable()
#if defined(OS_LINUX)
.SetMethod("blockShutdown", &PowerMonitor::BlockShutdown)
.SetMethod("unblockShutdown", &PowerMonitor::UnblockShutdown)
#endif
.SetMethod("getSystemIdleState", &PowerMonitor::GetSystemIdleState)
.SetMethod("getSystemIdleTime", &PowerMonitor::GetSystemIdleTime);
}
} // namespace api
} // namespace atom
namespace {
using atom::api::PowerMonitor;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
mate::Dictionary dict(isolate, exports);
dict.Set("createPowerMonitor",
base::BindRepeating(&PowerMonitor::Create, isolate));
dict.Set("PowerMonitor", PowerMonitor::GetConstructor(isolate)
->GetFunction(context)
.ToLocalChecked());
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_browser_power_monitor, Initialize)

View file

@ -0,0 +1,81 @@
// 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_BROWSER_API_ATOM_API_POWER_MONITOR_H_
#define ATOM_BROWSER_API_ATOM_API_POWER_MONITOR_H_
#include "atom/browser/api/trackable_object.h"
#include "atom/browser/lib/power_observer.h"
#include "base/compiler_specific.h"
#include "native_mate/handle.h"
#include "ui/base/idle/idle.h"
namespace atom {
namespace api {
class PowerMonitor : public mate::TrackableObject<PowerMonitor>,
public PowerObserver {
public:
static v8::Local<v8::Value> Create(v8::Isolate* isolate);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
protected:
explicit PowerMonitor(v8::Isolate* isolate);
~PowerMonitor() override;
// Called by native calles.
bool ShouldShutdown();
#if defined(OS_LINUX)
// Private JS APIs.
void BlockShutdown();
void UnblockShutdown();
#endif
#if defined(OS_MACOSX) || defined(OS_WIN)
void InitPlatformSpecificMonitors();
#endif
// base::PowerObserver implementations:
void OnPowerStateChange(bool on_battery_power) override;
void OnSuspend() override;
void OnResume() override;
private:
ui::IdleState GetSystemIdleState(v8::Isolate* isolate, int idle_threshold);
int GetSystemIdleTime();
#if defined(OS_WIN)
// Static callback invoked when a message comes in to our messaging window.
static LRESULT CALLBACK WndProcStatic(HWND hwnd,
UINT message,
WPARAM wparam,
LPARAM lparam);
LRESULT CALLBACK WndProc(HWND hwnd,
UINT message,
WPARAM wparam,
LPARAM lparam);
// The window class of |window_|.
ATOM atom_;
// The handle of the module that contains the window procedure of |window_|.
HMODULE instance_;
// The window used for processing events.
HWND window_;
#endif
DISALLOW_COPY_AND_ASSIGN(PowerMonitor);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_POWER_MONITOR_H_

View file

@ -0,0 +1,76 @@
// 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/browser/api/atom_api_power_monitor.h"
#include <vector>
#import <ApplicationServices/ApplicationServices.h>
#import <Cocoa/Cocoa.h>
@interface MacLockMonitor : NSObject {
@private
std::vector<atom::api::PowerMonitor*> emitters;
}
- (void)addEmitter:(atom::api::PowerMonitor*)monitor_;
@end
@implementation MacLockMonitor
- (id)init {
if ((self = [super init])) {
NSDistributedNotificationCenter* distCenter =
[NSDistributedNotificationCenter defaultCenter];
[distCenter addObserver:self
selector:@selector(onScreenLocked:)
name:@"com.apple.screenIsLocked"
object:nil];
[distCenter addObserver:self
selector:@selector(onScreenUnlocked:)
name:@"com.apple.screenIsUnlocked"
object:nil];
}
return self;
}
- (void)dealloc {
[[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
- (void)addEmitter:(atom::api::PowerMonitor*)monitor_ {
self->emitters.push_back(monitor_);
}
- (void)onScreenLocked:(NSNotification*)notification {
for (auto*& emitter : self->emitters) {
emitter->Emit("lock-screen");
}
}
- (void)onScreenUnlocked:(NSNotification*)notification {
for (auto*& emitter : self->emitters) {
emitter->Emit("unlock-screen");
}
}
@end
namespace atom {
namespace api {
static MacLockMonitor* g_lock_monitor = nil;
void PowerMonitor::InitPlatformSpecificMonitors() {
if (!g_lock_monitor)
g_lock_monitor = [[MacLockMonitor alloc] init];
[g_lock_monitor addEmitter:this];
}
} // namespace api
} // namespace atom

View file

@ -0,0 +1,72 @@
// 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/browser/api/atom_api_power_monitor.h"
#include <windows.h>
#include <wtsapi32.h>
#include "base/win/wrapped_window_proc.h"
#include "ui/base/win/shell.h"
#include "ui/gfx/win/hwnd_util.h"
namespace atom {
namespace {
const wchar_t kPowerMonitorWindowClass[] = L"Electron_PowerMonitorHostWindow";
} // namespace
namespace api {
void PowerMonitor::InitPlatformSpecificMonitors() {
WNDCLASSEX window_class;
base::win::InitializeWindowClass(
kPowerMonitorWindowClass,
&base::win::WrappedWindowProc<PowerMonitor::WndProcStatic>, 0, 0, 0, NULL,
NULL, NULL, NULL, NULL, &window_class);
instance_ = window_class.hInstance;
atom_ = RegisterClassEx(&window_class);
// Create an offscreen window for receiving broadcast messages for the
// session lock and unlock events.
window_ = CreateWindow(MAKEINTATOM(atom_), 0, 0, 0, 0, 0, 0, HWND_MESSAGE, 0,
instance_, 0);
gfx::CheckWindowCreated(window_);
gfx::SetWindowUserData(window_, this);
// Tel windows we want to be notified with session events
WTSRegisterSessionNotification(window_, NOTIFY_FOR_THIS_SESSION);
}
LRESULT CALLBACK PowerMonitor::WndProcStatic(HWND hwnd,
UINT message,
WPARAM wparam,
LPARAM lparam) {
PowerMonitor* msg_wnd =
reinterpret_cast<PowerMonitor*>(GetWindowLongPtr(hwnd, GWLP_USERDATA));
if (msg_wnd)
return msg_wnd->WndProc(hwnd, message, wparam, lparam);
else
return ::DefWindowProc(hwnd, message, wparam, lparam);
}
LRESULT CALLBACK PowerMonitor::WndProc(HWND hwnd,
UINT message,
WPARAM wparam,
LPARAM lparam) {
if (message == WM_WTSSESSION_CHANGE) {
if (wparam == WTS_SESSION_LOCK) {
Emit("lock-screen");
} else if (wparam == WTS_SESSION_UNLOCK) {
Emit("unlock-screen");
}
}
return ::DefWindowProc(hwnd, message, wparam, lparam);
}
} // namespace api
} // namespace atom

View file

@ -0,0 +1,152 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/api/atom_api_power_save_blocker.h"
#include <string>
#include "atom/common/node_includes.h"
#include "base/bind_helpers.h"
#include "base/task/post_task.h"
#include "base/threading/thread_task_runner_handle.h"
#include "content/public/common/service_manager_connection.h"
#include "gin/dictionary.h"
#include "gin/function_template.h"
#include "services/device/public/mojom/constants.mojom.h"
#include "services/device/public/mojom/wake_lock_provider.mojom.h"
#include "services/service_manager/public/cpp/connector.h"
namespace gin {
template <>
struct Converter<device::mojom::WakeLockType> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
device::mojom::WakeLockType* out) {
std::string type;
if (!ConvertFromV8(isolate, val, &type))
return false;
if (type == "prevent-app-suspension")
*out = device::mojom::WakeLockType::kPreventAppSuspension;
else if (type == "prevent-display-sleep")
*out = device::mojom::WakeLockType::kPreventDisplaySleep;
else
return false;
return true;
}
};
} // namespace gin
namespace atom {
namespace api {
gin::WrapperInfo PowerSaveBlocker::kWrapperInfo = {gin::kEmbedderNativeGin};
PowerSaveBlocker::PowerSaveBlocker(v8::Isolate* isolate)
: current_lock_type_(device::mojom::WakeLockType::kPreventAppSuspension),
is_wake_lock_active_(false) {}
PowerSaveBlocker::~PowerSaveBlocker() {}
void PowerSaveBlocker::UpdatePowerSaveBlocker() {
if (wake_lock_types_.empty()) {
if (is_wake_lock_active_) {
GetWakeLock()->CancelWakeLock();
is_wake_lock_active_ = false;
}
return;
}
// |WakeLockType::kPreventAppSuspension| keeps system active, but allows
// screen to be turned off.
// |WakeLockType::kPreventDisplaySleep| keeps system and screen active, has a
// higher precedence level than |WakeLockType::kPreventAppSuspension|.
//
// Only the highest-precedence blocker type takes effect.
device::mojom::WakeLockType new_lock_type =
device::mojom::WakeLockType::kPreventAppSuspension;
for (const auto& element : wake_lock_types_) {
if (element.second == device::mojom::WakeLockType::kPreventDisplaySleep) {
new_lock_type = device::mojom::WakeLockType::kPreventDisplaySleep;
break;
}
}
if (current_lock_type_ != new_lock_type) {
GetWakeLock()->ChangeType(new_lock_type, base::DoNothing());
current_lock_type_ = new_lock_type;
}
if (!is_wake_lock_active_) {
GetWakeLock()->RequestWakeLock();
is_wake_lock_active_ = true;
}
}
device::mojom::WakeLock* PowerSaveBlocker::GetWakeLock() {
if (!wake_lock_) {
device::mojom::WakeLockProviderPtr wake_lock_provider;
DCHECK(content::ServiceManagerConnection::GetForProcess());
auto* connector =
content::ServiceManagerConnection::GetForProcess()->GetConnector();
connector->BindInterface(device::mojom::kServiceName,
mojo::MakeRequest(&wake_lock_provider));
wake_lock_provider->GetWakeLockWithoutContext(
device::mojom::WakeLockType::kPreventAppSuspension,
device::mojom::WakeLockReason::kOther, ELECTRON_PRODUCT_NAME,
mojo::MakeRequest(&wake_lock_));
}
return wake_lock_.get();
}
int PowerSaveBlocker::Start(device::mojom::WakeLockType type) {
static int count = 0;
wake_lock_types_[count] = type;
UpdatePowerSaveBlocker();
return count++;
}
bool PowerSaveBlocker::Stop(int id) {
bool success = wake_lock_types_.erase(id) > 0;
UpdatePowerSaveBlocker();
return success;
}
bool PowerSaveBlocker::IsStarted(int id) {
return wake_lock_types_.find(id) != wake_lock_types_.end();
}
// static
gin::Handle<PowerSaveBlocker> PowerSaveBlocker::Create(v8::Isolate* isolate) {
return gin::CreateHandle(isolate, new PowerSaveBlocker(isolate));
}
gin::ObjectTemplateBuilder PowerSaveBlocker::GetObjectTemplateBuilder(
v8::Isolate* isolate) {
return gin::Wrappable<PowerSaveBlocker>::GetObjectTemplateBuilder(isolate)
.SetMethod("start", &PowerSaveBlocker::Start)
.SetMethod("stop", &PowerSaveBlocker::Stop)
.SetMethod("isStarted", &PowerSaveBlocker::IsStarted);
}
} // namespace api
} // namespace atom
namespace {
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
gin::Dictionary dict(isolate, exports);
dict.Set("powerSaveBlocker", atom::api::PowerSaveBlocker::Create(isolate));
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_browser_power_save_blocker, Initialize)

View file

@ -0,0 +1,61 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_BROWSER_API_ATOM_API_POWER_SAVE_BLOCKER_H_
#define ATOM_BROWSER_API_ATOM_API_POWER_SAVE_BLOCKER_H_
#include <map>
#include <memory>
#include "gin/handle.h"
#include "gin/object_template_builder.h"
#include "gin/wrappable.h"
#include "services/device/public/mojom/wake_lock.mojom.h"
namespace atom {
namespace api {
class PowerSaveBlocker : public gin::Wrappable<PowerSaveBlocker> {
public:
static gin::Handle<PowerSaveBlocker> Create(v8::Isolate* isolate);
// gin::Wrappable
gin::ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) override;
static gin::WrapperInfo kWrapperInfo;
protected:
explicit PowerSaveBlocker(v8::Isolate* isolate);
~PowerSaveBlocker() override;
private:
void UpdatePowerSaveBlocker();
int Start(device::mojom::WakeLockType type);
bool Stop(int id);
bool IsStarted(int id);
device::mojom::WakeLock* GetWakeLock();
// Current wake lock level.
device::mojom::WakeLockType current_lock_type_;
// Whether the wake lock is currently active.
bool is_wake_lock_active_;
// Map from id to the corresponding blocker type for each request.
using WakeLockTypeMap = std::map<int, device::mojom::WakeLockType>;
WakeLockTypeMap wake_lock_types_;
device::mojom::WakeLockPtr wake_lock_;
DISALLOW_COPY_AND_ASSIGN(PowerSaveBlocker);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_POWER_SAVE_BLOCKER_H_

View file

@ -0,0 +1,316 @@
// 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/browser/api/atom_api_protocol.h"
#include "atom/browser/atom_browser_client.h"
#include "atom/browser/atom_browser_main_parts.h"
#include "atom/browser/browser.h"
#include "atom/browser/net/url_request_async_asar_job.h"
#include "atom/browser/net/url_request_buffer_job.h"
#include "atom/browser/net/url_request_fetch_job.h"
#include "atom/browser/net/url_request_stream_job.h"
#include "atom/browser/net/url_request_string_job.h"
#include "atom/common/native_mate_converters/callback.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_util.h"
#include "content/public/browser/child_process_security_policy.h"
#include "native_mate/dictionary.h"
#include "url/url_util.h"
using content::BrowserThread;
namespace {
// List of registered custom standard schemes.
std::vector<std::string> g_standard_schemes;
struct SchemeOptions {
bool standard = false;
bool secure = false;
bool bypassCSP = false;
bool allowServiceWorkers = false;
bool supportFetchAPI = false;
bool corsEnabled = false;
};
struct CustomScheme {
std::string scheme;
SchemeOptions options;
};
} // namespace
namespace mate {
template <>
struct Converter<CustomScheme> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
CustomScheme* out) {
mate::Dictionary dict;
if (!ConvertFromV8(isolate, val, &dict))
return false;
if (!dict.Get("scheme", &(out->scheme)))
return false;
mate::Dictionary opt;
// options are optional. Default values specified in SchemeOptions are used
if (dict.Get("privileges", &opt)) {
opt.Get("standard", &(out->options.standard));
opt.Get("supportFetchAPI", &(out->options.supportFetchAPI));
opt.Get("secure", &(out->options.secure));
opt.Get("bypassCSP", &(out->options.bypassCSP));
opt.Get("allowServiceWorkers", &(out->options.allowServiceWorkers));
opt.Get("supportFetchAPI", &(out->options.supportFetchAPI));
opt.Get("corsEnabled", &(out->options.corsEnabled));
}
return true;
}
};
} // namespace mate
namespace atom {
namespace api {
std::vector<std::string> GetStandardSchemes() {
return g_standard_schemes;
}
void RegisterSchemesAsPrivileged(v8::Local<v8::Value> val,
mate::Arguments* args) {
std::vector<CustomScheme> custom_schemes;
if (!mate::ConvertFromV8(args->isolate(), val, &custom_schemes)) {
args->ThrowError("Argument must be an array of custom schemes.");
return;
}
std::vector<std::string> secure_schemes, cspbypassing_schemes, fetch_schemes,
service_worker_schemes, cors_schemes;
for (const auto& custom_scheme : custom_schemes) {
// Register scheme to privileged list (https, wss, data, chrome-extension)
if (custom_scheme.options.standard) {
auto* policy = content::ChildProcessSecurityPolicy::GetInstance();
url::AddStandardScheme(custom_scheme.scheme.c_str(),
url::SCHEME_WITH_HOST);
g_standard_schemes.push_back(custom_scheme.scheme);
policy->RegisterWebSafeScheme(custom_scheme.scheme);
}
if (custom_scheme.options.secure) {
secure_schemes.push_back(custom_scheme.scheme);
url::AddSecureScheme(custom_scheme.scheme.c_str());
}
if (custom_scheme.options.bypassCSP) {
cspbypassing_schemes.push_back(custom_scheme.scheme);
url::AddCSPBypassingScheme(custom_scheme.scheme.c_str());
}
if (custom_scheme.options.corsEnabled) {
cors_schemes.push_back(custom_scheme.scheme);
url::AddCorsEnabledScheme(custom_scheme.scheme.c_str());
}
if (custom_scheme.options.supportFetchAPI) {
fetch_schemes.push_back(custom_scheme.scheme);
}
if (custom_scheme.options.allowServiceWorkers) {
service_worker_schemes.push_back(custom_scheme.scheme);
}
}
const auto AppendSchemesToCmdLine = [](const char* switch_name,
std::vector<std::string> schemes) {
// Add the schemes to command line switches, so child processes can also
// register them.
base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
switch_name, base::JoinString(schemes, ","));
};
AppendSchemesToCmdLine(atom::switches::kSecureSchemes, secure_schemes);
AppendSchemesToCmdLine(atom::switches::kBypassCSPSchemes,
cspbypassing_schemes);
AppendSchemesToCmdLine(atom::switches::kCORSSchemes, cors_schemes);
AppendSchemesToCmdLine(atom::switches::kFetchSchemes, fetch_schemes);
AppendSchemesToCmdLine(atom::switches::kServiceWorkerSchemes,
service_worker_schemes);
AppendSchemesToCmdLine(atom::switches::kStandardSchemes, g_standard_schemes);
}
Protocol::Protocol(v8::Isolate* isolate, AtomBrowserContext* browser_context)
: browser_context_(browser_context), weak_factory_(this) {
Init(isolate);
}
Protocol::~Protocol() {}
void Protocol::UnregisterProtocol(const std::string& scheme,
mate::Arguments* args) {
CompletionCallback callback;
args->GetNext(&callback);
auto* getter = static_cast<URLRequestContextGetter*>(
browser_context_->GetRequestContext());
base::PostTaskWithTraitsAndReplyWithResult(
FROM_HERE, {content::BrowserThread::IO},
base::BindOnce(&Protocol::UnregisterProtocolInIO,
base::RetainedRef(getter), scheme),
base::BindOnce(&Protocol::OnIOCompleted, GetWeakPtr(), callback));
}
// static
Protocol::ProtocolError Protocol::UnregisterProtocolInIO(
scoped_refptr<URLRequestContextGetter> request_context_getter,
const std::string& scheme) {
auto* job_factory = request_context_getter->job_factory();
if (!job_factory->HasProtocolHandler(scheme))
return ProtocolError::NOT_REGISTERED;
job_factory->SetProtocolHandler(scheme, nullptr);
return ProtocolError::OK;
}
bool IsProtocolHandledInIO(
scoped_refptr<URLRequestContextGetter> request_context_getter,
const std::string& scheme) {
bool is_handled =
request_context_getter->job_factory()->IsHandledProtocol(scheme);
return is_handled;
}
v8::Local<v8::Promise> Protocol::IsProtocolHandled(const std::string& scheme) {
util::Promise promise(isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
auto* getter = static_cast<URLRequestContextGetter*>(
browser_context_->GetRequestContext());
base::PostTaskWithTraitsAndReplyWithResult(
FROM_HERE, {content::BrowserThread::IO},
base::BindOnce(&IsProtocolHandledInIO, base::RetainedRef(getter), scheme),
base::BindOnce(util::Promise::ResolvePromise<bool>, std::move(promise)));
return handle;
}
void Protocol::UninterceptProtocol(const std::string& scheme,
mate::Arguments* args) {
CompletionCallback callback;
args->GetNext(&callback);
auto* getter = static_cast<URLRequestContextGetter*>(
browser_context_->GetRequestContext());
base::PostTaskWithTraitsAndReplyWithResult(
FROM_HERE, {content::BrowserThread::IO},
base::BindOnce(&Protocol::UninterceptProtocolInIO,
base::RetainedRef(getter), scheme),
base::BindOnce(&Protocol::OnIOCompleted, GetWeakPtr(), callback));
}
// static
Protocol::ProtocolError Protocol::UninterceptProtocolInIO(
scoped_refptr<URLRequestContextGetter> request_context_getter,
const std::string& scheme) {
return request_context_getter->job_factory()->UninterceptProtocol(scheme)
? ProtocolError::OK
: ProtocolError::NOT_INTERCEPTED;
}
void Protocol::OnIOCompleted(const CompletionCallback& callback,
ProtocolError error) {
// The completion callback is optional.
if (callback.is_null())
return;
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
if (error == ProtocolError::OK) {
callback.Run(v8::Null(isolate()));
} else {
std::string str = ErrorCodeToString(error);
callback.Run(v8::Exception::Error(mate::StringToV8(isolate(), str)));
}
}
std::string Protocol::ErrorCodeToString(ProtocolError error) {
switch (error) {
case ProtocolError::FAIL:
return "Failed to manipulate protocol factory";
case ProtocolError::REGISTERED:
return "The scheme has been registered";
case ProtocolError::NOT_REGISTERED:
return "The scheme has not been registered";
case ProtocolError::INTERCEPTED:
return "The scheme has been intercepted";
case ProtocolError::NOT_INTERCEPTED:
return "The scheme has not been intercepted";
default:
return "Unexpected error";
}
}
// static
mate::Handle<Protocol> Protocol::Create(v8::Isolate* isolate,
AtomBrowserContext* browser_context) {
return mate::CreateHandle(isolate, new Protocol(isolate, browser_context));
}
// static
void Protocol::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "Protocol"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.SetMethod("registerStringProtocol",
&Protocol::RegisterProtocol<URLRequestStringJob>)
.SetMethod("registerBufferProtocol",
&Protocol::RegisterProtocol<URLRequestBufferJob>)
.SetMethod("registerFileProtocol",
&Protocol::RegisterProtocol<URLRequestAsyncAsarJob>)
.SetMethod("registerHttpProtocol",
&Protocol::RegisterProtocol<URLRequestFetchJob>)
.SetMethod("registerStreamProtocol",
&Protocol::RegisterProtocol<URLRequestStreamJob>)
.SetMethod("unregisterProtocol", &Protocol::UnregisterProtocol)
.SetMethod("isProtocolHandled", &Protocol::IsProtocolHandled)
.SetMethod("interceptStringProtocol",
&Protocol::InterceptProtocol<URLRequestStringJob>)
.SetMethod("interceptBufferProtocol",
&Protocol::InterceptProtocol<URLRequestBufferJob>)
.SetMethod("interceptFileProtocol",
&Protocol::InterceptProtocol<URLRequestAsyncAsarJob>)
.SetMethod("interceptHttpProtocol",
&Protocol::InterceptProtocol<URLRequestFetchJob>)
.SetMethod("interceptStreamProtocol",
&Protocol::InterceptProtocol<URLRequestStreamJob>)
.SetMethod("uninterceptProtocol", &Protocol::UninterceptProtocol);
}
} // namespace api
} // namespace atom
namespace {
void RegisterSchemesAsPrivileged(v8::Local<v8::Value> val,
mate::Arguments* args) {
if (atom::Browser::Get()->is_ready()) {
args->ThrowError(
"protocol.registerSchemesAsPrivileged should be called before "
"app is ready");
return;
}
atom::api::RegisterSchemesAsPrivileged(val, args);
}
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
mate::Dictionary dict(isolate, exports);
dict.SetMethod("registerSchemesAsPrivileged", &RegisterSchemesAsPrivileged);
dict.SetMethod("getStandardSchemes", &atom::api::GetStandardSchemes);
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_browser_protocol, Initialize)

View file

@ -0,0 +1,198 @@
// 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_BROWSER_API_ATOM_API_PROTOCOL_H_
#define ATOM_BROWSER_API_ATOM_API_PROTOCOL_H_
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "atom/browser/api/trackable_object.h"
#include "atom/browser/atom_browser_context.h"
#include "atom/browser/net/atom_url_request_job_factory.h"
#include "atom/common/promise_util.h"
#include "base/callback.h"
#include "base/memory/weak_ptr.h"
#include "base/task/post_task.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "native_mate/arguments.h"
#include "native_mate/dictionary.h"
#include "native_mate/handle.h"
#include "net/url_request/url_request_context.h"
namespace base {
class DictionaryValue;
}
namespace atom {
namespace api {
std::vector<std::string> GetStandardSchemes();
void RegisterSchemesAsPrivileged(v8::Local<v8::Value> val,
mate::Arguments* args);
class Protocol : public mate::TrackableObject<Protocol> {
public:
using Handler = base::RepeatingCallback<void(const base::DictionaryValue&,
v8::Local<v8::Value>)>;
using CompletionCallback =
base::RepeatingCallback<void(v8::Local<v8::Value>)>;
static mate::Handle<Protocol> Create(v8::Isolate* isolate,
AtomBrowserContext* browser_context);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
protected:
Protocol(v8::Isolate* isolate, AtomBrowserContext* browser_context);
~Protocol() override;
private:
// Possible errors.
enum class ProtocolError {
OK, // no error
FAIL, // operation failed, should never occur
REGISTERED,
NOT_REGISTERED,
INTERCEPTED,
NOT_INTERCEPTED,
};
// The protocol handler that will create a protocol handler for certain
// request job.
template <typename RequestJob>
class CustomProtocolHandler
: public net::URLRequestJobFactory::ProtocolHandler {
public:
CustomProtocolHandler(v8::Isolate* isolate,
net::URLRequestContextGetter* request_context,
const Handler& handler)
: isolate_(isolate),
request_context_(request_context),
handler_(handler) {}
~CustomProtocolHandler() override {}
net::URLRequestJob* MaybeCreateJob(
net::URLRequest* request,
net::NetworkDelegate* network_delegate) const override {
RequestJob* request_job = new RequestJob(request, network_delegate);
request_job->SetHandlerInfo(isolate_, request_context_, handler_);
return request_job;
}
private:
v8::Isolate* isolate_;
net::URLRequestContextGetter* request_context_;
Protocol::Handler handler_;
DISALLOW_COPY_AND_ASSIGN(CustomProtocolHandler);
};
// Register the protocol with certain request job.
template <typename RequestJob>
void RegisterProtocol(const std::string& scheme,
const Handler& handler,
mate::Arguments* args) {
CompletionCallback callback;
args->GetNext(&callback);
auto* getter = static_cast<URLRequestContextGetter*>(
browser_context_->GetRequestContext());
base::PostTaskWithTraitsAndReplyWithResult(
FROM_HERE, {content::BrowserThread::IO},
base::BindOnce(&Protocol::RegisterProtocolInIO<RequestJob>,
base::RetainedRef(getter), isolate(), scheme, handler),
base::BindOnce(&Protocol::OnIOCompleted, GetWeakPtr(), callback));
}
template <typename RequestJob>
static ProtocolError RegisterProtocolInIO(
scoped_refptr<URLRequestContextGetter> request_context_getter,
v8::Isolate* isolate,
const std::string& scheme,
const Handler& handler) {
auto* job_factory = request_context_getter->job_factory();
if (job_factory->IsHandledProtocol(scheme))
return ProtocolError::REGISTERED;
auto protocol_handler = std::make_unique<CustomProtocolHandler<RequestJob>>(
isolate, request_context_getter.get(), handler);
if (job_factory->SetProtocolHandler(scheme, std::move(protocol_handler)))
return ProtocolError::OK;
else
return ProtocolError::FAIL;
}
// Unregister the protocol handler that handles |scheme|.
void UnregisterProtocol(const std::string& scheme, mate::Arguments* args);
static ProtocolError UnregisterProtocolInIO(
scoped_refptr<URLRequestContextGetter> request_context_getter,
const std::string& scheme);
// Whether the protocol has handler registered.
v8::Local<v8::Promise> IsProtocolHandled(const std::string& scheme);
// Replace the protocol handler with a new one.
template <typename RequestJob>
void InterceptProtocol(const std::string& scheme,
const Handler& handler,
mate::Arguments* args) {
CompletionCallback callback;
args->GetNext(&callback);
auto* getter = static_cast<URLRequestContextGetter*>(
browser_context_->GetRequestContext());
base::PostTaskWithTraitsAndReplyWithResult(
FROM_HERE, {content::BrowserThread::IO},
base::BindOnce(&Protocol::InterceptProtocolInIO<RequestJob>,
base::RetainedRef(getter), isolate(), scheme, handler),
base::BindOnce(&Protocol::OnIOCompleted, GetWeakPtr(), callback));
}
template <typename RequestJob>
static ProtocolError InterceptProtocolInIO(
scoped_refptr<URLRequestContextGetter> request_context_getter,
v8::Isolate* isolate,
const std::string& scheme,
const Handler& handler) {
auto* job_factory = request_context_getter->job_factory();
if (!job_factory->IsHandledProtocol(scheme))
return ProtocolError::NOT_REGISTERED;
// It is possible a protocol is handled but can not be intercepted.
if (!job_factory->HasProtocolHandler(scheme))
return ProtocolError::FAIL;
auto protocol_handler = std::make_unique<CustomProtocolHandler<RequestJob>>(
isolate, request_context_getter.get(), handler);
if (!job_factory->InterceptProtocol(scheme, std::move(protocol_handler)))
return ProtocolError::INTERCEPTED;
return ProtocolError::OK;
}
// Restore the |scheme| to its original protocol handler.
void UninterceptProtocol(const std::string& scheme, mate::Arguments* args);
static ProtocolError UninterceptProtocolInIO(
scoped_refptr<URLRequestContextGetter> request_context_getter,
const std::string& scheme);
// Convert error code to JS exception and call the callback.
void OnIOCompleted(const CompletionCallback& callback, ProtocolError error);
// Convert error code to string.
std::string ErrorCodeToString(ProtocolError error);
base::WeakPtr<Protocol> GetWeakPtr() { return weak_factory_.GetWeakPtr(); }
scoped_refptr<AtomBrowserContext> browser_context_;
base::WeakPtrFactory<Protocol> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(Protocol);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_PROTOCOL_H_

View file

@ -0,0 +1,181 @@
// Copyright (c) 2019 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/api/atom_api_protocol_ns.h"
#include <memory>
#include <utility>
#include "atom/browser/atom_browser_context.h"
#include "atom/common/native_mate_converters/net_converter.h"
#include "atom/common/native_mate_converters/once_callback.h"
#include "atom/common/promise_util.h"
#include "base/stl_util.h"
namespace atom {
namespace api {
namespace {
const char* kBuiltinSchemes[] = {
"about", "file", "http", "https", "data", "filesystem",
};
// Convert error code to string.
std::string ErrorCodeToString(ProtocolError error) {
switch (error) {
case ProtocolError::REGISTERED:
return "The scheme has been registered";
case ProtocolError::NOT_REGISTERED:
return "The scheme has not been registered";
case ProtocolError::INTERCEPTED:
return "The scheme has been intercepted";
case ProtocolError::NOT_INTERCEPTED:
return "The scheme has not been intercepted";
default:
return "Unexpected error";
}
}
} // namespace
ProtocolNS::ProtocolNS(v8::Isolate* isolate,
AtomBrowserContext* browser_context) {
Init(isolate);
AttachAsUserData(browser_context);
}
ProtocolNS::~ProtocolNS() = default;
void ProtocolNS::RegisterURLLoaderFactories(
content::ContentBrowserClient::NonNetworkURLLoaderFactoryMap* factories) {
for (const auto& it : handlers_) {
factories->emplace(it.first, std::make_unique<AtomURLLoaderFactory>(
it.second.first, it.second.second));
}
}
ProtocolError ProtocolNS::RegisterProtocol(ProtocolType type,
const std::string& scheme,
const ProtocolHandler& handler) {
ProtocolError error = ProtocolError::OK;
if (!base::ContainsKey(handlers_, scheme))
handlers_[scheme] = std::make_pair(type, handler);
else
error = ProtocolError::REGISTERED;
return error;
}
void ProtocolNS::UnregisterProtocol(const std::string& scheme,
mate::Arguments* args) {
ProtocolError error = ProtocolError::OK;
if (base::ContainsKey(handlers_, scheme))
handlers_.erase(scheme);
else
error = ProtocolError::NOT_REGISTERED;
HandleOptionalCallback(args, error);
}
bool ProtocolNS::IsProtocolRegistered(const std::string& scheme) {
return base::ContainsKey(handlers_, scheme);
}
ProtocolError ProtocolNS::InterceptProtocol(ProtocolType type,
const std::string& scheme,
const ProtocolHandler& handler) {
ProtocolError error = ProtocolError::OK;
if (!base::ContainsKey(intercept_handlers_, scheme))
intercept_handlers_[scheme] = std::make_pair(type, handler);
else
error = ProtocolError::INTERCEPTED;
return error;
}
void ProtocolNS::UninterceptProtocol(const std::string& scheme,
mate::Arguments* args) {
ProtocolError error = ProtocolError::OK;
if (base::ContainsKey(intercept_handlers_, scheme))
intercept_handlers_.erase(scheme);
else
error = ProtocolError::NOT_INTERCEPTED;
HandleOptionalCallback(args, error);
}
bool ProtocolNS::IsProtocolIntercepted(const std::string& scheme) {
return base::ContainsKey(intercept_handlers_, scheme);
}
v8::Local<v8::Promise> ProtocolNS::IsProtocolHandled(
const std::string& scheme) {
util::Promise promise(isolate());
promise.Resolve(IsProtocolRegistered(scheme) ||
IsProtocolIntercepted(scheme) ||
// The |isProtocolHandled| should return true for builtin
// schemes, however with NetworkService it is impossible to
// know which schemes are registered until a real network
// request is sent.
// So we have to test against a hard-coded builtin schemes
// list make it work with old code. We should deprecate this
// API with the new |isProtocolRegistered| API.
base::ContainsValue(kBuiltinSchemes, scheme));
return promise.GetHandle();
}
void ProtocolNS::HandleOptionalCallback(mate::Arguments* args,
ProtocolError error) {
CompletionCallback callback;
if (args->GetNext(&callback)) {
if (error == ProtocolError::OK)
callback.Run(v8::Null(args->isolate()));
else
callback.Run(v8::Exception::Error(
mate::StringToV8(isolate(), ErrorCodeToString(error))));
}
}
// static
mate::Handle<ProtocolNS> ProtocolNS::Create(
v8::Isolate* isolate,
AtomBrowserContext* browser_context) {
return mate::CreateHandle(isolate, new ProtocolNS(isolate, browser_context));
}
// static
void ProtocolNS::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "Protocol"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.SetMethod("registerStringProtocol",
&ProtocolNS::RegisterProtocolFor<ProtocolType::kString>)
.SetMethod("registerBufferProtocol",
&ProtocolNS::RegisterProtocolFor<ProtocolType::kBuffer>)
.SetMethod("registerFileProtocol",
&ProtocolNS::RegisterProtocolFor<ProtocolType::kFile>)
.SetMethod("registerHttpProtocol",
&ProtocolNS::RegisterProtocolFor<ProtocolType::kHttp>)
.SetMethod("registerStreamProtocol",
&ProtocolNS::RegisterProtocolFor<ProtocolType::kStream>)
.SetMethod("registerProtocol",
&ProtocolNS::RegisterProtocolFor<ProtocolType::kFree>)
.SetMethod("unregisterProtocol", &ProtocolNS::UnregisterProtocol)
.SetMethod("isProtocolRegistered", &ProtocolNS::IsProtocolRegistered)
.SetMethod("isProtocolHandled", &ProtocolNS::IsProtocolHandled)
.SetMethod("interceptStringProtocol",
&ProtocolNS::InterceptProtocolFor<ProtocolType::kString>)
.SetMethod("interceptBufferProtocol",
&ProtocolNS::InterceptProtocolFor<ProtocolType::kBuffer>)
.SetMethod("interceptFileProtocol",
&ProtocolNS::InterceptProtocolFor<ProtocolType::kFile>)
.SetMethod("interceptHttpProtocol",
&ProtocolNS::InterceptProtocolFor<ProtocolType::kHttp>)
.SetMethod("interceptStreamProtocol",
&ProtocolNS::InterceptProtocolFor<ProtocolType::kStream>)
.SetMethod("interceptProtocol",
&ProtocolNS::InterceptProtocolFor<ProtocolType::kFree>)
.SetMethod("uninterceptProtocol", &ProtocolNS::UninterceptProtocol)
.SetMethod("isProtocolIntercepted", &ProtocolNS::IsProtocolIntercepted);
}
} // namespace api
} // namespace atom

View file

@ -0,0 +1,95 @@
// Copyright (c) 2019 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_BROWSER_API_ATOM_API_PROTOCOL_NS_H_
#define ATOM_BROWSER_API_ATOM_API_PROTOCOL_NS_H_
#include <string>
#include "atom/browser/api/trackable_object.h"
#include "atom/browser/net/atom_url_loader_factory.h"
#include "content/public/browser/content_browser_client.h"
#include "native_mate/dictionary.h"
#include "native_mate/handle.h"
namespace atom {
class AtomBrowserContext;
namespace api {
// Possible errors.
enum class ProtocolError {
OK, // no error
REGISTERED,
NOT_REGISTERED,
INTERCEPTED,
NOT_INTERCEPTED,
};
// Protocol implementation based on network services.
class ProtocolNS : public mate::TrackableObject<ProtocolNS> {
public:
static mate::Handle<ProtocolNS> Create(v8::Isolate* isolate,
AtomBrowserContext* browser_context);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
// Used by AtomBrowserClient for creating URLLoaderFactory.
void RegisterURLLoaderFactories(
content::ContentBrowserClient::NonNetworkURLLoaderFactoryMap* factories);
const HandlersMap& intercept_handlers() const { return intercept_handlers_; }
private:
ProtocolNS(v8::Isolate* isolate, AtomBrowserContext* browser_context);
~ProtocolNS() override;
// Callback types.
using CompletionCallback =
base::RepeatingCallback<void(v8::Local<v8::Value>)>;
// JS APIs.
ProtocolError RegisterProtocol(ProtocolType type,
const std::string& scheme,
const ProtocolHandler& handler);
void UnregisterProtocol(const std::string& scheme, mate::Arguments* args);
bool IsProtocolRegistered(const std::string& scheme);
ProtocolError InterceptProtocol(ProtocolType type,
const std::string& scheme,
const ProtocolHandler& handler);
void UninterceptProtocol(const std::string& scheme, mate::Arguments* args);
bool IsProtocolIntercepted(const std::string& scheme);
// Old async version of IsProtocolRegistered.
v8::Local<v8::Promise> IsProtocolHandled(const std::string& scheme);
// Helper for converting old registration APIs to new RegisterProtocol API.
template <ProtocolType type>
void RegisterProtocolFor(const std::string& scheme,
const ProtocolHandler& handler,
mate::Arguments* args) {
HandleOptionalCallback(args, RegisterProtocol(type, scheme, handler));
}
template <ProtocolType type>
void InterceptProtocolFor(const std::string& scheme,
const ProtocolHandler& handler,
mate::Arguments* args) {
HandleOptionalCallback(args, InterceptProtocol(type, scheme, handler));
}
// Be compatible with old interface, which accepts optional callback.
void HandleOptionalCallback(mate::Arguments* args, ProtocolError error);
HandlersMap handlers_;
HandlersMap intercept_handlers_;
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_PROTOCOL_NS_H_

View file

@ -0,0 +1,174 @@
// 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/browser/api/atom_api_screen.h"
#include <algorithm>
#include <string>
#include "atom/browser/api/atom_api_browser_window.h"
#include "atom/browser/browser.h"
#include "atom/common/native_mate_converters/gfx_converter.h"
#include "atom/common/node_includes.h"
#include "base/bind.h"
#include "native_mate/dictionary.h"
#include "native_mate/object_template_builder.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/gfx/geometry/point.h"
#if defined(OS_WIN)
#include "ui/display/win/screen_win.h"
#endif
namespace atom {
namespace api {
namespace {
// Find an item in container according to its ID.
template <class T>
typename T::iterator FindById(T* container, int id) {
auto predicate = [id](const typename T::value_type& item) -> bool {
return item.id() == id;
};
return std::find_if(container->begin(), container->end(), predicate);
}
// Convert the changed_metrics bitmask to string array.
std::vector<std::string> MetricsToArray(uint32_t metrics) {
std::vector<std::string> array;
if (metrics & display::DisplayObserver::DISPLAY_METRIC_BOUNDS)
array.push_back("bounds");
if (metrics & display::DisplayObserver::DISPLAY_METRIC_WORK_AREA)
array.push_back("workArea");
if (metrics & display::DisplayObserver::DISPLAY_METRIC_DEVICE_SCALE_FACTOR)
array.push_back("scaleFactor");
if (metrics & display::DisplayObserver::DISPLAY_METRIC_ROTATION)
array.push_back("rotation");
return array;
}
} // namespace
Screen::Screen(v8::Isolate* isolate, display::Screen* screen)
: screen_(screen) {
screen_->AddObserver(this);
Init(isolate);
}
Screen::~Screen() {
screen_->RemoveObserver(this);
}
gfx::Point Screen::GetCursorScreenPoint() {
return screen_->GetCursorScreenPoint();
}
display::Display Screen::GetPrimaryDisplay() {
return screen_->GetPrimaryDisplay();
}
std::vector<display::Display> Screen::GetAllDisplays() {
return screen_->GetAllDisplays();
}
display::Display Screen::GetDisplayNearestPoint(const gfx::Point& point) {
return screen_->GetDisplayNearestPoint(point);
}
display::Display Screen::GetDisplayMatching(const gfx::Rect& match_rect) {
return screen_->GetDisplayMatching(match_rect);
}
#if defined(OS_WIN)
static gfx::Rect ScreenToDIPRect(atom::NativeWindow* window,
const gfx::Rect& rect) {
HWND hwnd = window ? window->GetAcceleratedWidget() : nullptr;
return display::win::ScreenWin::ScreenToDIPRect(hwnd, rect);
}
static gfx::Rect DIPToScreenRect(atom::NativeWindow* window,
const gfx::Rect& rect) {
HWND hwnd = window ? window->GetAcceleratedWidget() : nullptr;
return display::win::ScreenWin::DIPToScreenRect(hwnd, rect);
}
#endif
void Screen::OnDisplayAdded(const display::Display& new_display) {
Emit("display-added", new_display);
}
void Screen::OnDisplayRemoved(const display::Display& old_display) {
Emit("display-removed", old_display);
}
void Screen::OnDisplayMetricsChanged(const display::Display& display,
uint32_t changed_metrics) {
Emit("display-metrics-changed", display, MetricsToArray(changed_metrics));
}
// static
v8::Local<v8::Value> Screen::Create(v8::Isolate* isolate) {
if (!Browser::Get()->is_ready()) {
isolate->ThrowException(v8::Exception::Error(mate::StringToV8(
isolate,
"The 'screen' module can't be used before the app 'ready' event")));
return v8::Null(isolate);
}
display::Screen* screen = display::Screen::GetScreen();
if (!screen) {
isolate->ThrowException(v8::Exception::Error(
mate::StringToV8(isolate, "Failed to get screen information")));
return v8::Null(isolate);
}
return mate::CreateHandle(isolate, new Screen(isolate, screen)).ToV8();
}
// static
void Screen::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "Screen"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.SetMethod("getCursorScreenPoint", &Screen::GetCursorScreenPoint)
.SetMethod("getPrimaryDisplay", &Screen::GetPrimaryDisplay)
.SetMethod("getAllDisplays", &Screen::GetAllDisplays)
.SetMethod("getDisplayNearestPoint", &Screen::GetDisplayNearestPoint)
#if defined(OS_WIN)
.SetMethod("screenToDipPoint", &display::win::ScreenWin::ScreenToDIPPoint)
.SetMethod("dipToScreenPoint", &display::win::ScreenWin::DIPToScreenPoint)
.SetMethod("screenToDipRect", &ScreenToDIPRect)
.SetMethod("dipToScreenRect", &DIPToScreenRect)
#endif
.SetMethod("getDisplayMatching", &Screen::GetDisplayMatching);
}
} // namespace api
} // namespace atom
namespace {
using atom::api::Screen;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
mate::Dictionary dict(isolate, exports);
dict.Set("createScreen", base::BindRepeating(&Screen::Create, isolate));
dict.Set(
"Screen",
Screen::GetConstructor(isolate)->GetFunction(context).ToLocalChecked());
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_common_screen, Initialize)

View file

@ -0,0 +1,59 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_BROWSER_API_ATOM_API_SCREEN_H_
#define ATOM_BROWSER_API_ATOM_API_SCREEN_H_
#include <vector>
#include "atom/browser/api/event_emitter.h"
#include "native_mate/handle.h"
#include "ui/display/display_observer.h"
#include "ui/display/screen.h"
namespace gfx {
class Point;
class Rect;
class Screen;
} // namespace gfx
namespace atom {
namespace api {
class Screen : public mate::EventEmitter<Screen>,
public display::DisplayObserver {
public:
static v8::Local<v8::Value> Create(v8::Isolate* isolate);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
protected:
Screen(v8::Isolate* isolate, display::Screen* screen);
~Screen() override;
gfx::Point GetCursorScreenPoint();
display::Display GetPrimaryDisplay();
std::vector<display::Display> GetAllDisplays();
display::Display GetDisplayNearestPoint(const gfx::Point& point);
display::Display GetDisplayMatching(const gfx::Rect& match_rect);
// display::DisplayObserver:
void OnDisplayAdded(const display::Display& new_display) override;
void OnDisplayRemoved(const display::Display& old_display) override;
void OnDisplayMetricsChanged(const display::Display& display,
uint32_t changed_metrics) override;
private:
display::Screen* screen_;
DISALLOW_COPY_AND_ASSIGN(Screen);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_SCREEN_H_

View file

@ -0,0 +1,745 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/api/atom_api_session.h"
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "atom/browser/api/atom_api_cookies.h"
#include "atom/browser/api/atom_api_download_item.h"
#include "atom/browser/api/atom_api_net_log.h"
#include "atom/browser/api/atom_api_protocol.h"
#include "atom/browser/api/atom_api_protocol_ns.h"
#include "atom/browser/api/atom_api_web_request.h"
#include "atom/browser/atom_browser_context.h"
#include "atom/browser/atom_browser_main_parts.h"
#include "atom/browser/atom_permission_manager.h"
#include "atom/browser/browser.h"
#include "atom/browser/media/media_device_id_salt.h"
#include "atom/browser/net/atom_cert_verifier.h"
#include "atom/browser/net/system_network_context_manager.h"
#include "atom/browser/session_preferences.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/content_converter.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
#include "atom/common/native_mate_converters/gurl_converter.h"
#include "atom/common/native_mate_converters/net_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/node_includes.h"
#include "atom/common/options_switches.h"
#include "base/files/file_path.h"
#include "base/guid.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/task/post_task.h"
#include "chrome/browser/browser_process.h"
#include "chrome/common/pref_names.h"
#include "components/download/public/common/download_danger_type.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/value_map_pref_store.h"
#include "components/proxy_config/proxy_config_dictionary.h"
#include "components/proxy_config/proxy_config_pref_names.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/download_item_utils.h"
#include "content/public/browser/download_manager_delegate.h"
#include "content/public/browser/network_service_instance.h"
#include "content/public/browser/storage_partition.h"
#include "native_mate/dictionary.h"
#include "native_mate/object_template_builder.h"
#include "net/base/completion_repeating_callback.h"
#include "net/base/load_flags.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_auth_preferences.h"
#include "net/http/http_cache.h"
#include "net/http/http_transaction_factory.h"
#include "net/url_request/static_http_user_agent_settings.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
#include "services/network/public/cpp/features.h"
#include "ui/base/l10n/l10n_util.h"
using content::BrowserThread;
using content::StoragePartition;
namespace {
struct ClearStorageDataOptions {
GURL origin;
uint32_t storage_types = StoragePartition::REMOVE_DATA_MASK_ALL;
uint32_t quota_types = StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL;
};
uint32_t GetStorageMask(const std::vector<std::string>& storage_types) {
uint32_t storage_mask = 0;
for (const auto& it : storage_types) {
auto type = base::ToLowerASCII(it);
if (type == "appcache")
storage_mask |= StoragePartition::REMOVE_DATA_MASK_APPCACHE;
else if (type == "cookies")
storage_mask |= StoragePartition::REMOVE_DATA_MASK_COOKIES;
else if (type == "filesystem")
storage_mask |= StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS;
else if (type == "indexdb")
storage_mask |= StoragePartition::REMOVE_DATA_MASK_INDEXEDDB;
else if (type == "localstorage")
storage_mask |= StoragePartition::REMOVE_DATA_MASK_LOCAL_STORAGE;
else if (type == "shadercache")
storage_mask |= StoragePartition::REMOVE_DATA_MASK_SHADER_CACHE;
else if (type == "websql")
storage_mask |= StoragePartition::REMOVE_DATA_MASK_WEBSQL;
else if (type == "serviceworkers")
storage_mask |= StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS;
else if (type == "cachestorage")
storage_mask |= StoragePartition::REMOVE_DATA_MASK_CACHE_STORAGE;
}
return storage_mask;
}
uint32_t GetQuotaMask(const std::vector<std::string>& quota_types) {
uint32_t quota_mask = 0;
for (const auto& it : quota_types) {
auto type = base::ToLowerASCII(it);
if (type == "temporary")
quota_mask |= StoragePartition::QUOTA_MANAGED_STORAGE_MASK_TEMPORARY;
else if (type == "persistent")
quota_mask |= StoragePartition::QUOTA_MANAGED_STORAGE_MASK_PERSISTENT;
else if (type == "syncable")
quota_mask |= StoragePartition::QUOTA_MANAGED_STORAGE_MASK_SYNCABLE;
}
return quota_mask;
}
void SetUserAgentInIO(scoped_refptr<net::URLRequestContextGetter> getter,
const std::string& accept_lang,
const std::string& user_agent) {
getter->GetURLRequestContext()->set_http_user_agent_settings(
new net::StaticHttpUserAgentSettings(
net::HttpUtil::GenerateAcceptLanguageHeader(accept_lang),
user_agent));
}
} // namespace
namespace mate {
template <>
struct Converter<ClearStorageDataOptions> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
ClearStorageDataOptions* out) {
mate::Dictionary options;
if (!ConvertFromV8(isolate, val, &options))
return false;
options.Get("origin", &out->origin);
std::vector<std::string> types;
if (options.Get("storages", &types))
out->storage_types = GetStorageMask(types);
if (options.Get("quotas", &types))
out->quota_types = GetQuotaMask(types);
return true;
}
};
template <>
struct Converter<atom::VerifyRequestParams> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
atom::VerifyRequestParams val) {
mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
dict.Set("hostname", val.hostname);
dict.Set("certificate", val.certificate);
dict.Set("verificationResult", val.default_result);
dict.Set("errorCode", val.error_code);
return dict.GetHandle();
}
};
} // namespace mate
namespace atom {
namespace api {
namespace {
const char kPersistPrefix[] = "persist:";
// Referenced session objects.
std::map<uint32_t, v8::Global<v8::Object>> g_sessions;
void SetCertVerifyProcInIO(
const scoped_refptr<net::URLRequestContextGetter>& context_getter,
const AtomCertVerifier::VerifyProc& proc) {
auto* request_context = context_getter->GetURLRequestContext();
static_cast<AtomCertVerifier*>(request_context->cert_verifier())
->SetVerifyProc(proc);
}
void DownloadIdCallback(content::DownloadManager* download_manager,
const base::FilePath& path,
const std::vector<GURL>& url_chain,
const std::string& mime_type,
int64_t offset,
int64_t length,
const std::string& last_modified,
const std::string& etag,
const base::Time& start_time,
uint32_t id) {
download_manager->CreateDownloadItem(
base::GenerateGUID(), id, path, path, url_chain, GURL(), GURL(), GURL(),
GURL(), base::nullopt, mime_type, mime_type, start_time, base::Time(),
etag, last_modified, offset, length, std::string(),
download::DownloadItem::INTERRUPTED,
download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
download::DOWNLOAD_INTERRUPT_REASON_NETWORK_TIMEOUT, false, base::Time(),
false, std::vector<download::DownloadItem::ReceivedSlice>());
}
void DestroyGlobalHandle(v8::Isolate* isolate,
const v8::Global<v8::Value>& global_handle) {
v8::Locker locker(isolate);
v8::HandleScope handle_scope(isolate);
if (!global_handle.IsEmpty()) {
v8::Local<v8::Value> local_handle = global_handle.Get(isolate);
v8::Local<v8::Object> object;
if (local_handle->IsObject() &&
local_handle->ToObject(isolate->GetCurrentContext()).ToLocal(&object)) {
void* ptr = object->GetAlignedPointerFromInternalField(0);
if (!ptr)
return;
delete static_cast<mate::WrappableBase*>(ptr);
object->SetAlignedPointerInInternalField(0, nullptr);
}
}
}
} // namespace
Session::Session(v8::Isolate* isolate, AtomBrowserContext* browser_context)
: network_emulation_token_(base::UnguessableToken::Create()),
browser_context_(browser_context) {
// Observe DownloadManager to get download notifications.
content::BrowserContext::GetDownloadManager(browser_context)
->AddObserver(this);
new SessionPreferences(browser_context);
Init(isolate);
AttachAsUserData(browser_context);
}
Session::~Session() {
content::BrowserContext::GetDownloadManager(browser_context())
->RemoveObserver(this);
DestroyGlobalHandle(isolate(), cookies_);
DestroyGlobalHandle(isolate(), web_request_);
DestroyGlobalHandle(isolate(), protocol_);
DestroyGlobalHandle(isolate(), net_log_);
g_sessions.erase(weak_map_id());
}
void Session::OnDownloadCreated(content::DownloadManager* manager,
download::DownloadItem* item) {
if (item->IsSavePackageDownload())
return;
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
auto handle = DownloadItem::Create(isolate(), item);
if (item->GetState() == download::DownloadItem::INTERRUPTED)
handle->SetSavePath(item->GetTargetFilePath());
content::WebContents* web_contents =
content::DownloadItemUtils::GetWebContents(item);
bool prevent_default = Emit("will-download", handle, web_contents);
if (prevent_default) {
item->Cancel(true);
item->Remove();
}
}
v8::Local<v8::Promise> Session::ResolveProxy(mate::Arguments* args) {
v8::Isolate* isolate = args->isolate();
util::Promise promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
GURL url;
args->GetNext(&url);
browser_context_->GetResolveProxyHelper()->ResolveProxy(
url, base::BindOnce(util::Promise::ResolvePromise<std::string>,
std::move(promise)));
return handle;
}
v8::Local<v8::Promise> Session::GetCacheSize() {
auto* isolate = v8::Isolate::GetCurrent();
auto promise = util::Promise(isolate);
auto handle = promise.GetHandle();
content::BrowserContext::GetDefaultStoragePartition(browser_context_.get())
->GetNetworkContext()
->ComputeHttpCacheSize(base::Time(), base::Time::Max(),
base::BindOnce(
[](util::Promise promise, bool is_upper_bound,
int64_t size_or_error) {
if (size_or_error < 0) {
promise.RejectWithErrorMessage(
net::ErrorToString(size_or_error));
} else {
promise.Resolve(size_or_error);
}
},
std::move(promise)));
return handle;
}
v8::Local<v8::Promise> Session::ClearCache() {
auto* isolate = v8::Isolate::GetCurrent();
auto promise = util::Promise(isolate);
auto handle = promise.GetHandle();
content::BrowserContext::GetDefaultStoragePartition(browser_context_.get())
->GetNetworkContext()
->ClearHttpCache(base::Time(), base::Time::Max(), nullptr,
base::BindOnce(util::Promise::ResolveEmptyPromise,
std::move(promise)));
return handle;
}
v8::Local<v8::Promise> Session::ClearStorageData(mate::Arguments* args) {
v8::Isolate* isolate = args->isolate();
util::Promise promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
ClearStorageDataOptions options;
args->GetNext(&options);
auto* storage_partition =
content::BrowserContext::GetStoragePartition(browser_context(), nullptr);
if (options.storage_types & StoragePartition::REMOVE_DATA_MASK_COOKIES) {
// Reset media device id salt when cookies are cleared.
// https://w3c.github.io/mediacapture-main/#dom-mediadeviceinfo-deviceid
MediaDeviceIDSalt::Reset(browser_context()->prefs());
}
storage_partition->ClearData(
options.storage_types, options.quota_types, options.origin, base::Time(),
base::Time::Max(),
base::BindOnce(util::Promise::ResolveEmptyPromise, std::move(promise)));
return handle;
}
void Session::FlushStorageData() {
auto* storage_partition =
content::BrowserContext::GetStoragePartition(browser_context(), nullptr);
storage_partition->Flush();
}
v8::Local<v8::Promise> Session::SetProxy(mate::Arguments* args) {
v8::Isolate* isolate = args->isolate();
util::Promise promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
mate::Dictionary options;
args->GetNext(&options);
if (!browser_context_->in_memory_pref_store()) {
promise.Resolve();
return handle;
}
std::string proxy_rules, bypass_list, pac_url;
options.Get("pacScript", &pac_url);
options.Get("proxyRules", &proxy_rules);
options.Get("proxyBypassRules", &bypass_list);
// pacScript takes precedence over proxyRules.
if (!pac_url.empty()) {
browser_context_->in_memory_pref_store()->SetValue(
proxy_config::prefs::kProxy,
std::make_unique<base::Value>(ProxyConfigDictionary::CreatePacScript(
pac_url, true /* pac_mandatory */)),
WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS);
} else {
browser_context_->in_memory_pref_store()->SetValue(
proxy_config::prefs::kProxy,
std::make_unique<base::Value>(ProxyConfigDictionary::CreateFixedServers(
proxy_rules, bypass_list)),
WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS);
}
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(util::Promise::ResolveEmptyPromise, std::move(promise)));
return handle;
}
void Session::SetDownloadPath(const base::FilePath& path) {
browser_context_->prefs()->SetFilePath(prefs::kDownloadDefaultDirectory,
path);
}
void Session::EnableNetworkEmulation(const mate::Dictionary& options) {
auto conditions = network::mojom::NetworkConditions::New();
options.Get("offline", &conditions->offline);
options.Get("downloadThroughput", &conditions->download_throughput);
options.Get("uploadThroughput", &conditions->upload_throughput);
double latency = 0.0;
if (options.Get("latency", &latency) && latency) {
conditions->latency = base::TimeDelta::FromMillisecondsD(latency);
}
auto* network_context = content::BrowserContext::GetDefaultStoragePartition(
browser_context_.get())
->GetNetworkContext();
network_context->SetNetworkConditions(network_emulation_token_,
std::move(conditions));
}
void Session::DisableNetworkEmulation() {
auto* network_context = content::BrowserContext::GetDefaultStoragePartition(
browser_context_.get())
->GetNetworkContext();
network_context->SetNetworkConditions(
network_emulation_token_, network::mojom::NetworkConditions::New());
}
void WrapVerifyProc(
base::RepeatingCallback<void(const VerifyRequestParams& request,
base::RepeatingCallback<void(int)>)> proc,
const VerifyRequestParams& request,
base::OnceCallback<void(int)> cb) {
proc.Run(request, base::AdaptCallbackForRepeating(std::move(cb)));
}
void Session::SetCertVerifyProc(v8::Local<v8::Value> val,
mate::Arguments* args) {
base::RepeatingCallback<void(const VerifyRequestParams& request,
base::RepeatingCallback<void(int)>)>
proc;
if (!(val->IsNull() || mate::ConvertFromV8(args->isolate(), val, &proc))) {
args->ThrowError("Must pass null or function");
return;
}
base::PostTaskWithTraits(
FROM_HERE, {BrowserThread::IO},
base::BindOnce(&SetCertVerifyProcInIO,
WrapRefCounted(browser_context_->GetRequestContext()),
base::BindRepeating(&WrapVerifyProc, proc)));
}
void Session::SetPermissionRequestHandler(v8::Local<v8::Value> val,
mate::Arguments* args) {
auto* permission_manager = static_cast<AtomPermissionManager*>(
browser_context()->GetPermissionControllerDelegate());
if (val->IsNull()) {
permission_manager->SetPermissionRequestHandler(
AtomPermissionManager::RequestHandler());
return;
}
auto handler = std::make_unique<AtomPermissionManager::RequestHandler>();
if (!mate::ConvertFromV8(args->isolate(), val, handler.get())) {
args->ThrowError("Must pass null or function");
return;
}
permission_manager->SetPermissionRequestHandler(base::BindRepeating(
[](AtomPermissionManager::RequestHandler* handler,
content::WebContents* web_contents,
content::PermissionType permission_type,
AtomPermissionManager::StatusCallback callback,
const base::Value& details) {
handler->Run(web_contents, permission_type,
base::AdaptCallbackForRepeating(std::move(callback)),
details);
},
base::Owned(std::move(handler))));
}
void Session::SetPermissionCheckHandler(v8::Local<v8::Value> val,
mate::Arguments* args) {
AtomPermissionManager::CheckHandler handler;
if (!(val->IsNull() || mate::ConvertFromV8(args->isolate(), val, &handler))) {
args->ThrowError("Must pass null or function");
return;
}
auto* permission_manager = static_cast<AtomPermissionManager*>(
browser_context()->GetPermissionControllerDelegate());
permission_manager->SetPermissionCheckHandler(handler);
}
v8::Local<v8::Promise> Session::ClearHostResolverCache(mate::Arguments* args) {
v8::Isolate* isolate = args->isolate();
util::Promise promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
content::BrowserContext::GetDefaultStoragePartition(browser_context_.get())
->GetNetworkContext()
->ClearHostCache(nullptr,
base::BindOnce(util::Promise::ResolveEmptyPromise,
std::move(promise)));
return handle;
}
v8::Local<v8::Promise> Session::ClearAuthCache() {
auto* isolate = v8::Isolate::GetCurrent();
util::Promise promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
content::BrowserContext::GetDefaultStoragePartition(browser_context_.get())
->GetNetworkContext()
->ClearHttpAuthCache(base::Time(),
base::BindOnce(util::Promise::ResolveEmptyPromise,
std::move(promise)));
return handle;
}
void Session::AllowNTLMCredentialsForDomains(const std::string& domains) {
auto auth_params = CreateHttpAuthDynamicParams();
auth_params->server_whitelist = domains;
content::GetNetworkService()->ConfigureHttpAuthPrefs(std::move(auth_params));
}
void Session::SetUserAgent(const std::string& user_agent,
mate::Arguments* args) {
browser_context_->SetUserAgent(user_agent);
std::string accept_lang = g_browser_process->GetApplicationLocale();
args->GetNext(&accept_lang);
scoped_refptr<net::URLRequestContextGetter> getter(
browser_context_->GetRequestContext());
getter->GetNetworkTaskRunner()->PostTask(
FROM_HERE,
base::BindOnce(&SetUserAgentInIO, getter, accept_lang, user_agent));
}
std::string Session::GetUserAgent() {
return browser_context_->GetUserAgent();
}
v8::Local<v8::Promise> Session::GetBlobData(v8::Isolate* isolate,
const std::string& uuid) {
util::Promise promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
AtomBlobReader* blob_reader = browser_context()->GetBlobReader();
base::PostTaskWithTraits(
FROM_HERE, {BrowserThread::IO},
base::BindOnce(&AtomBlobReader::StartReading,
base::Unretained(blob_reader), uuid, std::move(promise)));
return handle;
}
void Session::CreateInterruptedDownload(const mate::Dictionary& options) {
int64_t offset = 0, length = 0;
double start_time = 0.0;
std::string mime_type, last_modified, etag;
base::FilePath path;
std::vector<GURL> url_chain;
options.Get("path", &path);
options.Get("urlChain", &url_chain);
options.Get("mimeType", &mime_type);
options.Get("offset", &offset);
options.Get("length", &length);
options.Get("lastModified", &last_modified);
options.Get("eTag", &etag);
options.Get("startTime", &start_time);
if (path.empty() || url_chain.empty() || length == 0) {
isolate()->ThrowException(v8::Exception::Error(mate::StringToV8(
isolate(), "Must pass non-empty path, urlChain and length.")));
return;
}
if (offset >= length) {
isolate()->ThrowException(v8::Exception::Error(mate::StringToV8(
isolate(), "Must pass an offset value less than length.")));
return;
}
auto* download_manager =
content::BrowserContext::GetDownloadManager(browser_context());
download_manager->GetDelegate()->GetNextId(base::BindRepeating(
&DownloadIdCallback, download_manager, path, url_chain, mime_type, offset,
length, last_modified, etag, base::Time::FromDoubleT(start_time)));
}
void Session::SetPreloads(
const std::vector<base::FilePath::StringType>& preloads) {
auto* prefs = SessionPreferences::FromBrowserContext(browser_context());
DCHECK(prefs);
prefs->set_preloads(preloads);
}
std::vector<base::FilePath::StringType> Session::GetPreloads() const {
auto* prefs = SessionPreferences::FromBrowserContext(browser_context());
DCHECK(prefs);
return prefs->preloads();
}
v8::Local<v8::Value> Session::Cookies(v8::Isolate* isolate) {
if (cookies_.IsEmpty()) {
auto handle = Cookies::Create(isolate, browser_context());
cookies_.Reset(isolate, handle.ToV8());
}
return v8::Local<v8::Value>::New(isolate, cookies_);
}
v8::Local<v8::Value> Session::Protocol(v8::Isolate* isolate) {
if (protocol_.IsEmpty()) {
v8::Local<v8::Value> handle;
if (base::FeatureList::IsEnabled(network::features::kNetworkService))
handle = ProtocolNS::Create(isolate, browser_context()).ToV8();
else
handle = Protocol::Create(isolate, browser_context()).ToV8();
protocol_.Reset(isolate, handle);
}
return v8::Local<v8::Value>::New(isolate, protocol_);
}
v8::Local<v8::Value> Session::WebRequest(v8::Isolate* isolate) {
if (web_request_.IsEmpty()) {
auto handle = atom::api::WebRequest::Create(isolate, browser_context());
web_request_.Reset(isolate, handle.ToV8());
}
return v8::Local<v8::Value>::New(isolate, web_request_);
}
v8::Local<v8::Value> Session::NetLog(v8::Isolate* isolate) {
if (net_log_.IsEmpty()) {
auto handle = atom::api::NetLog::Create(isolate, browser_context());
net_log_.Reset(isolate, handle.ToV8());
}
return v8::Local<v8::Value>::New(isolate, net_log_);
}
// static
mate::Handle<Session> Session::CreateFrom(v8::Isolate* isolate,
AtomBrowserContext* browser_context) {
auto* existing = TrackableObject::FromWrappedClass(isolate, browser_context);
if (existing)
return mate::CreateHandle(isolate, static_cast<Session*>(existing));
auto handle =
mate::CreateHandle(isolate, new Session(isolate, browser_context));
// The Sessions should never be garbage collected, since the common pattern is
// to use partition strings, instead of using the Session object directly.
g_sessions[handle->weak_map_id()] =
v8::Global<v8::Object>(isolate, handle.ToV8());
return handle;
}
// static
mate::Handle<Session> Session::FromPartition(
v8::Isolate* isolate,
const std::string& partition,
const base::DictionaryValue& options) {
scoped_refptr<AtomBrowserContext> browser_context;
if (partition.empty()) {
browser_context = AtomBrowserContext::From("", false, options);
} else if (base::StartsWith(partition, kPersistPrefix,
base::CompareCase::SENSITIVE)) {
std::string name = partition.substr(8);
browser_context = AtomBrowserContext::From(name, false, options);
} else {
browser_context = AtomBrowserContext::From(partition, true, options);
}
return CreateFrom(isolate, browser_context.get());
}
// static
void Session::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "Session"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.MakeDestroyable()
.SetMethod("resolveProxy", &Session::ResolveProxy)
.SetMethod("getCacheSize", &Session::GetCacheSize)
.SetMethod("clearCache", &Session::ClearCache)
.SetMethod("clearStorageData", &Session::ClearStorageData)
.SetMethod("flushStorageData", &Session::FlushStorageData)
.SetMethod("setProxy", &Session::SetProxy)
.SetMethod("setDownloadPath", &Session::SetDownloadPath)
.SetMethod("enableNetworkEmulation", &Session::EnableNetworkEmulation)
.SetMethod("disableNetworkEmulation", &Session::DisableNetworkEmulation)
.SetMethod("setCertificateVerifyProc", &Session::SetCertVerifyProc)
.SetMethod("setPermissionRequestHandler",
&Session::SetPermissionRequestHandler)
.SetMethod("setPermissionCheckHandler",
&Session::SetPermissionCheckHandler)
.SetMethod("clearHostResolverCache", &Session::ClearHostResolverCache)
.SetMethod("clearAuthCache", &Session::ClearAuthCache)
.SetMethod("allowNTLMCredentialsForDomains",
&Session::AllowNTLMCredentialsForDomains)
.SetMethod("setUserAgent", &Session::SetUserAgent)
.SetMethod("getUserAgent", &Session::GetUserAgent)
.SetMethod("getBlobData", &Session::GetBlobData)
.SetMethod("createInterruptedDownload",
&Session::CreateInterruptedDownload)
.SetMethod("setPreloads", &Session::SetPreloads)
.SetMethod("getPreloads", &Session::GetPreloads)
.SetProperty("cookies", &Session::Cookies)
.SetProperty("netLog", &Session::NetLog)
.SetProperty("protocol", &Session::Protocol)
.SetProperty("webRequest", &Session::WebRequest);
}
} // namespace api
} // namespace atom
namespace {
using atom::api::Cookies;
using atom::api::NetLog;
using atom::api::Protocol;
using atom::api::Session;
v8::Local<v8::Value> FromPartition(const std::string& partition,
mate::Arguments* args) {
if (!atom::Browser::Get()->is_ready()) {
args->ThrowError("Session can only be received when app is ready");
return v8::Null(args->isolate());
}
base::DictionaryValue options;
args->GetNext(&options);
return Session::FromPartition(args->isolate(), partition, options).ToV8();
}
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
mate::Dictionary dict(isolate, exports);
dict.Set(
"Session",
Session::GetConstructor(isolate)->GetFunction(context).ToLocalChecked());
dict.Set(
"Cookies",
Cookies::GetConstructor(isolate)->GetFunction(context).ToLocalChecked());
dict.Set(
"NetLog",
NetLog::GetConstructor(isolate)->GetFunction(context).ToLocalChecked());
dict.Set(
"Protocol",
Protocol::GetConstructor(isolate)->GetFunction(context).ToLocalChecked());
dict.SetMethod("fromPartition", &FromPartition);
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_browser_session, Initialize)

View file

@ -0,0 +1,116 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_BROWSER_API_ATOM_API_SESSION_H_
#define ATOM_BROWSER_API_ATOM_API_SESSION_H_
#include <string>
#include <vector>
#include "atom/browser/api/trackable_object.h"
#include "atom/browser/atom_blob_reader.h"
#include "atom/browser/net/resolve_proxy_helper.h"
#include "atom/common/promise_util.h"
#include "base/values.h"
#include "content/public/browser/download_manager.h"
#include "native_mate/handle.h"
class GURL;
namespace base {
class FilePath;
}
namespace mate {
class Arguments;
class Dictionary;
} // namespace mate
namespace net {
class ProxyConfig;
}
namespace atom {
class AtomBrowserContext;
namespace api {
class Session : public mate::TrackableObject<Session>,
public content::DownloadManager::Observer {
public:
// Gets or creates Session from the |browser_context|.
static mate::Handle<Session> CreateFrom(v8::Isolate* isolate,
AtomBrowserContext* browser_context);
// Gets the Session of |partition|.
static mate::Handle<Session> FromPartition(
v8::Isolate* isolate,
const std::string& partition,
const base::DictionaryValue& options = base::DictionaryValue());
AtomBrowserContext* browser_context() const { return browser_context_.get(); }
// mate::TrackableObject:
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
// Methods.
v8::Local<v8::Promise> ResolveProxy(mate::Arguments* args);
v8::Local<v8::Promise> GetCacheSize();
v8::Local<v8::Promise> ClearCache();
v8::Local<v8::Promise> ClearStorageData(mate::Arguments* args);
void FlushStorageData();
v8::Local<v8::Promise> SetProxy(mate::Arguments* args);
void SetDownloadPath(const base::FilePath& path);
void EnableNetworkEmulation(const mate::Dictionary& options);
void DisableNetworkEmulation();
void SetCertVerifyProc(v8::Local<v8::Value> proc, mate::Arguments* args);
void SetPermissionRequestHandler(v8::Local<v8::Value> val,
mate::Arguments* args);
void SetPermissionCheckHandler(v8::Local<v8::Value> val,
mate::Arguments* args);
v8::Local<v8::Promise> ClearHostResolverCache(mate::Arguments* args);
v8::Local<v8::Promise> ClearAuthCache();
void AllowNTLMCredentialsForDomains(const std::string& domains);
void SetUserAgent(const std::string& user_agent, mate::Arguments* args);
std::string GetUserAgent();
v8::Local<v8::Promise> GetBlobData(v8::Isolate* isolate,
const std::string& uuid);
void CreateInterruptedDownload(const mate::Dictionary& options);
void SetPreloads(const std::vector<base::FilePath::StringType>& preloads);
std::vector<base::FilePath::StringType> GetPreloads() const;
v8::Local<v8::Value> Cookies(v8::Isolate* isolate);
v8::Local<v8::Value> Protocol(v8::Isolate* isolate);
v8::Local<v8::Value> WebRequest(v8::Isolate* isolate);
v8::Local<v8::Value> NetLog(v8::Isolate* isolate);
protected:
Session(v8::Isolate* isolate, AtomBrowserContext* browser_context);
~Session() override;
// content::DownloadManager::Observer:
void OnDownloadCreated(content::DownloadManager* manager,
download::DownloadItem* item) override;
private:
// Cached object.
v8::Global<v8::Value> cookies_;
v8::Global<v8::Value> protocol_;
v8::Global<v8::Value> web_request_;
v8::Global<v8::Value> net_log_;
// The client id to enable the network throttler.
base::UnguessableToken network_emulation_token_;
scoped_refptr<AtomBrowserContext> browser_context_;
DISALLOW_COPY_AND_ASSIGN(Session);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_SESSION_H_

View file

@ -0,0 +1,152 @@
// 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/browser/api/atom_api_system_preferences.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/node_includes.h"
#include "native_mate/dictionary.h"
#include "ui/gfx/animation/animation.h"
#include "ui/gfx/color_utils.h"
namespace atom {
namespace api {
SystemPreferences::SystemPreferences(v8::Isolate* isolate) {
Init(isolate);
#if defined(OS_WIN)
InitializeWindow();
#endif
}
SystemPreferences::~SystemPreferences() {
#if defined(OS_WIN)
Browser::Get()->RemoveObserver(this);
#endif
}
#if !defined(OS_MACOSX)
bool SystemPreferences::IsDarkMode() {
return false;
}
#endif
bool SystemPreferences::IsInvertedColorScheme() {
return color_utils::IsInvertedColorScheme();
}
#if !defined(OS_WIN)
bool SystemPreferences::IsHighContrastColorScheme() {
return false;
}
#endif // !defined(OS_WIN)
v8::Local<v8::Value> SystemPreferences::GetAnimationSettings(
v8::Isolate* isolate) {
mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
dict.SetHidden("simple", true);
dict.Set("shouldRenderRichAnimation",
gfx::Animation::ShouldRenderRichAnimation());
dict.Set("scrollAnimationsEnabledBySystem",
gfx::Animation::ScrollAnimationsEnabledBySystem());
dict.Set("prefersReducedMotion", gfx::Animation::PrefersReducedMotion());
return dict.GetHandle();
}
// static
mate::Handle<SystemPreferences> SystemPreferences::Create(
v8::Isolate* isolate) {
return mate::CreateHandle(isolate, new SystemPreferences(isolate));
}
// static
void SystemPreferences::BuildPrototype(
v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "SystemPreferences"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
#if defined(OS_WIN) || defined(OS_MACOSX)
.SetMethod("getColor", &SystemPreferences::GetColor)
.SetMethod("getAccentColor", &SystemPreferences::GetAccentColor)
#endif
#if defined(OS_WIN)
.SetMethod("isAeroGlassEnabled", &SystemPreferences::IsAeroGlassEnabled)
#elif defined(OS_MACOSX)
.SetMethod("postNotification", &SystemPreferences::PostNotification)
.SetMethod("subscribeNotification",
&SystemPreferences::SubscribeNotification)
.SetMethod("unsubscribeNotification",
&SystemPreferences::UnsubscribeNotification)
.SetMethod("postLocalNotification",
&SystemPreferences::PostLocalNotification)
.SetMethod("subscribeLocalNotification",
&SystemPreferences::SubscribeLocalNotification)
.SetMethod("unsubscribeLocalNotification",
&SystemPreferences::UnsubscribeLocalNotification)
.SetMethod("postWorkspaceNotification",
&SystemPreferences::PostWorkspaceNotification)
.SetMethod("subscribeWorkspaceNotification",
&SystemPreferences::SubscribeWorkspaceNotification)
.SetMethod("unsubscribeWorkspaceNotification",
&SystemPreferences::UnsubscribeWorkspaceNotification)
.SetMethod("registerDefaults", &SystemPreferences::RegisterDefaults)
.SetMethod("getUserDefault", &SystemPreferences::GetUserDefault)
.SetMethod("setUserDefault", &SystemPreferences::SetUserDefault)
.SetMethod("removeUserDefault", &SystemPreferences::RemoveUserDefault)
.SetMethod("isSwipeTrackingFromScrollEventsEnabled",
&SystemPreferences::IsSwipeTrackingFromScrollEventsEnabled)
.SetMethod("getEffectiveAppearance",
&SystemPreferences::GetEffectiveAppearance)
.SetMethod("_getAppLevelAppearance",
&SystemPreferences::GetAppLevelAppearance)
.SetMethod("_setAppLevelAppearance",
&SystemPreferences::SetAppLevelAppearance)
.SetProperty("appLevelAppearance",
&SystemPreferences::GetAppLevelAppearance,
&SystemPreferences::SetAppLevelAppearance)
.SetMethod("getSystemColor", &SystemPreferences::GetSystemColor)
.SetMethod("canPromptTouchID", &SystemPreferences::CanPromptTouchID)
.SetMethod("promptTouchID", &SystemPreferences::PromptTouchID)
.SetMethod("isTrustedAccessibilityClient",
&SystemPreferences::IsTrustedAccessibilityClient)
.SetMethod("getMediaAccessStatus",
&SystemPreferences::GetMediaAccessStatus)
.SetMethod("askForMediaAccess", &SystemPreferences::AskForMediaAccess)
#endif
.SetMethod("isInvertedColorScheme",
&SystemPreferences::IsInvertedColorScheme)
.SetMethod("isHighContrastColorScheme",
&SystemPreferences::IsHighContrastColorScheme)
.SetMethod("isDarkMode", &SystemPreferences::IsDarkMode)
.SetMethod("getAnimationSettings",
&SystemPreferences::GetAnimationSettings);
}
} // namespace api
} // namespace atom
namespace {
using atom::api::SystemPreferences;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
mate::Dictionary dict(isolate, exports);
dict.Set("systemPreferences", SystemPreferences::Create(isolate));
dict.Set("SystemPreferences", SystemPreferences::GetConstructor(isolate)
->GetFunction(context)
.ToLocalChecked());
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_browser_system_preferences, Initialize)

View file

@ -0,0 +1,171 @@
// 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_BROWSER_API_ATOM_API_SYSTEM_PREFERENCES_H_
#define ATOM_BROWSER_API_ATOM_API_SYSTEM_PREFERENCES_H_
#include <memory>
#include <string>
#include "atom/browser/api/event_emitter.h"
#include "atom/common/promise_util.h"
#include "base/callback.h"
#include "base/values.h"
#include "native_mate/handle.h"
#if defined(OS_WIN)
#include "atom/browser/browser.h"
#include "atom/browser/browser_observer.h"
#include "ui/gfx/sys_color_change_listener.h"
#endif
namespace base {
class DictionaryValue;
}
namespace atom {
namespace api {
#if defined(OS_MACOSX)
enum NotificationCenterKind {
kNSDistributedNotificationCenter = 0,
kNSNotificationCenter,
kNSWorkspaceNotificationCenter,
};
#endif
class SystemPreferences : public mate::EventEmitter<SystemPreferences>
#if defined(OS_WIN)
,
public BrowserObserver,
public gfx::SysColorChangeListener
#endif
{
public:
static mate::Handle<SystemPreferences> Create(v8::Isolate* isolate);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
#if defined(OS_WIN) || defined(OS_MACOSX)
std::string GetAccentColor();
std::string GetColor(const std::string& color, mate::Arguments* args);
#endif
#if defined(OS_WIN)
bool IsAeroGlassEnabled();
void InitializeWindow();
// gfx::SysColorChangeListener:
void OnSysColorChange() override;
// BrowserObserver:
void OnFinishLaunching(const base::DictionaryValue& launch_info) override;
#elif defined(OS_MACOSX)
using NotificationCallback =
base::RepeatingCallback<void(const std::string&,
const base::DictionaryValue&)>;
void PostNotification(const std::string& name,
const base::DictionaryValue& user_info,
mate::Arguments* args);
int SubscribeNotification(const std::string& name,
const NotificationCallback& callback);
void UnsubscribeNotification(int id);
void PostLocalNotification(const std::string& name,
const base::DictionaryValue& user_info);
int SubscribeLocalNotification(const std::string& name,
const NotificationCallback& callback);
void UnsubscribeLocalNotification(int request_id);
void PostWorkspaceNotification(const std::string& name,
const base::DictionaryValue& user_info);
int SubscribeWorkspaceNotification(const std::string& name,
const NotificationCallback& callback);
void UnsubscribeWorkspaceNotification(int request_id);
v8::Local<v8::Value> GetUserDefault(const std::string& name,
const std::string& type);
void RegisterDefaults(mate::Arguments* args);
void SetUserDefault(const std::string& name,
const std::string& type,
mate::Arguments* args);
void RemoveUserDefault(const std::string& name);
bool IsSwipeTrackingFromScrollEventsEnabled();
std::string GetSystemColor(const std::string& color, mate::Arguments* args);
bool CanPromptTouchID();
v8::Local<v8::Promise> PromptTouchID(v8::Isolate* isolate,
const std::string& reason);
static bool IsTrustedAccessibilityClient(bool prompt);
// TODO(codebytere): Write tests for these methods once we
// are running tests on a Mojave machine
std::string GetMediaAccessStatus(const std::string& media_type,
mate::Arguments* args);
v8::Local<v8::Promise> AskForMediaAccess(v8::Isolate* isolate,
const std::string& media_type);
// TODO(MarshallOfSound): Write tests for these methods once we
// are running tests on a Mojave machine
v8::Local<v8::Value> GetEffectiveAppearance(v8::Isolate* isolate);
v8::Local<v8::Value> GetAppLevelAppearance(v8::Isolate* isolate);
void SetAppLevelAppearance(mate::Arguments* args);
#endif
bool IsDarkMode();
bool IsInvertedColorScheme();
bool IsHighContrastColorScheme();
v8::Local<v8::Value> GetAnimationSettings(v8::Isolate* isolate);
protected:
explicit SystemPreferences(v8::Isolate* isolate);
~SystemPreferences() override;
#if defined(OS_MACOSX)
int DoSubscribeNotification(const std::string& name,
const NotificationCallback& callback,
NotificationCenterKind kind);
void DoUnsubscribeNotification(int request_id, NotificationCenterKind kind);
#endif
private:
#if defined(OS_WIN)
// Static callback invoked when a message comes in to our messaging window.
static LRESULT CALLBACK WndProcStatic(HWND hwnd,
UINT message,
WPARAM wparam,
LPARAM lparam);
LRESULT CALLBACK WndProc(HWND hwnd,
UINT message,
WPARAM wparam,
LPARAM lparam);
// The window class of |window_|.
ATOM atom_;
// The handle of the module that contains the window procedure of |window_|.
HMODULE instance_;
// The window used for processing events.
HWND window_;
std::string current_color_;
bool invertered_color_scheme_;
bool high_contrast_color_scheme_;
std::unique_ptr<gfx::ScopedSysColorChangeListener> color_change_listener_;
#endif
DISALLOW_COPY_AND_ASSIGN(SystemPreferences);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_SYSTEM_PREFERENCES_H_

View file

@ -0,0 +1,671 @@
// 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/browser/api/atom_api_system_preferences.h"
#include <map>
#include <memory>
#include <string>
#include <utility>
#import <AVFoundation/AVFoundation.h>
#import <Cocoa/Cocoa.h>
#import <LocalAuthentication/LocalAuthentication.h>
#import <Security/Security.h>
#include "atom/browser/mac/atom_application.h"
#include "atom/browser/mac/dict_util.h"
#include "atom/browser/ui/cocoa/NSColor+Hex.h"
#include "atom/common/native_mate_converters/gurl_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "base/mac/scoped_cftyperef.h"
#include "base/mac/sdk_forward_declarations.h"
#include "base/sequenced_task_runner.h"
#include "base/strings/stringprintf.h"
#include "base/strings/sys_string_conversions.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "base/values.h"
#include "native_mate/object_template_builder.h"
#include "net/base/mac/url_conversions.h"
namespace mate {
template <>
struct Converter<NSAppearance*> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
NSAppearance** out) {
if (val->IsNull()) {
*out = nil;
return true;
}
std::string name;
if (!mate::ConvertFromV8(isolate, val, &name)) {
return false;
}
if (name == "light") {
*out = [NSAppearance appearanceNamed:NSAppearanceNameAqua];
return true;
} else if (name == "dark") {
if (@available(macOS 10.14, *)) {
*out = [NSAppearance appearanceNamed:NSAppearanceNameDarkAqua];
} else {
*out = [NSAppearance appearanceNamed:NSAppearanceNameAqua];
}
return true;
}
return false;
}
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, NSAppearance* val) {
if (val == nil) {
return v8::Null(isolate);
}
if ([val.name isEqualToString:NSAppearanceNameAqua]) {
return mate::ConvertToV8(isolate, "light");
}
if (@available(macOS 10.14, *)) {
if ([val.name isEqualToString:NSAppearanceNameDarkAqua]) {
return mate::ConvertToV8(isolate, "dark");
}
}
return mate::ConvertToV8(isolate, "unknown");
}
};
} // namespace mate
namespace atom {
namespace api {
namespace {
int g_next_id = 0;
// The map to convert |id| to |int|.
std::map<int, id> g_id_map;
AVMediaType ParseMediaType(const std::string& media_type) {
if (media_type == "camera") {
return AVMediaTypeVideo;
} else if (media_type == "microphone") {
return AVMediaTypeAudio;
} else {
return nil;
}
}
std::string ConvertAuthorizationStatus(AVAuthorizationStatusMac status) {
switch (status) {
case AVAuthorizationStatusNotDeterminedMac:
return "not-determined";
case AVAuthorizationStatusRestrictedMac:
return "restricted";
case AVAuthorizationStatusDeniedMac:
return "denied";
case AVAuthorizationStatusAuthorizedMac:
return "granted";
default:
return "unknown";
}
}
} // namespace
void SystemPreferences::PostNotification(const std::string& name,
const base::DictionaryValue& user_info,
mate::Arguments* args) {
bool immediate = false;
args->GetNext(&immediate);
NSDistributedNotificationCenter* center =
[NSDistributedNotificationCenter defaultCenter];
[center postNotificationName:base::SysUTF8ToNSString(name)
object:nil
userInfo:DictionaryValueToNSDictionary(user_info)
deliverImmediately:immediate];
}
int SystemPreferences::SubscribeNotification(
const std::string& name,
const NotificationCallback& callback) {
return DoSubscribeNotification(name, callback,
kNSDistributedNotificationCenter);
}
void SystemPreferences::UnsubscribeNotification(int request_id) {
DoUnsubscribeNotification(request_id, kNSDistributedNotificationCenter);
}
void SystemPreferences::PostLocalNotification(
const std::string& name,
const base::DictionaryValue& user_info) {
NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
[center postNotificationName:base::SysUTF8ToNSString(name)
object:nil
userInfo:DictionaryValueToNSDictionary(user_info)];
}
int SystemPreferences::SubscribeLocalNotification(
const std::string& name,
const NotificationCallback& callback) {
return DoSubscribeNotification(name, callback, kNSNotificationCenter);
}
void SystemPreferences::UnsubscribeLocalNotification(int request_id) {
DoUnsubscribeNotification(request_id, kNSNotificationCenter);
}
void SystemPreferences::PostWorkspaceNotification(
const std::string& name,
const base::DictionaryValue& user_info) {
NSNotificationCenter* center =
[[NSWorkspace sharedWorkspace] notificationCenter];
[center postNotificationName:base::SysUTF8ToNSString(name)
object:nil
userInfo:DictionaryValueToNSDictionary(user_info)];
}
int SystemPreferences::SubscribeWorkspaceNotification(
const std::string& name,
const NotificationCallback& callback) {
return DoSubscribeNotification(name, callback,
kNSWorkspaceNotificationCenter);
}
void SystemPreferences::UnsubscribeWorkspaceNotification(int request_id) {
DoUnsubscribeNotification(request_id, kNSWorkspaceNotificationCenter);
}
int SystemPreferences::DoSubscribeNotification(
const std::string& name,
const NotificationCallback& callback,
NotificationCenterKind kind) {
int request_id = g_next_id++;
__block NotificationCallback copied_callback = callback;
NSNotificationCenter* center;
switch (kind) {
case kNSDistributedNotificationCenter:
center = [NSDistributedNotificationCenter defaultCenter];
break;
case kNSNotificationCenter:
center = [NSNotificationCenter defaultCenter];
break;
case kNSWorkspaceNotificationCenter:
center = [[NSWorkspace sharedWorkspace] notificationCenter];
break;
default:
break;
}
g_id_map[request_id] = [center
addObserverForName:base::SysUTF8ToNSString(name)
object:nil
queue:nil
usingBlock:^(NSNotification* notification) {
std::unique_ptr<base::DictionaryValue> user_info =
NSDictionaryToDictionaryValue(notification.userInfo);
if (user_info) {
copied_callback.Run(
base::SysNSStringToUTF8(notification.name), *user_info);
} else {
copied_callback.Run(
base::SysNSStringToUTF8(notification.name),
base::DictionaryValue());
}
}];
return request_id;
}
void SystemPreferences::DoUnsubscribeNotification(int request_id,
NotificationCenterKind kind) {
auto iter = g_id_map.find(request_id);
if (iter != g_id_map.end()) {
id observer = iter->second;
NSNotificationCenter* center;
switch (kind) {
case kNSDistributedNotificationCenter:
center = [NSDistributedNotificationCenter defaultCenter];
break;
case kNSNotificationCenter:
center = [NSNotificationCenter defaultCenter];
break;
case kNSWorkspaceNotificationCenter:
center = [[NSWorkspace sharedWorkspace] notificationCenter];
break;
default:
break;
}
[center removeObserver:observer];
g_id_map.erase(iter);
}
}
v8::Local<v8::Value> SystemPreferences::GetUserDefault(
const std::string& name,
const std::string& type) {
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
NSString* key = base::SysUTF8ToNSString(name);
if (type == "string") {
return mate::StringToV8(
isolate(), base::SysNSStringToUTF8([defaults stringForKey:key]));
} else if (type == "boolean") {
return v8::Boolean::New(isolate(), [defaults boolForKey:key]);
} else if (type == "float") {
return v8::Number::New(isolate(), [defaults floatForKey:key]);
} else if (type == "integer") {
return v8::Integer::New(isolate(), [defaults integerForKey:key]);
} else if (type == "double") {
return v8::Number::New(isolate(), [defaults doubleForKey:key]);
} else if (type == "url") {
return mate::ConvertToV8(isolate(),
net::GURLWithNSURL([defaults URLForKey:key]));
} else if (type == "array") {
std::unique_ptr<base::ListValue> list =
NSArrayToListValue([defaults arrayForKey:key]);
if (list == nullptr)
list.reset(new base::ListValue());
return mate::ConvertToV8(isolate(), *list);
} else if (type == "dictionary") {
std::unique_ptr<base::DictionaryValue> dictionary =
NSDictionaryToDictionaryValue([defaults dictionaryForKey:key]);
if (dictionary == nullptr)
dictionary.reset(new base::DictionaryValue());
return mate::ConvertToV8(isolate(), *dictionary);
} else {
return v8::Undefined(isolate());
}
}
void SystemPreferences::RegisterDefaults(mate::Arguments* args) {
base::DictionaryValue value;
if (!args->GetNext(&value)) {
args->ThrowError("Invalid userDefault data provided");
} else {
@try {
NSDictionary* dict = DictionaryValueToNSDictionary(value);
for (id key in dict) {
id value = [dict objectForKey:key];
if ([value isKindOfClass:[NSNull class]] || value == nil) {
args->ThrowError("Invalid userDefault data provided");
return;
}
}
[[NSUserDefaults standardUserDefaults] registerDefaults:dict];
} @catch (NSException* exception) {
args->ThrowError("Invalid userDefault data provided");
}
}
}
void SystemPreferences::SetUserDefault(const std::string& name,
const std::string& type,
mate::Arguments* args) {
const auto throwConversionError = [&] {
args->ThrowError("Unable to convert value to: " + type);
};
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
NSString* key = base::SysUTF8ToNSString(name);
if (type == "string") {
std::string value;
if (!args->GetNext(&value)) {
throwConversionError();
return;
}
[defaults setObject:base::SysUTF8ToNSString(value) forKey:key];
} else if (type == "boolean") {
bool value;
if (!args->GetNext(&value)) {
throwConversionError();
return;
}
[defaults setBool:value forKey:key];
} else if (type == "float") {
float value;
if (!args->GetNext(&value)) {
throwConversionError();
return;
}
[defaults setFloat:value forKey:key];
} else if (type == "integer") {
int value;
if (!args->GetNext(&value)) {
throwConversionError();
return;
}
[defaults setInteger:value forKey:key];
} else if (type == "double") {
double value;
if (!args->GetNext(&value)) {
throwConversionError();
return;
}
[defaults setDouble:value forKey:key];
} else if (type == "url") {
GURL value;
if (!args->GetNext(&value)) {
throwConversionError();
return;
}
if (NSURL* url = net::NSURLWithGURL(value)) {
[defaults setURL:url forKey:key];
}
} else if (type == "array") {
base::ListValue value;
if (!args->GetNext(&value)) {
throwConversionError();
return;
}
if (NSArray* array = ListValueToNSArray(value)) {
[defaults setObject:array forKey:key];
}
} else if (type == "dictionary") {
base::DictionaryValue value;
if (!args->GetNext(&value)) {
throwConversionError();
return;
}
if (NSDictionary* dict = DictionaryValueToNSDictionary(value)) {
[defaults setObject:dict forKey:key];
}
} else {
args->ThrowError("Invalid type: " + type);
return;
}
}
std::string SystemPreferences::GetAccentColor() {
NSColor* sysColor = nil;
if (@available(macOS 10.14, *))
sysColor = [NSColor controlAccentColor];
return base::SysNSStringToUTF8([sysColor RGBAValue]);
}
std::string SystemPreferences::GetSystemColor(const std::string& color,
mate::Arguments* args) {
NSColor* sysColor = nil;
if (color == "blue") {
sysColor = [NSColor systemBlueColor];
} else if (color == "brown") {
sysColor = [NSColor systemBrownColor];
} else if (color == "gray") {
sysColor = [NSColor systemGrayColor];
} else if (color == "green") {
sysColor = [NSColor systemGreenColor];
} else if (color == "orange") {
sysColor = [NSColor systemOrangeColor];
} else if (color == "pink") {
sysColor = [NSColor systemPinkColor];
} else if (color == "purple") {
sysColor = [NSColor systemPurpleColor];
} else if (color == "red") {
sysColor = [NSColor systemRedColor];
} else if (color == "yellow") {
sysColor = [NSColor systemYellowColor];
} else {
args->ThrowError("Unknown system color: " + color);
return "";
}
return base::SysNSStringToUTF8([sysColor hexadecimalValue]);
}
bool SystemPreferences::CanPromptTouchID() {
if (@available(macOS 10.12.2, *)) {
base::scoped_nsobject<LAContext> context([[LAContext alloc] init]);
if (![context
canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
error:nil])
return false;
if (@available(macOS 10.13.2, *))
return [context biometryType] == LABiometryTypeTouchID;
return true;
}
return false;
}
v8::Local<v8::Promise> SystemPreferences::PromptTouchID(
v8::Isolate* isolate,
const std::string& reason) {
util::Promise promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
if (@available(macOS 10.12.2, *)) {
base::scoped_nsobject<LAContext> context([[LAContext alloc] init]);
base::ScopedCFTypeRef<SecAccessControlRef> access_control =
base::ScopedCFTypeRef<SecAccessControlRef>(
SecAccessControlCreateWithFlags(
kCFAllocatorDefault,
kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
kSecAccessControlPrivateKeyUsage |
kSecAccessControlUserPresence,
nullptr));
scoped_refptr<base::SequencedTaskRunner> runner =
base::SequencedTaskRunnerHandle::Get();
__block util::Promise p = std::move(promise);
[context
evaluateAccessControl:access_control
operation:LAAccessControlOperationUseKeySign
localizedReason:[NSString stringWithUTF8String:reason.c_str()]
reply:^(BOOL success, NSError* error) {
if (!success) {
std::string err_msg = std::string(
[error.localizedDescription UTF8String]);
runner->PostTask(
FROM_HERE,
base::BindOnce(util::Promise::RejectPromise,
std::move(p),
std::move(err_msg)));
} else {
runner->PostTask(
FROM_HERE,
base::BindOnce(
util::Promise::ResolveEmptyPromise,
std::move(p)));
}
}];
} else {
promise.RejectWithErrorMessage(
"This API is not available on macOS versions older than 10.12.2");
}
return handle;
}
// static
bool SystemPreferences::IsTrustedAccessibilityClient(bool prompt) {
NSDictionary* options = @{(id)kAXTrustedCheckOptionPrompt : @(prompt)};
return AXIsProcessTrustedWithOptions((CFDictionaryRef)options);
}
std::string SystemPreferences::GetColor(const std::string& color,
mate::Arguments* args) {
NSColor* sysColor = nil;
if (color == "alternate-selected-control-text") {
sysColor = [NSColor alternateSelectedControlTextColor];
} else if (color == "control-background") {
sysColor = [NSColor controlBackgroundColor];
} else if (color == "control") {
sysColor = [NSColor controlColor];
} else if (color == "control-text") {
sysColor = [NSColor controlTextColor];
} else if (color == "disabled-control") {
sysColor = [NSColor disabledControlTextColor];
} else if (color == "find-highlight") {
if (@available(macOS 10.14, *))
sysColor = [NSColor findHighlightColor];
} else if (color == "grid") {
sysColor = [NSColor gridColor];
} else if (color == "header-text") {
sysColor = [NSColor headerTextColor];
} else if (color == "highlight") {
sysColor = [NSColor highlightColor];
} else if (color == "keyboard-focus-indicator") {
sysColor = [NSColor keyboardFocusIndicatorColor];
} else if (color == "label") {
sysColor = [NSColor labelColor];
} else if (color == "link") {
sysColor = [NSColor linkColor];
} else if (color == "placeholder-text") {
sysColor = [NSColor placeholderTextColor];
} else if (color == "quaternary-label") {
sysColor = [NSColor quaternaryLabelColor];
} else if (color == "scrubber-textured-background") {
if (@available(macOS 10.12.2, *))
sysColor = [NSColor scrubberTexturedBackgroundColor];
} else if (color == "secondary-label") {
sysColor = [NSColor secondaryLabelColor];
} else if (color == "selected-content-background") {
if (@available(macOS 10.14, *))
sysColor = [NSColor selectedContentBackgroundColor];
} else if (color == "selected-control") {
sysColor = [NSColor selectedControlColor];
} else if (color == "selected-control-text") {
sysColor = [NSColor selectedControlTextColor];
} else if (color == "selected-menu-item-text") {
sysColor = [NSColor selectedMenuItemTextColor];
} else if (color == "selected-text-background") {
sysColor = [NSColor selectedTextBackgroundColor];
} else if (color == "selected-text") {
sysColor = [NSColor selectedTextColor];
} else if (color == "separator") {
if (@available(macOS 10.14, *))
sysColor = [NSColor separatorColor];
} else if (color == "shadow") {
sysColor = [NSColor shadowColor];
} else if (color == "tertiary-label") {
sysColor = [NSColor tertiaryLabelColor];
} else if (color == "text-background") {
sysColor = [NSColor textBackgroundColor];
} else if (color == "text") {
sysColor = [NSColor textColor];
} else if (color == "under-page-background") {
sysColor = [NSColor underPageBackgroundColor];
} else if (color == "unemphasized-selected-content-background") {
if (@available(macOS 10.14, *))
sysColor = [NSColor unemphasizedSelectedContentBackgroundColor];
} else if (color == "unemphasized-selected-text-background") {
if (@available(macOS 10.14, *))
sysColor = [NSColor unemphasizedSelectedTextBackgroundColor];
} else if (color == "unemphasized-selected-text") {
if (@available(macOS 10.14, *))
sysColor = [NSColor unemphasizedSelectedTextColor];
} else if (color == "window-background") {
sysColor = [NSColor windowBackgroundColor];
} else if (color == "window-frame-text") {
sysColor = [NSColor windowFrameTextColor];
} else {
args->ThrowError("Unknown color: " + color);
return "";
}
return base::SysNSStringToUTF8([sysColor hexadecimalValue]);
}
std::string SystemPreferences::GetMediaAccessStatus(
const std::string& media_type,
mate::Arguments* args) {
if (auto type = ParseMediaType(media_type)) {
if (@available(macOS 10.14, *)) {
return ConvertAuthorizationStatus(
[AVCaptureDevice authorizationStatusForMediaType:type]);
} else {
// access always allowed pre-10.14 Mojave
return ConvertAuthorizationStatus(AVAuthorizationStatusAuthorizedMac);
}
} else {
args->ThrowError("Invalid media type");
return std::string();
}
}
v8::Local<v8::Promise> SystemPreferences::AskForMediaAccess(
v8::Isolate* isolate,
const std::string& media_type) {
util::Promise promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
if (auto type = ParseMediaType(media_type)) {
if (@available(macOS 10.14, *)) {
__block util::Promise p = std::move(promise);
[AVCaptureDevice requestAccessForMediaType:type
completionHandler:^(BOOL granted) {
dispatch_async(dispatch_get_main_queue(), ^{
p.Resolve(!!granted);
});
}];
} else {
// access always allowed pre-10.14 Mojave
promise.Resolve(true);
}
} else {
promise.RejectWithErrorMessage("Invalid media type");
}
return handle;
}
void SystemPreferences::RemoveUserDefault(const std::string& name) {
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults removeObjectForKey:base::SysUTF8ToNSString(name)];
}
bool SystemPreferences::IsDarkMode() {
NSString* mode = [[NSUserDefaults standardUserDefaults]
stringForKey:@"AppleInterfaceStyle"];
return [mode isEqualToString:@"Dark"];
}
bool SystemPreferences::IsSwipeTrackingFromScrollEventsEnabled() {
return [NSEvent isSwipeTrackingFromScrollEventsEnabled];
}
v8::Local<v8::Value> SystemPreferences::GetEffectiveAppearance(
v8::Isolate* isolate) {
if (@available(macOS 10.14, *)) {
return mate::ConvertToV8(
isolate, [NSApplication sharedApplication].effectiveAppearance);
}
return v8::Null(isolate);
}
v8::Local<v8::Value> SystemPreferences::GetAppLevelAppearance(
v8::Isolate* isolate) {
if (@available(macOS 10.14, *)) {
return mate::ConvertToV8(isolate,
[NSApplication sharedApplication].appearance);
}
return v8::Null(isolate);
}
void SystemPreferences::SetAppLevelAppearance(mate::Arguments* args) {
if (@available(macOS 10.14, *)) {
NSAppearance* appearance;
if (args->GetNext(&appearance)) {
[[NSApplication sharedApplication] setAppearance:appearance];
} else {
args->ThrowError("Invalid app appearance provided as first argument");
}
}
}
} // namespace api
} // namespace atom

View file

@ -0,0 +1,221 @@
// 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 <dwmapi.h>
#include <iomanip>
#include "atom/browser/api/atom_api_system_preferences.h"
#include "atom/common/color_util.h"
#include "base/win/wrapped_window_proc.h"
#include "ui/base/win/shell.h"
#include "ui/gfx/color_utils.h"
#include "ui/gfx/win/hwnd_util.h"
namespace atom {
namespace {
const wchar_t kSystemPreferencesWindowClass[] =
L"Electron_SystemPreferencesHostWindow";
bool g_is_high_contract_color_scheme = false;
bool g_is_high_contract_color_scheme_initialized = false;
void UpdateHighContrastColorScheme() {
HIGHCONTRAST high_contrast = {0};
high_contrast.cbSize = sizeof(HIGHCONTRAST);
g_is_high_contract_color_scheme =
SystemParametersInfo(SPI_GETHIGHCONTRAST, 0, &high_contrast, 0) &&
((high_contrast.dwFlags & HCF_HIGHCONTRASTON) != 0);
g_is_high_contract_color_scheme_initialized = true;
}
} // namespace
namespace api {
bool SystemPreferences::IsAeroGlassEnabled() {
return ui::win::IsAeroGlassEnabled();
}
bool SystemPreferences::IsHighContrastColorScheme() {
if (!g_is_high_contract_color_scheme_initialized)
UpdateHighContrastColorScheme();
return g_is_high_contract_color_scheme;
}
std::string hexColorDWORDToRGBA(DWORD color) {
DWORD rgba = color << 8 | color >> 24;
std::ostringstream stream;
stream << std::hex << std::setw(8) << std::setfill('0') << rgba;
return stream.str();
}
std::string SystemPreferences::GetAccentColor() {
DWORD color = 0;
BOOL opaque = FALSE;
if (FAILED(DwmGetColorizationColor(&color, &opaque))) {
return "";
}
return hexColorDWORDToRGBA(color);
}
std::string SystemPreferences::GetColor(const std::string& color,
mate::Arguments* args) {
int id;
if (color == "3d-dark-shadow") {
id = COLOR_3DDKSHADOW;
} else if (color == "3d-face") {
id = COLOR_3DFACE;
} else if (color == "3d-highlight") {
id = COLOR_3DHIGHLIGHT;
} else if (color == "3d-light") {
id = COLOR_3DLIGHT;
} else if (color == "3d-shadow") {
id = COLOR_3DSHADOW;
} else if (color == "active-border") {
id = COLOR_ACTIVEBORDER;
} else if (color == "active-caption") {
id = COLOR_ACTIVECAPTION;
} else if (color == "active-caption-gradient") {
id = COLOR_GRADIENTACTIVECAPTION;
} else if (color == "app-workspace") {
id = COLOR_APPWORKSPACE;
} else if (color == "button-text") {
id = COLOR_BTNTEXT;
} else if (color == "caption-text") {
id = COLOR_CAPTIONTEXT;
} else if (color == "desktop") {
id = COLOR_DESKTOP;
} else if (color == "disabled-text") {
id = COLOR_GRAYTEXT;
} else if (color == "highlight") {
id = COLOR_HIGHLIGHT;
} else if (color == "highlight-text") {
id = COLOR_HIGHLIGHTTEXT;
} else if (color == "hotlight") {
id = COLOR_HOTLIGHT;
} else if (color == "inactive-border") {
id = COLOR_INACTIVEBORDER;
} else if (color == "inactive-caption") {
id = COLOR_INACTIVECAPTION;
} else if (color == "inactive-caption-gradient") {
id = COLOR_GRADIENTINACTIVECAPTION;
} else if (color == "inactive-caption-text") {
id = COLOR_INACTIVECAPTIONTEXT;
} else if (color == "info-background") {
id = COLOR_INFOBK;
} else if (color == "info-text") {
id = COLOR_INFOTEXT;
} else if (color == "menu") {
id = COLOR_MENU;
} else if (color == "menu-highlight") {
id = COLOR_MENUHILIGHT;
} else if (color == "menubar") {
id = COLOR_MENUBAR;
} else if (color == "menu-text") {
id = COLOR_MENUTEXT;
} else if (color == "scrollbar") {
id = COLOR_SCROLLBAR;
} else if (color == "window") {
id = COLOR_WINDOW;
} else if (color == "window-frame") {
id = COLOR_WINDOWFRAME;
} else if (color == "window-text") {
id = COLOR_WINDOWTEXT;
} else {
args->ThrowError("Unknown color: " + color);
return "";
}
return ToRGBHex(color_utils::GetSysSkColor(id));
}
void SystemPreferences::InitializeWindow() {
invertered_color_scheme_ = IsInvertedColorScheme();
high_contrast_color_scheme_ = IsHighContrastColorScheme();
// Wait until app is ready before creating sys color listener
// Creating this listener before the app is ready causes global shortcuts
// to not fire
if (Browser::Get()->is_ready())
color_change_listener_.reset(new gfx::ScopedSysColorChangeListener(this));
else
Browser::Get()->AddObserver(this);
WNDCLASSEX window_class;
base::win::InitializeWindowClass(
kSystemPreferencesWindowClass,
&base::win::WrappedWindowProc<SystemPreferences::WndProcStatic>, 0, 0, 0,
NULL, NULL, NULL, NULL, NULL, &window_class);
instance_ = window_class.hInstance;
atom_ = RegisterClassEx(&window_class);
// Create an offscreen window for receiving broadcast messages for the system
// colorization color. Create a hidden WS_POPUP window instead of an
// HWND_MESSAGE window, because only top-level windows such as popups can
// receive broadcast messages like "WM_DWMCOLORIZATIONCOLORCHANGED".
window_ = CreateWindow(MAKEINTATOM(atom_), 0, WS_POPUP, 0, 0, 0, 0, 0, 0,
instance_, 0);
gfx::CheckWindowCreated(window_);
gfx::SetWindowUserData(window_, this);
}
LRESULT CALLBACK SystemPreferences::WndProcStatic(HWND hwnd,
UINT message,
WPARAM wparam,
LPARAM lparam) {
SystemPreferences* msg_wnd = reinterpret_cast<SystemPreferences*>(
GetWindowLongPtr(hwnd, GWLP_USERDATA));
if (msg_wnd)
return msg_wnd->WndProc(hwnd, message, wparam, lparam);
else
return ::DefWindowProc(hwnd, message, wparam, lparam);
}
LRESULT CALLBACK SystemPreferences::WndProc(HWND hwnd,
UINT message,
WPARAM wparam,
LPARAM lparam) {
if (message == WM_DWMCOLORIZATIONCOLORCHANGED) {
DWORD new_color = (DWORD)wparam;
std::string new_color_string = hexColorDWORDToRGBA(new_color);
if (new_color_string != current_color_) {
Emit("accent-color-changed", hexColorDWORDToRGBA(new_color));
current_color_ = new_color_string;
}
} else if (message == WM_SYSCOLORCHANGE ||
(message == WM_SETTINGCHANGE && wparam == SPI_SETHIGHCONTRAST)) {
UpdateHighContrastColorScheme();
}
return ::DefWindowProc(hwnd, message, wparam, lparam);
}
void SystemPreferences::OnSysColorChange() {
bool new_invertered_color_scheme = IsInvertedColorScheme();
if (new_invertered_color_scheme != invertered_color_scheme_) {
invertered_color_scheme_ = new_invertered_color_scheme;
Emit("inverted-color-scheme-changed", new_invertered_color_scheme);
}
bool new_high_contrast_color_scheme = IsHighContrastColorScheme();
if (new_high_contrast_color_scheme != high_contrast_color_scheme_) {
high_contrast_color_scheme_ = new_high_contrast_color_scheme;
Emit("high-contrast-color-scheme-changed", new_high_contrast_color_scheme);
}
Emit("color-changed");
}
void SystemPreferences::OnFinishLaunching(
const base::DictionaryValue& launch_info) {
color_change_listener_.reset(new gfx::ScopedSysColorChangeListener(this));
}
} // namespace api
} // namespace atom

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,286 @@
// 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_BROWSER_API_ATOM_API_TOP_LEVEL_WINDOW_H_
#define ATOM_BROWSER_API_ATOM_API_TOP_LEVEL_WINDOW_H_
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "atom/browser/api/trackable_object.h"
#include "atom/browser/native_window.h"
#include "atom/browser/native_window_observer.h"
#include "atom/common/api/atom_api_native_image.h"
#include "base/task/post_task.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "native_mate/handle.h"
namespace atom {
namespace api {
class View;
class TopLevelWindow : public mate::TrackableObject<TopLevelWindow>,
public NativeWindowObserver {
public:
static mate::WrappableBase* New(mate::Arguments* args);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
base::WeakPtr<TopLevelWindow> GetWeakPtr() {
return weak_factory_.GetWeakPtr();
}
NativeWindow* window() const { return window_.get(); }
protected:
// Common constructor.
TopLevelWindow(v8::Isolate* isolate, const mate::Dictionary& options);
// Creating independent TopLevelWindow instance.
TopLevelWindow(v8::Isolate* isolate,
v8::Local<v8::Object> wrapper,
const mate::Dictionary& options);
~TopLevelWindow() override;
// TrackableObject:
void InitWith(v8::Isolate* isolate, v8::Local<v8::Object> wrapper) override;
// NativeWindowObserver:
void WillCloseWindow(bool* prevent_default) override;
void OnWindowClosed() override;
void OnWindowEndSession() override;
void OnWindowBlur() override;
void OnWindowFocus() override;
void OnWindowShow() override;
void OnWindowHide() override;
void OnWindowMaximize() override;
void OnWindowUnmaximize() override;
void OnWindowMinimize() override;
void OnWindowRestore() override;
void OnWindowWillResize(const gfx::Rect& new_bounds,
bool* prevent_default) override;
void OnWindowResize() override;
void OnWindowWillMove(const gfx::Rect& new_bounds,
bool* prevent_default) override;
void OnWindowMove() override;
void OnWindowMoved() override;
void OnWindowScrollTouchBegin() override;
void OnWindowScrollTouchEnd() override;
void OnWindowSwipe(const std::string& direction) override;
void OnWindowSheetBegin() override;
void OnWindowSheetEnd() override;
void OnWindowEnterFullScreen() override;
void OnWindowLeaveFullScreen() override;
void OnWindowEnterHtmlFullScreen() override;
void OnWindowLeaveHtmlFullScreen() override;
void OnWindowAlwaysOnTopChanged() override;
void OnExecuteAppCommand(const std::string& command_name) override;
void OnTouchBarItemResult(const std::string& item_id,
const base::DictionaryValue& details) override;
void OnNewWindowForTab() override;
#if defined(OS_WIN)
void OnWindowMessage(UINT message, WPARAM w_param, LPARAM l_param) override;
#endif
// Public APIs of NativeWindow.
void SetContentView(mate::Handle<View> view);
void Close();
virtual void Focus();
virtual void Blur();
bool IsFocused();
void Show();
void ShowInactive();
void Hide();
bool IsVisible();
bool IsEnabled();
void SetEnabled(bool enable);
void Maximize();
void Unmaximize();
bool IsMaximized();
void Minimize();
void Restore();
bool IsMinimized();
void SetFullScreen(bool fullscreen);
bool IsFullscreen();
void SetBounds(const gfx::Rect& bounds, mate::Arguments* args);
gfx::Rect GetBounds();
void SetSize(int width, int height, mate::Arguments* args);
std::vector<int> GetSize();
void SetContentSize(int width, int height, mate::Arguments* args);
std::vector<int> GetContentSize();
void SetContentBounds(const gfx::Rect& bounds, mate::Arguments* args);
gfx::Rect GetContentBounds();
bool IsNormal();
gfx::Rect GetNormalBounds();
void SetMinimumSize(int width, int height);
std::vector<int> GetMinimumSize();
void SetMaximumSize(int width, int height);
std::vector<int> GetMaximumSize();
void SetSheetOffset(double offsetY, mate::Arguments* args);
void SetResizable(bool resizable);
bool IsResizable();
void SetMovable(bool movable);
void MoveTop();
bool IsMovable();
void SetMinimizable(bool minimizable);
bool IsMinimizable();
void SetMaximizable(bool maximizable);
bool IsMaximizable();
void SetFullScreenable(bool fullscreenable);
bool IsFullScreenable();
void SetClosable(bool closable);
bool IsClosable();
void SetAlwaysOnTop(bool top, mate::Arguments* args);
bool IsAlwaysOnTop();
void Center();
void SetPosition(int x, int y, mate::Arguments* args);
std::vector<int> GetPosition();
void SetTitle(const std::string& title);
std::string GetTitle();
void FlashFrame(bool flash);
void SetSkipTaskbar(bool skip);
void SetExcludedFromShownWindowsMenu(bool excluded);
bool IsExcludedFromShownWindowsMenu();
void SetSimpleFullScreen(bool simple_fullscreen);
bool IsSimpleFullScreen();
void SetKiosk(bool kiosk);
bool IsKiosk();
virtual void SetBackgroundColor(const std::string& color_name);
void SetHasShadow(bool has_shadow);
bool HasShadow();
void SetOpacity(const double opacity);
double GetOpacity();
void SetShape(const std::vector<gfx::Rect>& rects);
void SetRepresentedFilename(const std::string& filename);
std::string GetRepresentedFilename();
void SetDocumentEdited(bool edited);
bool IsDocumentEdited();
void SetIgnoreMouseEvents(bool ignore, mate::Arguments* args);
void SetContentProtection(bool enable);
void SetFocusable(bool focusable);
void SetMenu(v8::Isolate* isolate, v8::Local<v8::Value> menu);
void RemoveMenu();
void SetParentWindow(v8::Local<v8::Value> value, mate::Arguments* args);
virtual void SetBrowserView(v8::Local<v8::Value> value);
virtual void AddBrowserView(v8::Local<v8::Value> value);
virtual void RemoveBrowserView(v8::Local<v8::Value> value);
virtual std::vector<v8::Local<v8::Value>> GetBrowserViews() const;
virtual void ResetBrowserViews();
v8::Local<v8::Value> GetNativeWindowHandle();
void SetProgressBar(double progress, mate::Arguments* args);
void SetOverlayIcon(const gfx::Image& overlay,
const std::string& description);
void SetVisibleOnAllWorkspaces(bool visible, mate::Arguments* args);
bool IsVisibleOnAllWorkspaces();
void SetAutoHideCursor(bool auto_hide);
virtual void SetVibrancy(v8::Isolate* isolate, v8::Local<v8::Value> value);
void SetTouchBar(const std::vector<mate::PersistentDictionary>& items);
void RefreshTouchBarItem(const std::string& item_id);
void SetEscapeTouchBarItem(const mate::PersistentDictionary& item);
void SelectPreviousTab();
void SelectNextTab();
void MergeAllWindows();
void MoveTabToNewWindow();
void ToggleTabBar();
void AddTabbedWindow(NativeWindow* window, mate::Arguments* args);
void SetWindowButtonVisibility(bool visible, mate::Arguments* args);
void SetAutoHideMenuBar(bool auto_hide);
bool IsMenuBarAutoHide();
void SetMenuBarVisibility(bool visible);
bool IsMenuBarVisible();
void SetAspectRatio(double aspect_ratio, mate::Arguments* args);
void PreviewFile(const std::string& path, mate::Arguments* args);
void CloseFilePreview();
// Public getters of NativeWindow.
v8::Local<v8::Value> GetContentView() const;
v8::Local<v8::Value> GetParentWindow() const;
std::vector<v8::Local<v8::Object>> GetChildWindows() const;
v8::Local<v8::Value> GetBrowserView(mate::Arguments* args) const;
bool IsModal() const;
// Extra APIs added in JS.
bool SetThumbarButtons(mate::Arguments* args);
#if defined(TOOLKIT_VIEWS)
void SetIcon(mate::Handle<NativeImage> icon);
#endif
#if defined(OS_WIN)
typedef base::RepeatingCallback<void(v8::Local<v8::Value>,
v8::Local<v8::Value>)>
MessageCallback;
bool HookWindowMessage(UINT message, const MessageCallback& callback);
bool IsWindowMessageHooked(UINT message);
void UnhookWindowMessage(UINT message);
void UnhookAllWindowMessages();
bool SetThumbnailClip(const gfx::Rect& region);
bool SetThumbnailToolTip(const std::string& tooltip);
void SetAppDetails(const mate::Dictionary& options);
#endif
int32_t GetID() const;
// Helpers.
// Remove BrowserView.
void ResetBrowserView();
// Remove this window from parent window's |child_windows_|.
void RemoveFromParentChildWindows();
template <typename... Args>
void EmitEventSoon(base::StringPiece eventName) {
base::PostTaskWithTraits(
FROM_HERE, {content::BrowserThread::UI},
base::BindOnce(base::IgnoreResult(&TopLevelWindow::Emit<Args...>),
weak_factory_.GetWeakPtr(), eventName));
}
#if defined(OS_WIN)
typedef std::map<UINT, MessageCallback> MessageCallbackMap;
MessageCallbackMap messages_callback_map_;
#endif
v8::Global<v8::Value> content_view_;
std::map<int32_t, v8::Global<v8::Value>> browser_views_;
v8::Global<v8::Value> menu_;
v8::Global<v8::Value> parent_window_;
KeyWeakMap<int> child_windows_;
std::unique_ptr<NativeWindow> window_;
base::WeakPtrFactory<TopLevelWindow> weak_factory_;
};
} // namespace api
} // namespace atom
namespace mate {
template <>
struct Converter<atom::NativeWindow*> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
atom::NativeWindow** out) {
// null would be tranfered to NULL.
if (val->IsNull()) {
*out = NULL;
return true;
}
atom::api::TopLevelWindow* window;
if (!Converter<atom::api::TopLevelWindow*>::FromV8(isolate, val, &window))
return false;
*out = window->window();
return true;
}
};
} // namespace mate
#endif // ATOM_BROWSER_API_ATOM_API_TOP_LEVEL_WINDOW_H_

View file

@ -0,0 +1,272 @@
// 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/browser/api/atom_api_tray.h"
#include <string>
#include "atom/browser/api/atom_api_menu.h"
#include "atom/browser/browser.h"
#include "atom/common/api/atom_api_native_image.h"
#include "atom/common/native_mate_converters/gfx_converter.h"
#include "atom/common/native_mate_converters/image_converter.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/node_includes.h"
#include "base/threading/thread_task_runner_handle.h"
#include "native_mate/constructor.h"
#include "native_mate/dictionary.h"
#include "ui/gfx/image/image.h"
namespace mate {
template <>
struct Converter<atom::TrayIcon::HighlightMode> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
atom::TrayIcon::HighlightMode* out) {
using HighlightMode = atom::TrayIcon::HighlightMode;
std::string mode;
if (ConvertFromV8(isolate, val, &mode)) {
if (mode == "always") {
*out = HighlightMode::ALWAYS;
return true;
}
if (mode == "selection") {
*out = HighlightMode::SELECTION;
return true;
}
if (mode == "never") {
*out = HighlightMode::NEVER;
return true;
}
}
return false;
}
};
} // namespace mate
namespace atom {
namespace api {
Tray::Tray(v8::Isolate* isolate,
v8::Local<v8::Object> wrapper,
mate::Handle<NativeImage> image)
: tray_icon_(TrayIcon::Create()) {
SetImage(isolate, image);
tray_icon_->AddObserver(this);
InitWith(isolate, wrapper);
}
Tray::~Tray() = default;
// static
mate::WrappableBase* Tray::New(mate::Handle<NativeImage> image,
mate::Arguments* args) {
if (!Browser::Get()->is_ready()) {
args->ThrowError("Cannot create Tray before app is ready");
return nullptr;
}
return new Tray(args->isolate(), args->GetThis(), image);
}
void Tray::OnClicked(const gfx::Rect& bounds,
const gfx::Point& location,
int modifiers) {
EmitWithFlags("click", modifiers, bounds, location);
}
void Tray::OnDoubleClicked(const gfx::Rect& bounds, int modifiers) {
EmitWithFlags("double-click", modifiers, bounds);
}
void Tray::OnRightClicked(const gfx::Rect& bounds, int modifiers) {
EmitWithFlags("right-click", modifiers, bounds);
}
void Tray::OnBalloonShow() {
Emit("balloon-show");
}
void Tray::OnBalloonClicked() {
Emit("balloon-click");
}
void Tray::OnBalloonClosed() {
Emit("balloon-closed");
}
void Tray::OnDrop() {
Emit("drop");
}
void Tray::OnDropFiles(const std::vector<std::string>& files) {
Emit("drop-files", files);
}
void Tray::OnDropText(const std::string& text) {
Emit("drop-text", text);
}
void Tray::OnMouseEntered(const gfx::Point& location, int modifiers) {
EmitWithFlags("mouse-enter", modifiers, location);
}
void Tray::OnMouseExited(const gfx::Point& location, int modifiers) {
EmitWithFlags("mouse-leave", modifiers, location);
}
void Tray::OnMouseMoved(const gfx::Point& location, int modifiers) {
EmitWithFlags("mouse-move", modifiers, location);
}
void Tray::OnDragEntered() {
Emit("drag-enter");
}
void Tray::OnDragExited() {
Emit("drag-leave");
}
void Tray::OnDragEnded() {
Emit("drag-end");
}
void Tray::SetImage(v8::Isolate* isolate, mate::Handle<NativeImage> image) {
#if defined(OS_WIN)
tray_icon_->SetImage(image->GetHICON(GetSystemMetrics(SM_CXSMICON)));
#else
tray_icon_->SetImage(image->image());
#endif
}
void Tray::SetPressedImage(v8::Isolate* isolate,
mate::Handle<NativeImage> image) {
#if defined(OS_WIN)
tray_icon_->SetPressedImage(image->GetHICON(GetSystemMetrics(SM_CXSMICON)));
#else
tray_icon_->SetPressedImage(image->image());
#endif
}
void Tray::SetToolTip(const std::string& tool_tip) {
tray_icon_->SetToolTip(tool_tip);
}
void Tray::SetTitle(const std::string& title) {
#if defined(OS_MACOSX)
tray_icon_->SetTitle(title);
#endif
}
std::string Tray::GetTitle() {
#if defined(OS_MACOSX)
return tray_icon_->GetTitle();
#else
return "";
#endif
}
void Tray::SetHighlightMode(TrayIcon::HighlightMode mode) {
tray_icon_->SetHighlightMode(mode);
}
void Tray::SetIgnoreDoubleClickEvents(bool ignore) {
#if defined(OS_MACOSX)
tray_icon_->SetIgnoreDoubleClickEvents(ignore);
#endif
}
bool Tray::GetIgnoreDoubleClickEvents() {
#if defined(OS_MACOSX)
return tray_icon_->GetIgnoreDoubleClickEvents();
#else
return false;
#endif
}
void Tray::DisplayBalloon(mate::Arguments* args,
const mate::Dictionary& options) {
mate::Handle<NativeImage> icon;
options.Get("icon", &icon);
base::string16 title, content;
if (!options.Get("title", &title) || !options.Get("content", &content)) {
args->ThrowError("'title' and 'content' must be defined");
return;
}
#if defined(OS_WIN)
tray_icon_->DisplayBalloon(
icon.IsEmpty() ? NULL : icon->GetHICON(GetSystemMetrics(SM_CXSMICON)),
title, content);
#else
tray_icon_->DisplayBalloon(icon.IsEmpty() ? gfx::Image() : icon->image(),
title, content);
#endif
}
void Tray::PopUpContextMenu(mate::Arguments* args) {
mate::Handle<Menu> menu;
args->GetNext(&menu);
gfx::Point pos;
args->GetNext(&pos);
tray_icon_->PopUpContextMenu(pos, menu.IsEmpty() ? nullptr : menu->model());
}
void Tray::SetContextMenu(v8::Isolate* isolate, mate::Handle<Menu> menu) {
menu_.Reset(isolate, menu.ToV8());
tray_icon_->SetContextMenu(menu.IsEmpty() ? nullptr : menu->model());
}
gfx::Rect Tray::GetBounds() {
return tray_icon_->GetBounds();
}
// static
void Tray::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "Tray"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.MakeDestroyable()
.SetMethod("setImage", &Tray::SetImage)
.SetMethod("setPressedImage", &Tray::SetPressedImage)
.SetMethod("setToolTip", &Tray::SetToolTip)
.SetMethod("setTitle", &Tray::SetTitle)
.SetMethod("getTitle", &Tray::GetTitle)
.SetMethod("setHighlightMode", &Tray::SetHighlightMode)
.SetMethod("setIgnoreDoubleClickEvents",
&Tray::SetIgnoreDoubleClickEvents)
.SetMethod("getIgnoreDoubleClickEvents",
&Tray::GetIgnoreDoubleClickEvents)
.SetMethod("displayBalloon", &Tray::DisplayBalloon)
.SetMethod("popUpContextMenu", &Tray::PopUpContextMenu)
.SetMethod("setContextMenu", &Tray::SetContextMenu)
.SetMethod("getBounds", &Tray::GetBounds);
}
} // namespace api
} // namespace atom
namespace {
using atom::api::Tray;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
Tray::SetConstructor(isolate, base::BindRepeating(&Tray::New));
mate::Dictionary dict(isolate, exports);
dict.Set(
"Tray",
Tray::GetConstructor(isolate)->GetFunction(context).ToLocalChecked());
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_browser_tray, Initialize)

View file

@ -0,0 +1,92 @@
// 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_BROWSER_API_ATOM_API_TRAY_H_
#define ATOM_BROWSER_API_ATOM_API_TRAY_H_
#include <memory>
#include <string>
#include <vector>
#include "atom/browser/api/trackable_object.h"
#include "atom/browser/ui/tray_icon.h"
#include "atom/browser/ui/tray_icon_observer.h"
#include "native_mate/handle.h"
namespace gfx {
class Image;
}
namespace mate {
class Arguments;
class Dictionary;
} // namespace mate
namespace atom {
class TrayIcon;
namespace api {
class Menu;
class NativeImage;
class Tray : public mate::TrackableObject<Tray>, public TrayIconObserver {
public:
static mate::WrappableBase* New(mate::Handle<NativeImage> image,
mate::Arguments* args);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
protected:
Tray(v8::Isolate* isolate,
v8::Local<v8::Object> wrapper,
mate::Handle<NativeImage> image);
~Tray() override;
// TrayIconObserver:
void OnClicked(const gfx::Rect& bounds,
const gfx::Point& location,
int modifiers) override;
void OnDoubleClicked(const gfx::Rect& bounds, int modifiers) override;
void OnRightClicked(const gfx::Rect& bounds, int modifiers) override;
void OnBalloonShow() override;
void OnBalloonClicked() override;
void OnBalloonClosed() override;
void OnDrop() override;
void OnDropFiles(const std::vector<std::string>& files) override;
void OnDropText(const std::string& text) override;
void OnDragEntered() override;
void OnDragExited() override;
void OnDragEnded() override;
void OnMouseEntered(const gfx::Point& location, int modifiers) override;
void OnMouseExited(const gfx::Point& location, int modifiers) override;
void OnMouseMoved(const gfx::Point& location, int modifiers) override;
void SetImage(v8::Isolate* isolate, mate::Handle<NativeImage> image);
void SetPressedImage(v8::Isolate* isolate, mate::Handle<NativeImage> image);
void SetToolTip(const std::string& tool_tip);
void SetTitle(const std::string& title);
std::string GetTitle();
void SetHighlightMode(TrayIcon::HighlightMode mode);
void SetIgnoreDoubleClickEvents(bool ignore);
bool GetIgnoreDoubleClickEvents();
void DisplayBalloon(mate::Arguments* args, const mate::Dictionary& options);
void PopUpContextMenu(mate::Arguments* args);
void SetContextMenu(v8::Isolate* isolate, mate::Handle<Menu> menu);
gfx::Rect GetBounds();
private:
v8::Global<v8::Object> menu_;
std::unique_ptr<TrayIcon> tray_icon_;
DISALLOW_COPY_AND_ASSIGN(Tray);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_TRAY_H_

View file

@ -0,0 +1,496 @@
// 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/browser/api/atom_api_url_request.h"
#include <string>
#include "atom/browser/api/atom_api_session.h"
#include "atom/browser/net/atom_url_request.h"
#include "atom/common/api/event_emitter_caller.h"
#include "atom/common/native_mate_converters/gurl_converter.h"
#include "atom/common/native_mate_converters/net_converter.h"
#include "atom/common/native_mate_converters/once_callback.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/node_includes.h"
#include "native_mate/dictionary.h"
namespace mate {
template <>
struct Converter<scoped_refptr<const net::IOBufferWithSize>> {
static v8::Local<v8::Value> ToV8(
v8::Isolate* isolate,
scoped_refptr<const net::IOBufferWithSize> buffer) {
return node::Buffer::Copy(isolate, buffer->data(), buffer->size())
.ToLocalChecked();
}
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
scoped_refptr<const net::IOBufferWithSize>* out) {
auto size = node::Buffer::Length(val);
if (size == 0) {
// Support conversion from empty buffer. A use case is
// a GET request without body.
// Since zero-sized IOBuffer(s) are not supported, we set the
// out pointer to null.
*out = nullptr;
return true;
}
auto* data = node::Buffer::Data(val);
if (!data) {
// This is an error as size is positive but data is null.
return false;
}
*out = new net::IOBufferWithSize(size);
// We do a deep copy. We could have used Buffer's internal memory
// but that is much more complicated to be properly handled.
memcpy((*out)->data(), data, size);
return true;
}
};
} // namespace mate
namespace atom {
namespace api {
template <typename Flags>
URLRequest::StateBase<Flags>::StateBase(Flags initialState)
: state_(initialState) {}
template <typename Flags>
void URLRequest::StateBase<Flags>::SetFlag(Flags flag) {
state_ =
static_cast<Flags>(static_cast<int>(state_) | static_cast<int>(flag));
}
template <typename Flags>
bool URLRequest::StateBase<Flags>::operator==(Flags flag) const {
return state_ == flag;
}
template <typename Flags>
bool URLRequest::StateBase<Flags>::IsFlagSet(Flags flag) const {
return static_cast<int>(state_) & static_cast<int>(flag);
}
URLRequest::RequestState::RequestState()
: StateBase(RequestStateFlags::kNotStarted) {}
bool URLRequest::RequestState::NotStarted() const {
return *this == RequestStateFlags::kNotStarted;
}
bool URLRequest::RequestState::Started() const {
return IsFlagSet(RequestStateFlags::kStarted);
}
bool URLRequest::RequestState::Finished() const {
return IsFlagSet(RequestStateFlags::kFinished);
}
bool URLRequest::RequestState::Canceled() const {
return IsFlagSet(RequestStateFlags::kCanceled);
}
bool URLRequest::RequestState::Failed() const {
return IsFlagSet(RequestStateFlags::kFailed);
}
bool URLRequest::RequestState::Closed() const {
return IsFlagSet(RequestStateFlags::kClosed);
}
URLRequest::ResponseState::ResponseState()
: StateBase(ResponseStateFlags::kNotStarted) {}
bool URLRequest::ResponseState::NotStarted() const {
return *this == ResponseStateFlags::kNotStarted;
}
bool URLRequest::ResponseState::Started() const {
return IsFlagSet(ResponseStateFlags::kStarted);
}
bool URLRequest::ResponseState::Ended() const {
return IsFlagSet(ResponseStateFlags::kEnded);
}
bool URLRequest::ResponseState::Failed() const {
return IsFlagSet(ResponseStateFlags::kFailed);
}
mate::Dictionary URLRequest::GetUploadProgress(v8::Isolate* isolate) {
mate::Dictionary progress = mate::Dictionary::CreateEmpty(isolate);
if (atom_request_) {
progress.Set("active", true);
atom_request_->GetUploadProgress(&progress);
} else {
progress.Set("active", false);
}
return progress;
}
URLRequest::URLRequest(v8::Isolate* isolate, v8::Local<v8::Object> wrapper) {
InitWith(isolate, wrapper);
}
URLRequest::~URLRequest() {
// A request has been created in JS, it was not used and then
// it got collected, no close event to cleanup, only destructor
// is called.
if (atom_request_) {
atom_request_->Terminate();
}
}
// static
mate::WrappableBase* URLRequest::New(mate::Arguments* args) {
auto* isolate = args->isolate();
v8::Local<v8::Object> options;
args->GetNext(&options);
mate::Dictionary dict(isolate, options);
std::string method;
dict.Get("method", &method);
std::string url;
dict.Get("url", &url);
std::string redirect_policy;
dict.Get("redirect", &redirect_policy);
std::string partition;
mate::Handle<api::Session> session;
if (dict.Get("session", &session)) {
} else if (dict.Get("partition", &partition)) {
session = Session::FromPartition(isolate, partition);
} else {
// Use the default session if not specified.
session = Session::FromPartition(isolate, "");
}
auto* browser_context = session->browser_context();
auto* api_url_request = new URLRequest(args->isolate(), args->GetThis());
auto atom_url_request = AtomURLRequest::Create(
browser_context, method, url, redirect_policy, api_url_request);
api_url_request->atom_request_ = atom_url_request;
return api_url_request;
}
// static
void URLRequest::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "URLRequest"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
// Request API
.MakeDestroyable()
.SetMethod("write", &URLRequest::Write)
.SetMethod("cancel", &URLRequest::Cancel)
.SetMethod("setExtraHeader", &URLRequest::SetExtraHeader)
.SetMethod("removeExtraHeader", &URLRequest::RemoveExtraHeader)
.SetMethod("setChunkedUpload", &URLRequest::SetChunkedUpload)
.SetMethod("followRedirect", &URLRequest::FollowRedirect)
.SetMethod("_setLoadFlags", &URLRequest::SetLoadFlags)
.SetMethod("getUploadProgress", &URLRequest::GetUploadProgress)
.SetProperty("notStarted", &URLRequest::NotStarted)
.SetProperty("finished", &URLRequest::Finished)
// Response APi
.SetProperty("statusCode", &URLRequest::StatusCode)
.SetProperty("statusMessage", &URLRequest::StatusMessage)
.SetProperty("rawResponseHeaders", &URLRequest::RawResponseHeaders)
.SetProperty("httpVersionMajor", &URLRequest::ResponseHttpVersionMajor)
.SetProperty("httpVersionMinor", &URLRequest::ResponseHttpVersionMinor);
}
bool URLRequest::NotStarted() const {
return request_state_.NotStarted();
}
bool URLRequest::Finished() const {
return request_state_.Finished();
}
bool URLRequest::Canceled() const {
return request_state_.Canceled();
}
bool URLRequest::Write(scoped_refptr<const net::IOBufferWithSize> buffer,
bool is_last) {
if (request_state_.Canceled() || request_state_.Failed() ||
request_state_.Finished() || request_state_.Closed()) {
return false;
}
if (request_state_.NotStarted()) {
request_state_.SetFlag(RequestStateFlags::kStarted);
// Pin on first write.
Pin();
}
if (is_last) {
request_state_.SetFlag(RequestStateFlags::kFinished);
EmitRequestEvent(true, "finish");
}
DCHECK(atom_request_);
if (atom_request_) {
return atom_request_->Write(buffer, is_last);
}
return false;
}
void URLRequest::Cancel() {
if (request_state_.Canceled() || request_state_.Closed()) {
// Cancel only once.
return;
}
// Mark as canceled.
request_state_.SetFlag(RequestStateFlags::kCanceled);
DCHECK(atom_request_);
if (atom_request_ && request_state_.Started()) {
// Really cancel if it was started.
atom_request_->Cancel();
}
EmitRequestEvent(true, "abort");
if (response_state_.Started() && !response_state_.Ended()) {
EmitResponseEvent(true, "aborted");
}
Close();
}
void URLRequest::FollowRedirect() {
if (request_state_.Canceled() || request_state_.Closed()) {
return;
}
DCHECK(atom_request_);
if (atom_request_) {
atom_request_->FollowRedirect();
}
}
bool URLRequest::SetExtraHeader(const std::string& name,
const std::string& value) {
// Request state must be in the initial non started state.
if (!request_state_.NotStarted()) {
// Cannot change headers after send.
return false;
}
if (!net::HttpUtil::IsValidHeaderName(name)) {
return false;
}
if (!net::HttpUtil::IsValidHeaderValue(value)) {
return false;
}
DCHECK(atom_request_);
if (atom_request_) {
atom_request_->SetExtraHeader(name, value);
}
return true;
}
void URLRequest::RemoveExtraHeader(const std::string& name) {
// State must be equal to not started.
if (!request_state_.NotStarted()) {
// Cannot change headers after send.
return;
}
DCHECK(atom_request_);
if (atom_request_) {
atom_request_->RemoveExtraHeader(name);
}
}
void URLRequest::SetChunkedUpload(bool is_chunked_upload) {
// State must be equal to not started.
if (!request_state_.NotStarted()) {
// Cannot change headers after send.
return;
}
DCHECK(atom_request_);
if (atom_request_) {
atom_request_->SetChunkedUpload(is_chunked_upload);
}
}
void URLRequest::SetLoadFlags(int flags) {
// State must be equal to not started.
if (!request_state_.NotStarted()) {
// Cannot change load flags after start.
return;
}
DCHECK(atom_request_);
if (atom_request_) {
atom_request_->SetLoadFlags(flags);
}
}
void URLRequest::OnReceivedRedirect(
int status_code,
const std::string& method,
const GURL& url,
scoped_refptr<net::HttpResponseHeaders> response_headers) {
if (request_state_.Canceled() || request_state_.Closed()) {
return;
}
DCHECK(atom_request_);
if (!atom_request_) {
return;
}
EmitRequestEvent(false, "redirect", status_code, method, url,
response_headers.get());
}
void URLRequest::OnAuthenticationRequired(
const net::AuthChallengeInfo& auth_info) {
if (request_state_.Canceled() || request_state_.Closed()) {
return;
}
DCHECK(atom_request_);
if (!atom_request_) {
return;
}
Emit("login", auth_info,
base::BindOnce(&AtomURLRequest::PassLoginInformation, atom_request_));
}
void URLRequest::OnResponseStarted(
scoped_refptr<net::HttpResponseHeaders> response_headers) {
if (request_state_.Canceled() || request_state_.Failed() ||
request_state_.Closed()) {
// Don't emit any event after request cancel.
return;
}
response_headers_ = response_headers;
response_state_.SetFlag(ResponseStateFlags::kStarted);
Emit("response");
}
void URLRequest::OnResponseData(
scoped_refptr<const net::IOBufferWithSize> buffer) {
if (request_state_.Canceled() || request_state_.Closed() ||
request_state_.Failed() || response_state_.Failed()) {
// In case we received an unexpected event from Chromium net,
// don't emit any data event after request cancel/error/close.
return;
}
if (!buffer || !buffer->data() || !buffer->size()) {
return;
}
Emit("data", buffer);
}
void URLRequest::OnResponseCompleted() {
if (request_state_.Canceled() || request_state_.Closed() ||
request_state_.Failed() || response_state_.Failed()) {
// In case we received an unexpected event from Chromium net,
// don't emit any data event after request cancel/error/close.
return;
}
response_state_.SetFlag(ResponseStateFlags::kEnded);
Emit("end");
Close();
}
void URLRequest::OnError(const std::string& error, bool isRequestError) {
auto error_object = v8::Exception::Error(mate::StringToV8(isolate(), error));
if (isRequestError) {
request_state_.SetFlag(RequestStateFlags::kFailed);
EmitRequestEvent(false, "error", error_object);
} else {
response_state_.SetFlag(ResponseStateFlags::kFailed);
EmitResponseEvent(false, "error", error_object);
}
Close();
}
int URLRequest::StatusCode() const {
if (response_headers_) {
return response_headers_->response_code();
}
return -1;
}
std::string URLRequest::StatusMessage() const {
std::string result;
if (response_headers_) {
result = response_headers_->GetStatusText();
}
return result;
}
net::HttpResponseHeaders* URLRequest::RawResponseHeaders() const {
return response_headers_.get();
}
uint32_t URLRequest::ResponseHttpVersionMajor() const {
if (response_headers_) {
return response_headers_->GetHttpVersion().major_value();
}
return 0;
}
uint32_t URLRequest::ResponseHttpVersionMinor() const {
if (response_headers_) {
return response_headers_->GetHttpVersion().minor_value();
}
return 0;
}
void URLRequest::Close() {
if (!request_state_.Closed()) {
request_state_.SetFlag(RequestStateFlags::kClosed);
if (response_state_.Started()) {
// Emit a close event if we really have a response object.
EmitResponseEvent(true, "close");
}
EmitRequestEvent(true, "close");
}
Unpin();
if (atom_request_) {
// A request has been created in JS, used and then it ended.
// We release unneeded net resources.
atom_request_->Terminate();
}
atom_request_ = nullptr;
}
void URLRequest::Pin() {
if (wrapper_.IsEmpty()) {
wrapper_.Reset(isolate(), GetWrapper());
}
}
void URLRequest::Unpin() {
wrapper_.Reset();
}
template <typename... Args>
void URLRequest::EmitRequestEvent(Args... args) {
v8::HandleScope handle_scope(isolate());
mate::CustomEmit(isolate(), GetWrapper(), "_emitRequestEvent", args...);
}
template <typename... Args>
void URLRequest::EmitResponseEvent(Args... args) {
v8::HandleScope handle_scope(isolate());
mate::CustomEmit(isolate(), GetWrapper(), "_emitResponseEvent", args...);
}
} // namespace api
} // namespace atom

View file

@ -0,0 +1,214 @@
// 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_BROWSER_API_ATOM_API_URL_REQUEST_H_
#define ATOM_BROWSER_API_ATOM_API_URL_REQUEST_H_
#include <array>
#include <string>
#include "atom/browser/api/event_emitter.h"
#include "atom/browser/api/trackable_object.h"
#include "base/memory/weak_ptr.h"
#include "native_mate/dictionary.h"
#include "native_mate/handle.h"
#include "native_mate/wrappable_base.h"
#include "net/base/auth.h"
#include "net/base/io_buffer.h"
#include "net/http/http_response_headers.h"
#include "net/url_request/url_request_context.h"
namespace atom {
class AtomURLRequest;
namespace api {
//
// The URLRequest class implements the V8 binding between the JavaScript API
// and Chromium native net library. It is responsible for handling HTTP/HTTPS
// requests.
//
// The current class provides only the binding layer. Two other JavaScript
// classes (ClientRequest and IncomingMessage) in the net module provide the
// final API, including some state management and arguments validation.
//
// URLRequest's methods fall into two main categories: command and event
// methods. They are always executed on the Browser's UI thread.
// Command methods are called directly from JavaScript code via the API defined
// in BuildPrototype. A command method is generally implemented by forwarding
// the call to a corresponding method on AtomURLRequest which does the
// synchronization on the Browser IO thread. The latter then calls into Chromium
// net library. On the other hand, net library events originate on the IO
// thread in AtomURLRequest and are synchronized back on the UI thread, then
// forwarded to a corresponding event method in URLRequest and then to
// JavaScript via the EmitRequestEvent/EmitResponseEvent helpers.
//
// URLRequest lifetime management: we followed the Wrapper/Wrappable pattern
// defined in native_mate. However, we augment that pattern with a pin/unpin
// mechanism. The main reason is that we want the JS API to provide a similar
// lifetime guarantees as the XMLHttpRequest.
// https://xhr.spec.whatwg.org/#garbage-collection
//
// The primary motivation is to not garbage collect a URLInstance as long as the
// object is emitting network events. For instance, in the following JS code
//
// (function() {
// let request = new URLRequest(...);
// request.on('response', (response)=>{
// response.on('data', (data) = > {
// console.log(data.toString());
// });
// });
// })();
//
// we still want data to be logged even if the response/request objects are n
// more referenced in JavaScript.
//
// Binding by simply following the native_mate Wrapper/Wrappable pattern will
// delete the URLRequest object when the corresponding JS object is collected.
// The v8 handle is a private member in WrappableBase and it is always weak,
// there is no way to make it strong without changing native_mate.
// The solution we implement consists of maintaining some kind of state that
// prevents collection of JS wrappers as long as the request is emitting network
// events. At initialization, the object is unpinned. When the request starts,
// it is pinned. When no more events would be emitted, the object is unpinned
// and lifetime is again managed by the standard native mate Wrapper/Wrappable
// pattern.
//
// pin/unpin: are implemented by constructing/reseting a V8 strong persistent
// handle.
//
// The URLRequest/AtmURLRequest interaction could have been implemented in a
// single class. However, it implies that the resulting class lifetime will be
// managed by two conflicting mechanisms: JavaScript garbage collection and
// Chromium reference counting. Reasoning about lifetime issues become much
// more complex.
//
// We chose to split the implementation into two classes linked via a
// reference counted/raw pointers. A URLRequest instance is deleted if it is
// unpinned and the corresponding JS wrapper object is garbage collected. On the
// other hand, an AtmURLRequest instance lifetime is totally governed by
// reference counting.
//
class URLRequest : public mate::EventEmitter<URLRequest> {
public:
static mate::WrappableBase* New(mate::Arguments* args);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
// Methods for reporting events into JavaScript.
void OnReceivedRedirect(
int status_code,
const std::string& method,
const GURL& url,
scoped_refptr<net::HttpResponseHeaders> response_headers);
void OnAuthenticationRequired(const net::AuthChallengeInfo& auth_info);
void OnResponseStarted(
scoped_refptr<net::HttpResponseHeaders> response_headers);
void OnResponseData(scoped_refptr<const net::IOBufferWithSize> data);
void OnResponseCompleted();
void OnError(const std::string& error, bool isRequestError);
mate::Dictionary GetUploadProgress(v8::Isolate* isolate);
protected:
explicit URLRequest(v8::Isolate* isolate, v8::Local<v8::Object> wrapper);
~URLRequest() override;
private:
template <typename Flags>
class StateBase {
public:
void SetFlag(Flags flag);
protected:
explicit StateBase(Flags initialState);
bool operator==(Flags flag) const;
bool IsFlagSet(Flags flag) const;
private:
Flags state_;
};
enum class RequestStateFlags {
kNotStarted = 0x0,
kStarted = 0x1,
kFinished = 0x2,
kCanceled = 0x4,
kFailed = 0x8,
kClosed = 0x10
};
class RequestState : public StateBase<RequestStateFlags> {
public:
RequestState();
bool NotStarted() const;
bool Started() const;
bool Finished() const;
bool Canceled() const;
bool Failed() const;
bool Closed() const;
};
enum class ResponseStateFlags {
kNotStarted = 0x0,
kStarted = 0x1,
kEnded = 0x2,
kFailed = 0x4
};
class ResponseState : public StateBase<ResponseStateFlags> {
public:
ResponseState();
bool NotStarted() const;
bool Started() const;
bool Ended() const;
bool Canceled() const;
bool Failed() const;
bool Closed() const;
};
bool NotStarted() const;
bool Finished() const;
bool Canceled() const;
bool Failed() const;
bool Write(scoped_refptr<const net::IOBufferWithSize> buffer, bool is_last);
void Cancel();
void FollowRedirect();
bool SetExtraHeader(const std::string& name, const std::string& value);
void RemoveExtraHeader(const std::string& name);
void SetChunkedUpload(bool is_chunked_upload);
void SetLoadFlags(int flags);
int StatusCode() const;
std::string StatusMessage() const;
net::HttpResponseHeaders* RawResponseHeaders() const;
uint32_t ResponseHttpVersionMajor() const;
uint32_t ResponseHttpVersionMinor() const;
void Close();
void Pin();
void Unpin();
template <typename... Args>
void EmitRequestEvent(Args... args);
template <typename... Args>
void EmitResponseEvent(Args... args);
scoped_refptr<AtomURLRequest> atom_request_;
RequestState request_state_;
ResponseState response_state_;
// Used to implement pin/unpin.
v8::Global<v8::Object> wrapper_;
scoped_refptr<net::HttpResponseHeaders> response_headers_;
DISALLOW_COPY_AND_ASSIGN(URLRequest);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_URL_REQUEST_H_

View file

@ -0,0 +1,88 @@
// 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/browser/api/atom_api_view.h"
#include "atom/common/node_includes.h"
#include "native_mate/dictionary.h"
namespace atom {
namespace api {
View::View(views::View* view) : view_(view) {}
View::View() : view_(new views::View()) {
view_->set_owned_by_client();
}
View::~View() {
if (delete_view_)
delete view_;
}
#if BUILDFLAG(ENABLE_VIEW_API)
void View::SetLayoutManager(mate::Handle<LayoutManager> layout_manager) {
layout_manager_.Reset(isolate(), layout_manager->GetWrapper());
view()->SetLayoutManager(layout_manager->TakeOver());
}
void View::AddChildView(mate::Handle<View> child) {
AddChildViewAt(child, child_views_.size());
}
void View::AddChildViewAt(mate::Handle<View> child, size_t index) {
if (index > child_views_.size())
return;
child_views_.emplace(child_views_.begin() + index, // index
isolate(), child->GetWrapper()); // v8::Global(args...)
view()->AddChildViewAt(child->view(), index);
}
#endif
// static
mate::WrappableBase* View::New(mate::Arguments* args) {
auto* view = new View();
view->InitWith(args->isolate(), args->GetThis());
return view;
}
// static
void View::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "View"));
#if BUILDFLAG(ENABLE_VIEW_API)
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.SetMethod("setLayoutManager", &View::SetLayoutManager)
.SetMethod("addChildView", &View::AddChildView)
.SetMethod("addChildViewAt", &View::AddChildViewAt);
#endif
}
} // namespace api
} // namespace atom
namespace {
using atom::api::View;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
View::SetConstructor(isolate, base::BindRepeating(&View::New));
mate::Dictionary constructor(
isolate,
View::GetConstructor(isolate)->GetFunction(context).ToLocalChecked());
mate::Dictionary dict(isolate, exports);
dict.Set("View", constructor);
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_browser_view, Initialize)

View file

@ -0,0 +1,74 @@
// 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_BROWSER_API_ATOM_API_VIEW_H_
#define ATOM_BROWSER_API_ATOM_API_VIEW_H_
#include <memory>
#include <vector>
#include "atom/browser/api/views/atom_api_layout_manager.h"
#include "electron/buildflags/buildflags.h"
#include "native_mate/handle.h"
#include "ui/views/view.h"
namespace atom {
namespace api {
class View : public mate::TrackableObject<View> {
public:
static mate::WrappableBase* New(mate::Arguments* args);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
#if BUILDFLAG(ENABLE_VIEW_API)
void SetLayoutManager(mate::Handle<LayoutManager> layout_manager);
void AddChildView(mate::Handle<View> view);
void AddChildViewAt(mate::Handle<View> view, size_t index);
#endif
views::View* view() const { return view_; }
protected:
explicit View(views::View* view);
View();
~View() override;
// Should delete the |view_| in destructor.
void set_delete_view(bool should) { delete_view_ = should; }
private:
v8::Global<v8::Object> layout_manager_;
std::vector<v8::Global<v8::Object>> child_views_;
bool delete_view_ = true;
views::View* view_ = nullptr;
DISALLOW_COPY_AND_ASSIGN(View);
};
} // namespace api
} // namespace atom
namespace mate {
template <>
struct Converter<views::View*> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
views::View** out) {
atom::api::View* view;
if (!Converter<atom::api::View*>::FromV8(isolate, val, &view))
return false;
*out = view->view();
return true;
}
};
} // namespace mate
#endif // ATOM_BROWSER_API_ATOM_API_VIEW_H_

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,578 @@
// 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_BROWSER_API_ATOM_API_WEB_CONTENTS_H_
#define ATOM_BROWSER_API_ATOM_API_WEB_CONTENTS_H_
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "atom/browser/api/frame_subscriber.h"
#include "atom/browser/api/save_page_handler.h"
#include "atom/browser/api/trackable_object.h"
#include "atom/browser/common_web_contents_delegate.h"
#include "atom/browser/ui/autofill_popup.h"
#include "base/observer_list.h"
#include "base/observer_list_types.h"
#include "content/common/cursors/webcursor.h"
#include "content/public/browser/keyboard_event_processing_result.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_binding_set.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/common/favicon_url.h"
#include "electron/atom/common/api/api.mojom.h"
#include "electron/buildflags/buildflags.h"
#include "native_mate/handle.h"
#include "printing/buildflags/buildflags.h"
#include "services/service_manager/public/cpp/binder_registry.h"
#include "ui/gfx/image/image.h"
#if BUILDFLAG(ENABLE_PRINTING)
#include "atom/browser/printing/print_preview_message_handler.h"
#include "printing/backend/print_backend.h"
#endif
namespace blink {
struct WebDeviceEmulationParams;
}
namespace mate {
class Arguments;
class Dictionary;
} // namespace mate
namespace network {
class ResourceRequestBody;
}
namespace atom {
class AtomBrowserContext;
class AtomJavaScriptDialogManager;
class InspectableWebContents;
class WebContentsZoomController;
class WebViewGuestDelegate;
class FrameSubscriber;
#if BUILDFLAG(ENABLE_OSR)
class OffScreenRenderWidgetHostView;
#endif
namespace api {
// Certain events are only in WebContentsDelegate, provide our own Observer to
// dispatch those events.
class ExtendedWebContentsObserver : public base::CheckedObserver {
public:
virtual void OnCloseContents() {}
virtual void OnRendererResponsive() {}
virtual void OnDraggableRegionsUpdated(
const std::vector<mojom::DraggableRegionPtr>& regions) {}
protected:
~ExtendedWebContentsObserver() override {}
};
// Wrapper around the content::WebContents.
class WebContents : public mate::TrackableObject<WebContents>,
public CommonWebContentsDelegate,
public content::WebContentsObserver,
public mojom::ElectronBrowser {
public:
enum class Type {
BACKGROUND_PAGE, // A DevTools extension background page.
BROWSER_WINDOW, // Used by BrowserWindow.
BROWSER_VIEW, // Used by BrowserView.
REMOTE, // Thin wrap around an existing WebContents.
WEB_VIEW, // Used by <webview>.
OFF_SCREEN, // Used for offscreen rendering
};
// Create a new WebContents and return the V8 wrapper of it.
static mate::Handle<WebContents> Create(v8::Isolate* isolate,
const mate::Dictionary& options);
// Create a new V8 wrapper for an existing |web_content|.
//
// The lifetime of |web_contents| will be managed by this class.
static mate::Handle<WebContents> CreateAndTake(
v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
Type type);
// Get the V8 wrapper of |web_content|, return empty handle if not wrapped.
static mate::Handle<WebContents> From(v8::Isolate* isolate,
content::WebContents* web_content);
// Get the V8 wrapper of the |web_contents|, or create one if not existed.
//
// The lifetime of |web_contents| is NOT managed by this class, and the type
// of this wrapper is always REMOTE.
static mate::Handle<WebContents> FromOrCreate(
v8::Isolate* isolate,
content::WebContents* web_contents);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
base::WeakPtr<WebContents> GetWeakPtr() { return weak_factory_.GetWeakPtr(); }
// Destroy the managed content::WebContents instance.
//
// Note: The |async| should only be |true| when users are expecting to use the
// webContents immediately after the call. Always pass |false| if you are not
// sure.
// See https://github.com/electron/electron/issues/8930.
//
// Note: When destroying a webContents member inside a destructor, the |async|
// should always be |false|, otherwise the destroy task might be delayed after
// normal shutdown procedure, resulting in an assertion.
// The normal pattern for calling this method in destructor is:
// api_web_contents_->DestroyWebContents(!Browser::Get()->is_shutting_down())
// See https://github.com/electron/electron/issues/15133.
void DestroyWebContents(bool async);
void SetBackgroundThrottling(bool allowed);
int GetProcessID() const;
base::ProcessId GetOSProcessID() const;
Type GetType() const;
bool Equal(const WebContents* web_contents) const;
void LoadURL(const GURL& url, const mate::Dictionary& options);
void DownloadURL(const GURL& url);
GURL GetURL() const;
base::string16 GetTitle() const;
bool IsLoading() const;
bool IsLoadingMainFrame() const;
bool IsWaitingForResponse() const;
void Stop();
void ReloadIgnoringCache();
void GoBack();
void GoForward();
void GoToOffset(int offset);
const std::string GetWebRTCIPHandlingPolicy() const;
void SetWebRTCIPHandlingPolicy(const std::string& webrtc_ip_handling_policy);
bool IsCrashed() const;
void SetUserAgent(const std::string& user_agent, mate::Arguments* args);
std::string GetUserAgent();
void InsertCSS(const std::string& css);
v8::Local<v8::Promise> SavePage(const base::FilePath& full_file_path,
const content::SavePageType& save_type);
void OpenDevTools(mate::Arguments* args);
void CloseDevTools();
bool IsDevToolsOpened();
bool IsDevToolsFocused();
void ToggleDevTools();
void EnableDeviceEmulation(const blink::WebDeviceEmulationParams& params);
void DisableDeviceEmulation();
void InspectElement(int x, int y);
void InspectSharedWorker();
void InspectServiceWorker();
void SetIgnoreMenuShortcuts(bool ignore);
void SetAudioMuted(bool muted);
bool IsAudioMuted();
bool IsCurrentlyAudible();
void SetEmbedder(const WebContents* embedder);
void SetDevToolsWebContents(const WebContents* devtools);
v8::Local<v8::Value> GetNativeView() const;
#if BUILDFLAG(ENABLE_PRINTING)
void Print(mate::Arguments* args);
std::vector<printing::PrinterBasicInfo> GetPrinterList();
// Print current page as PDF.
v8::Local<v8::Promise> PrintToPDF(const base::DictionaryValue& settings);
#endif
// DevTools workspace api.
void AddWorkSpace(mate::Arguments* args, const base::FilePath& path);
void RemoveWorkSpace(mate::Arguments* args, const base::FilePath& path);
// Editing commands.
void Undo();
void Redo();
void Cut();
void Copy();
void Paste();
void PasteAndMatchStyle();
void Delete();
void SelectAll();
void Unselect();
void Replace(const base::string16& word);
void ReplaceMisspelling(const base::string16& word);
uint32_t FindInPage(mate::Arguments* args);
void StopFindInPage(content::StopFindAction action);
void ShowDefinitionForSelection();
void CopyImageAt(int x, int y);
// Focus.
void Focus();
bool IsFocused() const;
void TabTraverse(bool reverse);
// Send messages to browser.
bool SendIPCMessage(bool internal,
bool send_to_all,
const std::string& channel,
const base::ListValue& args);
bool SendIPCMessageWithSender(bool internal,
bool send_to_all,
const std::string& channel,
const base::ListValue& args,
int32_t sender_id = 0);
bool SendIPCMessageToFrame(bool internal,
bool send_to_all,
int32_t frame_id,
const std::string& channel,
const base::ListValue& args);
// Send WebInputEvent to the page.
void SendInputEvent(v8::Isolate* isolate, v8::Local<v8::Value> input_event);
// Subscribe to the frame updates.
void BeginFrameSubscription(mate::Arguments* args);
void EndFrameSubscription();
// Dragging native items.
void StartDrag(const mate::Dictionary& item, mate::Arguments* args);
// Captures the page with |rect|, |callback| would be called when capturing is
// done.
v8::Local<v8::Promise> CapturePage(mate::Arguments* args);
// Methods for creating <webview>.
bool IsGuest() const;
void AttachToIframe(content::WebContents* embedder_web_contents,
int embedder_frame_id);
void DetachFromOuterFrame();
// Methods for offscreen rendering
bool IsOffScreen() const;
#if BUILDFLAG(ENABLE_OSR)
void OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap);
void StartPainting();
void StopPainting();
bool IsPainting() const;
void SetFrameRate(int frame_rate);
int GetFrameRate() const;
#endif
void Invalidate();
gfx::Size GetSizeForNewRenderView(content::WebContents*) const override;
// Methods for zoom handling.
void SetZoomLevel(double level);
double GetZoomLevel() const;
void SetZoomFactor(double factor);
double GetZoomFactor() const;
// Callback triggered on permission response.
void OnEnterFullscreenModeForTab(content::WebContents* source,
const GURL& origin,
const blink::WebFullscreenOptions& options,
bool allowed);
// Create window with the given disposition.
void OnCreateWindow(const GURL& target_url,
const content::Referrer& referrer,
const std::string& frame_name,
WindowOpenDisposition disposition,
const std::vector<std::string>& features,
const scoped_refptr<network::ResourceRequestBody>& body);
// Returns the preload script path of current WebContents.
v8::Local<v8::Value> GetPreloadPath(v8::Isolate* isolate) const;
// Returns the web preferences of current WebContents.
v8::Local<v8::Value> GetWebPreferences(v8::Isolate* isolate) const;
v8::Local<v8::Value> GetLastWebPreferences(v8::Isolate* isolate) const;
bool IsRemoteModuleEnabled() const;
// Returns the owner window.
v8::Local<v8::Value> GetOwnerBrowserWindow() const;
// Grants the child process the capability to access URLs with the origin of
// the specified URL.
void GrantOriginAccess(const GURL& url);
v8::Local<v8::Promise> TakeHeapSnapshot(const base::FilePath& file_path);
// Properties.
int32_t ID() const;
v8::Local<v8::Value> Session(v8::Isolate* isolate);
content::WebContents* HostWebContents();
v8::Local<v8::Value> DevToolsWebContents(v8::Isolate* isolate);
v8::Local<v8::Value> Debugger(v8::Isolate* isolate);
WebContentsZoomController* GetZoomController() { return zoom_controller_; }
void AddObserver(ExtendedWebContentsObserver* obs) {
observers_.AddObserver(obs);
}
void RemoveObserver(ExtendedWebContentsObserver* obs) {
// Trying to remove from an empty collection leads to an access violation
if (observers_.might_have_observers())
observers_.RemoveObserver(obs);
}
bool EmitNavigationEvent(const std::string& event,
content::NavigationHandle* navigation_handle);
protected:
// Does not manage lifetime of |web_contents|.
WebContents(v8::Isolate* isolate, content::WebContents* web_contents);
// Takes over ownership of |web_contents|.
WebContents(v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
Type type);
// Creates a new content::WebContents.
WebContents(v8::Isolate* isolate, const mate::Dictionary& options);
~WebContents() override;
void InitWithSessionAndOptions(
v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
mate::Handle<class Session> session,
const mate::Dictionary& options);
// content::WebContentsDelegate:
bool DidAddMessageToConsole(content::WebContents* source,
blink::mojom::ConsoleMessageLevel level,
const base::string16& message,
int32_t line_no,
const base::string16& source_id) override;
void WebContentsCreated(content::WebContents* source_contents,
int opener_render_process_id,
int opener_render_frame_id,
const std::string& frame_name,
const GURL& target_url,
content::WebContents* new_contents) override;
void AddNewContents(content::WebContents* source,
std::unique_ptr<content::WebContents> new_contents,
WindowOpenDisposition disposition,
const gfx::Rect& initial_rect,
bool user_gesture,
bool* was_blocked) override;
content::WebContents* OpenURLFromTab(
content::WebContents* source,
const content::OpenURLParams& params) override;
void BeforeUnloadFired(content::WebContents* tab,
bool proceed,
bool* proceed_to_fire_unload) override;
void SetContentsBounds(content::WebContents* source,
const gfx::Rect& pos) override;
void CloseContents(content::WebContents* source) override;
void ActivateContents(content::WebContents* contents) override;
void UpdateTargetURL(content::WebContents* source, const GURL& url) override;
bool HandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) override;
content::KeyboardEventProcessingResult PreHandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) override;
void ContentsZoomChange(bool zoom_in) override;
void EnterFullscreenModeForTab(
content::WebContents* source,
const GURL& origin,
const blink::WebFullscreenOptions& options) override;
void ExitFullscreenModeForTab(content::WebContents* source) override;
void RendererUnresponsive(
content::WebContents* source,
content::RenderWidgetHost* render_widget_host,
base::RepeatingClosure hang_monitor_restarter) override;
void RendererResponsive(
content::WebContents* source,
content::RenderWidgetHost* render_widget_host) override;
bool HandleContextMenu(content::RenderFrameHost* render_frame_host,
const content::ContextMenuParams& params) override;
bool OnGoToEntryOffset(int offset) override;
void FindReply(content::WebContents* web_contents,
int request_id,
int number_of_matches,
const gfx::Rect& selection_rect,
int active_match_ordinal,
bool final_update) override;
bool CheckMediaAccessPermission(content::RenderFrameHost* render_frame_host,
const GURL& security_origin,
blink::MediaStreamType type) override;
void RequestMediaAccessPermission(
content::WebContents* web_contents,
const content::MediaStreamRequest& request,
content::MediaResponseCallback callback) override;
void RequestToLockMouse(content::WebContents* web_contents,
bool user_gesture,
bool last_unlocked_by_target) override;
std::unique_ptr<content::BluetoothChooser> RunBluetoothChooser(
content::RenderFrameHost* frame,
const content::BluetoothChooser::EventHandler& handler) override;
content::JavaScriptDialogManager* GetJavaScriptDialogManager(
content::WebContents* source) override;
void OnAudioStateChanged(bool audible) override;
// content::WebContentsObserver:
void BeforeUnloadFired(bool proceed,
const base::TimeTicks& proceed_time) override;
void RenderViewCreated(content::RenderViewHost*) override;
void RenderViewHostChanged(content::RenderViewHost* old_host,
content::RenderViewHost* new_host) override;
void RenderViewDeleted(content::RenderViewHost*) override;
void RenderProcessGone(base::TerminationStatus status) override;
void RenderFrameDeleted(content::RenderFrameHost* render_frame_host) override;
void DocumentLoadedInFrame(
content::RenderFrameHost* render_frame_host) override;
void DidFinishLoad(content::RenderFrameHost* render_frame_host,
const GURL& validated_url) override;
void DidFailLoad(content::RenderFrameHost* render_frame_host,
const GURL& validated_url,
int error_code,
const base::string16& error_description) override;
void DidStartLoading() override;
void DidStopLoading() override;
void DidStartNavigation(
content::NavigationHandle* navigation_handle) override;
void DidRedirectNavigation(
content::NavigationHandle* navigation_handle) override;
void DidFinishNavigation(
content::NavigationHandle* navigation_handle) override;
bool OnMessageReceived(const IPC::Message& message) override;
void WebContentsDestroyed() override;
void NavigationEntryCommitted(
const content::LoadCommittedDetails& load_details) override;
void TitleWasSet(content::NavigationEntry* entry) override;
void DidUpdateFaviconURL(
const std::vector<content::FaviconURL>& urls) override;
void PluginCrashed(const base::FilePath& plugin_path,
base::ProcessId plugin_pid) override;
void MediaStartedPlaying(const MediaPlayerInfo& video_type,
const content::MediaPlayerId& id) override;
void MediaStoppedPlaying(
const MediaPlayerInfo& video_type,
const content::MediaPlayerId& id,
content::WebContentsObserver::MediaStoppedReason reason) override;
void DidChangeThemeColor(base::Optional<SkColor> theme_color) override;
void OnInterfaceRequestFromFrame(
content::RenderFrameHost* render_frame_host,
const std::string& interface_name,
mojo::ScopedMessagePipeHandle* interface_pipe) override;
void DidAcquireFullscreen(content::RenderFrameHost* rfh) override;
// InspectableWebContentsDelegate:
void DevToolsReloadPage() override;
// InspectableWebContentsViewDelegate:
void DevToolsFocused() override;
void DevToolsOpened() override;
void DevToolsClosed() override;
#if defined(TOOLKIT_VIEWS)
void ShowAutofillPopup(content::RenderFrameHost* frame_host,
const gfx::RectF& bounds,
const std::vector<base::string16>& values,
const std::vector<base::string16>& labels);
#endif
private:
AtomBrowserContext* GetBrowserContext() const;
// Binds the given request for the ElectronBrowser API. When the
// RenderFrameHost is destroyed, all related bindings will be removed.
void BindElectronBrowser(mojom::ElectronBrowserRequest request,
content::RenderFrameHost* render_frame_host);
void OnElectronBrowserConnectionError();
uint32_t GetNextRequestId() { return ++request_id_; }
#if BUILDFLAG(ENABLE_OSR)
OffScreenWebContentsView* GetOffScreenWebContentsView() const override;
OffScreenRenderWidgetHostView* GetOffScreenRenderWidgetHostView() const;
#endif
// mojom::ElectronBrowser
void Message(bool internal,
const std::string& channel,
base::Value arguments) override;
void Invoke(const std::string& channel,
base::Value arguments,
InvokeCallback callback) override;
void MessageSync(bool internal,
const std::string& channel,
base::Value arguments,
MessageSyncCallback callback) override;
void MessageTo(bool internal,
bool send_to_all,
int32_t web_contents_id,
const std::string& channel,
base::Value arguments) override;
void MessageHost(const std::string& channel, base::Value arguments) override;
void UpdateDraggableRegions(
std::vector<mojom::DraggableRegionPtr> regions) override;
void SetTemporaryZoomLevel(double level) override;
void DoGetZoomLevel(DoGetZoomLevelCallback callback) override;
void ShowAutofillPopup(const gfx::RectF& bounds,
const std::vector<base::string16>& values,
const std::vector<base::string16>& labels) override;
void HideAutofillPopup() override;
// Called when we receive a CursorChange message from chromium.
void OnCursorChange(const content::WebCursor& cursor);
// Called when received a synchronous message from renderer to
// get the zoom level.
void OnGetZoomLevel(content::RenderFrameHost* frame_host,
IPC::Message* reply_msg);
void InitZoomController(content::WebContents* web_contents,
const mate::Dictionary& options);
v8::Global<v8::Value> session_;
v8::Global<v8::Value> devtools_web_contents_;
v8::Global<v8::Value> debugger_;
std::unique_ptr<AtomJavaScriptDialogManager> dialog_manager_;
std::unique_ptr<WebViewGuestDelegate> guest_delegate_;
std::unique_ptr<FrameSubscriber> frame_subscriber_;
// The host webcontents that may contain this webcontents.
WebContents* embedder_ = nullptr;
// The zoom controller for this webContents.
WebContentsZoomController* zoom_controller_ = nullptr;
// The type of current WebContents.
Type type_ = Type::BROWSER_WINDOW;
// Request id used for findInPage request.
uint32_t request_id_ = 0;
// Whether background throttling is disabled.
bool background_throttling_ = true;
// Whether to enable devtools.
bool enable_devtools_ = true;
// Observers of this WebContents.
base::ObserverList<ExtendedWebContentsObserver> observers_;
// The ID of the process of the currently committed RenderViewHost.
// -1 means no speculative RVH has been committed yet.
int currently_committed_process_id_ = -1;
service_manager::BinderRegistryWithArgs<content::RenderFrameHost*> registry_;
mojo::BindingSet<mojom::ElectronBrowser, content::RenderFrameHost*> bindings_;
std::map<content::RenderFrameHost*, std::vector<mojo::BindingId>>
frame_to_bindings_map_;
base::WeakPtrFactory<WebContents> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(WebContents);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_WEB_CONTENTS_H_

View file

@ -0,0 +1,62 @@
// 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/browser/api/atom_api_web_contents.h"
#include "content/browser/frame_host/frame_tree.h" // nogncheck
#include "content/browser/frame_host/frame_tree_node.h" // nogncheck
#include "content/browser/web_contents/web_contents_impl.h" // nogncheck
#include "content/public/browser/guest_mode.h"
#if BUILDFLAG(ENABLE_OSR)
#include "atom/browser/osr/osr_render_widget_host_view.h"
#include "atom/browser/osr/osr_web_contents_view.h"
#endif
// Including both web_contents_impl.h and node.h would introduce a error, we
// have to isolate the usage of WebContentsImpl into a clean file to fix it:
// error C2371: 'ssize_t': redefinition; different basic types
namespace atom {
namespace api {
void WebContents::DetachFromOuterFrame() {
// See detach_webview_frame.patch on how to detach.
DCHECK(content::GuestMode::IsCrossProcessFrameGuest(web_contents()));
int frame_tree_node_id =
static_cast<content::WebContentsImpl*>(web_contents())
->GetOuterDelegateFrameTreeNodeId();
if (frame_tree_node_id != content::FrameTreeNode::kFrameTreeNodeInvalidId) {
auto* node = content::FrameTreeNode::GloballyFindByID(frame_tree_node_id);
DCHECK(node->parent());
node->frame_tree()->RemoveFrame(node);
}
}
#if BUILDFLAG(ENABLE_OSR)
OffScreenWebContentsView* WebContents::GetOffScreenWebContentsView() const {
if (IsOffScreen()) {
const auto* impl =
static_cast<const content::WebContentsImpl*>(web_contents());
return static_cast<OffScreenWebContentsView*>(impl->GetView());
} else {
return nullptr;
}
}
OffScreenRenderWidgetHostView* WebContents::GetOffScreenRenderWidgetHostView()
const {
if (IsOffScreen()) {
return static_cast<OffScreenRenderWidgetHostView*>(
web_contents()->GetRenderWidgetHostView());
} else {
return nullptr;
}
}
#endif
} // namespace api
} // namespace atom

View file

@ -0,0 +1,32 @@
// 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/browser/api/atom_api_web_contents.h"
#include "content/public/browser/render_widget_host_view.h"
#import <Cocoa/Cocoa.h>
namespace atom {
namespace api {
bool WebContents::IsFocused() const {
auto* view = web_contents()->GetRenderWidgetHostView();
if (!view)
return false;
if (GetType() != Type::BACKGROUND_PAGE) {
auto window = [web_contents()->GetNativeView().GetNativeNSView() window];
// On Mac the render widget host view does not lose focus when the window
// loses focus so check if the top level window is the key window.
if (window && ![window isKeyWindow])
return false;
}
return view->HasFocus();
}
} // namespace api
} // namespace atom

View file

@ -0,0 +1,134 @@
// 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/browser/api/atom_api_web_contents_view.h"
#include "atom/browser/api/atom_api_web_contents.h"
#include "atom/browser/browser.h"
#include "atom/browser/ui/inspectable_web_contents_view.h"
#include "atom/common/api/constructor.h"
#include "atom/common/node_includes.h"
#include "content/public/browser/web_contents_user_data.h"
#include "native_mate/dictionary.h"
#if defined(OS_MACOSX)
#include "atom/browser/ui/cocoa/delayed_native_view_host.h"
#endif
namespace {
// Used to indicate whether a WebContents already has a view.
class WebContentsViewRelay
: public content::WebContentsUserData<WebContentsViewRelay> {
public:
~WebContentsViewRelay() override {}
private:
explicit WebContentsViewRelay(content::WebContents* contents) {}
friend class content::WebContentsUserData<WebContentsViewRelay>;
atom::api::WebContentsView* view_ = nullptr;
WEB_CONTENTS_USER_DATA_KEY_DECL();
DISALLOW_COPY_AND_ASSIGN(WebContentsViewRelay);
};
WEB_CONTENTS_USER_DATA_KEY_IMPL(WebContentsViewRelay)
} // namespace
namespace atom {
namespace api {
WebContentsView::WebContentsView(v8::Isolate* isolate,
mate::Handle<WebContents> web_contents,
InspectableWebContents* iwc)
#if defined(OS_MACOSX)
: View(new DelayedNativeViewHost(iwc->GetView()->GetNativeView())),
#else
: View(iwc->GetView()->GetView()),
#endif
web_contents_(isolate, web_contents->GetWrapper()),
api_web_contents_(web_contents.get()) {
#if defined(OS_MACOSX)
// On macOS a View is created to wrap the NSView, and its lifetime is managed
// by us.
view()->set_owned_by_client();
#else
// On other platforms the View is managed by InspectableWebContents.
set_delete_view(false);
#endif
WebContentsViewRelay::CreateForWebContents(web_contents->web_contents());
Observe(web_contents->web_contents());
}
WebContentsView::~WebContentsView() {
if (api_web_contents_) { // destroy() is called
// Destroy WebContents asynchronously unless app is shutting down,
// because destroy() might be called inside WebContents's event handler.
api_web_contents_->DestroyWebContents(!Browser::Get()->is_shutting_down());
}
}
void WebContentsView::WebContentsDestroyed() {
api_web_contents_ = nullptr;
web_contents_.Reset();
}
// static
mate::WrappableBase* WebContentsView::New(
mate::Arguments* args,
mate::Handle<WebContents> web_contents) {
// Currently we only support InspectableWebContents, e.g. the WebContents
// created by users directly. To support devToolsWebContents we need to create
// a wrapper view.
if (!web_contents->managed_web_contents()) {
const char* error = "The WebContents must be created by user";
args->isolate()->ThrowException(
v8::Exception::Error(mate::StringToV8(args->isolate(), error)));
return nullptr;
}
// Check if the WebContents has already been added to a view.
if (WebContentsViewRelay::FromWebContents(web_contents->web_contents())) {
const char* error = "The WebContents has already been added to a View";
args->isolate()->ThrowException(
v8::Exception::Error(mate::StringToV8(args->isolate(), error)));
return nullptr;
}
// Constructor call.
auto* view = new WebContentsView(args->isolate(), web_contents,
web_contents->managed_web_contents());
view->InitWith(args->isolate(), args->GetThis());
return view;
}
// static
void WebContentsView::BuildPrototype(
v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {}
} // namespace api
} // namespace atom
namespace {
using atom::api::WebContentsView;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
mate::Dictionary dict(isolate, exports);
dict.Set("WebContentsView",
mate::CreateConstructor<WebContentsView>(
isolate, base::BindRepeating(&WebContentsView::New)));
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_browser_web_contents_view, Initialize)

View file

@ -0,0 +1,49 @@
// 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_BROWSER_API_ATOM_API_WEB_CONTENTS_VIEW_H_
#define ATOM_BROWSER_API_ATOM_API_WEB_CONTENTS_VIEW_H_
#include "atom/browser/api/atom_api_view.h"
#include "content/public/browser/web_contents_observer.h"
#include "native_mate/handle.h"
namespace atom {
class InspectableWebContents;
namespace api {
class WebContents;
class WebContentsView : public View, public content::WebContentsObserver {
public:
static mate::WrappableBase* New(mate::Arguments* args,
mate::Handle<WebContents> web_contents);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
protected:
WebContentsView(v8::Isolate* isolate,
mate::Handle<WebContents> web_contents,
InspectableWebContents* iwc);
~WebContentsView() override;
// content::WebContentsObserver:
void WebContentsDestroyed() override;
private:
// Keep a reference to v8 wrapper.
v8::Global<v8::Value> web_contents_;
api::WebContents* api_web_contents_;
DISALLOW_COPY_AND_ASSIGN(WebContentsView);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_WEB_CONTENTS_VIEW_H_

View file

@ -0,0 +1,147 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/api/atom_api_web_request.h"
#include <string>
#include <utility>
#include "atom/browser/atom_browser_context.h"
#include "atom/browser/net/atom_network_delegate.h"
#include "atom/common/native_mate_converters/net_converter.h"
#include "atom/common/native_mate_converters/once_callback.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "base/task/post_task.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "native_mate/dictionary.h"
#include "native_mate/object_template_builder.h"
using content::BrowserThread;
namespace mate {
template <>
struct Converter<URLPattern> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
URLPattern* out) {
std::string pattern;
if (!ConvertFromV8(isolate, val, &pattern))
return false;
*out = URLPattern(URLPattern::SCHEME_ALL);
return out->Parse(pattern) == URLPattern::ParseResult::kSuccess;
}
};
} // namespace mate
namespace atom {
namespace api {
namespace {
template <typename Method, typename Event, typename Listener>
void CallNetworkDelegateMethod(
URLRequestContextGetter* url_request_context_getter,
Method method,
Event type,
URLPatterns patterns,
Listener listener) {
// Force creating network delegate.
url_request_context_getter->GetURLRequestContext();
// Then call the method.
auto* network_delegate = url_request_context_getter->network_delegate();
(network_delegate->*method)(type, std::move(patterns), std::move(listener));
}
} // namespace
WebRequest::WebRequest(v8::Isolate* isolate,
AtomBrowserContext* browser_context)
: browser_context_(browser_context) {
Init(isolate);
}
WebRequest::~WebRequest() {}
template <AtomNetworkDelegate::SimpleEvent type>
void WebRequest::SetSimpleListener(mate::Arguments* args) {
SetListener<AtomNetworkDelegate::SimpleListener>(
&AtomNetworkDelegate::SetSimpleListenerInIO, type, args);
}
template <AtomNetworkDelegate::ResponseEvent type>
void WebRequest::SetResponseListener(mate::Arguments* args) {
SetListener<AtomNetworkDelegate::ResponseListener>(
&AtomNetworkDelegate::SetResponseListenerInIO, type, args);
}
template <typename Listener, typename Method, typename Event>
void WebRequest::SetListener(Method method, Event type, mate::Arguments* args) {
// { urls }.
URLPatterns patterns;
mate::Dictionary dict;
args->GetNext(&dict) && dict.Get("urls", &patterns);
// Function or null.
v8::Local<v8::Value> value;
Listener listener;
if (!args->GetNext(&listener) &&
!(args->GetNext(&value) && value->IsNull())) {
args->ThrowError("Must pass null or a Function");
return;
}
auto* url_request_context_getter = static_cast<URLRequestContextGetter*>(
browser_context_->GetRequestContext());
if (!url_request_context_getter)
return;
base::PostTaskWithTraits(
FROM_HERE, {BrowserThread::IO},
base::BindOnce(&CallNetworkDelegateMethod<Method, Event, Listener>,
base::RetainedRef(url_request_context_getter), method,
type, std::move(patterns), std::move(listener)));
}
// static
mate::Handle<WebRequest> WebRequest::Create(
v8::Isolate* isolate,
AtomBrowserContext* browser_context) {
return mate::CreateHandle(isolate, new WebRequest(isolate, browser_context));
}
// static
void WebRequest::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "WebRequest"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.SetMethod("onBeforeRequest", &WebRequest::SetResponseListener<
AtomNetworkDelegate::kOnBeforeRequest>)
.SetMethod("onBeforeSendHeaders",
&WebRequest::SetResponseListener<
AtomNetworkDelegate::kOnBeforeSendHeaders>)
.SetMethod("onHeadersReceived",
&WebRequest::SetResponseListener<
AtomNetworkDelegate::kOnHeadersReceived>)
.SetMethod(
"onSendHeaders",
&WebRequest::SetSimpleListener<AtomNetworkDelegate::kOnSendHeaders>)
.SetMethod("onBeforeRedirect",
&WebRequest::SetSimpleListener<
AtomNetworkDelegate::kOnBeforeRedirect>)
.SetMethod("onResponseStarted",
&WebRequest::SetSimpleListener<
AtomNetworkDelegate::kOnResponseStarted>)
.SetMethod(
"onCompleted",
&WebRequest::SetSimpleListener<AtomNetworkDelegate::kOnCompleted>)
.SetMethod("onErrorOccurred", &WebRequest::SetSimpleListener<
AtomNetworkDelegate::kOnErrorOccurred>);
}
} // namespace api
} // namespace atom

View file

@ -0,0 +1,49 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_BROWSER_API_ATOM_API_WEB_REQUEST_H_
#define ATOM_BROWSER_API_ATOM_API_WEB_REQUEST_H_
#include "atom/browser/api/trackable_object.h"
#include "atom/browser/net/atom_network_delegate.h"
#include "native_mate/arguments.h"
#include "native_mate/handle.h"
namespace atom {
class AtomBrowserContext;
namespace api {
class WebRequest : public mate::TrackableObject<WebRequest> {
public:
static mate::Handle<WebRequest> Create(v8::Isolate* isolate,
AtomBrowserContext* browser_context);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
protected:
WebRequest(v8::Isolate* isolate, AtomBrowserContext* browser_context);
~WebRequest() override;
// C++ can not distinguish overloaded member function.
template <AtomNetworkDelegate::SimpleEvent type>
void SetSimpleListener(mate::Arguments* args);
template <AtomNetworkDelegate::ResponseEvent type>
void SetResponseListener(mate::Arguments* args);
template <typename Listener, typename Method, typename Event>
void SetListener(Method method, Event type, mate::Arguments* args);
private:
scoped_refptr<AtomBrowserContext> browser_context_;
DISALLOW_COPY_AND_ASSIGN(WebRequest);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_WEB_REQUEST_H_

View file

@ -0,0 +1,55 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/web_contents_preferences.h"
#include "atom/browser/web_contents_zoom_controller.h"
#include "atom/browser/web_view_manager.h"
#include "atom/common/native_mate_converters/content_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/node_includes.h"
#include "atom/common/options_switches.h"
#include "content/public/browser/browser_context.h"
#include "native_mate/dictionary.h"
using atom::WebContentsPreferences;
namespace {
void AddGuest(int guest_instance_id,
int element_instance_id,
content::WebContents* embedder,
content::WebContents* guest_web_contents,
const base::DictionaryValue& options) {
auto* manager = atom::WebViewManager::GetWebViewManager(embedder);
if (manager)
manager->AddGuest(guest_instance_id, element_instance_id, embedder,
guest_web_contents);
double zoom_factor;
if (options.GetDouble(atom::options::kZoomFactor, &zoom_factor)) {
atom::WebContentsZoomController::FromWebContents(guest_web_contents)
->SetDefaultZoomFactor(zoom_factor);
}
WebContentsPreferences::From(guest_web_contents)->Merge(options);
}
void RemoveGuest(content::WebContents* embedder, int guest_instance_id) {
auto* manager = atom::WebViewManager::GetWebViewManager(embedder);
if (manager)
manager->RemoveGuest(guest_instance_id);
}
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.SetMethod("addGuest", &AddGuest);
dict.SetMethod("removeGuest", &RemoveGuest);
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_browser_web_view_manager, Initialize)

View file

@ -0,0 +1,83 @@
// 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/browser/api/event.h"
#include <utility>
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "native_mate/object_template_builder.h"
namespace mate {
Event::Event(v8::Isolate* isolate) {
Init(isolate);
}
Event::~Event() {}
void Event::SetSenderAndMessage(content::RenderFrameHost* sender,
base::Optional<MessageSyncCallback> callback) {
DCHECK(!sender_);
DCHECK(!callback_);
sender_ = sender;
callback_ = std::move(callback);
Observe(content::WebContents::FromRenderFrameHost(sender));
}
void Event::RenderFrameDeleted(content::RenderFrameHost* rfh) {
if (sender_ != rfh)
return;
sender_ = nullptr;
callback_.reset();
}
void Event::RenderFrameHostChanged(content::RenderFrameHost* old_rfh,
content::RenderFrameHost* new_rfh) {
if (sender_ && sender_ == old_rfh)
sender_ = new_rfh;
}
void Event::FrameDeleted(content::RenderFrameHost* rfh) {
if (sender_ != rfh)
return;
sender_ = nullptr;
callback_.reset();
}
void Event::PreventDefault(v8::Isolate* isolate) {
GetWrapper()
->Set(isolate->GetCurrentContext(),
StringToV8(isolate, "defaultPrevented"), v8::True(isolate))
.Check();
}
bool Event::SendReply(const base::Value& result) {
if (!callback_ || sender_ == nullptr)
return false;
std::move(*callback_).Run(result.Clone());
callback_.reset();
return true;
}
// static
Handle<Event> Event::Create(v8::Isolate* isolate) {
return mate::CreateHandle(isolate, new Event(isolate));
}
// static
void Event::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "Event"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.SetMethod("preventDefault", &Event::PreventDefault)
.SetMethod("sendReply", &Event::SendReply);
}
} // namespace mate

59
shell/browser/api/event.h Normal file
View file

@ -0,0 +1,59 @@
// 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_BROWSER_API_EVENT_H_
#define ATOM_BROWSER_API_EVENT_H_
#include "base/optional.h"
#include "content/public/browser/web_contents_observer.h"
#include "electron/atom/common/api/api.mojom.h"
#include "native_mate/handle.h"
#include "native_mate/wrappable.h"
namespace IPC {
class Message;
}
namespace mate {
class Event : public Wrappable<Event>, public content::WebContentsObserver {
public:
using MessageSyncCallback = atom::mojom::ElectronBrowser::MessageSyncCallback;
static Handle<Event> Create(v8::Isolate* isolate);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
// Pass the sender and message to be replied.
void SetSenderAndMessage(content::RenderFrameHost* sender,
base::Optional<MessageSyncCallback> callback);
// event.PreventDefault().
void PreventDefault(v8::Isolate* isolate);
// event.sendReply(value), used for replying to synchronous messages and
// `invoke` calls.
bool SendReply(const base::Value& result);
protected:
explicit Event(v8::Isolate* isolate);
~Event() override;
// content::WebContentsObserver implementations:
void RenderFrameDeleted(content::RenderFrameHost* rfh) override;
void RenderFrameHostChanged(content::RenderFrameHost* old_rfh,
content::RenderFrameHost* new_rfh) override;
void FrameDeleted(content::RenderFrameHost* rfh) override;
private:
// Replyer for the synchronous messages.
content::RenderFrameHost* sender_ = nullptr;
base::Optional<MessageSyncCallback> callback_;
DISALLOW_COPY_AND_ASSIGN(Event);
};
} // namespace mate
#endif // ATOM_BROWSER_API_EVENT_H_

View file

@ -0,0 +1,91 @@
// 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/browser/api/event_emitter.h"
#include <utility>
#include "atom/browser/api/event.h"
#include "atom/common/node_includes.h"
#include "content/public/browser/render_frame_host.h"
#include "native_mate/arguments.h"
#include "native_mate/dictionary.h"
#include "native_mate/object_template_builder.h"
#include "ui/events/event_constants.h"
namespace mate {
namespace {
v8::Persistent<v8::ObjectTemplate> event_template;
void PreventDefault(mate::Arguments* args) {
mate::Dictionary self(args->isolate(), args->GetThis());
self.Set("defaultPrevented", true);
}
// Create a pure JavaScript Event object.
v8::Local<v8::Object> CreateEventObject(v8::Isolate* isolate) {
if (event_template.IsEmpty()) {
event_template.Reset(
isolate,
ObjectTemplateBuilder(isolate, v8::ObjectTemplate::New(isolate))
.SetMethod("preventDefault", &PreventDefault)
.Build());
}
return v8::Local<v8::ObjectTemplate>::New(isolate, event_template)
->NewInstance(isolate->GetCurrentContext())
.ToLocalChecked();
}
} // namespace
namespace internal {
v8::Local<v8::Object> CreateJSEvent(
v8::Isolate* isolate,
v8::Local<v8::Object> object,
content::RenderFrameHost* sender,
base::Optional<atom::mojom::ElectronBrowser::MessageSyncCallback>
callback) {
v8::Local<v8::Object> event;
bool use_native_event = sender && callback;
if (use_native_event) {
mate::Handle<mate::Event> native_event = mate::Event::Create(isolate);
native_event->SetSenderAndMessage(sender, std::move(callback));
event = v8::Local<v8::Object>::Cast(native_event.ToV8());
} else {
event = CreateEventObject(isolate);
}
mate::Dictionary dict(isolate, event);
dict.Set("sender", object);
if (sender)
dict.Set("frameId", sender->GetRoutingID());
return event;
}
v8::Local<v8::Object> CreateCustomEvent(v8::Isolate* isolate,
v8::Local<v8::Object> object,
v8::Local<v8::Object> custom_event) {
v8::Local<v8::Object> event = CreateEventObject(isolate);
(void)event->SetPrototype(custom_event->CreationContext(), custom_event);
mate::Dictionary(isolate, event).Set("sender", object);
return event;
}
v8::Local<v8::Object> CreateEventFromFlags(v8::Isolate* isolate, int flags) {
mate::Dictionary obj = mate::Dictionary::CreateEmpty(isolate);
obj.Set("shiftKey", static_cast<bool>(flags & ui::EF_SHIFT_DOWN));
obj.Set("ctrlKey", static_cast<bool>(flags & ui::EF_CONTROL_DOWN));
obj.Set("altKey", static_cast<bool>(flags & ui::EF_ALT_DOWN));
obj.Set("metaKey", static_cast<bool>(flags & ui::EF_COMMAND_DOWN));
obj.Set("triggeredByAccelerator", static_cast<bool>(flags));
return obj.GetHandle();
}
} // namespace internal
} // namespace mate

View file

@ -0,0 +1,125 @@
// 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_BROWSER_API_EVENT_EMITTER_H_
#define ATOM_BROWSER_API_EVENT_EMITTER_H_
#include <utility>
#include <vector>
#include "atom/common/api/event_emitter_caller.h"
#include "base/optional.h"
#include "content/public/browser/browser_thread.h"
#include "electron/atom/common/api/api.mojom.h"
#include "native_mate/wrappable.h"
namespace content {
class RenderFrameHost;
}
namespace mate {
namespace internal {
v8::Local<v8::Object> CreateJSEvent(
v8::Isolate* isolate,
v8::Local<v8::Object> object,
content::RenderFrameHost* sender,
base::Optional<atom::mojom::ElectronBrowser::MessageSyncCallback> callback);
v8::Local<v8::Object> CreateCustomEvent(v8::Isolate* isolate,
v8::Local<v8::Object> object,
v8::Local<v8::Object> event);
v8::Local<v8::Object> CreateEventFromFlags(v8::Isolate* isolate, int flags);
} // namespace internal
// Provide helperers to emit event in JavaScript.
template <typename T>
class EventEmitter : public Wrappable<T> {
public:
typedef std::vector<v8::Local<v8::Value>> ValueArray;
// Make the convinient methods visible:
// https://isocpp.org/wiki/faq/templates#nondependent-name-lookup-members
v8::Isolate* isolate() const { return Wrappable<T>::isolate(); }
v8::Local<v8::Object> GetWrapper() const {
return Wrappable<T>::GetWrapper();
}
v8::MaybeLocal<v8::Object> GetWrapper(v8::Isolate* isolate) const {
return Wrappable<T>::GetWrapper(isolate);
}
// this.emit(name, event, args...);
template <typename... Args>
bool EmitCustomEvent(const base::StringPiece& name,
v8::Local<v8::Object> event,
Args&&... args) {
return EmitWithEvent(
name, internal::CreateCustomEvent(isolate(), GetWrapper(), event),
std::forward<Args>(args)...);
}
// this.emit(name, new Event(flags), args...);
template <typename... Args>
bool EmitWithFlags(const base::StringPiece& name, int flags, Args&&... args) {
return EmitCustomEvent(name,
internal::CreateEventFromFlags(isolate(), flags),
std::forward<Args>(args)...);
}
// this.emit(name, new Event(), args...);
template <typename... Args>
bool Emit(const base::StringPiece& name, Args&&... args) {
return EmitWithSender(name, nullptr, base::nullopt,
std::forward<Args>(args)...);
}
// this.emit(name, new Event(sender, message), args...);
template <typename... Args>
bool EmitWithSender(
const base::StringPiece& name,
content::RenderFrameHost* sender,
base::Optional<atom::mojom::ElectronBrowser::MessageSyncCallback>
callback,
Args&&... args) {
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
v8::Local<v8::Object> wrapper = GetWrapper();
if (wrapper.IsEmpty()) {
return false;
}
v8::Local<v8::Object> event = internal::CreateJSEvent(
isolate(), wrapper, sender, std::move(callback));
return EmitWithEvent(name, event, std::forward<Args>(args)...);
}
protected:
EventEmitter() {}
private:
// this.emit(name, event, args...);
template <typename... Args>
bool EmitWithEvent(const base::StringPiece& name,
v8::Local<v8::Object> event,
Args&&... args) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
EmitEvent(isolate(), GetWrapper(), name, event,
std::forward<Args>(args)...);
auto context = isolate()->GetCurrentContext();
v8::Local<v8::Value> defaultPrevented;
if (event->Get(context, StringToV8(isolate(), "defaultPrevented"))
.ToLocal(&defaultPrevented)) {
return defaultPrevented->BooleanValue(isolate());
}
return false;
}
DISALLOW_COPY_AND_ASSIGN(EventEmitter);
};
} // namespace mate
#endif // ATOM_BROWSER_API_EVENT_EMITTER_H_

View file

@ -0,0 +1,177 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/api/frame_subscriber.h"
#include <utility>
#include "atom/common/native_mate_converters/gfx_converter.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "media/capture/mojom/video_capture_types.mojom.h"
#include "ui/gfx/geometry/size_conversions.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/skbitmap_operations.h"
namespace atom {
namespace api {
constexpr static int kMaxFrameRate = 30;
FrameSubscriber::FrameSubscriber(content::WebContents* web_contents,
const FrameCaptureCallback& callback,
bool only_dirty)
: content::WebContentsObserver(web_contents),
callback_(callback),
only_dirty_(only_dirty),
weak_ptr_factory_(this) {
content::RenderViewHost* rvh = web_contents->GetRenderViewHost();
if (rvh)
AttachToHost(rvh->GetWidget());
}
FrameSubscriber::~FrameSubscriber() = default;
void FrameSubscriber::AttachToHost(content::RenderWidgetHost* host) {
host_ = host;
// The view can be null if the renderer process has crashed.
// (https://crbug.com/847363)
if (!host_->GetView())
return;
// Create and configure the video capturer.
gfx::Size size = GetRenderViewSize();
video_capturer_ = host_->GetView()->CreateVideoCapturer();
video_capturer_->SetResolutionConstraints(size, size, true);
video_capturer_->SetAutoThrottlingEnabled(false);
video_capturer_->SetMinSizeChangePeriod(base::TimeDelta());
video_capturer_->SetFormat(media::PIXEL_FORMAT_ARGB,
gfx::ColorSpace::CreateREC709());
video_capturer_->SetMinCapturePeriod(base::TimeDelta::FromSeconds(1) /
kMaxFrameRate);
video_capturer_->Start(this);
}
void FrameSubscriber::DetachFromHost() {
if (!host_)
return;
video_capturer_.reset();
host_ = nullptr;
}
void FrameSubscriber::RenderViewCreated(content::RenderViewHost* host) {
if (!host_)
AttachToHost(host->GetWidget());
}
void FrameSubscriber::RenderViewDeleted(content::RenderViewHost* host) {
if (host->GetWidget() == host_) {
DetachFromHost();
}
}
void FrameSubscriber::RenderViewHostChanged(content::RenderViewHost* old_host,
content::RenderViewHost* new_host) {
if ((old_host && old_host->GetWidget() == host_) || (!old_host && !host_)) {
DetachFromHost();
AttachToHost(new_host->GetWidget());
}
}
void FrameSubscriber::OnFrameCaptured(
base::ReadOnlySharedMemoryRegion data,
::media::mojom::VideoFrameInfoPtr info,
const gfx::Rect& content_rect,
viz::mojom::FrameSinkVideoConsumerFrameCallbacksPtr callbacks) {
gfx::Size size = GetRenderViewSize();
if (size != content_rect.size()) {
video_capturer_->SetResolutionConstraints(size, size, true);
video_capturer_->RequestRefreshFrame();
return;
}
if (!data.IsValid()) {
callbacks->Done();
return;
}
base::ReadOnlySharedMemoryMapping mapping = data.Map();
if (!mapping.IsValid()) {
DLOG(ERROR) << "Shared memory mapping failed.";
return;
}
if (mapping.size() <
media::VideoFrame::AllocationSize(info->pixel_format, info->coded_size)) {
DLOG(ERROR) << "Shared memory size was less than expected.";
return;
}
// The SkBitmap's pixels will be marked as immutable, but the installPixels()
// API requires a non-const pointer. So, cast away the const.
void* const pixels = const_cast<void*>(mapping.memory());
// Call installPixels() with a |releaseProc| that: 1) notifies the capturer
// that this consumer has finished with the frame, and 2) releases the shared
// memory mapping.
struct FramePinner {
// Keeps the shared memory that backs |frame_| mapped.
base::ReadOnlySharedMemoryMapping mapping;
// Prevents FrameSinkVideoCapturer from recycling the shared memory that
// backs |frame_|.
viz::mojom::FrameSinkVideoConsumerFrameCallbacksPtr releaser;
};
SkBitmap bitmap;
bitmap.installPixels(
SkImageInfo::MakeN32(content_rect.width(), content_rect.height(),
kPremul_SkAlphaType),
pixels,
media::VideoFrame::RowBytes(media::VideoFrame::kARGBPlane,
info->pixel_format, info->coded_size.width()),
[](void* addr, void* context) {
delete static_cast<FramePinner*>(context);
},
new FramePinner{std::move(mapping), std::move(callbacks)});
bitmap.setImmutable();
Done(content_rect, bitmap);
}
void FrameSubscriber::OnStopped() {}
void FrameSubscriber::Done(const gfx::Rect& damage, const SkBitmap& frame) {
if (frame.drawsNothing())
return;
const SkBitmap& bitmap = only_dirty_ ? SkBitmapOperations::CreateTiledBitmap(
frame, damage.x(), damage.y(),
damage.width(), damage.height())
: frame;
// Copying SkBitmap does not copy the internal pixels, we have to manually
// allocate and write pixels otherwise crash may happen when the original
// frame is modified.
SkBitmap copy;
copy.allocPixels(SkImageInfo::Make(bitmap.width(), bitmap.height(),
kRGBA_8888_SkColorType,
kPremul_SkAlphaType));
SkPixmap pixmap;
bool success = bitmap.peekPixels(&pixmap) && copy.writePixels(pixmap, 0, 0);
CHECK(success);
callback_.Run(gfx::Image::CreateFrom1xBitmap(copy), damage);
}
gfx::Size FrameSubscriber::GetRenderViewSize() const {
content::RenderWidgetHostView* view = host_->GetView();
gfx::Size size = view->GetViewBounds().size();
return gfx::ToRoundedSize(
gfx::ScaleSize(gfx::SizeF(size), view->GetDeviceScaleFactor()));
}
} // namespace api
} // namespace atom

View file

@ -0,0 +1,75 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_BROWSER_API_FRAME_SUBSCRIBER_H_
#define ATOM_BROWSER_API_FRAME_SUBSCRIBER_H_
#include <memory>
#include "base/callback.h"
#include "base/memory/weak_ptr.h"
#include "components/viz/host/client_frame_sink_video_capturer.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
#include "v8/include/v8.h"
namespace gfx {
class Image;
}
namespace atom {
namespace api {
class WebContents;
class FrameSubscriber : public content::WebContentsObserver,
public viz::mojom::FrameSinkVideoConsumer {
public:
using FrameCaptureCallback =
base::RepeatingCallback<void(const gfx::Image&, const gfx::Rect&)>;
FrameSubscriber(content::WebContents* web_contents,
const FrameCaptureCallback& callback,
bool only_dirty);
~FrameSubscriber() override;
private:
void AttachToHost(content::RenderWidgetHost* host);
void DetachFromHost();
void RenderViewCreated(content::RenderViewHost* host) override;
void RenderViewDeleted(content::RenderViewHost* host) override;
void RenderViewHostChanged(content::RenderViewHost* old_host,
content::RenderViewHost* new_host) override;
// viz::mojom::FrameSinkVideoConsumer implementation.
void OnFrameCaptured(
base::ReadOnlySharedMemoryRegion data,
::media::mojom::VideoFrameInfoPtr info,
const gfx::Rect& content_rect,
viz::mojom::FrameSinkVideoConsumerFrameCallbacksPtr callbacks) override;
void OnStopped() override;
void Done(const gfx::Rect& damage, const SkBitmap& frame);
// Get the pixel size of render view.
gfx::Size GetRenderViewSize() const;
FrameCaptureCallback callback_;
bool only_dirty_;
content::RenderWidgetHost* host_;
std::unique_ptr<viz::ClientFrameSinkVideoCapturer> video_capturer_;
base::WeakPtrFactory<FrameSubscriber> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(FrameSubscriber);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_FRAME_SUBSCRIBER_H_

View file

@ -0,0 +1,127 @@
// 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/browser/api/gpu_info_enumerator.h"
#include <utility>
namespace atom {
GPUInfoEnumerator::GPUInfoEnumerator()
: value_stack(), current(std::make_unique<base::DictionaryValue>()) {}
GPUInfoEnumerator::~GPUInfoEnumerator() {}
void GPUInfoEnumerator::AddInt64(const char* name, int64_t value) {
current->SetInteger(name, value);
}
void GPUInfoEnumerator::AddInt(const char* name, int value) {
current->SetInteger(name, value);
}
void GPUInfoEnumerator::AddString(const char* name, const std::string& value) {
if (!value.empty())
current->SetString(name, value);
}
void GPUInfoEnumerator::AddBool(const char* name, bool value) {
current->SetBoolean(name, value);
}
void GPUInfoEnumerator::AddTimeDeltaInSecondsF(const char* name,
const base::TimeDelta& value) {
current->SetInteger(name, value.InMilliseconds());
}
void GPUInfoEnumerator::BeginGPUDevice() {
value_stack.push(std::move(current));
current = std::make_unique<base::DictionaryValue>();
}
void GPUInfoEnumerator::EndGPUDevice() {
auto& top_value = value_stack.top();
// GPUDevice can be more than one. So create a list of all.
// The first one is the active GPU device.
if (top_value->HasKey(kGPUDeviceKey)) {
base::ListValue* list;
top_value->GetList(kGPUDeviceKey, &list);
list->Append(std::move(current));
} else {
auto gpus = std::make_unique<base::ListValue>();
gpus->Append(std::move(current));
top_value->SetList(kGPUDeviceKey, std::move(gpus));
}
current = std::move(top_value);
value_stack.pop();
}
void GPUInfoEnumerator::BeginVideoDecodeAcceleratorSupportedProfile() {
value_stack.push(std::move(current));
current = std::make_unique<base::DictionaryValue>();
}
void GPUInfoEnumerator::EndVideoDecodeAcceleratorSupportedProfile() {
auto& top_value = value_stack.top();
top_value->SetDictionary(kVideoDecodeAcceleratorSupportedProfileKey,
std::move(current));
current = std::move(top_value);
value_stack.pop();
}
void GPUInfoEnumerator::BeginVideoEncodeAcceleratorSupportedProfile() {
value_stack.push(std::move(current));
current = std::make_unique<base::DictionaryValue>();
}
void GPUInfoEnumerator::EndVideoEncodeAcceleratorSupportedProfile() {
auto& top_value = value_stack.top();
top_value->SetDictionary(kVideoEncodeAcceleratorSupportedProfileKey,
std::move(current));
current = std::move(top_value);
value_stack.pop();
}
void GPUInfoEnumerator::BeginImageDecodeAcceleratorSupportedProfile() {
value_stack.push(std::move(current));
current = std::make_unique<base::DictionaryValue>();
}
void GPUInfoEnumerator::EndImageDecodeAcceleratorSupportedProfile() {
auto& top_value = value_stack.top();
top_value->SetDictionary(kImageDecodeAcceleratorSupportedProfileKey,
std::move(current));
current = std::move(top_value);
value_stack.pop();
}
void GPUInfoEnumerator::BeginAuxAttributes() {
value_stack.push(std::move(current));
current = std::make_unique<base::DictionaryValue>();
}
void GPUInfoEnumerator::EndAuxAttributes() {
auto& top_value = value_stack.top();
top_value->SetDictionary(kAuxAttributesKey, std::move(current));
current = std::move(top_value);
value_stack.pop();
}
void GPUInfoEnumerator::BeginDx12VulkanVersionInfo() {
value_stack.push(std::move(current));
current = std::make_unique<base::DictionaryValue>();
}
void GPUInfoEnumerator::EndDx12VulkanVersionInfo() {
auto& top_value = value_stack.top();
top_value->SetDictionary(kDx12VulkanVersionInfoKey, std::move(current));
current = std::move(top_value);
value_stack.pop();
}
std::unique_ptr<base::DictionaryValue> GPUInfoEnumerator::GetDictionary() {
return std::move(current);
}
} // namespace atom

View file

@ -0,0 +1,60 @@
// 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_BROWSER_API_GPU_INFO_ENUMERATOR_H_
#define ATOM_BROWSER_API_GPU_INFO_ENUMERATOR_H_
#include <memory>
#include <stack>
#include <string>
#include "base/values.h"
#include "gpu/config/gpu_info.h"
namespace atom {
// This class implements the enumerator for reading all the attributes in
// GPUInfo into a dictionary.
class GPUInfoEnumerator final : public gpu::GPUInfo::Enumerator {
const char* kGPUDeviceKey = "gpuDevice";
const char* kVideoDecodeAcceleratorSupportedProfileKey =
"videoDecodeAcceleratorSupportedProfile";
const char* kVideoEncodeAcceleratorSupportedProfileKey =
"videoEncodeAcceleratorSupportedProfile";
const char* kImageDecodeAcceleratorSupportedProfileKey =
"imageDecodeAcceleratorSupportedProfile";
const char* kAuxAttributesKey = "auxAttributes";
const char* kDx12VulkanVersionInfoKey = "dx12VulkanVersionInfo";
public:
GPUInfoEnumerator();
~GPUInfoEnumerator() override;
void AddInt64(const char* name, int64_t value) override;
void AddInt(const char* name, int value) override;
void AddString(const char* name, const std::string& value) override;
void AddBool(const char* name, bool value) override;
void AddTimeDeltaInSecondsF(const char* name,
const base::TimeDelta& value) override;
void BeginGPUDevice() override;
void EndGPUDevice() override;
void BeginVideoDecodeAcceleratorSupportedProfile() override;
void EndVideoDecodeAcceleratorSupportedProfile() override;
void BeginVideoEncodeAcceleratorSupportedProfile() override;
void EndVideoEncodeAcceleratorSupportedProfile() override;
void BeginImageDecodeAcceleratorSupportedProfile() override;
void EndImageDecodeAcceleratorSupportedProfile() override;
void BeginAuxAttributes() override;
void EndAuxAttributes() override;
void BeginDx12VulkanVersionInfo() override;
void EndDx12VulkanVersionInfo() override;
std::unique_ptr<base::DictionaryValue> GetDictionary();
private:
// The stack is used to manage nested values
std::stack<std::unique_ptr<base::DictionaryValue>> value_stack;
std::unique_ptr<base::DictionaryValue> current;
};
} // namespace atom
#endif // ATOM_BROWSER_API_GPU_INFO_ENUMERATOR_H_

View file

@ -0,0 +1,95 @@
// 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/browser/api/gpuinfo_manager.h"
#include <utility>
#include "atom/browser/api/gpu_info_enumerator.h"
#include "base/memory/singleton.h"
#include "base/threading/thread_task_runner_handle.h"
#include "content/public/browser/browser_thread.h"
#include "gpu/config/gpu_info_collector.h"
namespace atom {
GPUInfoManager* GPUInfoManager::GetInstance() {
return base::Singleton<GPUInfoManager>::get();
}
GPUInfoManager::GPUInfoManager()
: gpu_data_manager_(content::GpuDataManagerImpl::GetInstance()) {
gpu_data_manager_->AddObserver(this);
}
GPUInfoManager::~GPUInfoManager() {
content::GpuDataManagerImpl::GetInstance()->RemoveObserver(this);
}
// Based on
// https://chromium.googlesource.com/chromium/src.git/+/69.0.3497.106/content/browser/gpu/gpu_data_manager_impl_private.cc#838
bool GPUInfoManager::NeedsCompleteGpuInfoCollection() const {
#if defined(OS_MACOSX)
return gpu_data_manager_->GetGPUInfo().gl_vendor.empty();
#elif defined(OS_WIN)
return (gpu_data_manager_->GetGPUInfo().dx_diagnostics.values.empty() &&
gpu_data_manager_->GetGPUInfo().dx_diagnostics.children.empty());
#else
return false;
#endif
}
// Should be posted to the task runner
void GPUInfoManager::ProcessCompleteInfo() {
const auto result = EnumerateGPUInfo(gpu_data_manager_->GetGPUInfo());
// We have received the complete information, resolve all promises that
// were waiting for this info.
for (auto& promise : complete_info_promise_set_) {
promise.Resolve(*result);
}
complete_info_promise_set_.clear();
}
void GPUInfoManager::OnGpuInfoUpdate() {
// Ignore if called when not asked for complete GPUInfo
if (NeedsCompleteGpuInfoCollection())
return;
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(&GPUInfoManager::ProcessCompleteInfo,
base::Unretained(this)));
}
// Should be posted to the task runner
void GPUInfoManager::CompleteInfoFetcher(util::Promise promise) {
complete_info_promise_set_.emplace_back(std::move(promise));
if (NeedsCompleteGpuInfoCollection()) {
gpu_data_manager_->RequestCompleteGpuInfoIfNeeded();
} else {
GPUInfoManager::OnGpuInfoUpdate();
}
}
void GPUInfoManager::FetchCompleteInfo(util::Promise promise) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(&GPUInfoManager::CompleteInfoFetcher,
base::Unretained(this), std::move(promise)));
}
// This fetches the info synchronously, so no need to post to the task queue.
// There cannot be multiple promises as they are resolved synchronously.
void GPUInfoManager::FetchBasicInfo(util::Promise promise) {
gpu::GPUInfo gpu_info;
CollectBasicGraphicsInfo(&gpu_info);
promise.Resolve(*EnumerateGPUInfo(gpu_info));
}
std::unique_ptr<base::DictionaryValue> GPUInfoManager::EnumerateGPUInfo(
gpu::GPUInfo gpu_info) const {
GPUInfoEnumerator enumerator;
gpu_info.EnumerateFields(&enumerator);
return enumerator.GetDictionary();
}
} // namespace atom

View file

@ -0,0 +1,49 @@
// 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_BROWSER_API_GPUINFO_MANAGER_H_
#define ATOM_BROWSER_API_GPUINFO_MANAGER_H_
#include <memory>
#include <unordered_set>
#include <vector>
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/promise_util.h"
#include "content/browser/gpu/gpu_data_manager_impl.h" // nogncheck
#include "content/public/browser/gpu_data_manager.h"
#include "content/public/browser/gpu_data_manager_observer.h"
namespace atom {
// GPUInfoManager is a singleton used to manage and fetch GPUInfo
class GPUInfoManager : public content::GpuDataManagerObserver {
public:
static GPUInfoManager* GetInstance();
GPUInfoManager();
~GPUInfoManager() override;
bool NeedsCompleteGpuInfoCollection() const;
void FetchCompleteInfo(util::Promise promise);
void FetchBasicInfo(util::Promise promise);
void OnGpuInfoUpdate() override;
private:
std::unique_ptr<base::DictionaryValue> EnumerateGPUInfo(
gpu::GPUInfo gpu_info) const;
// These should be posted to the task queue
void CompleteInfoFetcher(util::Promise promise);
void ProcessCompleteInfo();
// This set maintains all the promises that should be fulfilled
// once we have the complete information data
std::vector<util::Promise> complete_info_promise_set_;
content::GpuDataManager* gpu_data_manager_;
DISALLOW_COPY_AND_ASSIGN(GPUInfoManager);
};
} // namespace atom
#endif // ATOM_BROWSER_API_GPUINFO_MANAGER_H_

View file

@ -0,0 +1,109 @@
// Copyright (c) 2019 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/api/process_metric.h"
#include <memory>
#include <utility>
#if defined(OS_WIN)
#include <windows.h>
#endif
#if defined(OS_MACOSX)
extern "C" int sandbox_check(pid_t pid, const char* operation, int type, ...);
#endif
namespace atom {
ProcessMetric::ProcessMetric(int type,
base::ProcessHandle handle,
std::unique_ptr<base::ProcessMetrics> metrics) {
this->type = type;
this->metrics = std::move(metrics);
#if defined(OS_WIN)
HANDLE duplicate_handle = INVALID_HANDLE_VALUE;
::DuplicateHandle(::GetCurrentProcess(), handle, ::GetCurrentProcess(),
&duplicate_handle, 0, false, DUPLICATE_SAME_ACCESS);
this->process = base::Process(duplicate_handle);
#else
this->process = base::Process(handle);
#endif
}
ProcessMetric::~ProcessMetric() = default;
#if defined(OS_WIN)
ProcessIntegrityLevel ProcessMetric::GetIntegrityLevel() const {
HANDLE token = nullptr;
if (!::OpenProcessToken(process.Handle(), TOKEN_QUERY, &token)) {
return ProcessIntegrityLevel::Unknown;
}
base::win::ScopedHandle token_scoped(token);
DWORD token_info_length = 0;
if (::GetTokenInformation(token, TokenIntegrityLevel, nullptr, 0,
&token_info_length) ||
::GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
return ProcessIntegrityLevel::Unknown;
}
auto token_label_bytes = std::make_unique<char[]>(token_info_length);
TOKEN_MANDATORY_LABEL* token_label =
reinterpret_cast<TOKEN_MANDATORY_LABEL*>(token_label_bytes.get());
if (!::GetTokenInformation(token, TokenIntegrityLevel, token_label,
token_info_length, &token_info_length)) {
return ProcessIntegrityLevel::Unknown;
}
DWORD integrity_level = *::GetSidSubAuthority(
token_label->Label.Sid,
static_cast<DWORD>(*::GetSidSubAuthorityCount(token_label->Label.Sid) -
1));
if (integrity_level >= SECURITY_MANDATORY_UNTRUSTED_RID &&
integrity_level < SECURITY_MANDATORY_LOW_RID) {
return ProcessIntegrityLevel::Untrusted;
}
if (integrity_level >= SECURITY_MANDATORY_LOW_RID &&
integrity_level < SECURITY_MANDATORY_MEDIUM_RID) {
return ProcessIntegrityLevel::Low;
}
if (integrity_level >= SECURITY_MANDATORY_MEDIUM_RID &&
integrity_level < SECURITY_MANDATORY_HIGH_RID) {
return ProcessIntegrityLevel::Medium;
}
if (integrity_level >= SECURITY_MANDATORY_HIGH_RID &&
integrity_level < SECURITY_MANDATORY_SYSTEM_RID) {
return ProcessIntegrityLevel::High;
}
return ProcessIntegrityLevel::Unknown;
}
// static
bool ProcessMetric::IsSandboxed(ProcessIntegrityLevel integrity_level) {
return integrity_level > ProcessIntegrityLevel::Unknown &&
integrity_level < ProcessIntegrityLevel::Medium;
}
#elif defined(OS_MACOSX)
bool ProcessMetric::IsSandboxed() const {
#if defined(MAS_BUILD)
return true;
#else
return sandbox_check(process.Pid(), nullptr, 0) != 0;
#endif
}
#endif // defined(OS_MACOSX)
} // namespace atom

View file

@ -0,0 +1,46 @@
// Copyright (c) 2019 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_BROWSER_API_PROCESS_METRIC_H_
#define ATOM_BROWSER_API_PROCESS_METRIC_H_
#include <memory>
#include "base/process/process.h"
#include "base/process/process_handle.h"
#include "base/process/process_metrics.h"
namespace atom {
#if defined(OS_WIN)
enum class ProcessIntegrityLevel {
Unknown,
Untrusted,
Low,
Medium,
High,
};
#endif
struct ProcessMetric {
int type;
base::Process process;
std::unique_ptr<base::ProcessMetrics> metrics;
ProcessMetric(int type,
base::ProcessHandle handle,
std::unique_ptr<base::ProcessMetrics> metrics);
~ProcessMetric();
#if defined(OS_WIN)
ProcessIntegrityLevel GetIntegrityLevel() const;
static bool IsSandboxed(ProcessIntegrityLevel integrity_level);
#elif defined(OS_MACOSX)
bool IsSandboxed() const;
#endif
};
} // namespace atom
#endif // ATOM_BROWSER_API_PROCESS_METRIC_H_

View file

@ -0,0 +1,71 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/api/save_page_handler.h"
#include <string>
#include <utility>
#include "atom/browser/atom_browser_context.h"
#include "base/callback.h"
#include "base/files/file_path.h"
#include "content/public/browser/web_contents.h"
namespace atom {
namespace api {
SavePageHandler::SavePageHandler(content::WebContents* web_contents,
util::Promise promise)
: web_contents_(web_contents), promise_(std::move(promise)) {}
SavePageHandler::~SavePageHandler() {}
void SavePageHandler::OnDownloadCreated(content::DownloadManager* manager,
download::DownloadItem* item) {
// OnDownloadCreated is invoked during WebContents::SavePage, so the |item|
// here is the one stated by WebContents::SavePage.
item->AddObserver(this);
}
bool SavePageHandler::Handle(const base::FilePath& full_path,
const content::SavePageType& save_type) {
auto* download_manager = content::BrowserContext::GetDownloadManager(
web_contents_->GetBrowserContext());
download_manager->AddObserver(this);
// Chromium will create a 'foo_files' directory under the directory of saving
// page 'foo.html' for holding other resource files of 'foo.html'.
base::FilePath saved_main_directory_path = full_path.DirName().Append(
full_path.RemoveExtension().BaseName().value() +
FILE_PATH_LITERAL("_files"));
bool result =
web_contents_->SavePage(full_path, saved_main_directory_path, save_type);
download_manager->RemoveObserver(this);
// If initialization fails which means fail to create |DownloadItem|, we need
// to delete the |SavePageHandler| instance to avoid memory-leak.
if (!result) {
promise_.RejectWithErrorMessage("Failed to save the page");
delete this;
}
return result;
}
void SavePageHandler::OnDownloadUpdated(download::DownloadItem* item) {
if (item->IsDone()) {
if (item->GetState() == download::DownloadItem::COMPLETE)
promise_.Resolve();
else
promise_.RejectWithErrorMessage("Failed to save the page.");
Destroy(item);
}
}
void SavePageHandler::Destroy(download::DownloadItem* item) {
item->RemoveObserver(this);
delete this;
}
} // namespace api
} // namespace atom

View file

@ -0,0 +1,57 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_BROWSER_API_SAVE_PAGE_HANDLER_H_
#define ATOM_BROWSER_API_SAVE_PAGE_HANDLER_H_
#include <string>
#include "atom/common/promise_util.h"
#include "components/download/public/common/download_item.h"
#include "content/public/browser/download_manager.h"
#include "content/public/browser/save_page_type.h"
#include "v8/include/v8.h"
namespace base {
class FilePath;
}
namespace content {
class WebContents;
}
namespace atom {
namespace api {
// A self-destroyed class for handling save page request.
class SavePageHandler : public content::DownloadManager::Observer,
public download::DownloadItem::Observer {
public:
SavePageHandler(content::WebContents* web_contents,
atom::util::Promise promise);
~SavePageHandler() override;
bool Handle(const base::FilePath& full_path,
const content::SavePageType& save_type);
private:
void Destroy(download::DownloadItem* item);
// content::DownloadManager::Observer:
void OnDownloadCreated(content::DownloadManager* manager,
download::DownloadItem* item) override;
// download::DownloadItem::Observer:
void OnDownloadUpdated(download::DownloadItem* item) override;
content::WebContents* web_contents_; // weak
atom::util::Promise promise_;
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_SAVE_PAGE_HANDLER_H_

View file

@ -0,0 +1,117 @@
// 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/browser/api/stream_subscriber.h"
#include <string>
#include "atom/browser/net/url_request_stream_job.h"
#include "atom/common/api/event_emitter_caller.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/node_includes.h"
#include "base/task/post_task.h"
#include "content/public/browser/browser_task_traits.h"
namespace mate {
StreamSubscriber::StreamSubscriber(
v8::Isolate* isolate,
v8::Local<v8::Object> emitter,
base::WeakPtr<atom::URLRequestStreamJob> url_job,
scoped_refptr<base::SequencedTaskRunner> ui_task_runner)
: base::RefCountedDeleteOnSequence<StreamSubscriber>(ui_task_runner),
isolate_(isolate),
emitter_(isolate, emitter),
url_job_(url_job),
weak_factory_(this) {
DCHECK(ui_task_runner->RunsTasksInCurrentSequence());
auto weak_self = weak_factory_.GetWeakPtr();
On("data", base::BindRepeating(&StreamSubscriber::OnData, weak_self));
On("end", base::BindRepeating(&StreamSubscriber::OnEnd, weak_self));
On("error", base::BindRepeating(&StreamSubscriber::OnError, weak_self));
}
StreamSubscriber::~StreamSubscriber() {
RemoveAllListeners();
}
void StreamSubscriber::On(const std::string& event,
EventCallback&& callback) { // NOLINT
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
DCHECK(js_handlers_.find(event) == js_handlers_.end());
v8::Locker locker(isolate_);
v8::Isolate::Scope isolate_scope(isolate_);
v8::HandleScope handle_scope(isolate_);
// emitter.on(event, EventEmitted)
auto fn = CallbackToV8(isolate_, callback);
js_handlers_[event] = v8::Global<v8::Value>(isolate_, fn);
internal::ValueVector args = {StringToV8(isolate_, event), fn};
internal::CallMethodWithArgs(isolate_, emitter_.Get(isolate_), "on", &args);
}
void StreamSubscriber::Off(const std::string& event) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
DCHECK(js_handlers_.find(event) != js_handlers_.end());
v8::Locker locker(isolate_);
v8::Isolate::Scope isolate_scope(isolate_);
v8::HandleScope handle_scope(isolate_);
auto js_handler = js_handlers_.find(event);
DCHECK(js_handler != js_handlers_.end());
RemoveListener(js_handler);
}
void StreamSubscriber::OnData(mate::Arguments* args) {
v8::Local<v8::Value> buf;
args->GetNext(&buf);
if (!node::Buffer::HasInstance(buf)) {
args->ThrowError("data must be Buffer");
return;
}
const char* data = node::Buffer::Data(buf);
size_t length = node::Buffer::Length(buf);
if (length == 0)
return;
// Pass the data to the URLJob in IO thread.
std::vector<char> buffer(data, data + length);
base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::IO},
base::BindOnce(&atom::URLRequestStreamJob::OnData,
url_job_, base::Passed(&buffer)));
}
void StreamSubscriber::OnEnd(mate::Arguments* args) {
base::PostTaskWithTraits(
FROM_HERE, {content::BrowserThread::IO},
base::BindOnce(&atom::URLRequestStreamJob::OnEnd, url_job_));
}
void StreamSubscriber::OnError(mate::Arguments* args) {
base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::IO},
base::BindOnce(&atom::URLRequestStreamJob::OnError,
url_job_, net::ERR_FAILED));
}
void StreamSubscriber::RemoveAllListeners() {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
v8::Locker locker(isolate_);
v8::Isolate::Scope isolate_scope(isolate_);
v8::HandleScope handle_scope(isolate_);
while (!js_handlers_.empty()) {
RemoveListener(js_handlers_.begin());
}
}
void StreamSubscriber::RemoveListener(JSHandlersMap::iterator it) {
internal::ValueVector args = {StringToV8(isolate_, it->first),
it->second.Get(isolate_)};
internal::CallMethodWithArgs(isolate_, emitter_.Get(isolate_),
"removeListener", &args);
js_handlers_.erase(it);
}
} // namespace mate

View file

@ -0,0 +1,68 @@
// 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_BROWSER_API_STREAM_SUBSCRIBER_H_
#define ATOM_BROWSER_API_STREAM_SUBSCRIBER_H_
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "base/callback.h"
#include "base/memory/ref_counted.h"
#include "base/memory/ref_counted_delete_on_sequence.h"
#include "base/memory/weak_ptr.h"
#include "content/public/browser/browser_thread.h"
#include "v8/include/v8.h"
namespace atom {
class URLRequestStreamJob;
}
namespace mate {
class Arguments;
class StreamSubscriber
: public base::RefCountedDeleteOnSequence<StreamSubscriber> {
public:
REQUIRE_ADOPTION_FOR_REFCOUNTED_TYPE();
StreamSubscriber(v8::Isolate* isolate,
v8::Local<v8::Object> emitter,
base::WeakPtr<atom::URLRequestStreamJob> url_job,
scoped_refptr<base::SequencedTaskRunner> ui_task_runner);
private:
friend class base::DeleteHelper<StreamSubscriber>;
friend class base::RefCountedDeleteOnSequence<StreamSubscriber>;
using JSHandlersMap = std::map<std::string, v8::Global<v8::Value>>;
using EventCallback = base::RepeatingCallback<void(mate::Arguments* args)>;
~StreamSubscriber();
void On(const std::string& event, EventCallback&& callback); // NOLINT
void Off(const std::string& event);
void OnData(mate::Arguments* args);
void OnEnd(mate::Arguments* args);
void OnError(mate::Arguments* args);
void RemoveAllListeners();
void RemoveListener(JSHandlersMap::iterator it);
v8::Isolate* isolate_;
v8::Global<v8::Object> emitter_;
base::WeakPtr<atom::URLRequestStreamJob> url_job_;
JSHandlersMap js_handlers_;
base::WeakPtrFactory<StreamSubscriber> weak_factory_;
};
} // namespace mate
#endif // ATOM_BROWSER_API_STREAM_SUBSCRIBER_H_

View file

@ -0,0 +1,66 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/api/trackable_object.h"
#include <memory>
#include "atom/browser/atom_browser_main_parts.h"
#include "base/bind.h"
#include "base/supports_user_data.h"
namespace mate {
namespace {
const char* kTrackedObjectKey = "TrackedObjectKey";
class IDUserData : public base::SupportsUserData::Data {
public:
explicit IDUserData(int32_t id) : id_(id) {}
operator int32_t() const { return id_; }
private:
int32_t id_;
DISALLOW_COPY_AND_ASSIGN(IDUserData);
};
} // namespace
TrackableObjectBase::TrackableObjectBase() : weak_factory_(this) {
atom::AtomBrowserMainParts::Get()->RegisterDestructionCallback(
GetDestroyClosure());
}
TrackableObjectBase::~TrackableObjectBase() {}
base::OnceClosure TrackableObjectBase::GetDestroyClosure() {
return base::BindOnce(&TrackableObjectBase::Destroy,
weak_factory_.GetWeakPtr());
}
void TrackableObjectBase::Destroy() {
delete this;
}
void TrackableObjectBase::AttachAsUserData(base::SupportsUserData* wrapped) {
wrapped->SetUserData(kTrackedObjectKey,
std::make_unique<IDUserData>(weak_map_id_));
}
// static
int32_t TrackableObjectBase::GetIDFromWrappedClass(
base::SupportsUserData* wrapped) {
if (wrapped) {
auto* id =
static_cast<IDUserData*>(wrapped->GetUserData(kTrackedObjectKey));
if (id)
return *id;
}
return 0;
}
} // namespace mate

View file

@ -0,0 +1,137 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_BROWSER_API_TRACKABLE_OBJECT_H_
#define ATOM_BROWSER_API_TRACKABLE_OBJECT_H_
#include <vector>
#include "atom/browser/api/event_emitter.h"
#include "atom/common/key_weak_map.h"
#include "base/bind.h"
#include "base/memory/weak_ptr.h"
#include "native_mate/object_template_builder.h"
namespace base {
class SupportsUserData;
}
namespace mate {
// Users should use TrackableObject instead.
class TrackableObjectBase {
public:
TrackableObjectBase();
// The ID in weak map.
int32_t weak_map_id() const { return weak_map_id_; }
// Wrap TrackableObject into a class that SupportsUserData.
void AttachAsUserData(base::SupportsUserData* wrapped);
// Get the weak_map_id from SupportsUserData.
static int32_t GetIDFromWrappedClass(base::SupportsUserData* wrapped);
protected:
virtual ~TrackableObjectBase();
// Returns a closure that can destroy the native class.
base::OnceClosure GetDestroyClosure();
int32_t weak_map_id_ = 0;
private:
void Destroy();
base::WeakPtrFactory<TrackableObjectBase> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(TrackableObjectBase);
};
// All instances of TrackableObject will be kept in a weak map and can be got
// from its ID.
template <typename T>
class TrackableObject : public TrackableObjectBase,
public mate::EventEmitter<T> {
public:
// Mark the JS object as destroyed.
void MarkDestroyed() {
v8::Local<v8::Object> wrapper = Wrappable<T>::GetWrapper();
if (!wrapper.IsEmpty()) {
wrapper->SetAlignedPointerInInternalField(0, nullptr);
}
}
bool IsDestroyed() {
v8::Local<v8::Object> wrapper = Wrappable<T>::GetWrapper();
return wrapper->InternalFieldCount() == 0 ||
wrapper->GetAlignedPointerFromInternalField(0) == nullptr;
}
// Finds out the TrackableObject from its ID in weak map.
static T* FromWeakMapID(v8::Isolate* isolate, int32_t id) {
if (!weak_map_)
return nullptr;
v8::MaybeLocal<v8::Object> object = weak_map_->Get(isolate, id);
if (object.IsEmpty())
return nullptr;
T* self = nullptr;
mate::ConvertFromV8(isolate, object.ToLocalChecked(), &self);
return self;
}
// Finds out the TrackableObject from the class it wraps.
static T* FromWrappedClass(v8::Isolate* isolate,
base::SupportsUserData* wrapped) {
int32_t id = GetIDFromWrappedClass(wrapped);
if (!id)
return nullptr;
return FromWeakMapID(isolate, id);
}
// Returns all objects in this class's weak map.
static std::vector<v8::Local<v8::Object>> GetAll(v8::Isolate* isolate) {
if (weak_map_)
return weak_map_->Values(isolate);
else
return std::vector<v8::Local<v8::Object>>();
}
// Removes this instance from the weak map.
void RemoveFromWeakMap() {
if (weak_map_ && weak_map_->Has(weak_map_id()))
weak_map_->Remove(weak_map_id());
}
protected:
TrackableObject() { weak_map_id_ = ++next_id_; }
~TrackableObject() override { RemoveFromWeakMap(); }
void InitWith(v8::Isolate* isolate, v8::Local<v8::Object> wrapper) override {
WrappableBase::InitWith(isolate, wrapper);
if (!weak_map_) {
weak_map_ = new atom::KeyWeakMap<int32_t>;
}
weak_map_->Set(isolate, weak_map_id_, wrapper);
}
private:
static int32_t next_id_;
static atom::KeyWeakMap<int32_t>* weak_map_; // leaked on purpose
DISALLOW_COPY_AND_ASSIGN(TrackableObject);
};
template <typename T>
int32_t TrackableObject<T>::next_id_ = 0;
template <typename T>
atom::KeyWeakMap<int32_t>* TrackableObject<T>::weak_map_ = nullptr;
} // namespace mate
#endif // ATOM_BROWSER_API_TRACKABLE_OBJECT_H_

View file

@ -0,0 +1,86 @@
// 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/browser/api/views/atom_api_box_layout.h"
#include <string>
#include "atom/browser/api/atom_api_view.h"
#include "atom/common/api/constructor.h"
#include "atom/common/node_includes.h"
#include "native_mate/dictionary.h"
namespace mate {
template <>
struct Converter<views::BoxLayout::Orientation> {
static bool FromV8(v8::Isolate* isolate,
v8::Handle<v8::Value> val,
views::BoxLayout::Orientation* out) {
std::string orientation;
if (!ConvertFromV8(isolate, val, &orientation))
return false;
if (orientation == "horizontal")
*out = views::BoxLayout::kHorizontal;
else if (orientation == "vertical")
*out = views::BoxLayout::kVertical;
else
return false;
return true;
}
};
} // namespace mate
namespace atom {
namespace api {
BoxLayout::BoxLayout(views::BoxLayout::Orientation orientation)
: LayoutManager(new views::BoxLayout(orientation)) {}
BoxLayout::~BoxLayout() {}
void BoxLayout::SetFlexForView(mate::Handle<View> view, int flex) {
auto* box_layout = static_cast<views::BoxLayout*>(layout_manager());
box_layout->SetFlexForView(view->view(), flex);
}
// static
mate::WrappableBase* BoxLayout::New(mate::Arguments* args,
views::BoxLayout::Orientation orientation) {
auto* layout = new BoxLayout(orientation);
layout->InitWith(args->isolate(), args->GetThis());
return layout;
}
// static
void BoxLayout::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "BoxLayout"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.SetMethod("setFlexForView", &BoxLayout::SetFlexForView);
}
} // namespace api
} // namespace atom
namespace {
using atom::api::BoxLayout;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
mate::Dictionary dict(isolate, exports);
dict.Set("BoxLayout", mate::CreateConstructor<BoxLayout>(
isolate, base::BindRepeating(&BoxLayout::New)));
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_browser_box_layout, Initialize)

View file

@ -0,0 +1,40 @@
// 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_BROWSER_API_VIEWS_ATOM_API_BOX_LAYOUT_H_
#define ATOM_BROWSER_API_VIEWS_ATOM_API_BOX_LAYOUT_H_
#include "atom/browser/api/views/atom_api_layout_manager.h"
#include "native_mate/handle.h"
#include "ui/views/layout/box_layout.h"
namespace atom {
namespace api {
class View;
class BoxLayout : public LayoutManager {
public:
static mate::WrappableBase* New(mate::Arguments* args,
views::BoxLayout::Orientation orientation);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
void SetFlexForView(mate::Handle<View> view, int flex);
protected:
explicit BoxLayout(views::BoxLayout::Orientation orientation);
~BoxLayout() override;
private:
DISALLOW_COPY_AND_ASSIGN(BoxLayout);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_VIEWS_ATOM_API_BOX_LAYOUT_H_

View file

@ -0,0 +1,59 @@
// 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/browser/api/views/atom_api_button.h"
#include "atom/common/api/constructor.h"
#include "atom/common/node_includes.h"
#include "native_mate/dictionary.h"
namespace atom {
namespace api {
Button::Button(views::Button* impl) : View(impl) {
view()->set_owned_by_client();
// Make the button focusable as per the platform.
button()->SetFocusForPlatform();
}
Button::~Button() {}
void Button::ButtonPressed(views::Button* sender, const ui::Event& event) {
Emit("click");
}
// static
mate::WrappableBase* Button::New(mate::Arguments* args) {
args->ThrowError("Button can not be created directly");
return nullptr;
}
// static
void Button::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "Button"));
}
} // namespace api
} // namespace atom
namespace {
using atom::api::Button;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
mate::Dictionary dict(isolate, exports);
dict.Set("Button", mate::CreateConstructor<Button>(
isolate, base::BindRepeating(&Button::New)));
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_browser_button, Initialize)

View file

@ -0,0 +1,40 @@
// 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_BROWSER_API_VIEWS_ATOM_API_BUTTON_H_
#define ATOM_BROWSER_API_VIEWS_ATOM_API_BUTTON_H_
#include "atom/browser/api/atom_api_view.h"
#include "native_mate/handle.h"
#include "ui/views/controls/button/button.h"
namespace atom {
namespace api {
class Button : public View, public views::ButtonListener {
public:
static mate::WrappableBase* New(mate::Arguments* args);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
protected:
explicit Button(views::Button* view);
~Button() override;
// views::ButtonListener:
void ButtonPressed(views::Button* sender, const ui::Event& event) override;
views::Button* button() const { return static_cast<views::Button*>(view()); }
private:
DISALLOW_COPY_AND_ASSIGN(Button);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_VIEWS_ATOM_API_BUTTON_H_

View file

@ -0,0 +1,79 @@
// 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/browser/api/views/atom_api_label_button.h"
#include "atom/common/api/constructor.h"
#include "atom/common/node_includes.h"
#include "base/strings/utf_string_conversions.h"
#include "native_mate/dictionary.h"
namespace atom {
namespace api {
LabelButton::LabelButton(views::LabelButton* impl) : Button(impl) {}
LabelButton::LabelButton(const std::string& text)
: Button(new views::LabelButton(this, base::UTF8ToUTF16(text))) {}
LabelButton::~LabelButton() {}
const base::string16& LabelButton::GetText() const {
return label_button()->GetText();
}
void LabelButton::SetText(const base::string16& text) {
label_button()->SetText(text);
}
bool LabelButton::IsDefault() const {
return label_button()->is_default();
}
void LabelButton::SetIsDefault(bool is_default) {
label_button()->SetIsDefault(is_default);
}
// static
mate::WrappableBase* LabelButton::New(mate::Arguments* args,
const std::string& text) {
// Constructor call.
auto* view = new LabelButton(text);
view->InitWith(args->isolate(), args->GetThis());
return view;
}
// static
void LabelButton::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "LabelButton"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.SetMethod("getText", &LabelButton::GetText)
.SetMethod("setText", &LabelButton::SetText)
.SetMethod("isDefault", &LabelButton::IsDefault)
.SetMethod("setIsDefault", &LabelButton::SetIsDefault);
}
} // namespace api
} // namespace atom
namespace {
using atom::api::LabelButton;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
mate::Dictionary dict(isolate, exports);
dict.Set("LabelButton", mate::CreateConstructor<LabelButton>(
isolate, base::BindRepeating(&LabelButton::New)));
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_browser_label_button, Initialize)

View file

@ -0,0 +1,47 @@
// 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_BROWSER_API_VIEWS_ATOM_API_LABEL_BUTTON_H_
#define ATOM_BROWSER_API_VIEWS_ATOM_API_LABEL_BUTTON_H_
#include <string>
#include "atom/browser/api/views/atom_api_button.h"
#include "ui/views/controls/button/label_button.h"
namespace atom {
namespace api {
class LabelButton : public Button {
public:
static mate::WrappableBase* New(mate::Arguments* args,
const std::string& text);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
const base::string16& GetText() const;
void SetText(const base::string16& text);
bool IsDefault() const;
void SetIsDefault(bool is_default);
protected:
explicit LabelButton(views::LabelButton* impl);
explicit LabelButton(const std::string& text);
~LabelButton() override;
views::LabelButton* label_button() const {
return static_cast<views::LabelButton*>(view());
}
private:
DISALLOW_COPY_AND_ASSIGN(LabelButton);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_VIEWS_ATOM_API_LABEL_BUTTON_H_

View file

@ -0,0 +1,63 @@
// 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/browser/api/views/atom_api_layout_manager.h"
#include "atom/common/api/constructor.h"
#include "atom/common/node_includes.h"
#include "native_mate/dictionary.h"
namespace atom {
namespace api {
LayoutManager::LayoutManager(views::LayoutManager* layout_manager)
: layout_manager_(layout_manager) {
DCHECK(layout_manager_);
}
LayoutManager::~LayoutManager() {
if (managed_by_us_)
delete layout_manager_;
}
std::unique_ptr<views::LayoutManager> LayoutManager::TakeOver() {
if (!managed_by_us_) // already taken over.
return nullptr;
managed_by_us_ = false;
return std::unique_ptr<views::LayoutManager>(layout_manager_);
}
// static
mate::WrappableBase* LayoutManager::New(mate::Arguments* args) {
args->ThrowError("LayoutManager can not be created directly");
return nullptr;
}
// static
void LayoutManager::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {}
} // namespace api
} // namespace atom
namespace {
using atom::api::LayoutManager;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
mate::Dictionary dict(isolate, exports);
dict.Set("LayoutManager",
mate::CreateConstructor<LayoutManager>(
isolate, base::BindRepeating(&LayoutManager::New)));
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_browser_layout_manager, Initialize)

View file

@ -0,0 +1,44 @@
// 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_BROWSER_API_VIEWS_ATOM_API_LAYOUT_MANAGER_H_
#define ATOM_BROWSER_API_VIEWS_ATOM_API_LAYOUT_MANAGER_H_
#include <memory>
#include "atom/browser/api/trackable_object.h"
#include "ui/views/layout/layout_manager.h"
namespace atom {
namespace api {
class LayoutManager : public mate::TrackableObject<LayoutManager> {
public:
static mate::WrappableBase* New(mate::Arguments* args);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
// Take over the ownership of the LayoutManager, and leave weak ref here.
std::unique_ptr<views::LayoutManager> TakeOver();
views::LayoutManager* layout_manager() const { return layout_manager_; }
protected:
explicit LayoutManager(views::LayoutManager* layout_manager);
~LayoutManager() override;
private:
bool managed_by_us_ = true;
views::LayoutManager* layout_manager_;
DISALLOW_COPY_AND_ASSIGN(LayoutManager);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_VIEWS_ATOM_API_LAYOUT_MANAGER_H_

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