Merge pull request #140 from atom/chrome31

Update to Chrome 31
This commit is contained in:
Cheng Zhao 2013-12-26 22:07:17 -08:00
commit 2945e1b50a
128 changed files with 1489 additions and 1579 deletions

3
.gitmodules vendored
View file

@ -4,9 +4,6 @@
[submodule "vendor/node"] [submodule "vendor/node"]
path = vendor/node path = vendor/node
url = https://github.com/atom/node.git url = https://github.com/atom/node.git
[submodule "vendor/gyp"]
path = vendor/gyp
url = https://github.com/svn2github/gyp.git
[submodule "vendor/depot_tools"] [submodule "vendor/depot_tools"]
path = vendor/depot_tools path = vendor/depot_tools
url = https://chromium.googlesource.com/chromium/tools/depot_tools.git url = https://chromium.googlesource.com/chromium/tools/depot_tools.git

View file

@ -23,19 +23,23 @@ AtomMainDelegate::~AtomMainDelegate() {
bool AtomMainDelegate::BasicStartupComplete(int* exit_code) { bool AtomMainDelegate::BasicStartupComplete(int* exit_code) {
// Disable logging out to debug.log on Windows // Disable logging out to debug.log on Windows
#if defined(OS_WIN) #if defined(OS_WIN)
logging::InitLogging( logging::LoggingSettings settings;
L"debug.log",
#if defined(DEBUG) #if defined(DEBUG)
logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG , settings.logging_dest = logging::LOG_TO_ALL;
settings.log_file = L"debug.log";
settings.lock_log = logging::LOCK_LOG_FILE;
settings.delete_old = logging::DELETE_OLD_LOG_FILE;
#else #else
logging::LOG_ONLY_TO_SYSTEM_DEBUG_LOG, settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
#endif // defined(NDEBUG) #endif
logging::LOCK_LOG_FILE, settings.dcheck_state =
logging::DELETE_OLD_LOG_FILE, logging::DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS;
logging::DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS); logging::InitLogging(settings);
logging::SetLogItems(true, false, true, false);
#endif // defined(OS_WIN) #endif // defined(OS_WIN)
// Logging with pid and timestamp.
logging::SetLogItems(true, false, true, false);
return brightray::MainDelegate::BasicStartupComplete(exit_code); return brightray::MainDelegate::BasicStartupComplete(exit_code);
} }
@ -43,13 +47,20 @@ void AtomMainDelegate::PreSandboxStartup() {
#if defined(OS_MACOSX) #if defined(OS_MACOSX)
OverrideChildProcessPath(); OverrideChildProcessPath();
OverrideFrameworkBundlePath(); OverrideFrameworkBundlePath();
SetProcessName();
#endif #endif
InitializeResourceBundle(); InitializeResourceBundle();
// Disable renderer sandbox for most of node's functions.
CommandLine* command_line = CommandLine::ForCurrentProcess(); CommandLine* command_line = CommandLine::ForCurrentProcess();
// Disable renderer sandbox for most of node's functions.
command_line->AppendSwitch(switches::kNoSandbox); command_line->AppendSwitch(switches::kNoSandbox);
// Disable accelerated compositing since it caused a lot of troubles (black
// devtools, screen flashes) and needed lots of effort to make it right.
command_line->AppendSwitch(switches::kDisableAcceleratedCompositing);
// Add a flag to mark the end of switches added by atom-shell.
command_line->AppendSwitch("no-more-switches");
} }
void AtomMainDelegate::InitializeResourceBundle() { void AtomMainDelegate::InitializeResourceBundle() {

View file

@ -23,7 +23,6 @@ class AtomMainDelegate : public brightray::MainDelegate {
virtual base::FilePath GetResourcesPakFilePath(); virtual base::FilePath GetResourcesPakFilePath();
virtual void OverrideChildProcessPath(); virtual void OverrideChildProcessPath();
virtual void OverrideFrameworkBundlePath(); virtual void OverrideFrameworkBundlePath();
virtual void SetProcessName();
#endif #endif
private: private:

View file

@ -45,22 +45,4 @@ void AtomMainDelegate::OverrideChildProcessPath() {
PathService::Override(content::CHILD_PROCESS_EXE, helper_path); PathService::Override(content::CHILD_PROCESS_EXE, helper_path);
} }
void AtomMainDelegate::SetProcessName() {
const auto& command_line = *CommandLine::ForCurrentProcess();
auto process_type = command_line.GetSwitchValueASCII(switches::kProcessType);
std::string suffix;
if (process_type == switches::kRendererProcess)
suffix = "Renderer";
else if (process_type == switches::kPluginProcess ||
process_type == switches::kPpapiPluginProcess)
suffix = "Plug-In Host";
else if (process_type == switches::kUtilityProcess)
suffix = "Utility";
else
return;
base::mac::SetProcessName(base::mac::NSToCFCast(base::SysUTF8ToNSString(
brightray::GetApplicationName() + " " + suffix)));
}
} // namespace atom } // namespace atom

View file

@ -12,7 +12,6 @@
], ],
'coffee_sources': [ 'coffee_sources': [
'browser/api/lib/app.coffee', 'browser/api/lib/app.coffee',
'browser/api/lib/atom-delegate.coffee',
'browser/api/lib/auto-updater.coffee', 'browser/api/lib/auto-updater.coffee',
'browser/api/lib/browser-window.coffee', 'browser/api/lib/browser-window.coffee',
'browser/api/lib/dialog.coffee', 'browser/api/lib/dialog.coffee',
@ -21,14 +20,15 @@
'browser/api/lib/menu-item.coffee', 'browser/api/lib/menu-item.coffee',
'browser/api/lib/power-monitor.coffee', 'browser/api/lib/power-monitor.coffee',
'browser/api/lib/protocol.coffee', 'browser/api/lib/protocol.coffee',
'browser/atom/atom.coffee', 'browser/lib/init.coffee',
'browser/atom/objects-registry.coffee', 'browser/lib/objects-registry.coffee',
'browser/atom/rpc-server.coffee', 'browser/lib/rpc-server.coffee',
'common/api/lib/callbacks-registry.coffee', 'common/api/lib/callbacks-registry.coffee',
'common/api/lib/clipboard.coffee', 'common/api/lib/clipboard.coffee',
'common/api/lib/crash-reporter.coffee', 'common/api/lib/crash-reporter.coffee',
'common/api/lib/id-weak-map.coffee', 'common/api/lib/id-weak-map.coffee',
'common/api/lib/shell.coffee', 'common/api/lib/shell.coffee',
'renderer/lib/init.coffee',
'renderer/api/lib/ipc.coffee', 'renderer/api/lib/ipc.coffee',
'renderer/api/lib/remote.coffee', 'renderer/api/lib/remote.coffee',
], ],
@ -165,9 +165,11 @@
'common/platform_util_mac.mm', 'common/platform_util_mac.mm',
'common/platform_util_win.cc', 'common/platform_util_win.cc',
'common/swap_or_assign.h', 'common/swap_or_assign.h',
'common/v8_conversions.h', 'common/v8/node_common.h',
'common/v8_value_converter_impl.cc', 'common/v8/scoped_persistent.h',
'common/v8_value_converter_impl.h', 'common/v8/native_type_conversions.h',
'common/v8/v8_value_converter.cc',
'common/v8/v8_value_converter.h',
'renderer/api/atom_api_renderer_ipc.cc', 'renderer/api/atom_api_renderer_ipc.cc',
'renderer/api/atom_api_renderer_ipc.h', 'renderer/api/atom_api_renderer_ipc.h',
'renderer/api/atom_renderer_bindings.cc', 'renderer/api/atom_renderer_bindings.cc',
@ -318,7 +320,7 @@
'type': 'static_library', 'type': 'static_library',
'dependencies': [ 'dependencies': [
'vendor/brightray/brightray.gyp:brightray', 'vendor/brightray/brightray.gyp:brightray',
'vendor/node/node.gyp:node', 'vendor/node/node.gyp:node_lib',
], ],
'sources': [ 'sources': [
'<@(lib_sources)', '<@(lib_sources)',
@ -326,6 +328,14 @@
'include_dirs': [ 'include_dirs': [
'.', '.',
'vendor', 'vendor',
# Include directories for uv and node.
'vendor/node/src',
'vendor/node/deps/http_parser',
'vendor/node/deps/uv/include',
# The `node.h` is using `#include"v8.h"`.
'vendor/brightray/vendor/download/libchromiumcontent/src/v8/include',
# The `node.h` is using `#include"ares.h"`.
'vendor/node/deps/cares/include',
], ],
'direct_dependent_settings': { 'direct_dependent_settings': {
'include_dirs': [ 'include_dirs': [

View file

@ -7,8 +7,9 @@
#include "base/values.h" #include "base/values.h"
#include "base/command_line.h" #include "base/command_line.h"
#include "browser/browser.h" #include "browser/browser.h"
#include "common/v8_conversions.h" #include "common/v8/native_type_conversions.h"
#include "vendor/node/src/node.h"
#include "common/v8/node_common.h"
namespace atom { namespace atom {
@ -48,97 +49,69 @@ void App::OnWillFinishLaunching() {
} }
void App::OnFinishLaunching() { void App::OnFinishLaunching() {
Emit("finish-launching"); Emit("ready");
} }
// static // static
v8::Handle<v8::Value> App::New(const v8::Arguments &args) { void App::New(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope; v8::HandleScope scope(args.GetIsolate());
if (!args.IsConstructCall()) if (!args.IsConstructCall())
return node::ThrowError("Require constructor call"); return node::ThrowError("Require constructor call");
new App(args.This()); new App(args.This());
return args.This();
} }
// static // static
v8::Handle<v8::Value> App::Quit(const v8::Arguments &args) { void App::Quit(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope;
Browser::Get()->Quit(); Browser::Get()->Quit();
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> App::Exit(const v8::Arguments &args) { void App::Exit(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope;
exit(args[0]->IntegerValue()); exit(args[0]->IntegerValue());
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> App::Terminate(const v8::Arguments &args) { void App::Terminate(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope;
Browser::Get()->Terminate(); Browser::Get()->Terminate();
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> App::Focus(const v8::Arguments &args) { void App::Focus(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope;
Browser::Get()->Focus(); Browser::Get()->Focus();
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> App::GetVersion(const v8::Arguments &args) { void App::GetVersion(const v8::FunctionCallbackInfo<v8::Value>& args) {
return ToV8Value(Browser::Get()->GetVersion()); args.GetReturnValue().Set(ToV8Value(Browser::Get()->GetVersion()));
} }
// static // static
v8::Handle<v8::Value> App::SetVersion(const v8::Arguments &args) { void App::SetVersion(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope;
std::string version; std::string version;
if (!FromV8Arguments(args, &version)) if (!FromV8Arguments(args, &version))
return node::ThrowError("Bad argument"); return node::ThrowError("Bad argument");
Browser::Get()->SetVersion(version); Browser::Get()->SetVersion(version);
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> App::GetName(const v8::Arguments &args) { void App::GetName(const v8::FunctionCallbackInfo<v8::Value>& args) {
return ToV8Value(Browser::Get()->GetName()); return args.GetReturnValue().Set(ToV8Value(Browser::Get()->GetName()));
} }
// static // static
v8::Handle<v8::Value> App::SetName(const v8::Arguments &args) { void App::SetName(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope;
std::string name; std::string name;
if (!FromV8Arguments(args, &name)) if (!FromV8Arguments(args, &name))
return node::ThrowError("Bad argument"); return node::ThrowError("Bad argument");
Browser::Get()->SetName(name); Browser::Get()->SetName(name);
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> App::AppendSwitch(const v8::Arguments &args) { void App::AppendSwitch(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope;
std::string switch_string; std::string switch_string;
if (!FromV8Arguments(args, &switch_string)) if (!FromV8Arguments(args, &switch_string))
return node::ThrowError("Bad argument"); return node::ThrowError("Bad argument");
@ -150,27 +123,21 @@ v8::Handle<v8::Value> App::AppendSwitch(const v8::Arguments &args) {
CommandLine::ForCurrentProcess()->AppendSwitchASCII( CommandLine::ForCurrentProcess()->AppendSwitchASCII(
switch_string, value); switch_string, value);
} }
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> App::AppendArgument(const v8::Arguments &args) { void App::AppendArgument(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope;
std::string value; std::string value;
if (!FromV8Arguments(args, &value)) if (!FromV8Arguments(args, &value))
return node::ThrowError("Bad argument"); return node::ThrowError("Bad argument");
CommandLine::ForCurrentProcess()->AppendArg(value); CommandLine::ForCurrentProcess()->AppendArg(value);
return v8::Undefined();
} }
#if defined(OS_MACOSX) #if defined(OS_MACOSX)
// static // static
v8::Handle<v8::Value> App::DockBounce(const v8::Arguments& args) { void App::DockBounce(const v8::FunctionCallbackInfo<v8::Value>& args) {
std::string type; std::string type;
if (!FromV8Arguments(args, &type)) if (!FromV8Arguments(args, &type))
return node::ThrowError("Bad argument"); return node::ThrowError("Bad argument");
@ -184,34 +151,32 @@ v8::Handle<v8::Value> App::DockBounce(const v8::Arguments& args) {
else else
return node::ThrowTypeError("Invalid bounce type"); return node::ThrowTypeError("Invalid bounce type");
return ToV8Value(request_id); args.GetReturnValue().Set(request_id);
} }
// static // static
v8::Handle<v8::Value> App::DockCancelBounce(const v8::Arguments& args) { void App::DockCancelBounce(const v8::FunctionCallbackInfo<v8::Value>& args) {
Browser::Get()->DockCancelBounce(FromV8Value(args[0])); Browser::Get()->DockCancelBounce(FromV8Value(args[0]));
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> App::DockSetBadgeText(const v8::Arguments& args) { void App::DockSetBadgeText(const v8::FunctionCallbackInfo<v8::Value>& args) {
Browser::Get()->DockSetBadgeText(FromV8Value(args[0])); Browser::Get()->DockSetBadgeText(FromV8Value(args[0]));
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> App::DockGetBadgeText(const v8::Arguments& args) { void App::DockGetBadgeText(const v8::FunctionCallbackInfo<v8::Value>& args) {
std::string text(Browser::Get()->DockGetBadgeText()); std::string text(Browser::Get()->DockGetBadgeText());
return ToV8Value(text); args.GetReturnValue().Set(ToV8Value(text));
} }
#endif // defined(OS_MACOSX) #endif // defined(OS_MACOSX)
// static // static
void App::Initialize(v8::Handle<v8::Object> target) { void App::Initialize(v8::Handle<v8::Object> target) {
v8::HandleScope scope; v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(App::New); v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(New);
t->InstanceTemplate()->SetInternalFieldCount(1); t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(v8::String::NewSymbol("Application")); t->SetClassName(v8::String::NewSymbol("Application"));

View file

@ -33,24 +33,24 @@ class App : public EventEmitter,
virtual void OnFinishLaunching() OVERRIDE; virtual void OnFinishLaunching() OVERRIDE;
private: private:
static v8::Handle<v8::Value> New(const v8::Arguments &args); static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> Quit(const v8::Arguments &args); static void Quit(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> Exit(const v8::Arguments &args); static void Exit(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> Terminate(const v8::Arguments &args); static void Terminate(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> Focus(const v8::Arguments &args); static void Focus(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> GetVersion(const v8::Arguments &args); static void GetVersion(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> SetVersion(const v8::Arguments &args); static void SetVersion(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> GetName(const v8::Arguments &args); static void GetName(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> SetName(const v8::Arguments &args); static void SetName(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> AppendSwitch(const v8::Arguments &args); static void AppendSwitch(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> AppendArgument(const v8::Arguments &args); static void AppendArgument(const v8::FunctionCallbackInfo<v8::Value>& args);
#if defined(OS_MACOSX) #if defined(OS_MACOSX)
static v8::Handle<v8::Value> DockBounce(const v8::Arguments& args); static void DockBounce(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> DockCancelBounce(const v8::Arguments& args); static void DockCancelBounce(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> DockSetBadgeText(const v8::Arguments& args); static void DockSetBadgeText(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> DockGetBadgeText(const v8::Arguments& args); static void DockGetBadgeText(const v8::FunctionCallbackInfo<v8::Value>& args);
#endif // defined(OS_MACOSX) #endif // defined(OS_MACOSX)
DISALLOW_COPY_AND_ASSIGN(App); DISALLOW_COPY_AND_ASSIGN(App);

View file

@ -6,7 +6,9 @@
#include "base/values.h" #include "base/values.h"
#include "browser/auto_updater.h" #include "browser/auto_updater.h"
#include "common/v8_conversions.h" #include "common/v8/native_type_conversions.h"
#include "common/v8/node_common.h"
namespace atom { namespace atom {
@ -44,69 +46,63 @@ void AutoUpdater::ReadyForUpdateOnQuit(const std::string& version,
} }
// static // static
v8::Handle<v8::Value> AutoUpdater::New(const v8::Arguments &args) { void AutoUpdater::New(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope; v8::HandleScope handle_scope(args.GetIsolate());
if (!args.IsConstructCall()) if (!args.IsConstructCall())
return node::ThrowError("Require constructor call"); return node::ThrowError("Require constructor call");
new AutoUpdater(args.This()); new AutoUpdater(args.This());
return args.This();
} }
// static // static
v8::Handle<v8::Value> AutoUpdater::SetFeedURL(const v8::Arguments &args) { void AutoUpdater::SetFeedURL(const v8::FunctionCallbackInfo<v8::Value>& args) {
auto_updater::AutoUpdater::SetFeedURL(FromV8Value(args[0])); auto_updater::AutoUpdater::SetFeedURL(FromV8Value(args[0]));
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> AutoUpdater::SetAutomaticallyChecksForUpdates( void AutoUpdater::SetAutomaticallyChecksForUpdates(
const v8::Arguments &args) { const v8::FunctionCallbackInfo<v8::Value>& args) {
auto_updater::AutoUpdater::SetAutomaticallyChecksForUpdates( auto_updater::AutoUpdater::SetAutomaticallyChecksForUpdates(
args[0]->BooleanValue()); FromV8Value(args[0]));
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> AutoUpdater::SetAutomaticallyDownloadsUpdates( void AutoUpdater::SetAutomaticallyDownloadsUpdates(
const v8::Arguments &args) { const v8::FunctionCallbackInfo<v8::Value>& args) {
auto_updater::AutoUpdater::SetAutomaticallyDownloadsUpdates( auto_updater::AutoUpdater::SetAutomaticallyDownloadsUpdates(
args[0]->BooleanValue()); FromV8Value(args[0]));
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> AutoUpdater::CheckForUpdates(const v8::Arguments &args) { void AutoUpdater::CheckForUpdates(
const v8::FunctionCallbackInfo<v8::Value>& args) {
auto_updater::AutoUpdater::CheckForUpdates(); auto_updater::AutoUpdater::CheckForUpdates();
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> AutoUpdater::CheckForUpdatesInBackground( void AutoUpdater::CheckForUpdatesInBackground(
const v8::Arguments &args) { const v8::FunctionCallbackInfo<v8::Value>& args) {
auto_updater::AutoUpdater::CheckForUpdatesInBackground(); auto_updater::AutoUpdater::CheckForUpdatesInBackground();
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> AutoUpdater::ContinueUpdate(const v8::Arguments &args) { void AutoUpdater::ContinueUpdate(
const v8::FunctionCallbackInfo<v8::Value>& args) {
AutoUpdater* self = AutoUpdater::Unwrap<AutoUpdater>(args.This()); AutoUpdater* self = AutoUpdater::Unwrap<AutoUpdater>(args.This());
self->continue_update_.Run(); self->continue_update_.Run();
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> AutoUpdater::QuitAndInstall(const v8::Arguments &args) { void AutoUpdater::QuitAndInstall(
const v8::FunctionCallbackInfo<v8::Value>& args) {
AutoUpdater* self = AutoUpdater::Unwrap<AutoUpdater>(args.This()); AutoUpdater* self = AutoUpdater::Unwrap<AutoUpdater>(args.This());
self->quit_and_install_.Run(); self->quit_and_install_.Run();
return v8::Undefined();
} }
// static // static
void AutoUpdater::Initialize(v8::Handle<v8::Object> target) { void AutoUpdater::Initialize(v8::Handle<v8::Object> target) {
v8::HandleScope scope; v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
v8::Local<v8::FunctionTemplate> t( v8::Local<v8::FunctionTemplate> t(
v8::FunctionTemplate::New(AutoUpdater::New)); v8::FunctionTemplate::New(AutoUpdater::New));

View file

@ -31,19 +31,19 @@ class AutoUpdater : public EventEmitter,
const base::Closure& quit_and_install) OVERRIDE; const base::Closure& quit_and_install) OVERRIDE;
private: private:
static v8::Handle<v8::Value> New(const v8::Arguments &args); static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> SetFeedURL(const v8::Arguments &args); static void SetFeedURL(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> SetAutomaticallyChecksForUpdates( static void SetAutomaticallyChecksForUpdates(
const v8::Arguments &args); const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> SetAutomaticallyDownloadsUpdates( static void SetAutomaticallyDownloadsUpdates(
const v8::Arguments &args); const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> CheckForUpdates(const v8::Arguments &args); static void CheckForUpdates(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> CheckForUpdatesInBackground( static void CheckForUpdatesInBackground(
const v8::Arguments &args); const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> ContinueUpdate(const v8::Arguments &args); static void ContinueUpdate(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> QuitAndInstall(const v8::Arguments &args); static void QuitAndInstall(const v8::FunctionCallbackInfo<v8::Value>& args);
base::Closure continue_update_; base::Closure continue_update_;
base::Closure quit_and_install_; base::Closure quit_and_install_;

View file

@ -5,22 +5,18 @@
#include "browser/api/atom_api_browser_ipc.h" #include "browser/api/atom_api_browser_ipc.h"
#include "common/api/api_messages.h" #include "common/api/api_messages.h"
#include "common/v8_conversions.h" #include "common/v8/node_common.h"
#include "common/v8/native_type_conversions.h"
#include "content/public/browser/render_view_host.h" #include "content/public/browser/render_view_host.h"
#include "vendor/node/src/node.h"
#include "vendor/node/src/node_internals.h"
using content::RenderViewHost; using content::RenderViewHost;
using content::V8ValueConverter;
namespace atom { namespace atom {
namespace api { namespace api {
// static // static
v8::Handle<v8::Value> BrowserIPC::Send(const v8::Arguments &args) { void BrowserIPC::Send(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope;
string16 channel; string16 channel;
int process_id, routing_id; int process_id, routing_id;
scoped_ptr<base::Value> arguments; scoped_ptr<base::Value> arguments;
@ -34,17 +30,15 @@ v8::Handle<v8::Value> BrowserIPC::Send(const v8::Arguments &args) {
if (!render_view_host) if (!render_view_host)
return node::ThrowError("Invalid render view host"); return node::ThrowError("Invalid render view host");
render_view_host->Send(new AtomViewMsg_Message( args.GetReturnValue().Set(render_view_host->Send(new AtomViewMsg_Message(
routing_id, routing_id,
channel, channel,
*static_cast<base::ListValue*>(arguments.get()))); *static_cast<base::ListValue*>(arguments.get()))));
return v8::Undefined();
} }
// static // static
void BrowserIPC::Initialize(v8::Handle<v8::Object> target) { void BrowserIPC::Initialize(v8::Handle<v8::Object> target) {
node::SetMethod(target, "send", Send); NODE_SET_METHOD(target, "send", Send);
} }
} // namespace api } // namespace api

View file

@ -17,7 +17,7 @@ class BrowserIPC {
static void Initialize(v8::Handle<v8::Object> target); static void Initialize(v8::Handle<v8::Object> target);
private: private:
static v8::Handle<v8::Value> Send(const v8::Arguments &args); static void Send(const v8::FunctionCallbackInfo<v8::Value>& args);
DISALLOW_IMPLICIT_CONSTRUCTORS(BrowserIPC); DISALLOW_IMPLICIT_CONSTRUCTORS(BrowserIPC);
}; };

View file

@ -8,10 +8,8 @@
#include "browser/native_window.h" #include "browser/native_window.h"
#include "browser/ui/file_dialog.h" #include "browser/ui/file_dialog.h"
#include "browser/ui/message_box.h" #include "browser/ui/message_box.h"
#include "common/v8_conversions.h" #include "common/v8/node_common.h"
#include "vendor/node/src/node_internals.h" #include "common/v8/native_type_conversions.h"
using node::node_isolate;
namespace atom { namespace atom {
@ -20,19 +18,14 @@ namespace api {
namespace { namespace {
template<typename T> template<typename T>
void CallV8Function(v8::Persistent<v8::Function> callback, T arg) { void CallV8Function(const RefCountedV8Function& callback, T arg) {
DCHECK(!callback.IsEmpty());
v8::HandleScope scope;
v8::Handle<v8::Value> value = ToV8Value(arg); v8::Handle<v8::Value> value = ToV8Value(arg);
callback->Call(callback, 1, &value); callback->NewHandle(node_isolate)->Call(
callback.Dispose(node_isolate); v8::Context::GetCurrent()->Global(), 1, &value);
} }
template<typename T> template<typename T>
void CallV8Function2(v8::Persistent<v8::Function> callback, void CallV8Function2(const RefCountedV8Function& callback, bool result, T arg) {
bool result,
T arg) {
if (result) if (result)
return CallV8Function<T>(callback, arg); return CallV8Function<T>(callback, arg);
else else
@ -40,7 +33,7 @@ void CallV8Function2(v8::Persistent<v8::Function> callback,
} }
void Initialize(v8::Handle<v8::Object> target) { void Initialize(v8::Handle<v8::Object> target) {
v8::HandleScope scope; v8::HandleScope handle_scope(node_isolate);
NODE_SET_METHOD(target, "showMessageBox", ShowMessageBox); NODE_SET_METHOD(target, "showMessageBox", ShowMessageBox);
NODE_SET_METHOD(target, "showOpenDialog", ShowOpenDialog); NODE_SET_METHOD(target, "showOpenDialog", ShowOpenDialog);
@ -49,9 +42,7 @@ void Initialize(v8::Handle<v8::Object> target) {
} // namespace } // namespace
v8::Handle<v8::Value> ShowMessageBox(const v8::Arguments &args) { void ShowMessageBox(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope;
int type; int type;
std::vector<std::string> buttons; std::vector<std::string> buttons;
std::string title, message, detail; std::string title, message, detail;
@ -68,9 +59,9 @@ v8::Handle<v8::Value> ShowMessageBox(const v8::Arguments &args) {
title, title,
message, message,
detail); detail);
return scope.Close(v8::Integer::New(chosen)); args.GetReturnValue().Set(chosen);
} else { } else {
v8::Persistent<v8::Function> callback = FromV8Value(args[6]); RefCountedV8Function callback = FromV8Value(args[6]);
atom::ShowMessageBox( atom::ShowMessageBox(
native_window, native_window,
(MessageBoxType)type, (MessageBoxType)type,
@ -79,13 +70,10 @@ v8::Handle<v8::Value> ShowMessageBox(const v8::Arguments &args) {
message, message,
detail, detail,
base::Bind(&CallV8Function<int>, callback)); base::Bind(&CallV8Function<int>, callback));
return v8::Undefined();
} }
} }
v8::Handle<v8::Value> ShowOpenDialog(const v8::Arguments &args) { void ShowOpenDialog(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope;
std::string title; std::string title;
base::FilePath default_path; base::FilePath default_path;
int properties; int properties;
@ -101,15 +89,15 @@ v8::Handle<v8::Value> ShowOpenDialog(const v8::Arguments &args) {
default_path, default_path,
properties, properties,
&paths)) &paths))
return v8::Undefined(); return;
v8::Handle<v8::Array> result = v8::Array::New(paths.size()); v8::Handle<v8::Array> result = v8::Array::New(paths.size());
for (size_t i = 0; i < paths.size(); ++i) for (size_t i = 0; i < paths.size(); ++i)
result->Set(i, ToV8Value(paths[i])); result->Set(i, ToV8Value(paths[i]));
return scope.Close(result); args.GetReturnValue().Set(result);
} else { } else {
v8::Persistent<v8::Function> callback = FromV8Value(args[4]); RefCountedV8Function callback = FromV8Value(args[4]);
file_dialog::ShowOpenDialog( file_dialog::ShowOpenDialog(
native_window, native_window,
title, title,
@ -117,13 +105,10 @@ v8::Handle<v8::Value> ShowOpenDialog(const v8::Arguments &args) {
properties, properties,
base::Bind(&CallV8Function2<const std::vector<base::FilePath>&>, base::Bind(&CallV8Function2<const std::vector<base::FilePath>&>,
callback)); callback));
return v8::Undefined();
} }
} }
v8::Handle<v8::Value> ShowSaveDialog(const v8::Arguments &args) { void ShowSaveDialog(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope;
std::string title; std::string title;
base::FilePath default_path; base::FilePath default_path;
if (!FromV8Arguments(args, &title, &default_path)) if (!FromV8Arguments(args, &title, &default_path))
@ -133,21 +118,18 @@ v8::Handle<v8::Value> ShowSaveDialog(const v8::Arguments &args) {
if (!args[3]->IsFunction()) { if (!args[3]->IsFunction()) {
base::FilePath path; base::FilePath path;
if (!file_dialog::ShowSaveDialog(native_window, if (file_dialog::ShowSaveDialog(native_window,
title, title,
default_path, default_path,
&path)) &path))
return v8::Undefined(); args.GetReturnValue().Set(ToV8Value(path));
return scope.Close(ToV8Value(path));
} else { } else {
v8::Persistent<v8::Function> callback = FromV8Value(args[3]); RefCountedV8Function callback = FromV8Value(args[3]);
file_dialog::ShowSaveDialog( file_dialog::ShowSaveDialog(
native_window, native_window,
title, title,
default_path, default_path,
base::Bind(&CallV8Function2<const base::FilePath&>, callback)); base::Bind(&CallV8Function2<const base::FilePath&>, callback));
return v8::Undefined();
} }
} }

View file

@ -11,9 +11,9 @@ namespace atom {
namespace api { namespace api {
v8::Handle<v8::Value> ShowMessageBox(const v8::Arguments &args); void ShowMessageBox(const v8::FunctionCallbackInfo<v8::Value>& args);
v8::Handle<v8::Value> ShowOpenDialog(const v8::Arguments &args); void ShowOpenDialog(const v8::FunctionCallbackInfo<v8::Value>& args);
v8::Handle<v8::Value> ShowSaveDialog(const v8::Arguments &args); void ShowSaveDialog(const v8::FunctionCallbackInfo<v8::Value>& args);
} // namespace api } // namespace api

View file

@ -6,15 +6,14 @@
#include "browser/native_window.h" #include "browser/native_window.h"
#include "common/api/api_messages.h" #include "common/api/api_messages.h"
#include "common/v8_conversions.h" #include "common/v8/node_common.h"
#include "common/v8/native_type_conversions.h"
using node::node_isolate;
namespace atom { namespace atom {
namespace api { namespace api {
v8::Persistent<v8::FunctionTemplate> Event::constructor_template_; ScopedPersistent<v8::Function> Event::constructor_template_;
Event::Event() Event::Event()
: sender_(NULL), : sender_(NULL),
@ -29,24 +28,20 @@ Event::~Event() {
// static // static
v8::Handle<v8::Object> Event::CreateV8Object() { v8::Handle<v8::Object> Event::CreateV8Object() {
v8::HandleScope scope;
if (constructor_template_.IsEmpty()) { if (constructor_template_.IsEmpty()) {
v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(New); v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(New);
constructor_template_ = v8::Persistent<v8::FunctionTemplate>::New( t->InstanceTemplate()->SetInternalFieldCount(1);
node_isolate, t); t->SetClassName(v8::String::NewSymbol("Event"));
constructor_template_->InstanceTemplate()->SetInternalFieldCount(1);
constructor_template_->SetClassName(v8::String::NewSymbol("Event"));
NODE_SET_PROTOTYPE_METHOD(t, "preventDefault", PreventDefault); NODE_SET_PROTOTYPE_METHOD(t, "preventDefault", PreventDefault);
NODE_SET_PROTOTYPE_METHOD(t, "sendReply", SendReply); NODE_SET_PROTOTYPE_METHOD(t, "sendReply", SendReply);
NODE_SET_PROTOTYPE_METHOD(t, "destroy", Destroy); NODE_SET_PROTOTYPE_METHOD(t, "destroy", Destroy);
constructor_template_.reset(t->GetFunction());
} }
v8::Handle<v8::Object> v8_event = v8::Handle<v8::Function> t = constructor_template_.NewHandle(node_isolate);
constructor_template_->GetFunction()->NewInstance(0, NULL); return t->NewInstance(0, NULL);
return scope.Close(v8_event);
} }
void Event::SetSenderAndMessage(NativeWindow* sender, IPC::Message* message) { void Event::SetSenderAndMessage(NativeWindow* sender, IPC::Message* message) {
@ -64,26 +59,22 @@ void Event::OnWindowClosed() {
} }
// static // static
v8::Handle<v8::Value> Event::New(const v8::Arguments& args) { void Event::New(const v8::FunctionCallbackInfo<v8::Value>& args) {
Event* event = new Event; Event* event = new Event;
event->Wrap(args.This()); event->Wrap(args.This());
return args.This();
} }
// static // static
v8::Handle<v8::Value> Event::PreventDefault(const v8::Arguments& args) { void Event::PreventDefault(const v8::FunctionCallbackInfo<v8::Value>& args) {
Event* event = Unwrap<Event>(args.This()); Event* event = Unwrap<Event>(args.This());
if (event == NULL) if (event == NULL)
return node::ThrowError("Event is already destroyed"); return node::ThrowError("Event is already destroyed");
event->prevent_default_ = true; event->prevent_default_ = true;
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Event::SendReply(const v8::Arguments& args) { void Event::SendReply(const v8::FunctionCallbackInfo<v8::Value>& args) {
Event* event = Unwrap<Event>(args.This()); Event* event = Unwrap<Event>(args.This());
if (event == NULL) if (event == NULL)
return node::ThrowError("Event is already destroyed"); return node::ThrowError("Event is already destroyed");
@ -97,14 +88,11 @@ v8::Handle<v8::Value> Event::SendReply(const v8::Arguments& args) {
event->sender_->Send(event->message_); event->sender_->Send(event->message_);
delete event; delete event;
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Event::Destroy(const v8::Arguments& args) { void Event::Destroy(const v8::FunctionCallbackInfo<v8::Value>& args) {
delete Unwrap<Event>(args.This()); delete Unwrap<Event>(args.This());
return v8::Undefined();
} }
} // namespace api } // namespace api

View file

@ -7,8 +7,9 @@
#include "base/basictypes.h" #include "base/basictypes.h"
#include "base/compiler_specific.h" #include "base/compiler_specific.h"
#include "base/string16.h" #include "base/strings/string16.h"
#include "browser/native_window_observer.h" #include "browser/native_window_observer.h"
#include "common/v8/scoped_persistent.h"
#include "vendor/node/src/node_object_wrap.h" #include "vendor/node/src/node_object_wrap.h"
namespace IPC { namespace IPC {
@ -32,9 +33,6 @@ class Event : public node::ObjectWrap,
// Pass the sender and message to be replied. // Pass the sender and message to be replied.
void SetSenderAndMessage(NativeWindow* sender, IPC::Message* message); void SetSenderAndMessage(NativeWindow* sender, IPC::Message* message);
// Accessor to return handle_, this follows Google C++ Style.
v8::Persistent<v8::Object>& handle() { return handle_; }
// Whether event.preventDefault() is called. // Whether event.preventDefault() is called.
bool prevent_default() const { return prevent_default_; } bool prevent_default() const { return prevent_default_; }
@ -45,13 +43,13 @@ class Event : public node::ObjectWrap,
virtual void OnWindowClosed() OVERRIDE; virtual void OnWindowClosed() OVERRIDE;
private: private:
static v8::Handle<v8::Value> New(const v8::Arguments& args); static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> PreventDefault(const v8::Arguments& args); static void PreventDefault(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> SendReply(const v8::Arguments& args); static void SendReply(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> Destroy(const v8::Arguments& args); static void Destroy(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Persistent<v8::FunctionTemplate> constructor_template_; static ScopedPersistent<v8::Function> constructor_template_;
// Replyer for the synchronous messages. // Replyer for the synchronous messages.
NativeWindow* sender_; NativeWindow* sender_;

View file

@ -8,9 +8,9 @@
#include "base/logging.h" #include "base/logging.h"
#include "browser/api/atom_api_event.h" #include "browser/api/atom_api_event.h"
#include "common/v8_conversions.h" #include "common/v8/native_type_conversions.h"
#include "vendor/node/src/node.h"
#include "vendor/node/src/node_internals.h" #include "common/v8/node_common.h"
namespace atom { namespace atom {
@ -18,13 +18,6 @@ namespace api {
EventEmitter::EventEmitter(v8::Handle<v8::Object> wrapper) { EventEmitter::EventEmitter(v8::Handle<v8::Object> wrapper) {
Wrap(wrapper); Wrap(wrapper);
// process.emit('ATOM_BROWSER_INTERNAL_NEW', this).
v8::Handle<v8::Value> args[] = {
v8::String::New("ATOM_BROWSER_INTERNAL_NEW"),
wrapper,
};
node::MakeCallback(node::process, "emit", 2, args);
} }
EventEmitter::~EventEmitter() { EventEmitter::~EventEmitter() {
@ -36,10 +29,10 @@ bool EventEmitter::Emit(const std::string& name) {
} }
bool EventEmitter::Emit(const std::string& name, base::ListValue* args) { bool EventEmitter::Emit(const std::string& name, base::ListValue* args) {
v8::HandleScope scope; v8::HandleScope handle_scope(node_isolate);
v8::Handle<v8::Context> context = v8::Context::GetCurrent(); v8::Handle<v8::Context> context = v8::Context::GetCurrent();
scoped_ptr<content::V8ValueConverter> converter(new V8ValueConverterImpl); scoped_ptr<V8ValueConverter> converter(new V8ValueConverter);
v8::Handle<v8::Object> v8_event = Event::CreateV8Object(); v8::Handle<v8::Object> v8_event = Event::CreateV8Object();
Event* event = Event::Unwrap<Event>(v8_event); Event* event = Event::Unwrap<Event>(v8_event);

View file

@ -29,9 +29,6 @@ class EventEmitter : public node::ObjectWrap {
bool Emit(const std::string& name); bool Emit(const std::string& name);
bool Emit(const std::string& name, base::ListValue* args); bool Emit(const std::string& name, base::ListValue* args);
// Small accessor to return handle_, this follows Google C++ Style.
v8::Persistent<v8::Object> handle() const { return handle_; }
protected: protected:
explicit EventEmitter(v8::Handle<v8::Object> wrapper); explicit EventEmitter(v8::Handle<v8::Object> wrapper);

View file

@ -5,7 +5,8 @@
#include "browser/api/atom_api_menu.h" #include "browser/api/atom_api_menu.h"
#include "browser/ui/accelerator_util.h" #include "browser/ui/accelerator_util.h"
#include "common/v8_conversions.h" #include "common/v8/node_common.h"
#include "common/v8/native_type_conversions.h"
#define UNWRAP_MEMNU_AND_CHECK \ #define UNWRAP_MEMNU_AND_CHECK \
Menu* self = ObjectWrap::Unwrap<Menu>(args.This()); \ Menu* self = ObjectWrap::Unwrap<Menu>(args.This()); \
@ -23,7 +24,7 @@ v8::Handle<v8::Value> CallDelegate(v8::Handle<v8::Value> default_value,
v8::Handle<v8::Object> menu, v8::Handle<v8::Object> menu,
const char* method, const char* method,
int command_id) { int command_id) {
v8::HandleScope scope; v8::HandleScope handle_scope(node_isolate);
v8::Handle<v8::Value> delegate = menu->Get(v8::String::New("delegate")); v8::Handle<v8::Value> delegate = menu->Get(v8::String::New("delegate"));
if (!delegate->IsObject()) if (!delegate->IsObject())
@ -36,7 +37,7 @@ v8::Handle<v8::Value> CallDelegate(v8::Handle<v8::Value> default_value,
v8::Handle<v8::Value> argv = v8::Integer::New(command_id); v8::Handle<v8::Value> argv = v8::Integer::New(command_id);
return scope.Close( return handle_scope.Close(
function->Call(v8::Context::GetCurrent()->Global(), 1, &argv)); function->Call(v8::Context::GetCurrent()->Global(), 1, &argv));
} }
@ -51,32 +52,32 @@ Menu::~Menu() {
} }
bool Menu::IsCommandIdChecked(int command_id) const { bool Menu::IsCommandIdChecked(int command_id) const {
v8::HandleScope scope; v8::HandleScope handle_scope(node_isolate);
return CallDelegate(v8::False(), return CallDelegate(v8::False(),
handle(), const_cast<Menu*>(this)->handle(),
"isCommandIdChecked", "isCommandIdChecked",
command_id)->BooleanValue(); command_id)->BooleanValue();
} }
bool Menu::IsCommandIdEnabled(int command_id) const { bool Menu::IsCommandIdEnabled(int command_id) const {
v8::HandleScope scope; v8::HandleScope handle_scope(node_isolate);
return CallDelegate(v8::True(), return CallDelegate(v8::True(),
handle(), const_cast<Menu*>(this)->handle(),
"isCommandIdEnabled", "isCommandIdEnabled",
command_id)->BooleanValue(); command_id)->BooleanValue();
} }
bool Menu::IsCommandIdVisible(int command_id) const { bool Menu::IsCommandIdVisible(int command_id) const {
v8::HandleScope scope; v8::HandleScope handle_scope(node_isolate);
return CallDelegate(v8::True(), return CallDelegate(v8::True(),
handle(), const_cast<Menu*>(this)->handle(),
"isCommandIdVisible", "isCommandIdVisible",
command_id)->BooleanValue(); command_id)->BooleanValue();
} }
bool Menu::GetAcceleratorForCommandId(int command_id, bool Menu::GetAcceleratorForCommandId(int command_id,
ui::Accelerator* accelerator) { ui::Accelerator* accelerator) {
v8::HandleScope scope; v8::HandleScope handle_scope(node_isolate);
v8::Handle<v8::Value> shortcut = CallDelegate(v8::Undefined(), v8::Handle<v8::Value> shortcut = CallDelegate(v8::Undefined(),
handle(), handle(),
"getAcceleratorForCommandId", "getAcceleratorForCommandId",
@ -90,48 +91,46 @@ bool Menu::GetAcceleratorForCommandId(int command_id,
} }
bool Menu::IsItemForCommandIdDynamic(int command_id) const { bool Menu::IsItemForCommandIdDynamic(int command_id) const {
v8::HandleScope scope; v8::HandleScope handle_scope(node_isolate);
return CallDelegate(v8::False(), return CallDelegate(v8::False(),
handle(), const_cast<Menu*>(this)->handle(),
"isItemForCommandIdDynamic", "isItemForCommandIdDynamic",
command_id)->BooleanValue(); command_id)->BooleanValue();
} }
string16 Menu::GetLabelForCommandId(int command_id) const { string16 Menu::GetLabelForCommandId(int command_id) const {
v8::HandleScope scope; v8::HandleScope handle_scope(node_isolate);
return FromV8Value(CallDelegate(v8::False(), return FromV8Value(CallDelegate(v8::False(),
handle(), const_cast<Menu*>(this)->handle(),
"getLabelForCommandId", "getLabelForCommandId",
command_id)); command_id));
} }
string16 Menu::GetSublabelForCommandId(int command_id) const { string16 Menu::GetSublabelForCommandId(int command_id) const {
v8::HandleScope scope; v8::HandleScope handle_scope(node_isolate);
return FromV8Value(CallDelegate(v8::False(), return FromV8Value(CallDelegate(v8::False(),
handle(), const_cast<Menu*>(this)->handle(),
"getSubLabelForCommandId", "getSubLabelForCommandId",
command_id)); command_id));
} }
void Menu::ExecuteCommand(int command_id, int event_flags) { void Menu::ExecuteCommand(int command_id, int event_flags) {
v8::HandleScope scope; v8::HandleScope handle_scope(node_isolate);
CallDelegate(v8::False(), handle(), "executeCommand", command_id); CallDelegate(v8::False(), handle(), "executeCommand", command_id);
} }
// static // static
v8::Handle<v8::Value> Menu::New(const v8::Arguments &args) { void Menu::New(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope; v8::HandleScope handle_scope(args.GetIsolate());
if (!args.IsConstructCall()) if (!args.IsConstructCall())
return node::ThrowError("Require constructor call"); return node::ThrowError("Require constructor call");
Menu::Create(args.This()); Menu::Create(args.This());
return args.This();
} }
// static // static
v8::Handle<v8::Value> Menu::InsertItem(const v8::Arguments &args) { void Menu::InsertItem(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_MEMNU_AND_CHECK; UNWRAP_MEMNU_AND_CHECK;
int index, command_id; int index, command_id;
@ -143,12 +142,10 @@ v8::Handle<v8::Value> Menu::InsertItem(const v8::Arguments &args) {
self->model_->AddItem(command_id, label); self->model_->AddItem(command_id, label);
else else
self->model_->InsertItemAt(index, command_id, label); self->model_->InsertItemAt(index, command_id, label);
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Menu::InsertCheckItem(const v8::Arguments &args) { void Menu::InsertCheckItem(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_MEMNU_AND_CHECK; UNWRAP_MEMNU_AND_CHECK;
int index, command_id; int index, command_id;
@ -160,12 +157,10 @@ v8::Handle<v8::Value> Menu::InsertCheckItem(const v8::Arguments &args) {
self->model_->AddCheckItem(command_id, label); self->model_->AddCheckItem(command_id, label);
else else
self->model_->InsertCheckItemAt(index, command_id, label); self->model_->InsertCheckItemAt(index, command_id, label);
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Menu::InsertRadioItem(const v8::Arguments &args) { void Menu::InsertRadioItem(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_MEMNU_AND_CHECK; UNWRAP_MEMNU_AND_CHECK;
int index, command_id, group_id; int index, command_id, group_id;
@ -177,12 +172,10 @@ v8::Handle<v8::Value> Menu::InsertRadioItem(const v8::Arguments &args) {
self->model_->AddRadioItem(command_id, label, group_id); self->model_->AddRadioItem(command_id, label, group_id);
else else
self->model_->InsertRadioItemAt(index, command_id, label, group_id); self->model_->InsertRadioItemAt(index, command_id, label, group_id);
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Menu::InsertSeparator(const v8::Arguments &args) { void Menu::InsertSeparator(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_MEMNU_AND_CHECK; UNWRAP_MEMNU_AND_CHECK;
int index; int index;
@ -193,12 +186,10 @@ v8::Handle<v8::Value> Menu::InsertSeparator(const v8::Arguments &args) {
self->model_->AddSeparator(ui::NORMAL_SEPARATOR); self->model_->AddSeparator(ui::NORMAL_SEPARATOR);
else else
self->model_->InsertSeparatorAt(index, ui::NORMAL_SEPARATOR); self->model_->InsertSeparatorAt(index, ui::NORMAL_SEPARATOR);
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Menu::InsertSubMenu(const v8::Arguments &args) { void Menu::InsertSubMenu(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_MEMNU_AND_CHECK; UNWRAP_MEMNU_AND_CHECK;
int index, command_id; int index, command_id;
@ -215,12 +206,10 @@ v8::Handle<v8::Value> Menu::InsertSubMenu(const v8::Arguments &args) {
else else
self->model_->InsertSubMenuAt( self->model_->InsertSubMenuAt(
index, command_id, label, submenu->model_.get()); index, command_id, label, submenu->model_.get());
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Menu::SetIcon(const v8::Arguments &args) { void Menu::SetIcon(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_MEMNU_AND_CHECK; UNWRAP_MEMNU_AND_CHECK;
int index; int index;
@ -229,12 +218,10 @@ v8::Handle<v8::Value> Menu::SetIcon(const v8::Arguments &args) {
return node::ThrowTypeError("Bad argument"); return node::ThrowTypeError("Bad argument");
// FIXME use webkit_glue's image decoder here. // FIXME use webkit_glue's image decoder here.
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Menu::SetSublabel(const v8::Arguments &args) { void Menu::SetSublabel(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_MEMNU_AND_CHECK; UNWRAP_MEMNU_AND_CHECK;
int index; int index;
@ -243,74 +230,72 @@ v8::Handle<v8::Value> Menu::SetSublabel(const v8::Arguments &args) {
return node::ThrowTypeError("Bad argument"); return node::ThrowTypeError("Bad argument");
self->model_->SetSublabel(index, label); self->model_->SetSublabel(index, label);
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Menu::Clear(const v8::Arguments &args) { void Menu::Clear(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_MEMNU_AND_CHECK; UNWRAP_MEMNU_AND_CHECK;
self->model_->Clear(); self->model_->Clear();
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Menu::GetIndexOfCommandId(const v8::Arguments &args) { void Menu::GetIndexOfCommandId(
const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_MEMNU_AND_CHECK; UNWRAP_MEMNU_AND_CHECK;
int index = args[0]->IntegerValue(); int index = FromV8Value(args[0]);
return v8::Integer::New(self->model_->GetIndexOfCommandId(index)); args.GetReturnValue().Set(self->model_->GetIndexOfCommandId(index));
} }
// static // static
v8::Handle<v8::Value> Menu::GetItemCount(const v8::Arguments &args) { void Menu::GetItemCount(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_MEMNU_AND_CHECK; UNWRAP_MEMNU_AND_CHECK;
return v8::Integer::New(self->model_->GetItemCount()); args.GetReturnValue().Set(self->model_->GetItemCount());
} }
// static // static
v8::Handle<v8::Value> Menu::GetCommandIdAt(const v8::Arguments &args) { void Menu::GetCommandIdAt(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_MEMNU_AND_CHECK; UNWRAP_MEMNU_AND_CHECK;
int index = args[0]->IntegerValue(); int index = FromV8Value(args[0]);
return v8::Integer::New(self->model_->GetCommandIdAt(index)); args.GetReturnValue().Set(self->model_->GetCommandIdAt(index));
} }
// static // static
v8::Handle<v8::Value> Menu::GetLabelAt(const v8::Arguments &args) { void Menu::GetLabelAt(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_MEMNU_AND_CHECK; UNWRAP_MEMNU_AND_CHECK;
int index = args[0]->IntegerValue(); int index = FromV8Value(args[0]);
return ToV8Value(self->model_->GetLabelAt(index)); args.GetReturnValue().Set(ToV8Value(self->model_->GetLabelAt(index)));
} }
// static // static
v8::Handle<v8::Value> Menu::GetSublabelAt(const v8::Arguments &args) { void Menu::GetSublabelAt(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_MEMNU_AND_CHECK; UNWRAP_MEMNU_AND_CHECK;
int index = args[0]->IntegerValue(); int index = FromV8Value(args[0]);
return ToV8Value(self->model_->GetSublabelAt(index)); args.GetReturnValue().Set(ToV8Value(self->model_->GetSublabelAt(index)));
} }
// static // static
v8::Handle<v8::Value> Menu::IsItemCheckedAt(const v8::Arguments &args) { void Menu::IsItemCheckedAt(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_MEMNU_AND_CHECK; UNWRAP_MEMNU_AND_CHECK;
int index = args[0]->IntegerValue(); int index = FromV8Value(args[0]);
return v8::Boolean::New(self->model_->IsItemCheckedAt(index)); args.GetReturnValue().Set(self->model_->IsItemCheckedAt(index));
} }
// static // static
v8::Handle<v8::Value> Menu::IsEnabledAt(const v8::Arguments &args) { void Menu::IsEnabledAt(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_MEMNU_AND_CHECK; UNWRAP_MEMNU_AND_CHECK;
return v8::Boolean::New(self->model_->IsEnabledAt(args[0]->IntegerValue())); int index = FromV8Value(args[0]);
args.GetReturnValue().Set(self->model_->IsEnabledAt(index));
} }
// static // static
v8::Handle<v8::Value> Menu::IsVisibleAt(const v8::Arguments &args) { void Menu::IsVisibleAt(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_MEMNU_AND_CHECK; UNWRAP_MEMNU_AND_CHECK;
return v8::Boolean::New(self->model_->IsVisibleAt(args[0]->IntegerValue())); int index = FromV8Value(args[0]);
args.GetReturnValue().Set(self->model_->IsVisibleAt(index));
} }
// static // static
v8::Handle<v8::Value> Menu::Popup(const v8::Arguments &args) { void Menu::Popup(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_MEMNU_AND_CHECK; UNWRAP_MEMNU_AND_CHECK;
atom::NativeWindow* window; atom::NativeWindow* window;
@ -318,12 +303,11 @@ v8::Handle<v8::Value> Menu::Popup(const v8::Arguments &args) {
return node::ThrowTypeError("Bad argument"); return node::ThrowTypeError("Bad argument");
self->Popup(window); self->Popup(window);
return v8::Undefined();
} }
// static // static
void Menu::Initialize(v8::Handle<v8::Object> target) { void Menu::Initialize(v8::Handle<v8::Object> target) {
v8::HandleScope scope; v8::HandleScope handle_scope(node_isolate);
v8::Local<v8::FunctionTemplate> t(v8::FunctionTemplate::New(Menu::New)); v8::Local<v8::FunctionTemplate> t(v8::FunctionTemplate::New(Menu::New));
t->InstanceTemplate()->SetInternalFieldCount(1); t->InstanceTemplate()->SetInternalFieldCount(1);

View file

@ -44,36 +44,38 @@ class Menu : public EventEmitter,
scoped_ptr<ui::SimpleMenuModel> model_; scoped_ptr<ui::SimpleMenuModel> model_;
private: private:
static v8::Handle<v8::Value> New(const v8::Arguments &args); static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> InsertItem(const v8::Arguments &args); static void InsertItem(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> InsertCheckItem(const v8::Arguments &args); static void InsertCheckItem(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> InsertRadioItem(const v8::Arguments &args); static void InsertRadioItem(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> InsertSeparator(const v8::Arguments &args); static void InsertSeparator(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> InsertSubMenu(const v8::Arguments &args); static void InsertSubMenu(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> SetIcon(const v8::Arguments &args); static void SetIcon(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> SetSublabel(const v8::Arguments &args); static void SetSublabel(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> Clear(const v8::Arguments &args); static void Clear(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> GetIndexOfCommandId(const v8::Arguments &args); static void GetIndexOfCommandId(
static v8::Handle<v8::Value> GetItemCount(const v8::Arguments &args); const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> GetCommandIdAt(const v8::Arguments &args); static void GetItemCount(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> GetLabelAt(const v8::Arguments &args); static void GetCommandIdAt(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> GetSublabelAt(const v8::Arguments &args); static void GetLabelAt(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> IsItemCheckedAt(const v8::Arguments &args); static void GetSublabelAt(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> IsEnabledAt(const v8::Arguments &args); static void IsItemCheckedAt(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> IsVisibleAt(const v8::Arguments &args); static void IsEnabledAt(const v8::FunctionCallbackInfo<v8::Value>& args);
static void IsVisibleAt(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> Popup(const v8::Arguments &args); static void Popup(const v8::FunctionCallbackInfo<v8::Value>& args);
#if defined(OS_WIN) #if defined(OS_WIN)
static v8::Handle<v8::Value> AttachToWindow(const v8::Arguments &args); static void AttachToWindow(const v8::FunctionCallbackInfo<v8::Value>& args);
#elif defined(OS_MACOSX) #elif defined(OS_MACOSX)
static v8::Handle<v8::Value> SetApplicationMenu(const v8::Arguments &args); static void SetApplicationMenu(
static v8::Handle<v8::Value> SendActionToFirstResponder( const v8::FunctionCallbackInfo<v8::Value>& args);
const v8::Arguments &args); static void SendActionToFirstResponder(
const v8::FunctionCallbackInfo<v8::Value>& args);
#endif #endif
DISALLOW_COPY_AND_ASSIGN(Menu); DISALLOW_COPY_AND_ASSIGN(Menu);

View file

@ -21,7 +21,7 @@ class MenuMac : public Menu {
protected: protected:
virtual void Popup(NativeWindow* window) OVERRIDE; virtual void Popup(NativeWindow* window) OVERRIDE;
scoped_nsobject<AtomMenuController> menu_controller_; base::scoped_nsobject<AtomMenuController> menu_controller_;
private: private:
friend class Menu; friend class Menu;

View file

@ -4,11 +4,12 @@
#import "browser/api/atom_api_menu_mac.h" #import "browser/api/atom_api_menu_mac.h"
#include "base/message_loop.h"
#include "base/mac/scoped_sending_event.h" #include "base/mac/scoped_sending_event.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/sys_string_conversions.h" #include "base/strings/sys_string_conversions.h"
#include "browser/native_window.h" #include "browser/native_window.h"
#include "common/v8_conversions.h" #include "common/v8/node_common.h"
#include "common/v8/native_type_conversions.h"
#include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_view.h" #include "content/public/browser/web_contents_view.h"
@ -24,7 +25,7 @@ MenuMac::~MenuMac() {
} }
void MenuMac::Popup(NativeWindow* native_window) { void MenuMac::Popup(NativeWindow* native_window) {
scoped_nsobject<AtomMenuController> menu_controller( base::scoped_nsobject<AtomMenuController> menu_controller(
[[AtomMenuController alloc] initWithModel:model_.get()]); [[AtomMenuController alloc] initWithModel:model_.get()]);
NSWindow* window = native_window->GetNativeWindow(); NSWindow* window = native_window->GetNativeWindow();
@ -46,7 +47,8 @@ void MenuMac::Popup(NativeWindow* native_window) {
{ {
// Make sure events can be pumped while the menu is up. // Make sure events can be pumped while the menu is up.
MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current()); base::MessageLoop::ScopedNestableTaskAllower allow(
base::MessageLoop::current());
// One of the events that could be pumped is |window.close()|. // One of the events that could be pumped is |window.close()|.
// User-initiated event-tracking loops protect against this by // User-initiated event-tracking loops protect against this by
@ -71,8 +73,8 @@ void MenuMac::SendActionToFirstResponder(const std::string& action) {
} }
// static // static
v8::Handle<v8::Value> Menu::SetApplicationMenu(const v8::Arguments &args) { void Menu::SetApplicationMenu(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope; v8::HandleScope handle_scope(args.GetIsolate());
if (!args[0]->IsObject()) if (!args[0]->IsObject())
return node::ThrowTypeError("Bad argument"); return node::ThrowTypeError("Bad argument");
@ -81,28 +83,24 @@ v8::Handle<v8::Value> Menu::SetApplicationMenu(const v8::Arguments &args) {
if (!menu) if (!menu)
return node::ThrowError("Menu is destroyed"); return node::ThrowError("Menu is destroyed");
scoped_nsobject<AtomMenuController> menu_controller( base::scoped_nsobject<AtomMenuController> menu_controller(
[[AtomMenuController alloc] initWithModel:menu->model_.get()]); [[AtomMenuController alloc] initWithModel:menu->model_.get()]);
[NSApp setMainMenu:[menu_controller menu]]; [NSApp setMainMenu:[menu_controller menu]];
// Ensure the menu_controller_ is destroyed after main menu is set. // Ensure the menu_controller_ is destroyed after main menu is set.
menu_controller.swap(menu->menu_controller_); menu_controller.swap(menu->menu_controller_);
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Menu::SendActionToFirstResponder( void Menu::SendActionToFirstResponder(
const v8::Arguments &args) { const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope; v8::HandleScope handle_scope(args.GetIsolate());
std::string action; std::string action;
if (!FromV8Arguments(args, &action)) if (!FromV8Arguments(args, &action))
return node::ThrowTypeError("Bad argument"); return node::ThrowTypeError("Bad argument");
MenuMac::SendActionToFirstResponder(action); MenuMac::SendActionToFirstResponder(action);
return v8::Undefined();
} }
// static // static

View file

@ -6,10 +6,12 @@
#include "browser/native_window_win.h" #include "browser/native_window_win.h"
#include "browser/ui/win/menu_2.h" #include "browser/ui/win/menu_2.h"
#include "common/v8_conversions.h" #include "common/v8/native_type_conversions.h"
#include "ui/gfx/point.h" #include "ui/gfx/point.h"
#include "ui/gfx/screen.h" #include "ui/gfx/screen.h"
#include "common/v8/node_common.h"
namespace atom { namespace atom {
namespace api { namespace api {
@ -28,8 +30,8 @@ void MenuWin::Popup(NativeWindow* native_window) {
} }
// static // static
v8::Handle<v8::Value> Menu::AttachToWindow(const v8::Arguments& args) { void Menu::AttachToWindow(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope; v8::HandleScope handle_scope(args.GetIsolate());
Menu* self = ObjectWrap::Unwrap<Menu>(args.This()); Menu* self = ObjectWrap::Unwrap<Menu>(args.This());
if (self == NULL) if (self == NULL)
@ -40,8 +42,6 @@ v8::Handle<v8::Value> Menu::AttachToWindow(const v8::Arguments& args) {
return node::ThrowTypeError("Bad argument"); return node::ThrowTypeError("Bad argument");
static_cast<NativeWindowWin*>(native_window)->SetMenu(self->model_.get()); static_cast<NativeWindowWin*>(native_window)->SetMenu(self->model_.get());
return v8::Undefined();
} }
// static // static

View file

@ -5,6 +5,9 @@
#include "browser/api/atom_api_power_monitor.h" #include "browser/api/atom_api_power_monitor.h"
#include "base/power_monitor/power_monitor.h" #include "base/power_monitor/power_monitor.h"
#include "base/power_monitor/power_monitor_device_source.h"
#include "common/v8/node_common.h"
namespace atom { namespace atom {
@ -35,20 +38,22 @@ void PowerMonitor::OnResume() {
} }
// static // static
v8::Handle<v8::Value> PowerMonitor::New(const v8::Arguments& args) { void PowerMonitor::New(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope; v8::HandleScope handle_scope(args.GetIsolate());
if (!args.IsConstructCall()) if (!args.IsConstructCall())
return node::ThrowError("Require constructor call"); return node::ThrowError("Require constructor call");
new PowerMonitor(args.This()); new PowerMonitor(args.This());
return args.This();
} }
// static // static
void PowerMonitor::Initialize(v8::Handle<v8::Object> target) { void PowerMonitor::Initialize(v8::Handle<v8::Object> target) {
v8::HandleScope scope; v8::HandleScope handle_scope(node_isolate);
#if defined(OS_MACOSX)
base::PowerMonitorDeviceSource::AllocateSystemIOPorts();
#endif
v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New( v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(
PowerMonitor::New); PowerMonitor::New);

View file

@ -29,7 +29,7 @@ class PowerMonitor : public EventEmitter,
virtual void OnResume() OVERRIDE; virtual void OnResume() OVERRIDE;
private: private:
static v8::Handle<v8::Value> New(const v8::Arguments &args); static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
DISALLOW_COPY_AND_ASSIGN(PowerMonitor); DISALLOW_COPY_AND_ASSIGN(PowerMonitor);
}; };

View file

@ -9,11 +9,11 @@
#include "browser/net/adapter_request_job.h" #include "browser/net/adapter_request_job.h"
#include "browser/net/atom_url_request_context_getter.h" #include "browser/net/atom_url_request_context_getter.h"
#include "browser/net/atom_url_request_job_factory.h" #include "browser/net/atom_url_request_job_factory.h"
#include "common/v8_conversions.h" #include "common/v8/native_type_conversions.h"
#include "content/public/browser/browser_thread.h" #include "content/public/browser/browser_thread.h"
#include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context.h"
#include "vendor/node/src/node.h"
#include "vendor/node/src/node_internals.h" #include "common/v8/node_common.h"
namespace atom { namespace atom {
@ -24,10 +24,10 @@ typedef net::URLRequestJobFactory::ProtocolHandler ProtocolHandler;
namespace { namespace {
// The protocol module object. // The protocol module object.
v8::Persistent<v8::Object> g_protocol_object; ScopedPersistent<v8::Object> g_protocol_object;
// Registered protocol handlers. // Registered protocol handlers.
typedef std::map<std::string, v8::Persistent<v8::Function>> HandlersMap; typedef std::map<std::string, RefCountedV8Function> HandlersMap;
static HandlersMap g_handlers; static HandlersMap g_handlers;
static const char* kEarlyUseProtocolError = "This method can only be used" static const char* kEarlyUseProtocolError = "This method can only be used"
@ -35,25 +35,23 @@ static const char* kEarlyUseProtocolError = "This method can only be used"
// Emit an event for the protocol module. // Emit an event for the protocol module.
void EmitEventInUI(const std::string& event, const std::string& parameter) { void EmitEventInUI(const std::string& event, const std::string& parameter) {
v8::HandleScope scope; v8::HandleScope handle_scope(node_isolate);
v8::Handle<v8::Value> argv[] = { v8::Handle<v8::Value> argv[] = {
ToV8Value(event), ToV8Value(event),
ToV8Value(parameter), ToV8Value(parameter),
}; };
node::MakeCallback(g_protocol_object, "emit", arraysize(argv), argv); node::MakeCallback(g_protocol_object.NewHandle(node_isolate),
"emit", 2, argv);
} }
// Convert the URLRequest object to V8 object. // Convert the URLRequest object to V8 object.
v8::Handle<v8::Object> ConvertURLRequestToV8Object( v8::Handle<v8::Object> ConvertURLRequestToV8Object(
const net::URLRequest* request) { const net::URLRequest* request) {
v8::Local<v8::Object> obj = v8::Object::New(); v8::Local<v8::Object> obj = v8::Object::New();
obj->Set(v8::String::New("method"), obj->Set(ToV8Value("method"), ToV8Value(request->method()));
v8::String::New(request->method().c_str())); obj->Set(ToV8Value("url"), ToV8Value(request->url().spec()));
obj->Set(v8::String::New("url"), obj->Set(ToV8Value("referrer"), ToV8Value(request->referrer()));
v8::String::New(request->url().spec().c_str()));
obj->Set(v8::String::New("referrer"),
v8::String::New(request->referrer().c_str()));
return obj; return obj;
} }
@ -74,13 +72,15 @@ class CustomProtocolRequestJob : public AdapterRequestJob {
virtual void GetJobTypeInUI() OVERRIDE { virtual void GetJobTypeInUI() OVERRIDE {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
v8::HandleScope handle_scope(node_isolate);
// Call the JS handler. // Call the JS handler.
v8::HandleScope scope;
v8::Handle<v8::Value> argv[] = { v8::Handle<v8::Value> argv[] = {
ConvertURLRequestToV8Object(request()), ConvertURLRequestToV8Object(request()),
}; };
v8::Handle<v8::Value> result = g_handlers[request()->url().scheme()]->Call( RefCountedV8Function callback = g_handlers[request()->url().scheme()];
v8::Context::GetCurrent()->Global(), arraysize(argv), argv); v8::Handle<v8::Value> result = callback->NewHandle(node_isolate)->Call(
v8::Context::GetCurrent()->Global(), 1, argv);
// Determine the type of the job we are going to create. // Determine the type of the job we are going to create.
if (result->IsString()) { if (result->IsString()) {
@ -180,14 +180,15 @@ class CustomProtocolHandler : public ProtocolHandler {
} // namespace } // namespace
// static // static
v8::Handle<v8::Value> Protocol::RegisterProtocol(const v8::Arguments& args) { void Protocol::RegisterProtocol(
const v8::FunctionCallbackInfo<v8::Value>& args) {
std::string scheme; std::string scheme;
v8::Persistent<v8::Function> callback; RefCountedV8Function callback;
if (!FromV8Arguments(args, &scheme, &callback)) if (!FromV8Arguments(args, &scheme, &callback))
return node::ThrowTypeError("Bad argument"); return node::ThrowTypeError("Bad argument");
if (g_handlers.find(scheme) != g_handlers.end() || if (g_handlers.find(scheme) != g_handlers.end() ||
net::URLRequest::IsHandledProtocol(scheme)) GetRequestJobFactory()->IsHandledProtocol(scheme))
return node::ThrowError("The scheme is already registered"); return node::ThrowError("The scheme is already registered");
if (AtomBrowserContext::Get()->url_request_context_getter() == NULL) if (AtomBrowserContext::Get()->url_request_context_getter() == NULL)
@ -199,12 +200,11 @@ v8::Handle<v8::Value> Protocol::RegisterProtocol(const v8::Arguments& args) {
content::BrowserThread::PostTask(content::BrowserThread::IO, content::BrowserThread::PostTask(content::BrowserThread::IO,
FROM_HERE, FROM_HERE,
base::Bind(&RegisterProtocolInIO, scheme)); base::Bind(&RegisterProtocolInIO, scheme));
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Protocol::UnregisterProtocol(const v8::Arguments& args) { void Protocol::UnregisterProtocol(
const v8::FunctionCallbackInfo<v8::Value>& args) {
std::string scheme; std::string scheme;
if (!FromV8Arguments(args, &scheme)) if (!FromV8Arguments(args, &scheme))
return node::ThrowTypeError("Bad argument"); return node::ThrowTypeError("Bad argument");
@ -221,19 +221,23 @@ v8::Handle<v8::Value> Protocol::UnregisterProtocol(const v8::Arguments& args) {
content::BrowserThread::PostTask(content::BrowserThread::IO, content::BrowserThread::PostTask(content::BrowserThread::IO,
FROM_HERE, FROM_HERE,
base::Bind(&UnregisterProtocolInIO, scheme)); base::Bind(&UnregisterProtocolInIO, scheme));
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Protocol::IsHandledProtocol(const v8::Arguments& args) { void Protocol::IsHandledProtocol(
return ToV8Value(net::URLRequest::IsHandledProtocol(FromV8Value(args[0]))); const v8::FunctionCallbackInfo<v8::Value>& args) {
}
// static
v8::Handle<v8::Value> Protocol::InterceptProtocol(const v8::Arguments& args) {
std::string scheme; std::string scheme;
v8::Persistent<v8::Function> callback; if (!FromV8Arguments(args, &scheme))
return node::ThrowTypeError("Bad argument");
args.GetReturnValue().Set(GetRequestJobFactory()->IsHandledProtocol(scheme));
}
// static
void Protocol::InterceptProtocol(
const v8::FunctionCallbackInfo<v8::Value>& args) {
std::string scheme;
RefCountedV8Function callback;
if (!FromV8Arguments(args, &scheme, &callback)) if (!FromV8Arguments(args, &scheme, &callback))
return node::ThrowTypeError("Bad argument"); return node::ThrowTypeError("Bad argument");
@ -252,11 +256,11 @@ v8::Handle<v8::Value> Protocol::InterceptProtocol(const v8::Arguments& args) {
content::BrowserThread::PostTask(content::BrowserThread::IO, content::BrowserThread::PostTask(content::BrowserThread::IO,
FROM_HERE, FROM_HERE,
base::Bind(&InterceptProtocolInIO, scheme)); base::Bind(&InterceptProtocolInIO, scheme));
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Protocol::UninterceptProtocol(const v8::Arguments& args) { void Protocol::UninterceptProtocol(
const v8::FunctionCallbackInfo<v8::Value>& args) {
std::string scheme; std::string scheme;
if (!FromV8Arguments(args, &scheme)) if (!FromV8Arguments(args, &scheme))
return node::ThrowTypeError("Bad argument"); return node::ThrowTypeError("Bad argument");
@ -274,7 +278,6 @@ v8::Handle<v8::Value> Protocol::UninterceptProtocol(const v8::Arguments& args) {
FROM_HERE, FROM_HERE,
base::Bind(&UninterceptProtocolInIO, base::Bind(&UninterceptProtocolInIO,
scheme)); scheme));
return v8::Undefined();
} }
// static // static
@ -361,14 +364,13 @@ void Protocol::UninterceptProtocolInIO(const std::string& scheme) {
// static // static
void Protocol::Initialize(v8::Handle<v8::Object> target) { void Protocol::Initialize(v8::Handle<v8::Object> target) {
// Remember the protocol object, used for emitting event later. // Remember the protocol object, used for emitting event later.
g_protocol_object = v8::Persistent<v8::Object>::New( g_protocol_object.reset(target);
node::node_isolate, target);
node::SetMethod(target, "registerProtocol", RegisterProtocol); NODE_SET_METHOD(target, "registerProtocol", RegisterProtocol);
node::SetMethod(target, "unregisterProtocol", UnregisterProtocol); NODE_SET_METHOD(target, "unregisterProtocol", UnregisterProtocol);
node::SetMethod(target, "isHandledProtocol", IsHandledProtocol); NODE_SET_METHOD(target, "isHandledProtocol", IsHandledProtocol);
node::SetMethod(target, "interceptProtocol", InterceptProtocol); NODE_SET_METHOD(target, "interceptProtocol", InterceptProtocol);
node::SetMethod(target, "uninterceptProtocol", UninterceptProtocol); NODE_SET_METHOD(target, "uninterceptProtocol", UninterceptProtocol);
} }
} // namespace api } // namespace api

View file

@ -20,12 +20,16 @@ class Protocol {
static void Initialize(v8::Handle<v8::Object> target); static void Initialize(v8::Handle<v8::Object> target);
private: private:
static v8::Handle<v8::Value> RegisterProtocol(const v8::Arguments& args); static void RegisterProtocol(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> UnregisterProtocol(const v8::Arguments& args); static void UnregisterProtocol(
static v8::Handle<v8::Value> IsHandledProtocol(const v8::Arguments& args); const v8::FunctionCallbackInfo<v8::Value>& args);
static void IsHandledProtocol(
const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> InterceptProtocol(const v8::Arguments& args); static void InterceptProtocol(
static v8::Handle<v8::Value> UninterceptProtocol(const v8::Arguments& args); const v8::FunctionCallbackInfo<v8::Value>& args);
static void UninterceptProtocol(
const v8::FunctionCallbackInfo<v8::Value>& args);
static void RegisterProtocolInIO(const std::string& scheme); static void RegisterProtocolInIO(const std::string& scheme);
static void UnregisterProtocolInIO(const std::string& scheme); static void UnregisterProtocolInIO(const std::string& scheme);

View file

@ -4,14 +4,16 @@
#include "browser/api/atom_api_window.h" #include "browser/api/atom_api_window.h"
#include "base/process_util.h" #include "base/process/kill.h"
#include "browser/native_window.h" #include "browser/native_window.h"
#include "common/v8_conversions.h" #include "common/v8/native_type_conversions.h"
#include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_entry.h"
#include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents.h"
#include "content/public/browser/render_process_host.h" #include "content/public/browser/render_process_host.h"
#include "ui/gfx/point.h" #include "ui/gfx/point.h"
#include "ui/gfx/size.h" #include "ui/gfx/size.h"
#include "common/v8/node_common.h"
#include "vendor/node/src/node_buffer.h" #include "vendor/node/src/node_buffer.h"
using content::NavigationController; using content::NavigationController;
@ -87,23 +89,20 @@ void Window::OnRendererCrashed() {
Emit("crashed"); Emit("crashed");
} }
void Window::OnCapturePageDone(v8::Persistent<v8::Function> callback, void Window::OnCapturePageDone(const RefCountedV8Function& callback,
const std::vector<unsigned char>& data) { const std::vector<unsigned char>& data) {
v8::HandleScope scope; v8::HandleScope handle_scope(node_isolate);
// TODO(zcbenz): Use new Buffer API when we updated to node v0.12.x. v8::Local<v8::Value> buffer = node::Buffer::New(
node::Buffer* buffer = node::Buffer::New(
reinterpret_cast<const char*>(data.data()), reinterpret_cast<const char*>(data.data()),
data.size()); data.size());
callback->NewHandle(node_isolate)->Call(
v8::Handle<v8::Value> arg = buffer->handle_; v8::Context::GetCurrent()->Global(), 1, &buffer);
callback->Call(v8::Context::GetCurrent()->Global(), 1, &arg);
callback.Dispose(v8::Isolate::GetCurrent());
} }
// static // static
v8::Handle<v8::Value> Window::New(const v8::Arguments &args) { void Window::New(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope; v8::HandleScope handle_scope(args.GetIsolate());
if (!args.IsConstructCall()) if (!args.IsConstructCall())
return node::ThrowError("Require constructor call"); return node::ThrowError("Require constructor call");
@ -119,12 +118,10 @@ v8::Handle<v8::Value> Window::New(const v8::Arguments &args) {
// Give js code a chance to do initialization. // Give js code a chance to do initialization.
node::MakeCallback(args.This(), "_init", 0, NULL); node::MakeCallback(args.This(), "_init", 0, NULL);
return args.This();
} }
// static // static
v8::Handle<v8::Value> Window::Destroy(const v8::Arguments &args) { void Window::Destroy(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
base::ProcessHandle handle = self->window_->GetRenderProcessHandle(); base::ProcessHandle handle = self->window_->GetRenderProcessHandle();
@ -135,96 +132,70 @@ v8::Handle<v8::Value> Window::Destroy(const v8::Arguments &args) {
if (!base::WaitForSingleProcess(handle, if (!base::WaitForSingleProcess(handle,
base::TimeDelta::FromMilliseconds(500))) base::TimeDelta::FromMilliseconds(500)))
base::KillProcess(handle, 0, true); base::KillProcess(handle, 0, true);
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Window::Close(const v8::Arguments &args) { void Window::Close(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
self->window_->Close(); self->window_->Close();
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Window::Focus(const v8::Arguments &args) { void Window::Focus(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
self->window_->Focus(args[0]->IsBoolean() ? args[0]->BooleanValue(): true); self->window_->Focus(args[0]->IsBoolean() ? args[0]->BooleanValue(): true);
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Window::IsFocused(const v8::Arguments &args) { void Window::IsFocused(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
return ToV8Value(self->window_->IsFocused()); args.GetReturnValue().Set(self->window_->IsFocused());
} }
// static // static
v8::Handle<v8::Value> Window::Show(const v8::Arguments &args) { void Window::Show(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
self->window_->Show(); self->window_->Show();
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Window::Hide(const v8::Arguments &args) { void Window::Hide(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
self->window_->Hide(); self->window_->Hide();
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Window::IsVisible(const v8::Arguments& args) { void Window::IsVisible(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
return ToV8Value(self->window_->IsVisible()); return args.GetReturnValue().Set(self->window_->IsVisible());
} }
// static // static
v8::Handle<v8::Value> Window::Maximize(const v8::Arguments &args) { void Window::Maximize(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
self->window_->Maximize(); self->window_->Maximize();
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Window::Unmaximize(const v8::Arguments &args) { void Window::Unmaximize(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
self->window_->Unmaximize(); self->window_->Unmaximize();
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Window::Minimize(const v8::Arguments &args) { void Window::Minimize(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
self->window_->Minimize(); self->window_->Minimize();
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Window::Restore(const v8::Arguments &args) { void Window::Restore(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
self->window_->Restore(); self->window_->Restore();
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Window::SetFullscreen(const v8::Arguments &args) { void Window::SetFullscreen(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
bool fs; bool fs;
@ -232,18 +203,16 @@ v8::Handle<v8::Value> Window::SetFullscreen(const v8::Arguments &args) {
return node::ThrowTypeError("Bad argument"); return node::ThrowTypeError("Bad argument");
self->window_->SetFullscreen(fs); self->window_->SetFullscreen(fs);
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Window::IsFullscreen(const v8::Arguments &args) { void Window::IsFullscreen(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
args.GetReturnValue().Set(self->window_->IsFullscreen());
return ToV8Value(self->window_->IsFullscreen());
} }
// static // static
v8::Handle<v8::Value> Window::SetSize(const v8::Arguments &args) { void Window::SetSize(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
int width, height; int width, height;
@ -251,11 +220,10 @@ v8::Handle<v8::Value> Window::SetSize(const v8::Arguments &args) {
return node::ThrowTypeError("Bad argument"); return node::ThrowTypeError("Bad argument");
self->window_->SetSize(gfx::Size(width, height)); self->window_->SetSize(gfx::Size(width, height));
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Window::GetSize(const v8::Arguments &args) { void Window::GetSize(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
gfx::Size size = self->window_->GetSize(); gfx::Size size = self->window_->GetSize();
@ -263,11 +231,11 @@ v8::Handle<v8::Value> Window::GetSize(const v8::Arguments &args) {
ret->Set(0, ToV8Value(size.width())); ret->Set(0, ToV8Value(size.width()));
ret->Set(1, ToV8Value(size.height())); ret->Set(1, ToV8Value(size.height()));
return ret; args.GetReturnValue().Set(ret);
} }
// static // static
v8::Handle<v8::Value> Window::SetMinimumSize(const v8::Arguments &args) { void Window::SetMinimumSize(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
int width, height; int width, height;
@ -275,11 +243,10 @@ v8::Handle<v8::Value> Window::SetMinimumSize(const v8::Arguments &args) {
return node::ThrowTypeError("Bad argument"); return node::ThrowTypeError("Bad argument");
self->window_->SetMinimumSize(gfx::Size(width, height)); self->window_->SetMinimumSize(gfx::Size(width, height));
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Window::GetMinimumSize(const v8::Arguments &args) { void Window::GetMinimumSize(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
gfx::Size size = self->window_->GetMinimumSize(); gfx::Size size = self->window_->GetMinimumSize();
@ -287,24 +254,22 @@ v8::Handle<v8::Value> Window::GetMinimumSize(const v8::Arguments &args) {
ret->Set(0, ToV8Value(size.width())); ret->Set(0, ToV8Value(size.width()));
ret->Set(1, ToV8Value(size.height())); ret->Set(1, ToV8Value(size.height()));
return ret; args.GetReturnValue().Set(ret);
} }
// static // static
v8::Handle<v8::Value> Window::SetMaximumSize(const v8::Arguments &args) { void Window::SetMaximumSize(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
int width, height; int width, height;
if (!FromV8Arguments(args, &width, &height)) if (!FromV8Arguments(args, &width, &height))
return node::ThrowTypeError("Bad argument"); return node::ThrowTypeError("Bad argument");
self->window_->SetMaximumSize(gfx::Size(width, height)); self->window_->SetMaximumSize(gfx::Size(width, height));
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Window::GetMaximumSize(const v8::Arguments &args) { void Window::GetMaximumSize(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
gfx::Size size = self->window_->GetMaximumSize(); gfx::Size size = self->window_->GetMaximumSize();
@ -312,11 +277,11 @@ v8::Handle<v8::Value> Window::GetMaximumSize(const v8::Arguments &args) {
ret->Set(0, ToV8Value(size.width())); ret->Set(0, ToV8Value(size.width()));
ret->Set(1, ToV8Value(size.height())); ret->Set(1, ToV8Value(size.height()));
return ret; args.GetReturnValue().Set(ret);
} }
// static // static
v8::Handle<v8::Value> Window::SetResizable(const v8::Arguments &args) { void Window::SetResizable(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
bool resizable; bool resizable;
@ -324,18 +289,16 @@ v8::Handle<v8::Value> Window::SetResizable(const v8::Arguments &args) {
return node::ThrowTypeError("Bad argument"); return node::ThrowTypeError("Bad argument");
self->window_->SetResizable(resizable); self->window_->SetResizable(resizable);
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Window::IsResizable(const v8::Arguments &args) { void Window::IsResizable(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
args.GetReturnValue().Set(self->window_->IsResizable());
return ToV8Value(self->window_->IsResizable());
} }
// static // static
v8::Handle<v8::Value> Window::SetAlwaysOnTop(const v8::Arguments &args) { void Window::SetAlwaysOnTop(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
bool top; bool top;
@ -343,27 +306,22 @@ v8::Handle<v8::Value> Window::SetAlwaysOnTop(const v8::Arguments &args) {
return node::ThrowTypeError("Bad argument"); return node::ThrowTypeError("Bad argument");
self->window_->SetAlwaysOnTop(top); self->window_->SetAlwaysOnTop(top);
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Window::IsAlwaysOnTop(const v8::Arguments &args) { void Window::IsAlwaysOnTop(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
args.GetReturnValue().Set(self->window_->IsAlwaysOnTop());
return ToV8Value(self->window_->IsAlwaysOnTop());
} }
// static // static
v8::Handle<v8::Value> Window::Center(const v8::Arguments &args) { void Window::Center(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
self->window_->Center(); self->window_->Center();
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Window::SetPosition(const v8::Arguments &args) { void Window::SetPosition(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
int x, y; int x, y;
@ -371,11 +329,10 @@ v8::Handle<v8::Value> Window::SetPosition(const v8::Arguments &args) {
return node::ThrowTypeError("Bad argument"); return node::ThrowTypeError("Bad argument");
self->window_->SetPosition(gfx::Point(x, y)); self->window_->SetPosition(gfx::Point(x, y));
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Window::GetPosition(const v8::Arguments &args) { void Window::GetPosition(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
gfx::Point pos = self->window_->GetPosition(); gfx::Point pos = self->window_->GetPosition();
@ -383,11 +340,11 @@ v8::Handle<v8::Value> Window::GetPosition(const v8::Arguments &args) {
ret->Set(0, ToV8Value(pos.x())); ret->Set(0, ToV8Value(pos.x()));
ret->Set(1, ToV8Value(pos.y())); ret->Set(1, ToV8Value(pos.y()));
return ret; args.GetReturnValue().Set(ret);
} }
// static // static
v8::Handle<v8::Value> Window::SetTitle(const v8::Arguments &args) { void Window::SetTitle(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
std::string title; std::string title;
@ -395,27 +352,23 @@ v8::Handle<v8::Value> Window::SetTitle(const v8::Arguments &args) {
return node::ThrowTypeError("Bad argument"); return node::ThrowTypeError("Bad argument");
self->window_->SetTitle(title); self->window_->SetTitle(title);
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Window::GetTitle(const v8::Arguments &args) { void Window::GetTitle(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
return ToV8Value(self->window_->GetTitle()); args.GetReturnValue().Set(ToV8Value(self->window_->GetTitle()));
} }
// static // static
v8::Handle<v8::Value> Window::FlashFrame(const v8::Arguments &args) { void Window::FlashFrame(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
self->window_->FlashFrame( self->window_->FlashFrame(
args[0]->IsBoolean() ? args[0]->BooleanValue(): true); args[0]->IsBoolean() ? args[0]->BooleanValue(): true);
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Window::SetKiosk(const v8::Arguments &args) { void Window::SetKiosk(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
bool kiosk; bool kiosk;
@ -423,42 +376,34 @@ v8::Handle<v8::Value> Window::SetKiosk(const v8::Arguments &args) {
return node::ThrowTypeError("Bad argument"); return node::ThrowTypeError("Bad argument");
self->window_->SetKiosk(kiosk); self->window_->SetKiosk(kiosk);
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Window::IsKiosk(const v8::Arguments &args) { void Window::IsKiosk(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
args.GetReturnValue().Set(self->window_->IsKiosk());
return ToV8Value(self->window_->IsKiosk());
} }
// static // static
v8::Handle<v8::Value> Window::OpenDevTools(const v8::Arguments &args) { void Window::OpenDevTools(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
self->window_->OpenDevTools(); self->window_->OpenDevTools();
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Window::CloseDevTools(const v8::Arguments &args) { void Window::CloseDevTools(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
self->window_->CloseDevTools(); self->window_->CloseDevTools();
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Window::IsDevToolsOpened(const v8::Arguments& args) { void Window::IsDevToolsOpened(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
return ToV8Value(self->window_->IsDevToolsOpened()); args.GetReturnValue().Set(self->window_->IsDevToolsOpened());
} }
// static // static
v8::Handle<v8::Value> Window::InspectElement(const v8::Arguments& args) { void Window::InspectElement(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
int x, y; int x, y;
@ -466,39 +411,32 @@ v8::Handle<v8::Value> Window::InspectElement(const v8::Arguments& args) {
return node::ThrowTypeError("Bad argument"); return node::ThrowTypeError("Bad argument");
self->window_->InspectElement(x, y); self->window_->InspectElement(x, y);
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Window::FocusOnWebView(const v8::Arguments &args) { void Window::FocusOnWebView(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
self->window_->FocusOnWebView(); self->window_->FocusOnWebView();
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Window::BlurWebView(const v8::Arguments &args) { void Window::BlurWebView(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
self->window_->BlurWebView(); self->window_->BlurWebView();
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Window::IsWebViewFocused(const v8::Arguments& args) { void Window::IsWebViewFocused(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
return ToV8Value(self->window_->IsWebViewFocused()); args.GetReturnValue().Set(self->window_->IsWebViewFocused());
} }
// static // static
v8::Handle<v8::Value> Window::CapturePage(const v8::Arguments& args) { void Window::CapturePage(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
gfx::Rect rect; gfx::Rect rect;
v8::Persistent<v8::Function> callback; RefCountedV8Function callback;
if (!FromV8Arguments(args, &rect, &callback) && if (!FromV8Arguments(args, &rect, &callback) &&
!FromV8Arguments(args, &callback)) !FromV8Arguments(args, &callback))
return node::ThrowTypeError("Bad argument"); return node::ThrowTypeError("Bad argument");
@ -506,64 +444,57 @@ v8::Handle<v8::Value> Window::CapturePage(const v8::Arguments& args) {
self->window_->CapturePage(rect, base::Bind(&Window::OnCapturePageDone, self->window_->CapturePage(rect, base::Bind(&Window::OnCapturePageDone,
base::Unretained(self), base::Unretained(self),
callback)); callback));
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Window::GetPageTitle(const v8::Arguments &args) { void Window::GetPageTitle(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
args.GetReturnValue().Set(ToV8Value(
return ToV8Value(self->window_->GetWebContents()->GetTitle()); self->window_->GetWebContents()->GetTitle()));
} }
// static // static
v8::Handle<v8::Value> Window::IsLoading(const v8::Arguments &args) { void Window::IsLoading(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
args.GetReturnValue().Set(self->window_->GetWebContents()->IsLoading());
return ToV8Value(self->window_->GetWebContents()->IsLoading());
} }
// static // static
v8::Handle<v8::Value> Window::IsWaitingForResponse(const v8::Arguments &args) { void Window::IsWaitingForResponse(
const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
args.GetReturnValue().Set(
return ToV8Value(self->window_->GetWebContents()->IsWaitingForResponse()); self->window_->GetWebContents()->IsWaitingForResponse());
} }
// static // static
v8::Handle<v8::Value> Window::Stop(const v8::Arguments &args) { void Window::Stop(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
self->window_->GetWebContents()->Stop(); self->window_->GetWebContents()->Stop();
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Window::GetRoutingID(const v8::Arguments &args) { void Window::GetRoutingID(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
args.GetReturnValue().Set(self->window_->GetWebContents()->GetRoutingID());
return ToV8Value(self->window_->GetWebContents()->GetRoutingID());
} }
// static // static
v8::Handle<v8::Value> Window::GetProcessID(const v8::Arguments &args) { void Window::GetProcessID(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
return ToV8Value( args.GetReturnValue().Set(
self->window_->GetWebContents()->GetRenderProcessHost()->GetID()); self->window_->GetWebContents()->GetRenderProcessHost()->GetID());
} }
// static // static
v8::Handle<v8::Value> Window::IsCrashed(const v8::Arguments &args) { void Window::IsCrashed(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
args.GetReturnValue().Set(self->window_->GetWebContents()->IsCrashed());
return ToV8Value(self->window_->GetWebContents()->IsCrashed());
} }
// static // static
v8::Handle<v8::Value> Window::LoadURL(const v8::Arguments &args) { void Window::LoadURL(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
GURL url; GURL url;
@ -577,12 +508,10 @@ v8::Handle<v8::Value> Window::LoadURL(const v8::Arguments &args) {
params.transition_type = content::PAGE_TRANSITION_TYPED; params.transition_type = content::PAGE_TRANSITION_TYPED;
params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE; params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE;
controller.LoadURLWithParams(params); controller.LoadURLWithParams(params);
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Window::GetURL(const v8::Arguments &args) { void Window::GetURL(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
NavigationController& controller = NavigationController& controller =
@ -591,31 +520,31 @@ v8::Handle<v8::Value> Window::GetURL(const v8::Arguments &args) {
if (controller.GetActiveEntry()) if (controller.GetActiveEntry())
url = controller.GetActiveEntry()->GetVirtualURL(); url = controller.GetActiveEntry()->GetVirtualURL();
return ToV8Value(url); args.GetReturnValue().Set(ToV8Value(url));
} }
// static // static
v8::Handle<v8::Value> Window::CanGoBack(const v8::Arguments &args) { void Window::CanGoBack(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
NavigationController& controller = NavigationController& controller =
self->window_->GetWebContents()->GetController(); self->window_->GetWebContents()->GetController();
return ToV8Value(controller.CanGoBack()); args.GetReturnValue().Set(controller.CanGoBack());
} }
// static // static
v8::Handle<v8::Value> Window::CanGoForward(const v8::Arguments &args) { void Window::CanGoForward(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
NavigationController& controller = NavigationController& controller =
self->window_->GetWebContents()->GetController(); self->window_->GetWebContents()->GetController();
return ToV8Value(controller.CanGoForward()); args.GetReturnValue().Set(controller.CanGoForward());
} }
// static // static
v8::Handle<v8::Value> Window::CanGoToOffset(const v8::Arguments &args) { void Window::CanGoToOffset(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
int offset; int offset;
@ -625,33 +554,29 @@ v8::Handle<v8::Value> Window::CanGoToOffset(const v8::Arguments &args) {
NavigationController& controller = NavigationController& controller =
self->window_->GetWebContents()->GetController(); self->window_->GetWebContents()->GetController();
return ToV8Value(controller.CanGoToOffset(offset)); args.GetReturnValue().Set(controller.CanGoToOffset(offset));
} }
// static // static
v8::Handle<v8::Value> Window::GoBack(const v8::Arguments &args) { void Window::GoBack(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
NavigationController& controller = NavigationController& controller =
self->window_->GetWebContents()->GetController(); self->window_->GetWebContents()->GetController();
controller.GoBack(); controller.GoBack();
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Window::GoForward(const v8::Arguments &args) { void Window::GoForward(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
NavigationController& controller = NavigationController& controller =
self->window_->GetWebContents()->GetController(); self->window_->GetWebContents()->GetController();
controller.GoForward(); controller.GoForward();
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Window::GoToIndex(const v8::Arguments &args) { void Window::GoToIndex(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
int index; int index;
@ -661,12 +586,10 @@ v8::Handle<v8::Value> Window::GoToIndex(const v8::Arguments &args) {
NavigationController& controller = NavigationController& controller =
self->window_->GetWebContents()->GetController(); self->window_->GetWebContents()->GetController();
controller.GoToIndex(index); controller.GoToIndex(index);
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Window::GoToOffset(const v8::Arguments &args) { void Window::GoToOffset(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
int offset; int offset;
@ -676,36 +599,31 @@ v8::Handle<v8::Value> Window::GoToOffset(const v8::Arguments &args) {
NavigationController& controller = NavigationController& controller =
self->window_->GetWebContents()->GetController(); self->window_->GetWebContents()->GetController();
controller.GoToOffset(offset); controller.GoToOffset(offset);
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Window::Reload(const v8::Arguments &args) { void Window::Reload(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
NavigationController& controller = NavigationController& controller =
self->window_->GetWebContents()->GetController(); self->window_->GetWebContents()->GetController();
controller.Reload(args[0]->IsBoolean() ? args[0]->BooleanValue(): false); controller.Reload(args[0]->IsBoolean() ? args[0]->BooleanValue(): false);
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Window::ReloadIgnoringCache(const v8::Arguments &args) { void Window::ReloadIgnoringCache(
const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK; UNWRAP_WINDOW_AND_CHECK;
NavigationController& controller = NavigationController& controller =
self->window_->GetWebContents()->GetController(); self->window_->GetWebContents()->GetController();
controller.ReloadIgnoringCache( controller.ReloadIgnoringCache(
args[0]->IsBoolean() ? args[0]->BooleanValue(): false); args[0]->IsBoolean() ? args[0]->BooleanValue(): false);
return v8::Undefined();
} }
// static // static
void Window::Initialize(v8::Handle<v8::Object> target) { void Window::Initialize(v8::Handle<v8::Object> target) {
v8::HandleScope scope; v8::HandleScope handle_scope(node_isolate);
v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(Window::New); v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(Window::New);
t->InstanceTemplate()->SetInternalFieldCount(1); t->InstanceTemplate()->SetInternalFieldCount(1);

View file

@ -10,6 +10,7 @@
#include "base/memory/scoped_ptr.h" #include "base/memory/scoped_ptr.h"
#include "browser/api/atom_api_event_emitter.h" #include "browser/api/atom_api_event_emitter.h"
#include "browser/native_window_observer.h" #include "browser/native_window_observer.h"
#include "common/v8/scoped_persistent.h"
namespace base { namespace base {
class DictionaryValue; class DictionaryValue;
@ -47,73 +48,75 @@ class Window : public EventEmitter,
virtual void OnRendererCrashed() OVERRIDE; virtual void OnRendererCrashed() OVERRIDE;
private: private:
static v8::Handle<v8::Value> New(const v8::Arguments &args); static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> Destroy(const v8::Arguments &args); static void Destroy(const v8::FunctionCallbackInfo<v8::Value>& args);
// APIs for NativeWindow. // APIs for NativeWindow.
static v8::Handle<v8::Value> Close(const v8::Arguments &args); static void Close(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> Focus(const v8::Arguments &args); static void Focus(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> IsFocused(const v8::Arguments &args); static void IsFocused(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> Show(const v8::Arguments &args); static void Show(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> Hide(const v8::Arguments &args); static void Hide(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> IsVisible(const v8::Arguments &args); static void IsVisible(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> Maximize(const v8::Arguments &args); static void Maximize(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> Unmaximize(const v8::Arguments &args); static void Unmaximize(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> Minimize(const v8::Arguments &args); static void Minimize(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> Restore(const v8::Arguments &args); static void Restore(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> SetFullscreen(const v8::Arguments &args); static void SetFullscreen(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> IsFullscreen(const v8::Arguments &args); static void IsFullscreen(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> SetSize(const v8::Arguments &args); static void SetSize(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> GetSize(const v8::Arguments &args); static void GetSize(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> SetMinimumSize(const v8::Arguments &args); static void SetMinimumSize(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> GetMinimumSize(const v8::Arguments &args); static void GetMinimumSize(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> SetMaximumSize(const v8::Arguments &args); static void SetMaximumSize(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> GetMaximumSize(const v8::Arguments &args); static void GetMaximumSize(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> SetResizable(const v8::Arguments &args); static void SetResizable(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> IsResizable(const v8::Arguments &args); static void IsResizable(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> SetAlwaysOnTop(const v8::Arguments &args); static void SetAlwaysOnTop(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> IsAlwaysOnTop(const v8::Arguments &args); static void IsAlwaysOnTop(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> Center(const v8::Arguments &args); static void Center(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> SetPosition(const v8::Arguments &args); static void SetPosition(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> GetPosition(const v8::Arguments &args); static void GetPosition(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> SetTitle(const v8::Arguments &args); static void SetTitle(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> GetTitle(const v8::Arguments &args); static void GetTitle(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> FlashFrame(const v8::Arguments &args); static void FlashFrame(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> SetKiosk(const v8::Arguments &args); static void SetKiosk(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> IsKiosk(const v8::Arguments &args); static void IsKiosk(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> OpenDevTools(const v8::Arguments &args); static void OpenDevTools(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> CloseDevTools(const v8::Arguments &args); static void CloseDevTools(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> IsDevToolsOpened(const v8::Arguments &args); static void IsDevToolsOpened(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> InspectElement(const v8::Arguments &args); static void InspectElement(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> FocusOnWebView(const v8::Arguments &args); static void FocusOnWebView(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> BlurWebView(const v8::Arguments &args); static void BlurWebView(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> IsWebViewFocused(const v8::Arguments& args); static void IsWebViewFocused(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> CapturePage(const v8::Arguments& args); static void CapturePage(const v8::FunctionCallbackInfo<v8::Value>& args);
// APIs for WebContents. // APIs for WebContents.
static v8::Handle<v8::Value> GetPageTitle(const v8::Arguments &args); static void GetPageTitle(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> IsLoading(const v8::Arguments &args); static void IsLoading(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> IsWaitingForResponse(const v8::Arguments &args); static void IsWaitingForResponse(
static v8::Handle<v8::Value> Stop(const v8::Arguments &args); const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> GetRoutingID(const v8::Arguments &args); static void Stop(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> GetProcessID(const v8::Arguments &args); static void GetRoutingID(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> IsCrashed(const v8::Arguments &args); static void GetProcessID(const v8::FunctionCallbackInfo<v8::Value>& args);
static void IsCrashed(const v8::FunctionCallbackInfo<v8::Value>& args);
// APIs for NavigationController. // APIs for NavigationController.
static v8::Handle<v8::Value> LoadURL(const v8::Arguments &args); static void LoadURL(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> GetURL(const v8::Arguments &args); static void GetURL(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> CanGoBack(const v8::Arguments &args); static void CanGoBack(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> CanGoForward(const v8::Arguments &args); static void CanGoForward(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> CanGoToOffset(const v8::Arguments &args); static void CanGoToOffset(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> GoBack(const v8::Arguments &args); static void GoBack(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> GoForward(const v8::Arguments &args); static void GoForward(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> GoToIndex(const v8::Arguments &args); static void GoToIndex(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> GoToOffset(const v8::Arguments &args); static void GoToOffset(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> Reload(const v8::Arguments &args); static void Reload(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> ReloadIgnoringCache(const v8::Arguments &args); static void ReloadIgnoringCache(
const v8::FunctionCallbackInfo<v8::Value>& args);
// Called when capturePage is done. // Called when capturePage is done.
void OnCapturePageDone(v8::Persistent<v8::Function> callback, void OnCapturePageDone(const RefCountedV8Function& callback,
const std::vector<unsigned char>& data); const std::vector<unsigned char>& data);
scoped_ptr<NativeWindow> window_; scoped_ptr<NativeWindow> window_;

View file

@ -8,13 +8,10 @@
#include "base/logging.h" #include "base/logging.h"
#include "browser/api/atom_api_event.h" #include "browser/api/atom_api_event.h"
#include "common/v8_conversions.h" #include "common/v8/native_type_conversions.h"
#include "content/public/browser/browser_thread.h" #include "content/public/browser/browser_thread.h"
#include "vendor/node/src/node.h"
#include "vendor/node/src/node_internals.h"
using content::V8ValueConverter; #include "common/v8/node_common.h"
using node::node_isolate;
namespace atom { namespace atom {
@ -24,31 +21,13 @@ AtomBrowserBindings::AtomBrowserBindings() {
AtomBrowserBindings::~AtomBrowserBindings() { AtomBrowserBindings::~AtomBrowserBindings() {
} }
void AtomBrowserBindings::AfterLoad() {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
v8::HandleScope scope;
v8::Handle<v8::Object> global = node::g_context->Global();
v8::Handle<v8::Object> atom =
global->Get(v8::String::New("__atom"))->ToObject();
DCHECK(!atom.IsEmpty());
browser_main_parts_ = v8::Persistent<v8::Object>::New(
node_isolate,
atom->Get(v8::String::New("browserMainParts"))->ToObject());
DCHECK(!browser_main_parts_.IsEmpty());
}
void AtomBrowserBindings::OnRendererMessage(int process_id, void AtomBrowserBindings::OnRendererMessage(int process_id,
int routing_id, int routing_id,
const string16& channel, const string16& channel,
const base::ListValue& args) { const base::ListValue& args) {
v8::HandleScope scope; v8::HandleScope handle_scope(node_isolate);
v8::Handle<v8::Context> context = v8::Context::GetCurrent(); scoped_ptr<V8ValueConverter> converter(new V8ValueConverter);
scoped_ptr<V8ValueConverter> converter(new V8ValueConverterImpl());
// process.emit(channel, 'message', process_id, routing_id); // process.emit(channel, 'message', process_id, routing_id);
std::vector<v8::Handle<v8::Value>> arguments; std::vector<v8::Handle<v8::Value>> arguments;
@ -56,17 +35,20 @@ void AtomBrowserBindings::OnRendererMessage(int process_id,
arguments.push_back(ToV8Value(channel)); arguments.push_back(ToV8Value(channel));
const base::Value* value; const base::Value* value;
if (args.Get(0, &value)) if (args.Get(0, &value))
arguments.push_back(converter->ToV8Value(value, context)); arguments.push_back(converter->ToV8Value(value, global_env->context()));
arguments.push_back(v8::Integer::New(process_id)); arguments.push_back(v8::Integer::New(process_id));
arguments.push_back(v8::Integer::New(routing_id)); arguments.push_back(v8::Integer::New(routing_id));
for (size_t i = 1; i < args.GetSize(); i++) { for (size_t i = 1; i < args.GetSize(); i++) {
const base::Value* value; const base::Value* value;
if (args.Get(i, &value)) if (args.Get(i, &value))
arguments.push_back(converter->ToV8Value(value, context)); arguments.push_back(converter->ToV8Value(value, global_env->context()));
} }
node::MakeCallback(node::process, "emit", arguments.size(), &arguments[0]); node::MakeCallback(global_env->process_object(),
"emit",
arguments.size(),
&arguments[0]);
} }
void AtomBrowserBindings::OnRendererMessageSync( void AtomBrowserBindings::OnRendererMessageSync(
@ -76,11 +58,9 @@ void AtomBrowserBindings::OnRendererMessageSync(
const base::ListValue& args, const base::ListValue& args,
NativeWindow* sender, NativeWindow* sender,
IPC::Message* message) { IPC::Message* message) {
v8::HandleScope scope; v8::HandleScope handle_scope(node_isolate);
v8::Handle<v8::Context> context = v8::Context::GetCurrent(); scoped_ptr<V8ValueConverter> converter(new V8ValueConverter);
scoped_ptr<V8ValueConverter> converter(new V8ValueConverterImpl());
// Create the event object. // Create the event object.
v8::Handle<v8::Object> event = api::Event::CreateV8Object(); v8::Handle<v8::Object> event = api::Event::CreateV8Object();
@ -92,7 +72,7 @@ void AtomBrowserBindings::OnRendererMessageSync(
arguments.push_back(ToV8Value(channel)); arguments.push_back(ToV8Value(channel));
const base::Value* value; const base::Value* value;
if (args.Get(0, &value)) if (args.Get(0, &value))
arguments.push_back(converter->ToV8Value(value, context)); arguments.push_back(converter->ToV8Value(value, global_env->context()));
arguments.push_back(event); arguments.push_back(event);
arguments.push_back(v8::Integer::New(process_id)); arguments.push_back(v8::Integer::New(process_id));
arguments.push_back(v8::Integer::New(routing_id)); arguments.push_back(v8::Integer::New(routing_id));
@ -100,10 +80,13 @@ void AtomBrowserBindings::OnRendererMessageSync(
for (size_t i = 1; i < args.GetSize(); i++) { for (size_t i = 1; i < args.GetSize(); i++) {
const base::Value* value; const base::Value* value;
if (args.Get(i, &value)) if (args.Get(i, &value))
arguments.push_back(converter->ToV8Value(value, context)); arguments.push_back(converter->ToV8Value(value, global_env->context()));
} }
node::MakeCallback(node::process, "emit", arguments.size(), &arguments[0]); node::MakeCallback(global_env->process_object(),
"emit",
arguments.size(),
&arguments[0]);
} }
} // namespace atom } // namespace atom

View file

@ -5,8 +5,9 @@
#ifndef ATOM_BROWSER_API_ATOM_BROWSER_BINDINGS_ #ifndef ATOM_BROWSER_API_ATOM_BROWSER_BINDINGS_
#define ATOM_BROWSER_API_ATOM_BROWSER_BINDINGS_ #define ATOM_BROWSER_API_ATOM_BROWSER_BINDINGS_
#include "base/string16.h" #include "base/strings/string16.h"
#include "common/api/atom_bindings.h" #include "common/api/atom_bindings.h"
#include "common/v8/scoped_persistent.h"
namespace base { namespace base {
class ListValue; class ListValue;
@ -25,9 +26,6 @@ class AtomBrowserBindings : public AtomBindings {
AtomBrowserBindings(); AtomBrowserBindings();
virtual ~AtomBrowserBindings(); virtual ~AtomBrowserBindings();
// Called when the node.js main script has been loaded.
virtual void AfterLoad();
// Called when received a message from renderer. // Called when received a message from renderer.
void OnRendererMessage(int process_id, void OnRendererMessage(int process_id,
int routing_id, int routing_id,
@ -42,14 +40,7 @@ class AtomBrowserBindings : public AtomBindings {
NativeWindow* sender, NativeWindow* sender,
IPC::Message* message); IPC::Message* message);
// The require('atom').browserMainParts object.
v8::Handle<v8::Object> browser_main_parts() {
return browser_main_parts_;
}
private: private:
v8::Persistent<v8::Object> browser_main_parts_;
DISALLOW_COPY_AND_ASSIGN(AtomBrowserBindings); DISALLOW_COPY_AND_ASSIGN(AtomBrowserBindings);
}; };

View file

@ -1,6 +1,8 @@
bindings = process.atomBinding 'app' BrowserWindow = require 'browser-window'
EventEmitter = require('events').EventEmitter EventEmitter = require('events').EventEmitter
bindings = process.atomBinding 'app'
Application = bindings.Application Application = bindings.Application
Application::__proto__ = EventEmitter.prototype Application::__proto__ = EventEmitter.prototype
@ -9,9 +11,6 @@ app = new Application
app.getHomeDir = -> app.getHomeDir = ->
process.env[if process.platform is 'win32' then 'USERPROFILE' else 'HOME'] process.env[if process.platform is 'win32' then 'USERPROFILE' else 'HOME']
app.getBrowserWindows = ->
require('../../atom/objects-registry.js').getAllWindows()
app.setApplicationMenu = (menu) -> app.setApplicationMenu = (menu) ->
require('menu').setApplicationMenu menu require('menu').setApplicationMenu menu
@ -24,10 +23,13 @@ app.commandLine =
if process.platform is 'darwin' if process.platform is 'darwin'
app.dock = app.dock =
bounce: (type = 'informational') -> bindings.dockBounce type bounce: (type='informational') -> bindings.dockBounce type
cancelBounce: bindings.dockCancelBounce cancelBounce: bindings.dockCancelBounce
setBadge: bindings.dockSetBadgeText setBadge: bindings.dockSetBadgeText
getBadge: bindings.dockGetBadgeText getBadge: bindings.dockGetBadgeText
# Support old event name.
app.once 'ready', -> app.emit 'finish-launching'
# Only one App object pemitted. # Only one App object pemitted.
module.exports = app module.exports = app

View file

@ -1 +0,0 @@
module.exports = global.__atom

View file

@ -1,16 +1,27 @@
EventEmitter = require('events').EventEmitter EventEmitter = require('events').EventEmitter
IDWeakMap = require 'id-weak-map'
app = require 'app' app = require 'app'
v8Util = process.atomBinding 'v8_util'
BrowserWindow = process.atomBinding('window').BrowserWindow BrowserWindow = process.atomBinding('window').BrowserWindow
BrowserWindow::__proto__ = EventEmitter.prototype BrowserWindow::__proto__ = EventEmitter.prototype
# Store all created windows in the weak map.
BrowserWindow.windows = new IDWeakMap
BrowserWindow::_init = -> BrowserWindow::_init = ->
# Simulate the application menu on platforms other than OS X. # Simulate the application menu on platforms other than OS X.
if process.platform isnt 'darwin' if process.platform isnt 'darwin'
menu = app.getApplicationMenu() menu = app.getApplicationMenu()
@setMenu menu if menu? @setMenu menu if menu?
# Remember the window.
id = BrowserWindow.windows.add this
# Remove the window from weak map immediately when it's destroyed, since we
# could be iterating windows before GC happended.
@once 'destroyed', ->
BrowserWindow.windows.remove id if BrowserWindow.windows.has id
# Tell the rpc server that a render view has been deleted and we need to # Tell the rpc server that a render view has been deleted and we need to
# release all objects owned by it. # release all objects owned by it.
@on 'render-view-deleted', (event, processId, routingId) -> @on 'render-view-deleted', (event, processId, routingId) ->
@ -30,12 +41,16 @@ BrowserWindow::setMenu = (menu) ->
@menu = menu # Keep a reference of menu in case of GC. @menu = menu # Keep a reference of menu in case of GC.
@menu.attachToWindow this @menu.attachToWindow this
BrowserWindow.getAllWindows = ->
windows = BrowserWindow.windows
windows.get key for key in windows.keys()
BrowserWindow.getFocusedWindow = -> BrowserWindow.getFocusedWindow = ->
windows = app.getBrowserWindows() windows = BrowserWindow.getAllWindows()
return window for window in windows when window.isFocused() return window for window in windows when window.isFocused()
BrowserWindow.fromProcessIdAndRoutingId = (processId, routingId) -> BrowserWindow.fromProcessIdAndRoutingId = (processId, routingId) ->
windows = app.getBrowserWindows() windows = BrowserWindow.getAllWindows()
return window for window in windows when window.getProcessId() == processId and return window for window in windows when window.getProcessId() == processId and
window.getRoutingId() == routingId window.getRoutingId() == routingId

View file

@ -1,9 +1,7 @@
BrowserWindow = require 'browser-window' BrowserWindow = require 'browser-window'
EventEmitter = require('events').EventEmitter EventEmitter = require('events').EventEmitter
IDWeakMap = require 'id-weak-map'
MenuItem = require 'menu-item' MenuItem = require 'menu-item'
app = require 'app'
bindings = process.atomBinding 'menu' bindings = process.atomBinding 'menu'
Menu = bindings.Menu Menu = bindings.Menu
@ -52,7 +50,7 @@ Menu.setApplicationMenu = (menu) ->
if process.platform is 'darwin' if process.platform is 'darwin'
bindings.setApplicationMenu menu bindings.setApplicationMenu menu
else else
windows = app.getBrowserWindows() windows = BrowserWindow.getAllWindows()
w.setMenu menu for w in windows w.setMenu menu for w in windows
Menu.getApplicationMenu = -> applicationMenu Menu.getApplicationMenu = -> applicationMenu

View file

@ -1,73 +0,0 @@
fs = require 'fs'
path = require 'path'
if process.platform is 'win32'
# Redirect node's console to use our own implementations, since node can not
# handle output when running as GUI program.
console.log = console.error = console.warn = process.log
process.stdout.write = process.stderr.write = process.log
# Always returns EOF for stdin stream.
Readable = require('stream').Readable
stdin = new Readable
stdin.push null
process.__defineGetter__ 'stdin', -> stdin
# Provide default Content API implementations.
atom = {}
atom.browserMainParts =
preMainMessageLoopRun: ->
# This is the start of the whole application, usually we should initialize
# the main window here.
# Store atom object in global scope, apps can just override methods of it to
# implement various logics.
global.__atom = atom
# Add browser/api/lib to require's search paths,
# which contains javascript part of Atom's built-in libraries.
globalPaths = require('module').globalPaths
globalPaths.push path.join process.resourcesPath, 'browser', 'api', 'lib'
# And also common/api/lib
globalPaths.push path.join process.resourcesPath, 'common', 'api', 'lib'
# Don't quit on fatal error.
process.on 'uncaughtException', (error) ->
# Show error in GUI.
message = error.stack ? "#{error.name}: #{error.message}"
require('dialog').showMessageBox
type: 'warning'
title: 'An javascript error occured in the browser'
message: 'uncaughtException'
detail: message
buttons: ['OK']
# Load the RPC server.
require './rpc-server.js'
# Now we try to load app's package.json.
packageJson = null
packagePath = path.join process.resourcesPath, 'app'
try
# First we try to load process.resourcesPath/app
packageJson = JSON.parse(fs.readFileSync(path.join(packagePath, 'package.json')))
catch error
# If not found then we load browser/default_app
packagePath = path.join process.resourcesPath, 'browser', 'default_app'
packageJson = JSON.parse(fs.readFileSync(path.join(packagePath, 'package.json')))
# Set application's version.
app = require 'app'
app.setVersion packageJson.version if packageJson.version?
# Set application's name.
if packageJson.productName?
app.setName packageJson.productName
else if packageJson.name?
app.setName packageJson.name
# Finally load app's main.js and transfer control to C++.
require path.join(packagePath, packageJson.main)

View file

@ -7,7 +7,7 @@
#include "browser/atom_browser_context.h" #include "browser/atom_browser_context.h"
#include "browser/atom_browser_main_parts.h" #include "browser/atom_browser_main_parts.h"
#include "browser/net/atom_url_request_context_getter.h" #include "browser/net/atom_url_request_context_getter.h"
#include "webkit/glue/webpreferences.h" #include "webkit/common/webpreferences.h"
namespace atom { namespace atom {

View file

@ -33,6 +33,14 @@ class AtomResourceContext : public content::ResourceContext {
return getter_->GetURLRequestContext(); return getter_->GetURLRequestContext();
} }
virtual bool AllowMicAccess(const GURL& origin) OVERRIDE {
return true;
}
virtual bool AllowCameraAccess(const GURL& origin) OVERRIDE {
return true;
}
private: private:
AtomURLRequestContextGetter* getter_; AtomURLRequestContextGetter* getter_;

View file

@ -4,15 +4,18 @@
#include "browser/atom_browser_main_parts.h" #include "browser/atom_browser_main_parts.h"
#include "base/power_monitor/power_monitor.h"
#include "browser/api/atom_browser_bindings.h" #include "browser/api/atom_browser_bindings.h"
#include "browser/atom_browser_client.h" #include "browser/atom_browser_client.h"
#include "browser/atom_browser_context.h" #include "browser/atom_browser_context.h"
#include "browser/browser.h" #include "browser/browser.h"
#include "common/node_bindings.h" #include "common/node_bindings.h"
#include "net/proxy/proxy_resolver_v8.h" #include "net/proxy/proxy_resolver_v8.h"
#include "vendor/node/src/node.h"
#include "vendor/node/src/node_internals.h" #if defined(OS_WIN)
#include "ui/gfx/win/dpi.h"
#endif
#include "common/v8/node_common.h"
namespace atom { namespace atom {
@ -43,37 +46,28 @@ brightray::BrowserContext* AtomBrowserMainParts::CreateBrowserContext() {
void AtomBrowserMainParts::PostEarlyInitialization() { void AtomBrowserMainParts::PostEarlyInitialization() {
brightray::BrowserMainParts::PostEarlyInitialization(); brightray::BrowserMainParts::PostEarlyInitialization();
#if defined(OS_MACOSX)
base::PowerMonitor::AllocateSystemIOPorts();
#endif
node_bindings_->Initialize(); node_bindings_->Initialize();
v8::V8::Initialize();
// Create context.
v8::HandleScope handle_scope(node_isolate);
v8::Local<v8::Context> context = v8::Context::New(node_isolate);
// Create the global environment.
global_env = node_bindings_->CreateEnvironment(context);
// Wrap whole process in one global context. // Wrap whole process in one global context.
node::g_context->Enter(); context->Enter();
atom_bindings_->BindTo(node::process); // Add atom-shell extended APIs.
atom_bindings_->BindTo(global_env->process_object());
node_bindings_->Load();
atom_bindings_->AfterLoad();
} }
void AtomBrowserMainParts::PreMainMessageLoopRun() { void AtomBrowserMainParts::PreMainMessageLoopRun() {
node_bindings_->PrepareMessageLoop();
brightray::BrowserMainParts::PreMainMessageLoopRun(); brightray::BrowserMainParts::PreMainMessageLoopRun();
{ node_bindings_->PrepareMessageLoop();
v8::HandleScope scope;
v8::Context::Scope context_scope(node::g_context);
v8::Handle<v8::Value> args;
node::MakeCallback(atom_bindings_->browser_main_parts(),
"preMainMessageLoopRun",
0, &args);
}
node_bindings_->RunMessageLoop(); node_bindings_->RunMessageLoop();
// Make sure the url request job factory is created before the // Make sure the url request job factory is created before the
@ -89,8 +83,17 @@ void AtomBrowserMainParts::PreMainMessageLoopRun() {
} }
int AtomBrowserMainParts::PreCreateThreads() { int AtomBrowserMainParts::PreCreateThreads() {
// TODO(zcbenz): Calling CreateIsolate() on Windows when updated to Chrome30. // Note that we are overriding the PreCreateThreads of brightray, since we
// are integrating node in browser, we can just be sure that an V8 instance
// would be prepared, while the ProxyResolverV8::CreateIsolate() would
// try to create a V8 isolate, which messed everything on Windows, so we
// have to override and call RememberDefaultIsolate on Windows instead.
net::ProxyResolverV8::RememberDefaultIsolate(); net::ProxyResolverV8::RememberDefaultIsolate();
#if defined(OS_WIN)
gfx::EnableHighDPISupport();
#endif
return 0; return 0;
} }

View file

@ -4,7 +4,7 @@
#include "browser/atom_javascript_dialog_manager.h" #include "browser/atom_javascript_dialog_manager.h"
#include "base/utf_string_conversions.h" #include "base/strings/utf_string_conversions.h"
namespace atom { namespace atom {

View file

@ -26,7 +26,9 @@ class AtomJavaScriptDialogManager : public content::JavaScriptDialogManager {
const string16& message_text, const string16& message_text,
bool is_reload, bool is_reload,
const DialogClosedCallback& callback) OVERRIDE; const DialogClosedCallback& callback) OVERRIDE;
virtual void ResetJavaScriptState( virtual void CancelActiveAndPendingDialogs(
content::WebContents* web_contents) OVERRIDE {}
virtual void WebContentsDestroyed(
content::WebContents* web_contents) OVERRIDE {} content::WebContents* web_contents) OVERRIDE {}
}; };

View file

@ -1,6 +1,5 @@
var app = require('app'); var app = require('app');
var dialog = require('dialog'); var dialog = require('dialog');
var delegate = require('atom-delegate');
var ipc = require('ipc'); var ipc = require('ipc');
var Menu = require('menu'); var Menu = require('menu');
var MenuItem = require('menu-item'); var MenuItem = require('menu-item');
@ -18,7 +17,7 @@ app.on('open-url', function(event, url) {
dialog.showMessageBox({message: url, buttons: ['OK']}); dialog.showMessageBox({message: url, buttons: ['OK']});
}); });
app.on('finish-launching', function() { app.on('ready', function() {
app.commandLine.appendSwitch('js-flags', '--harmony_collections'); app.commandLine.appendSwitch('js-flags', '--harmony_collections');
mainWindow = new BrowserWindow({ width: 800, height: 600 }); mainWindow = new BrowserWindow({ width: 800, height: 600 });

72
browser/lib/init.coffee Normal file
View file

@ -0,0 +1,72 @@
fs = require 'fs'
path = require 'path'
# Expose information of current process.
process.__atom_type = 'browser'
process.resourcesPath = path.resolve process.argv[1], '..', '..', '..'
# We modified the original process.argv to let node.js load the atom.js,
# we need to restore it here.
process.argv.splice 1, 1
if process.platform is 'win32'
# Redirect node's console to use our own implementations, since node can not
# handle output when running as GUI program.
console.log = console.error = console.warn = process.log
process.stdout.write = process.stderr.write = process.log
# Always returns EOF for stdin stream.
Readable = require('stream').Readable
stdin = new Readable
stdin.push null
process.__defineGetter__ 'stdin', -> stdin
# Add browser/api/lib to require's search paths,
# which contains javascript part of Atom's built-in libraries.
globalPaths = require('module').globalPaths
globalPaths.push path.join process.resourcesPath, 'browser', 'api', 'lib'
# And also common/api/lib
globalPaths.push path.join process.resourcesPath, 'common', 'api', 'lib'
# Do loading in next tick since we still need some initialize work before
# native bindings can work.
setImmediate ->
# Don't quit on fatal error.
process.on 'uncaughtException', (error) ->
# Show error in GUI.
message = error.stack ? "#{error.name}: #{error.message}"
require('dialog').showMessageBox
type: 'warning'
title: 'An javascript error occured in the browser'
message: 'uncaughtException'
detail: message
buttons: ['OK']
# Load the RPC server.
require './rpc-server.js'
# Now we try to load app's package.json.
packageJson = null
packagePath = path.join process.resourcesPath, 'app'
try
# First we try to load process.resourcesPath/app
packageJson = JSON.parse(fs.readFileSync(path.join(packagePath, 'package.json')))
catch error
# If not found then we load browser/default_app
packagePath = path.join process.resourcesPath, 'browser', 'default_app'
packageJson = JSON.parse(fs.readFileSync(path.join(packagePath, 'package.json')))
# Set application's version.
app = require 'app'
app.setVersion packageJson.version if packageJson.version?
# Set application's name.
if packageJson.productName?
app.setName packageJson.productName
else if packageJson.name?
app.setName packageJson.name
# Finally load app's main.js and transfer control to C++.
require path.join(packagePath, packageJson.main)

View file

@ -1,4 +1,3 @@
BrowserWindow = require 'browser-window'
EventEmitter = require('events').EventEmitter EventEmitter = require('events').EventEmitter
IDWeakMap = require 'id-weak-map' IDWeakMap = require 'id-weak-map'
v8Util = process.atomBinding 'v8_util' v8Util = process.atomBinding 'v8_util'
@ -41,6 +40,8 @@ class ObjectsStore
class ObjectsRegistry extends EventEmitter class ObjectsRegistry extends EventEmitter
constructor: -> constructor: ->
@setMaxListeners Number.MAX_VALUE
# Objects in weak map will be not referenced (so we won't leak memory), and # Objects in weak map will be not referenced (so we won't leak memory), and
# every object created in browser will have a unique id in weak map. # every object created in browser will have a unique id in weak map.
@objectsWeakMap = new IDWeakMap @objectsWeakMap = new IDWeakMap
@ -49,13 +50,6 @@ class ObjectsRegistry extends EventEmitter
v8Util.setHiddenValue obj, 'atomId', id v8Util.setHiddenValue obj, 'atomId', id
id id
# Remember all windows in the weak map.
@windowsWeakMap = new IDWeakMap
process.on 'ATOM_BROWSER_INTERNAL_NEW', (obj) =>
if obj.constructor is BrowserWindow
id = @windowsWeakMap.add obj
obj.on 'destroyed', => @windowsWeakMap.remove id
# Register a new object, the object would be kept referenced until you release # Register a new object, the object would be kept referenced until you release
# it explicitly. # it explicitly.
add: (processId, routingId, obj) -> add: (processId, routingId, obj) ->
@ -87,9 +81,4 @@ class ObjectsRegistry extends EventEmitter
@emit "release-renderer-view-#{processId}-#{routingId}" @emit "release-renderer-view-#{processId}-#{routingId}"
ObjectsStore.releaseForRenderView processId, routingId ObjectsStore.releaseForRenderView processId, routingId
# Return an array of all browser windows.
getAllWindows: ->
keys = @windowsWeakMap.keys()
@windowsWeakMap.get key for key in keys
module.exports = new ObjectsRegistry module.exports = new ObjectsRegistry

View file

@ -7,9 +7,9 @@
#include <string> #include <string>
#include "base/file_util.h" #include "base/file_util.h"
#include "base/message_loop.h" #include "base/message_loop/message_loop.h"
#include "base/stringprintf.h" #include "base/strings/stringprintf.h"
#include "base/utf_string_conversions.h" #include "base/strings/utf_string_conversions.h"
#include "base/values.h" #include "base/values.h"
#include "brightray/browser/inspectable_web_contents.h" #include "brightray/browser/inspectable_web_contents.h"
#include "brightray/browser/inspectable_web_contents_view.h" #include "brightray/browser/inspectable_web_contents_view.h"
@ -37,8 +37,7 @@
#include "ui/gfx/point.h" #include "ui/gfx/point.h"
#include "ui/gfx/rect.h" #include "ui/gfx/rect.h"
#include "ui/gfx/size.h" #include "ui/gfx/size.h"
#include "webkit/glue/image_decoder.h" #include "webkit/common/user_agent/user_agent_util.h"
#include "webkit/user_agent/user_agent_util.h"
using content::NavigationEntry; using content::NavigationEntry;
@ -165,7 +164,7 @@ void NativeWindow::CloseDevTools() {
} }
bool NativeWindow::IsDevToolsOpened() { bool NativeWindow::IsDevToolsOpened() {
return inspectable_web_contents()->IsDevToolsOpened(); return inspectable_web_contents()->IsDevToolsViewShowing();
} }
void NativeWindow::InspectElement(int x, int y) { void NativeWindow::InspectElement(int x, int y) {
@ -193,15 +192,14 @@ bool NativeWindow::SetIcon(const std::string& str_path) {
// Read the file from disk. // Read the file from disk.
std::string file_contents; std::string file_contents;
if (path.empty() || !file_util::ReadFileToString(path, &file_contents)) if (path.empty() || !base::ReadFileToString(path, &file_contents))
return false; return false;
// Decode the bitmap using WebKit's image decoder. // Decode the bitmap using WebKit's image decoder.
const unsigned char* data = const unsigned char* data =
reinterpret_cast<const unsigned char*>(file_contents.data()); reinterpret_cast<const unsigned char*>(file_contents.data());
webkit_glue::ImageDecoder decoder;
scoped_ptr<SkBitmap> decoded(new SkBitmap()); scoped_ptr<SkBitmap> decoded(new SkBitmap());
*decoded = decoder.Decode(data, file_contents.length()); gfx::PNGCodec::Decode(data, file_contents.length(), decoded.get());
if (decoded->empty()) if (decoded->empty())
return false; // Unable to decode. return false; // Unable to decode.
@ -383,6 +381,21 @@ void NativeWindow::RendererResponsive(content::WebContents* source) {
FOR_EACH_OBSERVER(NativeWindowObserver, observers_, OnRendererResponsive()); FOR_EACH_OBSERVER(NativeWindowObserver, observers_, OnRendererResponsive());
} }
void NativeWindow::RenderViewDeleted(content::RenderViewHost* rvh) {
FOR_EACH_OBSERVER(NativeWindowObserver, observers_,
OnRenderViewDeleted(rvh->GetProcess()->GetID(),
rvh->GetRoutingID()));
}
void NativeWindow::RenderProcessGone(base::TerminationStatus status) {
FOR_EACH_OBSERVER(NativeWindowObserver, observers_, OnRendererCrashed());
}
void NativeWindow::BeforeUnloadFired(const base::TimeTicks& proceed_time) {
// Do nothing, we override this method just to avoid compilation error since
// there are two virtual functions named BeforeUnloadFired.
}
bool NativeWindow::OnMessageReceived(const IPC::Message& message) { bool NativeWindow::OnMessageReceived(const IPC::Message& message) {
bool handled = true; bool handled = true;
IPC_BEGIN_MESSAGE_MAP(NativeWindow, message) IPC_BEGIN_MESSAGE_MAP(NativeWindow, message)
@ -397,16 +410,6 @@ bool NativeWindow::OnMessageReceived(const IPC::Message& message) {
return handled; return handled;
} }
void NativeWindow::RenderViewDeleted(content::RenderViewHost* rvh) {
FOR_EACH_OBSERVER(NativeWindowObserver, observers_,
OnRenderViewDeleted(rvh->GetProcess()->GetID(),
rvh->GetRoutingID()));
}
void NativeWindow::RenderViewGone(base::TerminationStatus status) {
FOR_EACH_OBSERVER(NativeWindowObserver, observers_, OnRendererCrashed());
}
void NativeWindow::Observe(int type, void NativeWindow::Observe(int type,
const content::NotificationSource& source, const content::NotificationSource& source,
const content::NotificationDetails& details) { const content::NotificationDetails& details) {

View file

@ -184,7 +184,8 @@ class NativeWindow : public brightray::DefaultWebContentsDelegate,
// Implementations of content::WebContentsObserver. // Implementations of content::WebContentsObserver.
virtual void RenderViewDeleted(content::RenderViewHost*) OVERRIDE; virtual void RenderViewDeleted(content::RenderViewHost*) OVERRIDE;
virtual void RenderViewGone(base::TerminationStatus status) OVERRIDE; virtual void RenderProcessGone(base::TerminationStatus status) OVERRIDE;
virtual void BeforeUnloadFired(const base::TimeTicks& proceed_time) OVERRIDE;
virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE; virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE;
// Implementations of content::NotificationObserver // Implementations of content::NotificationObserver

View file

@ -11,6 +11,7 @@
#define BASE_MAC_FOUNDATION_UTIL_H_ #define BASE_MAC_FOUNDATION_UTIL_H_
#include "base/mac/mac_util.h" #include "base/mac/mac_util.h"
#include "base/mac/scoped_nsobject.h"
#include "base/strings/sys_string_conversions.h" #include "base/strings/sys_string_conversions.h"
#include "base/values.h" #include "base/values.h"
#import "browser/ui/atom_event_processing_window.h" #import "browser/ui/atom_event_processing_window.h"
@ -490,7 +491,7 @@ void NativeWindowMac::InstallDraggableRegionViews() {
// Note that [webView subviews] returns the view's mutable internal array and // 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 should be copied to avoid mutating the original array while enumerating
// it. // it.
scoped_nsobject<NSArray> subviews([[webView subviews] copy]); base::scoped_nsobject<NSArray> subviews([[webView subviews] copy]);
for (NSView* subview in subviews.get()) for (NSView* subview in subviews.get())
if ([subview isKindOfClass:[ControlRegionView class]]) if ([subview isKindOfClass:[ControlRegionView class]])
[subview removeFromSuperview]; [subview removeFromSuperview];
@ -501,7 +502,7 @@ void NativeWindowMac::InstallDraggableRegionViews() {
system_drag_exclude_areas_.begin(); system_drag_exclude_areas_.begin();
iter != system_drag_exclude_areas_.end(); iter != system_drag_exclude_areas_.end();
++iter) { ++iter) {
scoped_nsobject<NSView> controlRegion( base::scoped_nsobject<NSView> controlRegion(
[[ControlRegionView alloc] initWithShellWindow:this]); [[ControlRegionView alloc] initWithShellWindow:this]);
[controlRegion setFrame:NSMakeRect(iter->x(), [controlRegion setFrame:NSMakeRect(iter->x(),
webViewHeight - iter->bottom(), webViewHeight - iter->bottom(),

View file

@ -439,10 +439,9 @@ void NativeWindowWin::Layout() {
OnViewWasResized(); OnViewWasResized();
} }
void NativeWindowWin::ViewHierarchyChanged(bool is_add, void NativeWindowWin::ViewHierarchyChanged(
views::View* parent, const ViewHierarchyChangedDetails& details) {
views::View* child) { if (details.is_add && details.child == this)
if (is_add && child == this)
AddChildView(web_view_); AddChildView(web_view_);
} }

View file

@ -5,7 +5,7 @@
#ifndef ATOM_BROWSER_NATIVE_WINDOW_WIN_H_ #ifndef ATOM_BROWSER_NATIVE_WINDOW_WIN_H_
#define ATOM_BROWSER_NATIVE_WINDOW_WIN_H_ #define ATOM_BROWSER_NATIVE_WINDOW_WIN_H_
#include "base/string16.h" #include "base/strings/string16.h"
#include "base/memory/scoped_ptr.h" #include "base/memory/scoped_ptr.h"
#include "browser/native_window.h" #include "browser/native_window.h"
@ -87,9 +87,8 @@ class NativeWindowWin : public NativeWindow,
// Overridden from views::View: // Overridden from views::View:
virtual void Layout() OVERRIDE; virtual void Layout() OVERRIDE;
virtual void ViewHierarchyChanged(bool is_add, virtual void ViewHierarchyChanged(
views::View* parent, const ViewHierarchyChangedDetails& details) OVERRIDE;
views::View* child) OVERRIDE;
virtual bool AcceleratorPressed(const ui::Accelerator& accelerator) OVERRIDE; virtual bool AcceleratorPressed(const ui::Accelerator& accelerator) OVERRIDE;
// Overridden from views::WidgetDelegate: // Overridden from views::WidgetDelegate:

View file

@ -4,6 +4,7 @@
#include "browser/net/adapter_request_job.h" #include "browser/net/adapter_request_job.h"
#include "base/threading/sequenced_worker_pool.h"
#include "browser/net/url_request_string_job.h" #include "browser/net/url_request_string_job.h"
#include "content/public/browser/browser_thread.h" #include "content/public/browser/browser_thread.h"
#include "net/base/net_errors.h" #include "net/base/net_errors.h"
@ -87,7 +88,13 @@ void AdapterRequestJob::CreateStringJobAndStart(const std::string& mime_type,
void AdapterRequestJob::CreateFileJobAndStart(const base::FilePath& path) { void AdapterRequestJob::CreateFileJobAndStart(const base::FilePath& path) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
real_job_ = new net::URLRequestFileJob(request(), network_delegate(), path); real_job_ = new net::URLRequestFileJob(
request(),
network_delegate(),
path,
content::BrowserThread::GetBlockingPool()->
GetTaskRunnerWithShutdownBehavior(
base::SequencedWorkerPool::SKIP_ON_SHUTDOWN));
real_job_->Start(); real_job_->Start();
} }

View file

@ -4,7 +4,8 @@
#include "browser/net/atom_url_request_context_getter.h" #include "browser/net/atom_url_request_context_getter.h"
#include "base/string_util.h" #include "base/strings/string_util.h"
#include "base/threading/sequenced_worker_pool.h"
#include "base/threading/worker_pool.h" #include "base/threading/worker_pool.h"
#include "browser/net/atom_url_request_job_factory.h" #include "browser/net/atom_url_request_job_factory.h"
#include "content/public/browser/browser_thread.h" #include "content/public/browser/browser_thread.h"
@ -36,8 +37,8 @@ using content::BrowserThread;
AtomURLRequestContextGetter::AtomURLRequestContextGetter( AtomURLRequestContextGetter::AtomURLRequestContextGetter(
const base::FilePath& base_path, const base::FilePath& base_path,
MessageLoop* io_loop, base::MessageLoop* io_loop,
MessageLoop* file_loop, base::MessageLoop* file_loop,
scoped_ptr<brightray::NetworkDelegate> network_delegate, scoped_ptr<brightray::NetworkDelegate> network_delegate,
content::ProtocolHandlerMap* protocol_handlers) content::ProtocolHandlerMap* protocol_handlers)
: base_path_(base_path), : base_path_(base_path),
@ -74,6 +75,7 @@ net::URLRequestContext* AtomURLRequestContextGetter::GetURLRequestContext() {
base_path_.Append(FILE_PATH_LITERAL("Cookies")), base_path_.Append(FILE_PATH_LITERAL("Cookies")),
false, false,
nullptr, nullptr,
nullptr,
nullptr)); nullptr));
storage_->set_server_bound_cert_service(new net::ServerBoundCertService( storage_->set_server_bound_cert_service(new net::ServerBoundCertService(
new net::DefaultServerBoundCertStore(NULL), new net::DefaultServerBoundCertStore(NULL),
@ -98,7 +100,9 @@ net::URLRequestContext* AtomURLRequestContextGetter::GetURLRequestContext() {
storage_->set_ssl_config_service(new net::SSLConfigServiceDefaults); storage_->set_ssl_config_service(new net::SSLConfigServiceDefaults);
storage_->set_http_auth_handler_factory( storage_->set_http_auth_handler_factory(
net::HttpAuthHandlerFactory::CreateDefault(host_resolver.get())); net::HttpAuthHandlerFactory::CreateDefault(host_resolver.get()));
storage_->set_http_server_properties(new net::HttpServerPropertiesImpl); scoped_ptr<net::HttpServerProperties> server_properties(
new net::HttpServerPropertiesImpl);
storage_->set_http_server_properties(server_properties.Pass());
base::FilePath cache_path = base_path_.Append(FILE_PATH_LITERAL("Cache")); base::FilePath cache_path = base_path_.Append(FILE_PATH_LITERAL("Cache"));
net::HttpCache::DefaultBackend* main_backend = net::HttpCache::DefaultBackend* main_backend =
@ -147,10 +151,15 @@ net::URLRequestContext* AtomURLRequestContextGetter::GetURLRequestContext() {
} }
protocol_handlers_.clear(); protocol_handlers_.clear();
scoped_ptr<net::FileProtocolHandler> file_protocol_handler(
new net::FileProtocolHandler(
content::BrowserThread::GetBlockingPool()->
GetTaskRunnerWithShutdownBehavior(
base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)));
job_factory_->SetProtocolHandler(chrome::kDataScheme, job_factory_->SetProtocolHandler(chrome::kDataScheme,
new net::DataProtocolHandler); new net::DataProtocolHandler);
job_factory_->SetProtocolHandler(chrome::kFileScheme, job_factory_->SetProtocolHandler(chrome::kFileScheme,
new net::FileProtocolHandler); file_protocol_handler.release());
storage_->set_job_factory(job_factory_); storage_->set_job_factory(job_factory_);
} }

View file

@ -6,7 +6,6 @@
#include "browser/net/atom_url_request_job_factory.h" #include "browser/net/atom_url_request_job_factory.h"
#include "base/stl_util.h" #include "base/stl_util.h"
#include "googleurl/src/gurl.h"
#include "net/base/load_flags.h" #include "net/base/load_flags.h"
#include "net/url_request/url_request.h" #include "net/url_request/url_request.h"
@ -102,4 +101,9 @@ bool AtomURLRequestJobFactory::IsHandledURL(const GURL& url) const {
return IsHandledProtocol(url.scheme()); return IsHandledProtocol(url.scheme());
} }
bool AtomURLRequestJobFactory::IsSafeRedirectTarget(
const GURL& location) const {
return IsHandledURL(location);
}
} // namespace atom } // namespace atom

View file

@ -45,6 +45,7 @@ class AtomURLRequestJobFactory : public net::URLRequestJobFactory {
net::NetworkDelegate* network_delegate) const OVERRIDE; net::NetworkDelegate* network_delegate) const OVERRIDE;
virtual bool IsHandledProtocol(const std::string& scheme) const OVERRIDE; virtual bool IsHandledProtocol(const std::string& scheme) const OVERRIDE;
virtual bool IsHandledURL(const GURL& url) const OVERRIDE; virtual bool IsHandledURL(const GURL& url) const OVERRIDE;
virtual bool IsSafeRedirectTarget(const GURL& location) const OVERRIDE;
private: private:
typedef std::map<std::string, ProtocolHandler*> ProtocolHandlerMap; typedef std::map<std::string, ProtocolHandler*> ProtocolHandlerMap;

View file

@ -8,7 +8,7 @@
#include <string> #include <string>
#include "base/string_util.h" #include "base/strings/string_util.h"
#include "base/strings/string_number_conversions.h" #include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h" #include "base/strings/string_split.h"
#include "ui/base/accelerators/accelerator.h" #include "ui/base/accelerators/accelerator.h"

View file

@ -6,7 +6,7 @@
#include "ui/base/accelerators/accelerator.h" #include "ui/base/accelerators/accelerator.h"
#import "ui/base/accelerators/platform_accelerator_cocoa.h" #import "ui/base/accelerators/platform_accelerator_cocoa.h"
#import "ui/base/keycodes/keyboard_code_conversion_mac.h" #import "ui/events/keycodes/keyboard_code_conversion_mac.h"
namespace accelerator_util { namespace accelerator_util {

View file

@ -7,8 +7,6 @@
#import <Cocoa/Cocoa.h> #import <Cocoa/Cocoa.h>
#include "base/memory/scoped_nsobject.h"
// Override NSWindow to access unhandled keyboard events (for command // Override NSWindow to access unhandled keyboard events (for command
// processing); subclassing NSWindow is the only method to do // processing); subclassing NSWindow is the only method to do
// this. // this.

View file

@ -8,8 +8,8 @@
#import <Cocoa/Cocoa.h> #import <Cocoa/Cocoa.h>
#include "base/memory/scoped_nsobject.h" #include "base/mac/scoped_nsobject.h"
#include "base/string16.h" #include "base/strings/string16.h"
namespace ui { namespace ui {
class MenuModel; class MenuModel;
@ -24,7 +24,7 @@ class MenuModel;
@interface AtomMenuController : NSObject<NSMenuDelegate> { @interface AtomMenuController : NSObject<NSMenuDelegate> {
@protected @protected
ui::MenuModel* model_; // weak ui::MenuModel* model_; // weak
scoped_nsobject<NSMenu> menu_; base::scoped_nsobject<NSMenu> menu_;
BOOL isMenuOpen_; BOOL isMenuOpen_;
} }

View file

@ -133,7 +133,7 @@ int EventFlagsFromNSEvent(NSEvent* event) {
fromModel:(ui::MenuModel*)model { fromModel:(ui::MenuModel*)model {
string16 label16 = model->GetLabelAt(index); string16 label16 = model->GetLabelAt(index);
NSString* label = l10n_util::FixUpWindowsStyleLabel(label16); NSString* label = l10n_util::FixUpWindowsStyleLabel(label16);
scoped_nsobject<NSMenuItem> item( base::scoped_nsobject<NSMenuItem> item(
[[NSMenuItem alloc] initWithTitle:label [[NSMenuItem alloc] initWithTitle:label
action:@selector(itemSelected:) action:@selector(itemSelected:)
keyEquivalent:@""]); keyEquivalent:@""]);

View file

@ -24,7 +24,7 @@ void SetupDialog(NSSavePanel* dialog,
NSString* default_dir = nil; NSString* default_dir = nil;
NSString* default_filename = nil; NSString* default_filename = nil;
if (!default_path.empty()) { if (!default_path.empty()) {
if (file_util::DirectoryExists(default_path)) { if (base::DirectoryExists(default_path)) {
default_dir = base::SysUTF8ToNSString(default_path.value()); default_dir = base::SysUTF8ToNSString(default_path.value());
} else { } else {
default_dir = base::SysUTF8ToNSString(default_path.DirName().value()); default_dir = base::SysUTF8ToNSString(default_path.DirName().value());

View file

@ -11,9 +11,9 @@
#include "base/file_util.h" #include "base/file_util.h"
#include "base/i18n/case_conversion.h" #include "base/i18n/case_conversion.h"
#include "base/string_util.h" #include "base/strings/string_util.h"
#include "base/strings/string_split.h" #include "base/strings/string_split.h"
#include "base/utf_string_conversions.h" #include "base/strings/utf_string_conversions.h"
#include "base/win/registry.h" #include "base/win/registry.h"
#include "browser/native_window.h" #include "browser/native_window.h"
#include "third_party/wtl/include/atlapp.h" #include "third_party/wtl/include/atlapp.h"

View file

@ -5,10 +5,10 @@
#include "browser/ui/message_box.h" #include "browser/ui/message_box.h"
#include "base/callback.h" #include "base/callback.h"
#include "base/message_loop.h" #include "base/message_loop/message_loop.h"
#include "base/run_loop.h" #include "base/run_loop.h"
#include "base/string_util.h" #include "base/strings/string_util.h"
#include "base/utf_string_conversions.h" #include "base/strings/utf_string_conversions.h"
#include "browser/native_window.h" #include "browser/native_window.h"
#include "skia/ext/skia_utils_win.h" #include "skia/ext/skia_utils_win.h"
#include "ui/views/controls/button/label_button.h" #include "ui/views/controls/button/label_button.h"

View file

@ -8,22 +8,22 @@
#include "base/bind.h" #include "base/bind.h"
#include "base/logging.h" #include "base/logging.h"
#include "base/message_loop.h" #include "base/message_loop/message_loop.h"
#include "base/stl_util.h" #include "base/stl_util.h"
#include "base/string_util.h" #include "base/strings/string_util.h"
#include "base/win/wrapped_window_proc.h" #include "base/win/wrapped_window_proc.h"
#include "browser/ui/win/menu_2.h" #include "browser/ui/win/menu_2.h"
#include "ui/base/accelerators/accelerator.h" #include "ui/base/accelerators/accelerator.h"
#include "ui/base/keycodes/keyboard_codes.h" #include "ui/events/keycodes/keyboard_codes.h"
#include "ui/base/l10n/l10n_util.h" #include "ui/base/l10n/l10n_util.h"
#include "ui/base/l10n/l10n_util_win.h" #include "ui/base/l10n/l10n_util_win.h"
#include "ui/base/models/menu_model.h" #include "ui/base/models/menu_model.h"
#include "ui/base/win/hwnd_util.h"
#include "ui/gfx/canvas.h" #include "ui/gfx/canvas.h"
#include "ui/gfx/font.h" #include "ui/gfx/font.h"
#include "ui/gfx/image/image.h" #include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_skia.h" #include "ui/gfx/image/image_skia.h"
#include "ui/gfx/rect.h" #include "ui/gfx/rect.h"
#include "ui/gfx/win/hwnd_util.h"
#include "ui/native_theme/native_theme.h" #include "ui/native_theme/native_theme.h"
#include "ui/native_theme/native_theme_win.h" #include "ui/native_theme/native_theme_win.h"
#include "ui/views/controls/menu/menu_config.h" #include "ui/views/controls/menu/menu_config.h"
@ -84,8 +84,8 @@ class NativeMenuWin::MenuHostWindow {
RegisterClass(); RegisterClass();
hwnd_ = CreateWindowEx(l10n_util::GetExtendedStyles(), kWindowClassName, hwnd_ = CreateWindowEx(l10n_util::GetExtendedStyles(), kWindowClassName,
L"", 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, NULL, NULL); L"", 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, NULL, NULL);
ui::CheckWindowCreated(hwnd_); gfx::CheckWindowCreated(hwnd_);
ui::SetWindowUserData(hwnd_, this); gfx::SetWindowUserData(hwnd_, this);
} }
~MenuHostWindow() { ~MenuHostWindow() {
@ -353,7 +353,7 @@ class NativeMenuWin::MenuHostWindow {
WPARAM w_param, WPARAM w_param,
LPARAM l_param) { LPARAM l_param) {
MenuHostWindow* host = MenuHostWindow* host =
reinterpret_cast<MenuHostWindow*>(ui::GetWindowUserData(window)); reinterpret_cast<MenuHostWindow*>(gfx::GetWindowUserData(window));
// host is null during initial construction. // host is null during initial construction.
LRESULT l_result = 0; LRESULT l_result = 0;
if (!host || !host->ProcessWindowMessage(window, message, w_param, l_param, if (!host || !host->ProcessWindowMessage(window, message, w_param, l_param,

View file

@ -13,7 +13,7 @@
#include "base/memory/scoped_ptr.h" #include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h" #include "base/memory/weak_ptr.h"
#include "base/observer_list.h" #include "base/observer_list.h"
#include "base/string16.h" #include "base/strings/string16.h"
namespace gfx { namespace gfx {
class Point; class Point;

View file

@ -13,6 +13,7 @@
}], }],
], ],
# Reflects node's config.gypi. # Reflects node's config.gypi.
'component%': 'static_library',
'python': 'python', 'python': 'python',
'node_install_npm': 'false', 'node_install_npm': 'false',
'node_prefix': '', 'node_prefix': '',
@ -29,11 +30,12 @@
'node_use_openssl': 'true', 'node_use_openssl': 'true',
'node_use_perfctr': 'false', 'node_use_perfctr': 'false',
'node_use_systemtap': 'false', 'node_use_systemtap': 'false',
'v8_postmortem_support': 'false',
}, },
# Settings to compile node under Windows. # Settings to compile node under Windows.
'target_defaults': { 'target_defaults': {
'target_conditions': [ 'target_conditions': [
['_target_name in ["libuv", "http_parser", "cares", "openssl", "node", "zlib"]', { ['_target_name in ["libuv", "http_parser", "cares", "openssl", "node_lib", "zlib"]', {
'msvs_disabled_warnings': [ 'msvs_disabled_warnings': [
4013, # 'free' undefined; assuming extern returning int 4013, # 'free' undefined; assuming extern returning int
4054, # 4054, #
@ -41,6 +43,7 @@
4189, # 4189, #
4131, # uses old-style declarator 4131, # uses old-style declarator
4133, # incompatible types 4133, # incompatible types
4146, # unary minus operator applied to unsigned type, result still unsigned
4152, # function/data pointer conversion in expression 4152, # function/data pointer conversion in expression
4206, # translation unit is empty 4206, # translation unit is empty
4204, # non-constant aggregate initializer 4204, # non-constant aggregate initializer
@ -51,6 +54,7 @@
4505, # unreferenced local function has been removed 4505, # unreferenced local function has been removed
4701, # potentially uninitialized local variable 'sizew' used 4701, # potentially uninitialized local variable 'sizew' used
4706, # assignment within conditional expression 4706, # assignment within conditional expression
4804, # unsafe use of type 'bool' in operation
4996, # 4996, #
], ],
'msvs_settings': { 'msvs_settings': {
@ -72,6 +76,11 @@
], ],
}, },
}], }],
['_target_name in ["node_lib", "atom_lib"]', {
'include_dirs': [
'vendor/brightray/vendor/download/libchromiumcontent/src/v8/include',
],
}],
['_target_name=="libuv"', { ['_target_name=="libuv"', {
'conditions': [ 'conditions': [
['OS=="win"', { ['OS=="win"', {

View file

@ -4,7 +4,7 @@
// Multiply-included file, no traditional include guard. // Multiply-included file, no traditional include guard.
#include "base/string16.h" #include "base/strings/string16.h"
#include "base/values.h" #include "base/values.h"
#include "common/draggable_region.h" #include "common/draggable_region.h"
#include "content/public/common/common_param_traits.h" #include "content/public/common/common_param_traits.h"

View file

@ -6,92 +6,81 @@
#include <string> #include <string>
#include "common/v8/native_type_conversions.h"
#include "ui/base/clipboard/clipboard.h" #include "ui/base/clipboard/clipboard.h"
#include "vendor/node/src/node.h"
#include "common/v8/node_common.h"
namespace atom { namespace atom {
namespace api { namespace api {
// static // static
v8::Handle<v8::Value> Clipboard::Has(const v8::Arguments &args) { void Clipboard::Has(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope; std::string format_string;
if (!FromV8Arguments(args, &format_string))
if (!args[0]->IsString())
return node::ThrowTypeError("Bad argument"); return node::ThrowTypeError("Bad argument");
ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
std::string format_string(*v8::String::Utf8Value(args[0]));
ui::Clipboard::FormatType format(ui::Clipboard::GetFormatType(format_string)); ui::Clipboard::FormatType format(ui::Clipboard::GetFormatType(format_string));
return scope.Close(v8::Boolean::New( args.GetReturnValue().Set(
clipboard->IsFormatAvailable(format, ui::Clipboard::BUFFER_STANDARD))); clipboard->IsFormatAvailable(format, ui::Clipboard::BUFFER_STANDARD));
} }
// static // static
v8::Handle<v8::Value> Clipboard::Read(const v8::Arguments &args) { void Clipboard::Read(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope; std::string format_string;
if (!FromV8Arguments(args, &format_string))
if (!args[0]->IsString())
return node::ThrowTypeError("Bad argument"); return node::ThrowTypeError("Bad argument");
ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
std::string format_string(*v8::String::Utf8Value(args[0]));
ui::Clipboard::FormatType format(ui::Clipboard::GetFormatType(format_string)); ui::Clipboard::FormatType format(ui::Clipboard::GetFormatType(format_string));
std::string data; std::string data;
clipboard->ReadData(format, &data); clipboard->ReadData(format, &data);
return scope.Close(v8::String::New(data.c_str(), data.size())); args.GetReturnValue().Set(ToV8Value(data));
} }
// static // static
v8::Handle<v8::Value> Clipboard::ReadText(const v8::Arguments &args) { void Clipboard::ReadText(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope;
ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
std::string data; std::string data;
clipboard->ReadAsciiText(ui::Clipboard::BUFFER_STANDARD, &data); clipboard->ReadAsciiText(ui::Clipboard::BUFFER_STANDARD, &data);
return scope.Close(v8::String::New(data.c_str(), data.size())); args.GetReturnValue().Set(ToV8Value(data));
} }
// static // static
v8::Handle<v8::Value> Clipboard::WriteText(const v8::Arguments &args) { void Clipboard::WriteText(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope; std::string text;
if (!FromV8Arguments(args, &text))
if (!args[0]->IsString())
return node::ThrowTypeError("Bad argument"); return node::ThrowTypeError("Bad argument");
ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
std::string text(*v8::String::Utf8Value(args[0]));
ui::Clipboard::ObjectMap object_map; ui::Clipboard::ObjectMap object_map;
object_map[ui::Clipboard::CBF_TEXT].push_back( object_map[ui::Clipboard::CBF_TEXT].push_back(
std::vector<char>(text.begin(), text.end())); std::vector<char>(text.begin(), text.end()));
clipboard->WriteObjects(ui::Clipboard::BUFFER_STANDARD, object_map, NULL);
return v8::Undefined(); ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
clipboard->WriteObjects(ui::Clipboard::BUFFER_STANDARD, object_map);
} }
// static // static
v8::Handle<v8::Value> Clipboard::Clear(const v8::Arguments &args) { void Clipboard::Clear(const v8::FunctionCallbackInfo<v8::Value>& args) {
ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); ui::Clipboard::GetForCurrentThread()->Clear(ui::Clipboard::BUFFER_STANDARD);
clipboard->Clear(ui::Clipboard::BUFFER_STANDARD);
return v8::Undefined();
} }
// static // static
void Clipboard::Initialize(v8::Handle<v8::Object> target) { void Clipboard::Initialize(v8::Handle<v8::Object> target) {
node::SetMethod(target, "has", Has); v8::HandleScope handle_scope(node_isolate);
node::SetMethod(target, "read", Read);
node::SetMethod(target, "readText", ReadText); NODE_SET_METHOD(target, "has", Has);
node::SetMethod(target, "writeText", WriteText); NODE_SET_METHOD(target, "read", Read);
node::SetMethod(target, "clear", Clear); NODE_SET_METHOD(target, "readText", ReadText);
NODE_SET_METHOD(target, "writeText", WriteText);
NODE_SET_METHOD(target, "clear", Clear);
} }
} // namespace api } // namespace api

View file

@ -17,11 +17,11 @@ class Clipboard {
static void Initialize(v8::Handle<v8::Object> target); static void Initialize(v8::Handle<v8::Object> target);
private: private:
static v8::Handle<v8::Value> Has(const v8::Arguments &args); static void Has(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> Read(const v8::Arguments &args); static void Read(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> ReadText(const v8::Arguments &args); static void ReadText(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> WriteText(const v8::Arguments &args); static void WriteText(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> Clear(const v8::Arguments &args); static void Clear(const v8::FunctionCallbackInfo<v8::Value>& args);
DISALLOW_IMPLICIT_CONSTRUCTORS(Clipboard); DISALLOW_IMPLICIT_CONSTRUCTORS(Clipboard);
}; };

View file

@ -5,16 +5,16 @@
#include "common/api/atom_api_crash_reporter.h" #include "common/api/atom_api_crash_reporter.h"
#include "common/crash_reporter/crash_reporter.h" #include "common/crash_reporter/crash_reporter.h"
#include "common/v8_conversions.h" #include "common/v8/native_type_conversions.h"
#include "vendor/node/src/node.h"
#include "vendor/node/src/node_internals.h" #include "common/v8/node_common.h"
namespace atom { namespace atom {
namespace api { namespace api {
// static // static
v8::Handle<v8::Value> CrashReporter::Start(const v8::Arguments& args) { void CrashReporter::Start(const v8::FunctionCallbackInfo<v8::Value>& args) {
std::string product_name, company_name, submit_url; std::string product_name, company_name, submit_url;
bool auto_submit, skip_system; bool auto_submit, skip_system;
std::map<std::string, std::string> dict; std::map<std::string, std::string> dict;
@ -24,13 +24,11 @@ v8::Handle<v8::Value> CrashReporter::Start(const v8::Arguments& args) {
crash_reporter::CrashReporter::GetInstance()->Start( crash_reporter::CrashReporter::GetInstance()->Start(
product_name, company_name, submit_url, auto_submit, skip_system, dict); product_name, company_name, submit_url, auto_submit, skip_system, dict);
return v8::Undefined();
} }
// static // static
void CrashReporter::Initialize(v8::Handle<v8::Object> target) { void CrashReporter::Initialize(v8::Handle<v8::Object> target) {
node::SetMethod(target, "start", Start); NODE_SET_METHOD(target, "start", Start);
} }
} // namespace api } // namespace api

View file

@ -17,7 +17,7 @@ class CrashReporter {
static void Initialize(v8::Handle<v8::Object> target); static void Initialize(v8::Handle<v8::Object> target);
private: private:
static v8::Handle<v8::Value> Start(const v8::Arguments& args); static void Start(const v8::FunctionCallbackInfo<v8::Value>& args);
DISALLOW_IMPLICIT_CONSTRUCTORS(CrashReporter); DISALLOW_IMPLICIT_CONSTRUCTORS(CrashReporter);
}; };

View file

@ -5,7 +5,11 @@
#include "common/api/atom_api_id_weak_map.h" #include "common/api/atom_api_id_weak_map.h"
#include <algorithm>
#include "base/logging.h" #include "base/logging.h"
#include "common/v8/native_type_conversions.h"
#include "common/v8/node_common.h"
namespace atom { namespace atom {
@ -16,29 +20,17 @@ IDWeakMap::IDWeakMap()
} }
IDWeakMap::~IDWeakMap() { IDWeakMap::~IDWeakMap() {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
auto copied_map = map_;
for (auto el = copied_map.begin(); el != copied_map.end(); ++el)
Erase(isolate, el->first);
} }
bool IDWeakMap::Has(int key) const { bool IDWeakMap::Has(int key) const {
return map_.find(key) != map_.end(); return map_.find(key) != map_.end();
} }
void IDWeakMap::Erase(v8::Isolate* isolate, int key) { void IDWeakMap::Erase(int key) {
if (!Has(key)) { if (Has(key))
map_.erase(key);
else
LOG(WARNING) << "Object with key " << key << " is being GCed for twice."; LOG(WARNING) << "Object with key " << key << " is being GCed for twice.";
return;
}
v8::Persistent<v8::Value> value = map_[key];
value.ClearWeak(isolate);
value.Dispose(isolate);
value.Clear();
map_.erase(key);
} }
int IDWeakMap::GetNextID() { int IDWeakMap::GetNextID() {
@ -47,104 +39,92 @@ int IDWeakMap::GetNextID() {
// static // static
void IDWeakMap::WeakCallback(v8::Isolate* isolate, void IDWeakMap::WeakCallback(v8::Isolate* isolate,
v8::Persistent<v8::Value> value, v8::Persistent<v8::Object>* value,
void *data) { IDWeakMap* self) {
v8::HandleScope scope; v8::HandleScope handle_scope(isolate);
v8::Local<v8::Object> local = v8::Local<v8::Object>::New(isolate, *value);
IDWeakMap* obj = static_cast<IDWeakMap*>(data); self->Erase(
int key = value->ToObject()->GetHiddenValue( FromV8Value(local->GetHiddenValue(v8::String::New("IDWeakMapKey"))));
v8::String::New("IDWeakMapKey"))->IntegerValue();
obj->Erase(isolate, key);
} }
// static // static
v8::Handle<v8::Value> IDWeakMap::New(const v8::Arguments& args) { void IDWeakMap::New(const v8::FunctionCallbackInfo<v8::Value>& args) {
IDWeakMap* obj = new IDWeakMap(); (new IDWeakMap)->Wrap(args.This());
obj->Wrap(args.This());
return args.This();
} }
// static // static
v8::Handle<v8::Value> IDWeakMap::Add(const v8::Arguments& args) { void IDWeakMap::Add(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (!args[0]->IsObject()) if (!args[0]->IsObject())
return node::ThrowTypeError("Bad argument"); return node::ThrowTypeError("Bad argument");
v8::Isolate* isolate = v8::Isolate::GetCurrent(); IDWeakMap* self = Unwrap<IDWeakMap>(args.This());
IDWeakMap* obj = ObjectWrap::Unwrap<IDWeakMap>(args.This());
int key = obj->GetNextID();
v8::Handle<v8::Value> v8_key = v8::Integer::New(key); int key = self->GetNextID();
v8::Persistent<v8::Value> value = v8::Local<v8::Object> v8_value = args[0]->ToObject();
v8::Persistent<v8::Value>::New(isolate, args[0]); v8_value->SetHiddenValue(v8::String::New("IDWeakMapKey"), ToV8Value(key));
value->ToObject()->SetHiddenValue(v8::String::New("IDWeakMapKey"), v8_key); self->map_[key] = new RefCountedPersistent<v8::Object>(v8_value);
value.MakeWeak(isolate, obj, WeakCallback); self->map_[key]->MakeWeak(self, WeakCallback);
obj->map_[key] = value;
return v8_key; args.GetReturnValue().Set(key);
} }
// static // static
v8::Handle<v8::Value> IDWeakMap::Get(const v8::Arguments& args) { void IDWeakMap::Get(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (!args[0]->IsNumber()) int key;
if (!FromV8Arguments(args, &key))
return node::ThrowTypeError("Bad argument"); return node::ThrowTypeError("Bad argument");
IDWeakMap* obj = ObjectWrap::Unwrap<IDWeakMap>(args.This()); IDWeakMap* self = Unwrap<IDWeakMap>(args.This());
if (!self->Has(key))
int key = args[0]->IntegerValue();
if (!obj->Has(key))
return node::ThrowError("Invalid key"); return node::ThrowError("Invalid key");
return obj->map_[key]; args.GetReturnValue().Set(self->map_[key]->NewHandle());
} }
// static // static
v8::Handle<v8::Value> IDWeakMap::Has(const v8::Arguments& args) { void IDWeakMap::Has(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (!args[0]->IsNumber()) int key;
if (!FromV8Arguments(args, &key))
return node::ThrowTypeError("Bad argument"); return node::ThrowTypeError("Bad argument");
IDWeakMap* obj = ObjectWrap::Unwrap<IDWeakMap>(args.This()); IDWeakMap* self = Unwrap<IDWeakMap>(args.This());
args.GetReturnValue().Set(self->Has(key));
int key = args[0]->IntegerValue();
return v8::Boolean::New(obj->Has(key));
} }
// static // static
v8::Handle<v8::Value> IDWeakMap::Keys(const v8::Arguments& args) { void IDWeakMap::Keys(const v8::FunctionCallbackInfo<v8::Value>& args) {
IDWeakMap* obj = ObjectWrap::Unwrap<IDWeakMap>(args.This()); IDWeakMap* self = Unwrap<IDWeakMap>(args.This());
v8::Handle<v8::Array> keys = v8::Array::New(obj->map_.size()); v8::Local<v8::Array> keys = v8::Array::New(self->map_.size());
int i = 0; int i = 0;
for (auto el = obj->map_.begin(); el != obj->map_.end(); ++el) { for (auto el = self->map_.begin(); el != self->map_.end(); ++el) {
keys->Set(i, v8::Integer::New(el->first)); keys->Set(i, ToV8Value(el->first));
++i; ++i;
} }
return keys; args.GetReturnValue().Set(keys);
} }
// static // static
v8::Handle<v8::Value> IDWeakMap::Remove(const v8::Arguments& args) { void IDWeakMap::Remove(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (!args[0]->IsNumber()) int key;
if (!FromV8Arguments(args, &key))
return node::ThrowTypeError("Bad argument"); return node::ThrowTypeError("Bad argument");
IDWeakMap* obj = ObjectWrap::Unwrap<IDWeakMap>(args.This()); IDWeakMap* self = Unwrap<IDWeakMap>(args.This());
if (!self->Has(key))
int key = args[0]->IntegerValue();
if (!obj->Has(key))
return node::ThrowError("Invalid key"); return node::ThrowError("Invalid key");
obj->Erase(v8::Isolate::GetCurrent(), key); self->Erase(key);
return v8::Undefined();
} }
// static // static
void IDWeakMap::Initialize(v8::Handle<v8::Object> target) { void IDWeakMap::Initialize(v8::Handle<v8::Object> target) {
v8::HandleScope scope; v8::HandleScope handle_scope(node_isolate);
v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(IDWeakMap::New); v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(New);
t->InstanceTemplate()->SetInternalFieldCount(1); t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(v8::String::NewSymbol("IDWeakMap")); t->SetClassName(v8::String::NewSymbol("IDWeakMap"));

View file

@ -9,6 +9,7 @@
#include <map> #include <map>
#include "base/basictypes.h" #include "base/basictypes.h"
#include "common/v8/scoped_persistent.h"
#include "vendor/node/src/node_object_wrap.h" #include "vendor/node/src/node_object_wrap.h"
namespace atom { namespace atom {
@ -24,23 +25,22 @@ class IDWeakMap : public node::ObjectWrap {
virtual ~IDWeakMap(); virtual ~IDWeakMap();
bool Has(int key) const; bool Has(int key) const;
void Erase(v8::Isolate* isolate, int key); void Erase(int key);
int GetNextID(); int GetNextID();
static void WeakCallback(v8::Isolate* isolate, static void WeakCallback(v8::Isolate* isolate,
v8::Persistent<v8::Value> value, v8::Persistent<v8::Object>* value,
void *data); IDWeakMap* self);
static v8::Handle<v8::Value> New(const v8::Arguments& args); static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> Add(const v8::Arguments& args); static void Add(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> Get(const v8::Arguments& args); static void Get(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> Has(const v8::Arguments& args); static void Has(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> Keys(const v8::Arguments& args); static void Keys(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> Remove(const v8::Arguments& args); static void Remove(const v8::FunctionCallbackInfo<v8::Value>& args);
int next_id_; int next_id_;
std::map<int, RefCountedV8Object> map_;
std::map<int, v8::Persistent<v8::Value>> map_;
DISALLOW_COPY_AND_ASSIGN(IDWeakMap); DISALLOW_COPY_AND_ASSIGN(IDWeakMap);
}; };

View file

@ -8,91 +8,65 @@
#include "base/files/file_path.h" #include "base/files/file_path.h"
#include "common/platform_util.h" #include "common/platform_util.h"
#include "googleurl/src/gurl.h" #include "common/v8/native_type_conversions.h"
#include "vendor/node/src/node.h" #include "url/gurl.h"
#include "common/v8/node_common.h"
namespace atom { namespace atom {
namespace api { namespace api {
namespace {
bool V8ValueToFilePath(v8::Handle<v8::Value> value, base::FilePath* path) {
if (!value->IsString())
return false;
std::string file_path_string(*v8::String::Utf8Value(value));
base::FilePath file_path = base::FilePath::FromUTF8Unsafe(file_path_string);
if (file_path.empty())
return false;
*path = file_path;
return true;
}
} // namespace
// static // static
v8::Handle<v8::Value> Shell::ShowItemInFolder(const v8::Arguments &args) { void Shell::ShowItemInFolder(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope;
base::FilePath file_path; base::FilePath file_path;
if (!V8ValueToFilePath(args[0], &file_path)) if (!FromV8Arguments(args, &file_path))
return node::ThrowTypeError("Bad argument"); return node::ThrowTypeError("Bad argument");
platform_util::ShowItemInFolder(file_path); platform_util::ShowItemInFolder(file_path);
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Shell::OpenItem(const v8::Arguments &args) { void Shell::OpenItem(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope;
base::FilePath file_path; base::FilePath file_path;
if (!V8ValueToFilePath(args[0], &file_path)) if (!FromV8Arguments(args, &file_path))
return node::ThrowTypeError("Bad argument"); return node::ThrowTypeError("Bad argument");
platform_util::OpenItem(file_path); platform_util::OpenItem(file_path);
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Shell::OpenExternal(const v8::Arguments &args) { void Shell::OpenExternal(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope; GURL url;
if (!FromV8Arguments(args, &url))
if (!args[0]->IsString())
return node::ThrowTypeError("Bad argument"); return node::ThrowTypeError("Bad argument");
platform_util::OpenExternal(GURL(*v8::String::Utf8Value(args[0]))); platform_util::OpenExternal(url);
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Shell::MoveItemToTrash(const v8::Arguments &args) { void Shell::MoveItemToTrash(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope;
base::FilePath file_path; base::FilePath file_path;
if (!V8ValueToFilePath(args[0], &file_path)) if (!FromV8Arguments(args, &file_path))
return node::ThrowTypeError("Bad argument"); return node::ThrowTypeError("Bad argument");
platform_util::MoveItemToTrash(file_path); platform_util::MoveItemToTrash(file_path);
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> Shell::Beep(const v8::Arguments &args) { void Shell::Beep(const v8::FunctionCallbackInfo<v8::Value>& args) {
platform_util::Beep(); platform_util::Beep();
return v8::Undefined();
} }
// static // static
void Shell::Initialize(v8::Handle<v8::Object> target) { void Shell::Initialize(v8::Handle<v8::Object> target) {
node::SetMethod(target, "showItemInFolder", ShowItemInFolder); v8::HandleScope handle_scope(node_isolate);
node::SetMethod(target, "openItem", OpenItem);
node::SetMethod(target, "openExternal", OpenExternal); NODE_SET_METHOD(target, "showItemInFolder", ShowItemInFolder);
node::SetMethod(target, "moveItemToTrash", MoveItemToTrash); NODE_SET_METHOD(target, "openItem", OpenItem);
node::SetMethod(target, "beep", Beep); NODE_SET_METHOD(target, "openExternal", OpenExternal);
NODE_SET_METHOD(target, "moveItemToTrash", MoveItemToTrash);
NODE_SET_METHOD(target, "beep", Beep);
} }
} // namespace api } // namespace api

View file

@ -17,11 +17,11 @@ class Shell {
static void Initialize(v8::Handle<v8::Object> target); static void Initialize(v8::Handle<v8::Object> target);
private: private:
static v8::Handle<v8::Value> ShowItemInFolder(const v8::Arguments &args); static void ShowItemInFolder(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> OpenItem(const v8::Arguments &args); static void OpenItem(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> OpenExternal(const v8::Arguments &args); static void OpenExternal(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> MoveItemToTrash(const v8::Arguments &args); static void MoveItemToTrash(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> Beep(const v8::Arguments &args); static void Beep(const v8::FunctionCallbackInfo<v8::Value>& args);
DISALLOW_IMPLICIT_CONSTRUCTORS(Shell); DISALLOW_IMPLICIT_CONSTRUCTORS(Shell);
}; };

View file

@ -3,9 +3,11 @@
// found in the LICENSE file. // found in the LICENSE file.
#include "common/api/object_life_monitor.h" #include "common/api/object_life_monitor.h"
#include "common/v8/native_type_conversions.h"
#include "v8/include/v8-profiler.h" #include "v8/include/v8-profiler.h"
#include "vendor/node/src/node.h"
#include "vendor/node/src/node_internals.h" #include "common/v8/node_common.h"
namespace atom { namespace atom {
@ -13,48 +15,39 @@ namespace api {
namespace { namespace {
v8::Handle<v8::Value> DummyNew(const v8::Arguments& args) { void CreateObjectWithName(const v8::FunctionCallbackInfo<v8::Value>& args) {
return args.This(); v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
}
v8::Handle<v8::Value> CreateObjectWithName(const v8::Arguments& args) {
v8::HandleScope scope;
v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(DummyNew);
t->SetClassName(args[0]->ToString()); t->SetClassName(args[0]->ToString());
args.GetReturnValue().Set(t->GetFunction()->NewInstance());
return scope.Close(t->GetFunction()->NewInstance());
} }
v8::Handle<v8::Value> GetHiddenValue(const v8::Arguments& args) { void GetHiddenValue(const v8::FunctionCallbackInfo<v8::Value>& args) {
return args[0]->ToObject()->GetHiddenValue(args[1]->ToString()); args.GetReturnValue().Set(
args[0]->ToObject()->GetHiddenValue(args[1]->ToString()));
} }
v8::Handle<v8::Value> SetHiddenValue(const v8::Arguments& args) { void SetHiddenValue(const v8::FunctionCallbackInfo<v8::Value>& args) {
args[0]->ToObject()->SetHiddenValue(args[1]->ToString(), args[2]); args[0]->ToObject()->SetHiddenValue(args[1]->ToString(), args[2]);
return v8::Undefined();
} }
v8::Handle<v8::Value> GetObjectHash(const v8::Arguments& args) { void GetObjectHash(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope handle_scope; args.GetReturnValue().Set(args[0]->ToObject()->GetIdentityHash());
return handle_scope.Close(v8::Integer::New(
args[0]->ToObject()->GetIdentityHash()));
} }
v8::Handle<v8::Value> SetDestructor(const v8::Arguments& args) { void SetDestructor(const v8::FunctionCallbackInfo<v8::Value>& args) {
ObjectLifeMonitor::BindTo(args[0]->ToObject(), args[1]); ObjectLifeMonitor::BindTo(args[0]->ToObject(), args[1]);
return v8::Undefined();
} }
v8::Handle<v8::Value> TakeHeapSnapshot(const v8::Arguments& args) { void TakeHeapSnapshot(const v8::FunctionCallbackInfo<v8::Value>& args) {
node::node_isolate->GetHeapProfiler()->TakeHeapSnapshot( node::node_isolate->GetHeapProfiler()->TakeHeapSnapshot(
v8::String::New("test")); v8::String::New("test"));
return v8::Undefined();
} }
} // namespace } // namespace
void InitializeV8Util(v8::Handle<v8::Object> target) { void InitializeV8Util(v8::Handle<v8::Object> target) {
v8::HandleScope handle_scope(node_isolate);
NODE_SET_METHOD(target, "createObjectWithName", CreateObjectWithName); NODE_SET_METHOD(target, "createObjectWithName", CreateObjectWithName);
NODE_SET_METHOD(target, "getHiddenValue", GetHiddenValue); NODE_SET_METHOD(target, "getHiddenValue", GetHiddenValue);
NODE_SET_METHOD(target, "setHiddenValue", SetHiddenValue); NODE_SET_METHOD(target, "setHiddenValue", SetHiddenValue);

View file

@ -6,8 +6,9 @@
#include "base/logging.h" #include "base/logging.h"
#include "common/atom_version.h" #include "common/atom_version.h"
#include "common/v8_conversions.h" #include "common/v8/native_type_conversions.h"
#include "vendor/node/src/node.h"
#include "common/v8/node_common.h"
namespace atom { namespace atom {
@ -50,22 +51,20 @@ AtomBindings::~AtomBindings() {
} }
void AtomBindings::BindTo(v8::Handle<v8::Object> process) { void AtomBindings::BindTo(v8::Handle<v8::Object> process) {
v8::HandleScope scope; v8::HandleScope handle_scope(node_isolate);
node::SetMethod(process, "atomBinding", Binding); NODE_SET_METHOD(process, "atomBinding", Binding);
node::SetMethod(process, "crash", Crash); NODE_SET_METHOD(process, "crash", Crash);
node::SetMethod(process, "activateUvLoop", ActivateUVLoop); NODE_SET_METHOD(process, "activateUvLoop", ActivateUVLoop);
node::SetMethod(process, "log", Log); NODE_SET_METHOD(process, "log", Log);
node::SetMethod(process, "getCurrentStackTrace", GetCurrentStackTrace); NODE_SET_METHOD(process, "getCurrentStackTrace", GetCurrentStackTrace);
process->Get(v8::String::New("versions"))->ToObject()-> process->Get(v8::String::New("versions"))->ToObject()->
Set(v8::String::New("atom-shell"), v8::String::New(ATOM_VERSION_STRING)); Set(v8::String::New("atom-shell"), v8::String::New(ATOM_VERSION_STRING));
} }
// static // static
v8::Handle<v8::Value> AtomBindings::Binding(const v8::Arguments& args) { void AtomBindings::Binding(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope;
v8::Local<v8::String> module = args[0]->ToString(); v8::Local<v8::String> module = args[0]->ToString();
v8::String::Utf8Value module_v(module); v8::String::Utf8Value module_v(module);
node::node_module_struct* modp; node::node_module_struct* modp;
@ -93,7 +92,7 @@ v8::Handle<v8::Value> AtomBindings::Binding(const v8::Arguments& args) {
if (binding_cache->Has(module)) { if (binding_cache->Has(module)) {
exports = binding_cache->Get(module)->ToObject(); exports = binding_cache->Get(module)->ToObject();
return scope.Close(exports); return args.GetReturnValue().Set(exports);
} }
if ((modp = GetBuiltinModule(*module_v, is_browser)) != NULL) { if ((modp = GetBuiltinModule(*module_v, is_browser)) != NULL) {
@ -102,39 +101,36 @@ v8::Handle<v8::Value> AtomBindings::Binding(const v8::Arguments& args) {
// only exports. // only exports.
modp->register_func(exports, v8::Undefined()); modp->register_func(exports, v8::Undefined());
binding_cache->Set(module, exports); binding_cache->Set(module, exports);
return scope.Close(exports); return args.GetReturnValue().Set(exports);
} }
return v8::ThrowException(v8::Exception::Error( return node::ThrowError("No such module");
v8::String::New("No such module")));
} }
// static // static
v8::Handle<v8::Value> AtomBindings::Crash(const v8::Arguments& args) { void AtomBindings::Crash(const v8::FunctionCallbackInfo<v8::Value>& args) {
static_cast<DummyClass*>(NULL)->crash = true; static_cast<DummyClass*>(NULL)->crash = true;
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> AtomBindings::ActivateUVLoop(const v8::Arguments& args) { void AtomBindings::ActivateUVLoop(
const v8::FunctionCallbackInfo<v8::Value>& args) {
uv_async_send(&dummy_uv_handle); uv_async_send(&dummy_uv_handle);
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> AtomBindings::Log(const v8::Arguments& args) { void AtomBindings::Log(const v8::FunctionCallbackInfo<v8::Value>& args) {
std::string message; std::string message;
for (int i = 0; i < args.Length(); ++i) for (int i = 0; i < args.Length(); ++i)
message += *v8::String::Utf8Value(args[i]); message += *v8::String::Utf8Value(args[i]);
logging::LogMessage("CONSOLE", 0, 0).stream() << message; logging::LogMessage("CONSOLE", 0, 0).stream() << message;
return v8::Undefined();
} }
// static // static
v8::Handle<v8::Value> AtomBindings::GetCurrentStackTrace( void AtomBindings::GetCurrentStackTrace(
const v8::Arguments& args) { const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope; v8::HandleScope handle_scope(args.GetIsolate());
int stack_limit = kMaxCallStackSize; int stack_limit = kMaxCallStackSize;
FromV8Arguments(args, &stack_limit); FromV8Arguments(args, &stack_limit);
@ -147,7 +143,7 @@ v8::Handle<v8::Value> AtomBindings::GetCurrentStackTrace(
for (int i = 0; i < frame_count; ++i) for (int i = 0; i < frame_count; ++i)
result->Set(i, DumpStackFrame(stack_trace->GetFrame(i))); result->Set(i, DumpStackFrame(stack_trace->GetFrame(i)));
return scope.Close(result); args.GetReturnValue().Set(result);
} }
} // namespace atom } // namespace atom

View file

@ -20,11 +20,12 @@ class AtomBindings {
virtual void BindTo(v8::Handle<v8::Object> process); virtual void BindTo(v8::Handle<v8::Object> process);
private: private:
static v8::Handle<v8::Value> Binding(const v8::Arguments& args); static void Binding(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> Crash(const v8::Arguments& args); static void Crash(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> ActivateUVLoop(const v8::Arguments& args); static void ActivateUVLoop(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> Log(const v8::Arguments& args); static void Log(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Handle<v8::Value> GetCurrentStackTrace(const v8::Arguments& args); static void GetCurrentStackTrace(
const v8::FunctionCallbackInfo<v8::Value>& args);
DISALLOW_COPY_AND_ASSIGN(AtomBindings); DISALLOW_COPY_AND_ASSIGN(AtomBindings);
}; };

View file

@ -5,10 +5,11 @@
#include <string.h> #include <string.h>
#include <stdio.h> #include <stdio.h>
#include "base/string_util.h" #include "base/strings/string_util.h"
#include "vendor/node/src/node.h"
#include "vendor/node/src/node_version.h" #include "vendor/node/src/node_version.h"
#include "common/v8/node_common.h"
namespace atom { namespace atom {
#undef NODE_EXT_LIST_START #undef NODE_EXT_LIST_START

View file

@ -10,42 +10,29 @@ namespace atom {
// static // static
void ObjectLifeMonitor::BindTo(v8::Handle<v8::Object> target, void ObjectLifeMonitor::BindTo(v8::Handle<v8::Object> target,
v8::Handle<v8::Value> destructor) { v8::Handle<v8::Value> destructor) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
target->SetHiddenValue(v8::String::New("destructor"), destructor); target->SetHiddenValue(v8::String::New("destructor"), destructor);
ObjectLifeMonitor* olm = new ObjectLifeMonitor(); ObjectLifeMonitor* olm = new ObjectLifeMonitor();
olm->handle_ = v8::Persistent<v8::Object>::New(isolate, target); olm->handle_.reset(target);
olm->handle_.MakeWeak(isolate, olm, WeakCallback); olm->handle_.MakeWeak(olm, WeakCallback);
} }
ObjectLifeMonitor::ObjectLifeMonitor() { ObjectLifeMonitor::ObjectLifeMonitor() {
} }
ObjectLifeMonitor::~ObjectLifeMonitor() {
if (!handle_.IsEmpty()) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
handle_.ClearWeak(isolate);
handle_.Dispose(isolate);
handle_.Clear();
}
}
// static // static
void ObjectLifeMonitor::WeakCallback(v8::Isolate* isolate, void ObjectLifeMonitor::WeakCallback(v8::Isolate* isolate,
v8::Persistent<v8::Value> value, v8::Persistent<v8::Object>* value,
void *data) { ObjectLifeMonitor* self) {
// destructor.call(object, object); // destructor.call(object, object);
{ {
v8::HandleScope scope; v8::HandleScope handle_scope(isolate);
v8::Local<v8::Object> obj = self->handle_.NewHandle();
v8::Local<v8::Object> obj = value->ToObject();
v8::Local<v8::Value> args[] = { obj };
v8::Local<v8::Function>::Cast(obj->GetHiddenValue( v8::Local<v8::Function>::Cast(obj->GetHiddenValue(
v8::String::New("destructor")))->Call(obj, 1, args); v8::String::New("destructor")))->Call(obj, 0, NULL);
} }
ObjectLifeMonitor* obj = static_cast<ObjectLifeMonitor*>(data); delete self;
delete obj;
} }
} // namespace atom } // namespace atom

View file

@ -7,7 +7,7 @@
#define ATOM_COMMON_API_OBJECT_LIFE_MONITOR_H_ #define ATOM_COMMON_API_OBJECT_LIFE_MONITOR_H_
#include "base/basictypes.h" #include "base/basictypes.h"
#include "v8/include/v8.h" #include "common/v8/scoped_persistent.h"
namespace atom { namespace atom {
@ -18,13 +18,12 @@ class ObjectLifeMonitor {
private: private:
ObjectLifeMonitor(); ObjectLifeMonitor();
virtual ~ObjectLifeMonitor();
static void WeakCallback(v8::Isolate* isolate, static void WeakCallback(v8::Isolate* isolate,
v8::Persistent<v8::Value> value, v8::Persistent<v8::Object>* value,
void *data); ObjectLifeMonitor* self);
v8::Persistent<v8::Object> handle_; ScopedPersistent<v8::Object> handle_;
DISALLOW_COPY_AND_ASSIGN(ObjectLifeMonitor); DISALLOW_COPY_AND_ASSIGN(ObjectLifeMonitor);
}; };

View file

@ -6,10 +6,10 @@
#define ATOM_VERSION_H #define ATOM_VERSION_H
#define ATOM_MAJOR_VERSION 0 #define ATOM_MAJOR_VERSION 0
#define ATOM_MINOR_VERSION 7 #define ATOM_MINOR_VERSION 8
#define ATOM_PATCH_VERSION 6 #define ATOM_PATCH_VERSION 0
#define ATOM_VERSION_IS_RELEASE 1 #define ATOM_VERSION_IS_RELEASE 0
#ifndef ATOM_TAG #ifndef ATOM_TAG
# define ATOM_TAG "" # define ATOM_TAG ""

View file

@ -7,8 +7,8 @@
#include "base/file_util.h" #include "base/file_util.h"
#include "base/logging.h" #include "base/logging.h"
#include "base/memory/singleton.h" #include "base/memory/singleton.h"
#include "base/string_util.h" #include "base/strings/string_util.h"
#include "base/utf_string_conversions.h" #include "base/strings/utf_string_conversions.h"
namespace crash_reporter { namespace crash_reporter {

View file

@ -350,7 +350,7 @@ void CrashService::OnClientDumpRequest(void* context,
file_util::CreateDirectoryW(alternate_dump_location); file_util::CreateDirectoryW(alternate_dump_location);
alternate_dump_location = alternate_dump_location.Append( alternate_dump_location = alternate_dump_location.Append(
dump_location.BaseName()); dump_location.BaseName());
file_util::Move(dump_location, alternate_dump_location); base::Move(dump_location, alternate_dump_location);
dump_location = alternate_dump_location; dump_location = alternate_dump_location;
} }

View file

@ -8,7 +8,7 @@
#include "base/command_line.h" #include "base/command_line.h"
#include "base/file_util.h" #include "base/file_util.h"
#include "base/logging.h" #include "base/logging.h"
#include "base/string_util.h" #include "base/strings/string_util.h"
#include "common/crash_reporter/win/crash_service.h" #include "common/crash_reporter/win/crash_service.h"
namespace crash_service { namespace crash_service {
@ -26,7 +26,7 @@ bool GetCrashServiceDirectory(const std::wstring& application_name,
if (!file_util::GetTempDir(&temp_dir)) if (!file_util::GetTempDir(&temp_dir))
return false; return false;
temp_dir = temp_dir.Append(application_name + L" Crashes"); temp_dir = temp_dir.Append(application_name + L" Crashes");
if (!file_util::PathExists(temp_dir)) { if (!base::PathExists(temp_dir)) {
if (!file_util::CreateDirectory(temp_dir)) if (!file_util::CreateDirectory(temp_dir))
return false; return false;
} }
@ -56,14 +56,14 @@ int Main(const wchar_t* cmd) {
GetCrashServiceDirectory(application_name, &operating_dir); GetCrashServiceDirectory(application_name, &operating_dir);
base::FilePath log_file = operating_dir.Append(kStandardLogFile); base::FilePath log_file = operating_dir.Append(kStandardLogFile);
// Logging out to a file. // Logging to stderr (to help with debugging failures on the
logging::InitLogging( // buildbots) and to a file.
log_file.value().c_str(), logging::LoggingSettings settings;
logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG , settings.logging_dest = logging::LOG_TO_ALL;
logging::LOCK_LOG_FILE, settings.log_file = log_file.value().c_str();
logging::DELETE_OLD_LOG_FILE, logging::InitLogging(settings);
logging::DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS); // Logging with pid, tid and timestamp.
logging::SetLogItems(true, false, true, false); logging::SetLogItems(true, true, true, false);
VLOG(1) << "Session start. cmdline is [" << cmd << "]"; VLOG(1) << "Session start. cmdline is [" << cmd << "]";

View file

@ -5,32 +5,62 @@
#include "common/node_bindings.h" #include "common/node_bindings.h"
#include "base/command_line.h" #include "base/command_line.h"
#include "base/logging.h" #include "base/message_loop/message_loop.h"
#include "base/message_loop.h" #include "base/base_paths.h"
#include "common/v8_conversions.h" #include "base/path_service.h"
#include "common/v8/native_type_conversions.h"
#include "content/public/browser/browser_thread.h" #include "content/public/browser/browser_thread.h"
#include "net/base/escape.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "vendor/node/src/node.h"
#include "vendor/node/src/node_internals.h"
#include "vendor/node/src/node_javascript.h"
#if defined(OS_WIN) #if defined(OS_WIN)
#include "base/strings/utf_string_conversions.h" #include "base/strings/utf_string_conversions.h"
#endif #endif
#include "common/v8/node_common.h"
using content::BrowserThread; using content::BrowserThread;
// Forward declaration of internal node functions.
namespace node {
void Init(int*, const char**, int*, const char***);
void Load(Environment* env);
void SetupProcessObject(Environment*, int, const char* const*, int,
const char* const*);
}
namespace atom { namespace atom {
namespace { namespace {
// Empty callback for async handle.
void UvNoOp(uv_async_t* handle, int status) { void UvNoOp(uv_async_t* handle, int status) {
} }
// Convert the given vector to an array of C-strings. The strings in the
// returned vector are only guaranteed valid so long as the vector of strings
// is not modified.
scoped_ptr<const char*[]> StringVectorToArgArray(
const std::vector<std::string>& vector) {
scoped_ptr<const char*[]> array(new const char*[vector.size()]);
for (size_t i = 0; i < vector.size(); ++i)
array[i] = vector[i].c_str();
return array.Pass();
}
#if defined(OS_WIN)
std::vector<std::string> String16VectorToStringVector(
const std::vector<string16>& vector) {
std::vector<std::string> utf8_vector;
utf8_vector.reserve(vector.size());
for (size_t i = 0; i < vector.size(); ++i)
utf8_vector.push_back(UTF16ToUTF8(vector[i]));
return utf8_vector;
}
#endif
} // namespace } // namespace
node::Environment* global_env = NULL;
NodeBindings::NodeBindings(bool is_browser) NodeBindings::NodeBindings(bool is_browser)
: is_browser_(is_browser), : is_browser_(is_browser),
message_loop_(NULL), message_loop_(NULL),
@ -54,84 +84,88 @@ NodeBindings::~NodeBindings() {
} }
void NodeBindings::Initialize() { void NodeBindings::Initialize() {
CommandLine::StringVector str_argv = CommandLine::ForCurrentProcess()->argv(); // Init idle GC for browser.
if (is_browser_) {
#if defined(OS_WIN) uv_timer_init(uv_default_loop(), &idle_timer_);
std::vector<std::string> utf8_str_argv; uv_timer_start(&idle_timer_, IdleCallback, 5000, 5000);
utf8_str_argv.reserve(str_argv.size());
#endif
// Convert string vector to char* array.
std::vector<char*> argv(str_argv.size(), NULL);
for (size_t i = 0; i < str_argv.size(); ++i) {
#if defined(OS_WIN)
utf8_str_argv.push_back(UTF16ToUTF8(str_argv[i]));
argv[i] = const_cast<char*>(utf8_str_argv[i].c_str());
#else
argv[i] = const_cast<char*>(str_argv[i].c_str());
#endif
} }
// Init idle GC.
uv_timer_init(uv_default_loop(), &idle_timer_);
uv_timer_start(&idle_timer_, IdleCallback, 5000, 5000);
// Open node's error reporting system for browser process. // Open node's error reporting system for browser process.
node::g_standalone_mode = is_browser_; node::g_standalone_mode = is_browser_;
node::g_upstream_node_mode = false; node::g_upstream_node_mode = false;
// Init node. // Init node.
node::Init(argv.size(), &argv[0]); // (we assume it would not node::Init would not modify the parameters under
v8::V8::Initialize(); // embedded mode).
node::Init(NULL, NULL, NULL, NULL);
// Load node.js.
v8::HandleScope scope;
node::g_context = v8::Persistent<v8::Context>::New(
node::node_isolate, v8::Context::New(node::node_isolate));
{
v8::Context::Scope context_scope(node::g_context);
v8::Handle<v8::Object> process = node::SetupProcessObject(
argv.size(), &argv[0]);
// Tell node.js we are in browser or renderer.
v8::Handle<v8::String> type =
is_browser_ ? v8::String::New("browser") : v8::String::New("renderer");
process->Set(v8::String::New("__atom_type"), type);
}
} }
void NodeBindings::Load() { node::Environment* NodeBindings::CreateEnvironment(
v8::HandleScope scope; v8::Handle<v8::Context> context) {
v8::Context::Scope context_scope(node::g_context); std::vector<std::string> args =
node::Load(node::process); #if defined(OS_WIN)
} String16VectorToStringVector(CommandLine::ForCurrentProcess()->argv());
#else
CommandLine::ForCurrentProcess()->argv();
#endif
void NodeBindings::BindTo(WebKit::WebFrame* frame) { // Feed node the path to initialization script.
v8::HandleScope handle_scope; base::FilePath exec_path(CommandLine::ForCurrentProcess()->argv()[0]);
PathService::Get(base::FILE_EXE, &exec_path);
base::FilePath resources_path =
#if defined(OS_MACOSX)
is_browser_ ? exec_path.DirName().DirName().Append("Resources") :
exec_path.DirName().DirName().DirName().DirName().DirName()
.Append("Resources");
#else
exec_path.DirName().AppendASCII("resources");
#endif
base::FilePath script_path =
resources_path.AppendASCII(is_browser_ ? "browser" : "renderer")
.AppendASCII("lib")
.AppendASCII("init.js");
std::string script_path_str = script_path.AsUTF8Unsafe();
args.insert(args.begin() + 1, script_path_str.c_str());
v8::Handle<v8::Context> context = frame->mainWorldScriptContext(); // Convert string vector to const char* array.
if (context.IsEmpty()) scoped_ptr<const char*[]> c_argv = StringVectorToArgArray(args);
return;
v8::Context::Scope scope(context); // Construct the parameters that passed to node::CreateEnvironment:
v8::Isolate* isolate = context->GetIsolate();
int argc = args.size();
const char** argv = c_argv.get();
int exec_argc = 0;
const char** exec_argv = NULL;
// Erase security token. using namespace v8; // NOLINT
context->SetSecurityToken(node::g_context->GetSecurityToken()); using namespace node; // NOLINT
// Evaluate cefode.js. // Following code are stripped from node::CreateEnvironment in node.cc:
v8::Handle<v8::Script> script = node::CompileCefodeMainSource(); HandleScope handle_scope(isolate);
v8::Local<v8::Value> result = script->Run(); Context::Scope context_scope(context);
// Run the script of cefode.js. Environment* env = Environment::New(context);
std::string script_path(GURL(frame->document().url()).path());
script_path = net::UnescapeURLComponent( uv_check_init(env->event_loop(), env->immediate_check_handle());
script_path, uv_unref(
net::UnescapeRule::SPACES | net::UnescapeRule::URL_SPECIAL_CHARS); reinterpret_cast<uv_handle_t*>(env->immediate_check_handle()));
v8::Handle<v8::Value> args[2] = { uv_idle_init(env->event_loop(), env->immediate_idle_handle());
v8::Local<v8::Value>::New(node::process),
ToV8Value(script_path), uv_prepare_init(env->event_loop(), env->idle_prepare_handle());
}; uv_check_init(env->event_loop(), env->idle_check_handle());
v8::Local<v8::Function>::Cast(result)->Call(context->Global(), 2, args); uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_prepare_handle()));
uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_check_handle()));
Local<FunctionTemplate> process_template = FunctionTemplate::New();
process_template->SetClassName(FIXED_ONE_BYTE_STRING(isolate, "process"));
Local<Object> process_object = process_template->GetFunction()->NewInstance();
env->set_process_object(process_object);
SetupProcessObject(env, argc, argv, exec_argc, exec_argv);
Load(env);
return env;
} }
void NodeBindings::PrepareMessageLoop() { void NodeBindings::PrepareMessageLoop() {
@ -160,8 +194,8 @@ void NodeBindings::UvRunOnce() {
DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI));
// Enter node context while dealing with uv events. // Enter node context while dealing with uv events.
v8::HandleScope scope; v8::HandleScope handle_scope(node_isolate);
v8::Context::Scope context_scope(node::g_context); v8::Context::Scope context_scope(global_env->context());
// Deal with uv events. // Deal with uv events.
int r = uv_run(uv_loop_, (uv_run_mode)(UV_RUN_ONCE | UV_RUN_NOWAIT)); int r = uv_run(uv_loop_, (uv_run_mode)(UV_RUN_ONCE | UV_RUN_NOWAIT));

View file

@ -2,20 +2,21 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
#ifndef RAVE_COMMON_NODE_BINDINGS_ #ifndef ATOM_COMMON_NODE_BINDINGS_H_
#define RAVE_COMMON_NODE_BINDINGS_ #define ATOM_COMMON_NODE_BINDINGS_H_
#include "base/basictypes.h" #include "base/basictypes.h"
#include "v8/include/v8.h"
#include "vendor/node/deps/uv/include/uv.h" #include "vendor/node/deps/uv/include/uv.h"
namespace WebKit {
class WebFrame;
}
namespace base { namespace base {
class MessageLoop; class MessageLoop;
} }
namespace node {
class Environment;
}
namespace atom { namespace atom {
class NodeBindings { class NodeBindings {
@ -24,14 +25,11 @@ class NodeBindings {
virtual ~NodeBindings(); virtual ~NodeBindings();
// Setup V8, libuv and the process object. // Setup V8, libuv.
virtual void Initialize(); virtual void Initialize();
// Load node.js main script. // Create the environment and load node.js.
virtual void Load(); virtual node::Environment* CreateEnvironment(v8::Handle<v8::Context> context);
// Load cefode.js script under web frame.
virtual void BindTo(WebKit::WebFrame* frame);
// Prepare for message loop integration. // Prepare for message loop integration.
virtual void PrepareMessageLoop(); virtual void PrepareMessageLoop();
@ -90,4 +88,4 @@ class NodeBindings {
} // namespace atom } // namespace atom
#endif // RAVE_COMMON_NODE_BINDINGS_ #endif // ATOM_COMMON_NODE_BINDINGS_H_

View file

@ -9,8 +9,7 @@
#include <sys/time.h> #include <sys/time.h>
#include <sys/types.h> #include <sys/types.h>
#include "vendor/node/src/node.h" #include "common/v8/node_common.h"
#include "vendor/node/src/node_internals.h"
namespace atom { namespace atom {
@ -27,23 +26,6 @@ NodeBindingsMac::NodeBindingsMac(bool is_browser)
NodeBindingsMac::~NodeBindingsMac() { NodeBindingsMac::~NodeBindingsMac() {
} }
void NodeBindingsMac::RunMessageLoop() {
// Get notified when libuv's watcher queue changes.
uv_loop_->data = this;
uv_loop_->on_watcher_queue_updated = OnWatcherQueueChanged;
NodeBindings::RunMessageLoop();
}
// static
void NodeBindingsMac::OnWatcherQueueChanged(uv_loop_t* loop) {
NodeBindingsMac* self = static_cast<NodeBindingsMac*>(loop->data);
// We need to break the io polling in the kqueue thread when loop's watcher
// queue changes, otherwise new events cannot be notified.
self->WakeupEmbedThread();
}
void NodeBindingsMac::PollEvents() { void NodeBindingsMac::PollEvents() {
struct timespec spec; struct timespec spec;
int timeout = uv_backend_timeout(uv_loop_); int timeout = uv_backend_timeout(uv_loop_);

View file

@ -15,12 +15,7 @@ class NodeBindingsMac : public NodeBindings {
explicit NodeBindingsMac(bool is_browser); explicit NodeBindingsMac(bool is_browser);
virtual ~NodeBindingsMac(); virtual ~NodeBindingsMac();
virtual void RunMessageLoop() OVERRIDE;
private: private:
// Called when uv's watcher queue changes.
static void OnWatcherQueueChanged(uv_loop_t* loop);
virtual void PollEvents() OVERRIDE; virtual void PollEvents() OVERRIDE;
// Kqueue to poll for uv's backend fd. // Kqueue to poll for uv's backend fd.

View file

@ -9,7 +9,6 @@
#include "base/logging.h" #include "base/logging.h"
extern "C" { extern "C" {
#include "vendor/node/deps/uv/include/uv-private/ngx-queue.h"
#include "vendor/node/deps/uv/src/win/internal.h" #include "vendor/node/deps/uv/src/win/internal.h"
} }
@ -32,7 +31,7 @@ void NodeBindingsWin::PollEvents() {
uv_loop_->endgame_handles == NULL && uv_loop_->endgame_handles == NULL &&
!uv_loop_->stop_flag && !uv_loop_->stop_flag &&
(uv_loop_->active_handles > 0 || (uv_loop_->active_handles > 0 ||
!ngx_queue_empty(&uv_loop_->active_reqs)); !QUEUE_EMPTY(&uv_loop_->active_reqs));
// When there is no other types of events, we block on the IOCP. // When there is no other types of events, we block on the IOCP.
if (block) { if (block) {

View file

@ -12,7 +12,7 @@
#include "base/mac/mac_logging.h" #include "base/mac/mac_logging.h"
#include "base/mac/scoped_aedesc.h" #include "base/mac/scoped_aedesc.h"
#include "base/strings/sys_string_conversions.h" #include "base/strings/sys_string_conversions.h"
#include "googleurl/src/gurl.h" #include "url/gurl.h"
namespace platform_util { namespace platform_util {

View file

@ -14,13 +14,13 @@
#include "base/bind_helpers.h" #include "base/bind_helpers.h"
#include "base/files/file_path.h" #include "base/files/file_path.h"
#include "base/logging.h" #include "base/logging.h"
#include "base/string_util.h" #include "base/strings/string_util.h"
#include "base/utf_string_conversions.h" #include "base/strings/utf_string_conversions.h"
#include "base/win/registry.h" #include "base/win/registry.h"
#include "base/win/scoped_co_mem.h" #include "base/win/scoped_co_mem.h"
#include "base/win/scoped_comptr.h" #include "base/win/scoped_comptr.h"
#include "base/win/windows_version.h" #include "base/win/windows_version.h"
#include "googleurl/src/gurl.h" #include "url/gurl.h"
#include "ui/base/win/shell.h" #include "ui/base/win/shell.h"
namespace { namespace {

View file

@ -2,24 +2,24 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
#ifndef COMMON_V8_CONVERSIONS_H_ #ifndef ATOM_COMMON_V8_NATIVE_TYPE_CONVERSIONS_H_
#define COMMON_V8_CONVERSIONS_H_ #define ATOM_COMMON_V8_NATIVE_TYPE_CONVERSIONS_H_
#include <map> #include <map>
#include <string> #include <string>
#include <vector> #include <vector>
#include "base/files/file_path.h" #include "base/files/file_path.h"
#include "base/string16.h" #include "base/strings/string16.h"
#include "base/template_util.h" #include "base/template_util.h"
#include "base/values.h" #include "base/values.h"
#include "browser/api/atom_api_window.h" #include "browser/api/atom_api_window.h"
#include "common/swap_or_assign.h" #include "common/swap_or_assign.h"
#include "common/v8_value_converter_impl.h" #include "common/v8/scoped_persistent.h"
#include "common/v8/v8_value_converter.h"
#include "content/public/renderer/v8_value_converter.h" #include "content/public/renderer/v8_value_converter.h"
#include "googleurl/src/gurl.h"
#include "ui/gfx/rect.h" #include "ui/gfx/rect.h"
#include "v8/include/v8.h" #include "url/gurl.h"
// Convert V8 value to arbitrary supported types. // Convert V8 value to arbitrary supported types.
struct FromV8Value { struct FromV8Value {
@ -66,8 +66,7 @@ struct FromV8Value {
} }
operator scoped_ptr<base::Value>() { operator scoped_ptr<base::Value>() {
scoped_ptr<content::V8ValueConverter> converter( scoped_ptr<atom::V8ValueConverter> converter(new atom::V8ValueConverter);
new atom::V8ValueConverterImpl);
return scoped_ptr<base::Value>( return scoped_ptr<base::Value>(
converter->FromV8Value(value_, v8::Context::GetCurrent())); converter->FromV8Value(value_, v8::Context::GetCurrent()));
} }
@ -104,10 +103,10 @@ struct FromV8Value {
return NULL; return NULL;
} }
operator v8::Persistent<v8::Function>() { operator atom::RefCountedV8Function() {
return v8::Persistent<v8::Function>::New( v8::Handle<v8::Function> func = v8::Handle<v8::Function>::Cast(value_);
node::node_isolate, return atom::RefCountedV8Function(
v8::Handle<v8::Function>::Cast(value_)); new atom::RefCountedPersistent<v8::Function>(func));
} }
v8::Handle<v8::Value> value_; v8::Handle<v8::Value> value_;
@ -226,14 +225,16 @@ bool V8ValueCanBeConvertedTo<atom::NativeWindow*>(v8::Handle<v8::Value> value) {
} }
template<> inline template<> inline
bool V8ValueCanBeConvertedTo<v8::Persistent<v8::Function>>( bool V8ValueCanBeConvertedTo<atom::RefCountedV8Function>(
v8::Handle<v8::Value> value) { v8::Handle<v8::Value> value) {
return value->IsFunction(); return value->IsFunction();
} }
// Check and convert V8's Arguments to native types. // Check and convert V8's Arguments to native types.
template<typename T1> inline template<typename T1> inline
bool FromV8Arguments(const v8::Arguments& args, T1* value, int index = 0) { bool FromV8Arguments(const v8::FunctionCallbackInfo<v8::Value>& args,
T1* value,
int index = 0) {
if (!V8ValueCanBeConvertedTo<T1>(args[index])) if (!V8ValueCanBeConvertedTo<T1>(args[index]))
return false; return false;
internal::SwapOrAssign(*value, internal::SwapOrAssign(*value,
@ -242,18 +243,23 @@ bool FromV8Arguments(const v8::Arguments& args, T1* value, int index = 0) {
} }
template<typename T1, typename T2> inline template<typename T1, typename T2> inline
bool FromV8Arguments(const v8::Arguments& args, T1* a1, T2* a2) { bool FromV8Arguments(const v8::FunctionCallbackInfo<v8::Value>& args,
T1* a1,
T2* a2) {
return FromV8Arguments<T1>(args, a1) && FromV8Arguments<T2>(args, a2, 1); return FromV8Arguments<T1>(args, a1) && FromV8Arguments<T2>(args, a2, 1);
} }
template<typename T1, typename T2, typename T3> inline template<typename T1, typename T2, typename T3> inline
bool FromV8Arguments(const v8::Arguments& args, T1* a1, T2* a2, T3* a3) { bool FromV8Arguments(const v8::FunctionCallbackInfo<v8::Value>& args,
T1* a1,
T2* a2,
T3* a3) {
return FromV8Arguments<T1, T2>(args, a1, a2) && return FromV8Arguments<T1, T2>(args, a1, a2) &&
FromV8Arguments<T3>(args, a3, 2); FromV8Arguments<T3>(args, a3, 2);
} }
template<typename T1, typename T2, typename T3, typename T4> inline template<typename T1, typename T2, typename T3, typename T4> inline
bool FromV8Arguments(const v8::Arguments& args, bool FromV8Arguments(const v8::FunctionCallbackInfo<v8::Value>& args,
T1* a1, T1* a1,
T2* a2, T2* a2,
T3* a3, T3* a3,
@ -263,7 +269,7 @@ bool FromV8Arguments(const v8::Arguments& args,
} }
template<typename T1, typename T2, typename T3, typename T4, typename T5> inline template<typename T1, typename T2, typename T3, typename T4, typename T5> inline
bool FromV8Arguments(const v8::Arguments& args, bool FromV8Arguments(const v8::FunctionCallbackInfo<v8::Value>& args,
T1* a1, T1* a1,
T2* a2, T2* a2,
T3* a3, T3* a3,
@ -275,7 +281,7 @@ bool FromV8Arguments(const v8::Arguments& args,
template<typename T1, typename T2, typename T3, typename T4, typename T5, template<typename T1, typename T2, typename T3, typename T4, typename T5,
typename T6> inline typename T6> inline
bool FromV8Arguments(const v8::Arguments& args, bool FromV8Arguments(const v8::FunctionCallbackInfo<v8::Value>& args,
T1* a1, T1* a1,
T2* a2, T2* a2,
T3* a3, T3* a3,
@ -288,7 +294,7 @@ bool FromV8Arguments(const v8::Arguments& args,
template<typename T1, typename T2, typename T3, typename T4, typename T5, template<typename T1, typename T2, typename T3, typename T4, typename T5,
typename T6, typename T7> inline typename T6, typename T7> inline
bool FromV8Arguments(const v8::Arguments& args, bool FromV8Arguments(const v8::FunctionCallbackInfo<v8::Value>& args,
T1* a1, T1* a1,
T2* a2, T2* a2,
T3* a3, T3* a3,
@ -301,4 +307,4 @@ bool FromV8Arguments(const v8::Arguments& args,
FromV8Arguments<T7>(args, a7, 6); FromV8Arguments<T7>(args, a7, 6);
} }
#endif // COMMON_V8_CONVERSIONS_H_ #endif // ATOM_COMMON_V8_NATIVE_TYPE_CONVERSIONS_H_

25
common/v8/node_common.h Normal file
View file

@ -0,0 +1,25 @@
// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ATOM_COMMON_V8_NODE_COMMON_H_
#define ATOM_COMMON_V8_NODE_COMMON_H_
// Include common headers for using node APIs.
#undef CHECK
#undef DISALLOW_COPY_AND_ASSIGN
#include "vendor/node/src/env.h"
#include "vendor/node/src/env-inl.h"
#include "vendor/node/src/node.h"
#include "vendor/node/src/node_internals.h"
using node::node_isolate;
namespace atom {
// Defined in node_bindings.cc.
// For renderer it's created in atom_renderer_client.cc.
// For browser it's created in atom_browser_main_parts.cc.
extern node::Environment* global_env;
}
#endif // ATOM_COMMON_V8_NODE_COMMON_H_

View file

@ -0,0 +1,115 @@
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ATOM_COMMON_SCOPED_PERSISTENT_H_
#define ATOM_COMMON_SCOPED_PERSISTENT_H_
#include "base/logging.h"
#include "base/memory/ref_counted.h"
#include "v8/include/v8.h"
namespace atom {
// A v8::Persistent handle to a V8 value which destroys and clears the
// underlying handle on destruction.
template <typename T>
class ScopedPersistent {
public:
ScopedPersistent() {
}
explicit ScopedPersistent(v8::Handle<T> handle) {
reset(handle);
}
~ScopedPersistent() {
reset();
}
void reset(v8::Handle<T> handle) {
if (!handle.IsEmpty())
handle_.Reset(GetIsolate(handle), handle);
else
reset();
}
void reset() {
handle_.Reset();
}
bool IsEmpty() const {
return handle_.IsEmpty();
}
v8::Handle<T> NewHandle() const {
if (handle_.IsEmpty())
return v8::Local<T>();
return v8::Local<T>::New(GetIsolate(handle_), handle_);
}
v8::Handle<T> NewHandle(v8::Isolate* isolate) const {
if (handle_.IsEmpty())
return v8::Local<T>();
return v8::Local<T>::New(isolate, handle_);
}
template <typename P>
void MakeWeak(P* parameters,
typename v8::WeakReferenceCallbacks<T, P>::Revivable callback) {
handle_.MakeWeak(parameters, callback);
}
private:
template <typename U>
static v8::Isolate* GetIsolate(v8::Handle<U> object_handle) {
// Only works for v8::Object and its subclasses. Add specialisations for
// anything else.
if (!object_handle.IsEmpty())
return GetIsolate(object_handle->CreationContext());
return v8::Isolate::GetCurrent();
}
static v8::Isolate* GetIsolate(v8::Handle<v8::Context> context_handle) {
if (!context_handle.IsEmpty())
return context_handle->GetIsolate();
return v8::Isolate::GetCurrent();
}
static v8::Isolate* GetIsolate(
v8::Handle<v8::ObjectTemplate> template_handle) {
return v8::Isolate::GetCurrent();
}
template <typename U>
static v8::Isolate* GetIsolate(const U& any_handle) {
return v8::Isolate::GetCurrent();
}
v8::Persistent<T> handle_;
DISALLOW_COPY_AND_ASSIGN(ScopedPersistent);
};
template <typename T>
class RefCountedPersistent : public ScopedPersistent<T>,
public base::RefCounted<RefCountedPersistent<T>> {
public:
RefCountedPersistent() {}
explicit RefCountedPersistent(v8::Handle<T> handle)
: ScopedPersistent<T>(handle) {
}
protected:
friend class base::RefCounted<RefCountedPersistent<T>>;
~RefCountedPersistent() {}
private:
DISALLOW_COPY_AND_ASSIGN(RefCountedPersistent);
};
typedef scoped_refptr<RefCountedPersistent<v8::Function>> RefCountedV8Function;
typedef scoped_refptr<RefCountedPersistent<v8::Object>> RefCountedV8Object;
} // namespace atom
#endif // ATOM_COMMON_SCOPED_PERSISTENT_H_

View file

@ -2,57 +2,56 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
#include "common/v8_value_converter_impl.h" #include "common/v8/v8_value_converter.h"
#include <string> #include <string>
#include "base/logging.h" #include "base/logging.h"
#include "base/memory/scoped_ptr.h" #include "base/memory/scoped_ptr.h"
#include "base/values.h" #include "base/values.h"
#include "v8/include/v8.h"
namespace atom { namespace atom {
V8ValueConverterImpl::V8ValueConverterImpl() V8ValueConverter::V8ValueConverter()
: date_allowed_(false), : date_allowed_(false),
reg_exp_allowed_(false), reg_exp_allowed_(false),
function_allowed_(false), function_allowed_(false),
strip_null_from_objects_(false), strip_null_from_objects_(false),
avoid_identity_hash_for_testing_(false) {} avoid_identity_hash_for_testing_(false) {}
void V8ValueConverterImpl::SetDateAllowed(bool val) { void V8ValueConverter::SetDateAllowed(bool val) {
date_allowed_ = val; date_allowed_ = val;
} }
void V8ValueConverterImpl::SetRegExpAllowed(bool val) { void V8ValueConverter::SetRegExpAllowed(bool val) {
reg_exp_allowed_ = val; reg_exp_allowed_ = val;
} }
void V8ValueConverterImpl::SetFunctionAllowed(bool val) { void V8ValueConverter::SetFunctionAllowed(bool val) {
function_allowed_ = val; function_allowed_ = val;
} }
void V8ValueConverterImpl::SetStripNullFromObjects(bool val) { void V8ValueConverter::SetStripNullFromObjects(bool val) {
strip_null_from_objects_ = val; strip_null_from_objects_ = val;
} }
v8::Handle<v8::Value> V8ValueConverterImpl::ToV8Value( v8::Handle<v8::Value> V8ValueConverter::ToV8Value(
const base::Value* value, v8::Handle<v8::Context> context) const { const base::Value* value, v8::Handle<v8::Context> context) const {
v8::Context::Scope context_scope(context); v8::Context::Scope context_scope(context);
v8::HandleScope handle_scope; v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
return handle_scope.Close(ToV8ValueImpl(value)); return handle_scope.Close(ToV8ValueImpl(value));
} }
Value* V8ValueConverterImpl::FromV8Value( Value* V8ValueConverter::FromV8Value(
v8::Handle<v8::Value> val, v8::Handle<v8::Value> val,
v8::Handle<v8::Context> context) const { v8::Handle<v8::Context> context) const {
v8::Context::Scope context_scope(context); v8::Context::Scope context_scope(context);
v8::HandleScope handle_scope; v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
HashToHandleMap unique_map; HashToHandleMap unique_map;
return FromV8ValueImpl(val, &unique_map); return FromV8ValueImpl(val, &unique_map);
} }
v8::Handle<v8::Value> V8ValueConverterImpl::ToV8ValueImpl( v8::Handle<v8::Value> V8ValueConverter::ToV8ValueImpl(
const base::Value* value) const { const base::Value* value) const {
CHECK(value); CHECK(value);
switch (value->GetType()) { switch (value->GetType()) {
@ -95,7 +94,7 @@ v8::Handle<v8::Value> V8ValueConverterImpl::ToV8ValueImpl(
} }
} }
v8::Handle<v8::Value> V8ValueConverterImpl::ToV8Array( v8::Handle<v8::Value> V8ValueConverter::ToV8Array(
const base::ListValue* val) const { const base::ListValue* val) const {
v8::Handle<v8::Array> result(v8::Array::New(val->GetSize())); v8::Handle<v8::Array> result(v8::Array::New(val->GetSize()));
@ -115,7 +114,7 @@ v8::Handle<v8::Value> V8ValueConverterImpl::ToV8Array(
return result; return result;
} }
v8::Handle<v8::Value> V8ValueConverterImpl::ToV8Object( v8::Handle<v8::Value> V8ValueConverter::ToV8Object(
const base::DictionaryValue* val) const { const base::DictionaryValue* val) const {
v8::Handle<v8::Object> result(v8::Object::New()); v8::Handle<v8::Object> result(v8::Object::New());
@ -136,7 +135,7 @@ v8::Handle<v8::Value> V8ValueConverterImpl::ToV8Object(
return result; return result;
} }
Value* V8ValueConverterImpl::FromV8ValueImpl(v8::Handle<v8::Value> val, Value* V8ValueConverter::FromV8ValueImpl(v8::Handle<v8::Value> val,
HashToHandleMap* unique_map) const { HashToHandleMap* unique_map) const {
CHECK(!val.IsEmpty()); CHECK(!val.IsEmpty());
@ -196,7 +195,7 @@ Value* V8ValueConverterImpl::FromV8ValueImpl(v8::Handle<v8::Value> val,
return NULL; return NULL;
} }
Value* V8ValueConverterImpl::FromV8Array(v8::Handle<v8::Array> val, Value* V8ValueConverter::FromV8Array(v8::Handle<v8::Array> val,
HashToHandleMap* unique_map) const { HashToHandleMap* unique_map) const {
if (!UpdateAndCheckUniqueness(unique_map, val)) if (!UpdateAndCheckUniqueness(unique_map, val))
return base::Value::CreateNullValue(); return base::Value::CreateNullValue();
@ -233,7 +232,7 @@ Value* V8ValueConverterImpl::FromV8Array(v8::Handle<v8::Array> val,
return result; return result;
} }
Value* V8ValueConverterImpl::FromV8Object( Value* V8ValueConverter::FromV8Object(
v8::Handle<v8::Object> val, v8::Handle<v8::Object> val,
HashToHandleMap* unique_map) const { HashToHandleMap* unique_map) const {
if (!UpdateAndCheckUniqueness(unique_map, val)) if (!UpdateAndCheckUniqueness(unique_map, val))
@ -310,7 +309,7 @@ Value* V8ValueConverterImpl::FromV8Object(
return result.release(); return result.release();
} }
bool V8ValueConverterImpl::UpdateAndCheckUniqueness( bool V8ValueConverter::UpdateAndCheckUniqueness(
HashToHandleMap* map, HashToHandleMap* map,
v8::Handle<v8::Object> handle) const { v8::Handle<v8::Object> handle) const {
typedef HashToHandleMap::const_iterator Iterator; typedef HashToHandleMap::const_iterator Iterator;

View file

@ -2,14 +2,14 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
#ifndef ATOM_COMMON_V8_VALUE_CONVERTER_IMPL_H_ #ifndef ATOM_COMMON_V8_V8_VALUE_CONVERTER_H_
#define ATOM_COMMON_V8_VALUE_CONVERTER_IMPL_H_ #define ATOM_COMMON_V8_V8_VALUE_CONVERTER_H_
#include <map> #include <map>
#include "base/basictypes.h" #include "base/basictypes.h"
#include "base/compiler_specific.h" #include "base/compiler_specific.h"
#include "content/public/renderer/v8_value_converter.h" #include "v8/include/v8.h"
namespace base { namespace base {
class BinaryValue; class BinaryValue;
@ -20,26 +20,20 @@ class Value;
namespace atom { namespace atom {
// The content::V8ValueConverter depends on WebKit, we get rid of the WebKit class V8ValueConverter {
// dependency by removing support of binary data.
class V8ValueConverterImpl : public content::V8ValueConverter {
public: public:
V8ValueConverterImpl(); V8ValueConverter();
// V8ValueConverter implementation. void SetDateAllowed(bool val);
virtual void SetDateAllowed(bool val) OVERRIDE; void SetRegExpAllowed(bool val);
virtual void SetRegExpAllowed(bool val) OVERRIDE; void SetFunctionAllowed(bool val);
virtual void SetFunctionAllowed(bool val) OVERRIDE; void SetStripNullFromObjects(bool val);
virtual void SetStripNullFromObjects(bool val) OVERRIDE; v8::Handle<v8::Value> ToV8Value(const base::Value* value,
virtual v8::Handle<v8::Value> ToV8Value( v8::Handle<v8::Context> context) const;
const base::Value* value, base::Value* FromV8Value(v8::Handle<v8::Value> value,
v8::Handle<v8::Context> context) const OVERRIDE; v8::Handle<v8::Context> context) const;
virtual base::Value* FromV8Value(
v8::Handle<v8::Value> value,
v8::Handle<v8::Context> context) const OVERRIDE;
private: private:
friend class ScopedAvoidIdentityHashForTesting;
typedef std::multimap<int, v8::Handle<v8::Object> > HashToHandleMap; typedef std::multimap<int, v8::Handle<v8::Object> > HashToHandleMap;
v8::Handle<v8::Value> ToV8ValueImpl(const base::Value* value) const; v8::Handle<v8::Value> ToV8ValueImpl(const base::Value* value) const;
@ -78,9 +72,9 @@ class V8ValueConverterImpl : public content::V8ValueConverter {
bool avoid_identity_hash_for_testing_; bool avoid_identity_hash_for_testing_;
DISALLOW_COPY_AND_ASSIGN(V8ValueConverterImpl); DISALLOW_COPY_AND_ASSIGN(V8ValueConverter);
}; };
} // namespace atom } // namespace atom
#endif // ATOM_COMMON_V8_VALUE_CONVERTER_IMPL_H_ #endif // ATOM_COMMON_V8_V8_VALUE_CONVERTER_H_

View file

@ -22,7 +22,6 @@ Renderer side modules:
Browser side modules: Browser side modules:
* [app](api/browser/app.md) * [app](api/browser/app.md)
* [atom-delegate](api/browser/atom-delegate.md)
* [auto-updater](api/browser/auto-updater.md) * [auto-updater](api/browser/auto-updater.md)
* [browser-window](api/browser/browser-window.md) * [browser-window](api/browser/browser-window.md)
* [dialog](api/browser/dialog.md) * [dialog](api/browser/dialog.md)

View file

@ -13,11 +13,17 @@ app.on('window-all-closed', function() {
## Event: will-finish-launching ## Event: will-finish-launching
Setup crash reporter and auto updater here. Emitted when application has done basic startup. On Windows and Linux it is the
same with `ready` event, on OS X this event represents the
`applicationWillFinishLaunching` message of `NSApplication`, usually you would
setup listeners to `open-file` and `open-url` events here, and start the crash
reporter and auto updater.
## Event: finish-launching Under most cases you should just do everything in `ready` event.
Do final startup like creating browser window here. ## Event: ready
Emitted when atom-shell has done everything initializaiton.
## Event: window-all-closed ## Event: window-all-closed
@ -91,10 +97,6 @@ to the spec of npm modules. So usually you should also specify a `productName`
field, which is your application's full capitalized name, and it will be field, which is your application's full capitalized name, and it will be
preferred over `name` by atom-shell. preferred over `name` by atom-shell.
## app.getBrowserWindows()
Returns an array of all browser windows.
## app.commandLine.appendSwitch(switch, [value]) ## app.commandLine.appendSwitch(switch, [value])
Append a switch [with optional value] to Chromium's command line. Append a switch [with optional value] to Chromium's command line.

View file

@ -1,31 +0,0 @@
# atom-delegate
The `atom-delegate` returns the delegate object for Chrome Content API. The
atom-shell would call methods of the delegate object when the corresponding
C++ code is called. Developers can override methods of it to control the
underlying behaviour of the browser.
An example of creating a new window when the browser is initialized:
```javascript
var delegate = require('atom-delegate'); // Delegate of Content API.
var BrowserWindow = require('browser-window'); // Module to create native browser window.
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the javascript object is GCed.
var mainWindow = null;
// This method will be called when atom-shell has done everything
// initialization and ready for creating browser windows.
delegate.browserMainParts.preMainMessageLoopRun = function() {
// Create the browser window,
mainWindow = new BrowserWindow({ width: 800, height: 600 });
// and load the index.html of the app.
mainWindow.loadUrl('file://' + __dirname + '/index.html');
}
```
## atom-delegate.browserMainParts.preMainMessageLoopRun()
Called when atom-shell has done everything initialization and ready for
creating browser windows.

View file

@ -99,6 +99,10 @@ shouldn't!).
Emitted when the memory taken by the native window is released. Usually you Emitted when the memory taken by the native window is released. Usually you
should dereference the javascript object when received this event. should dereference the javascript object when received this event.
### Class Method: BrowserWindow.getAllWindows()
Returns an array of all opened browser windows.
### Class Method: BrowserWindow.getFocusedWindow() ### Class Method: BrowserWindow.getFocusedWindow()
Returns the window that is focused in this application. Returns the window that is focused in this application.

View file

@ -53,7 +53,6 @@ every piece of the app. An example of `main.js` is:
```javascript ```javascript
var app = require('app'); // Module to control application life. var app = require('app'); // Module to control application life.
var delegate = require('atom_delegate'); // Delegate of Content API.
var Window = require('window'); // Module to create native browser window. var Window = require('window'); // Module to create native browser window.
// Keep a global reference of the window object, if you don't, the window will // Keep a global reference of the window object, if you don't, the window will
@ -67,7 +66,7 @@ app.on('window-all-closed', function() {
// This method will be called when atom-shell has done everything // This method will be called when atom-shell has done everything
// initialization and ready for creating browser windows. // initialization and ready for creating browser windows.
delegate.browserMainParts.preMainMessageLoopRun = function() { app.on('ready', function() {
// Create the browser window, // Create the browser window,
mainWindow = new Window({ width: 800, height: 600 }); mainWindow = new Window({ width: 800, height: 600 });
// and load the index.html of the app. // and load the index.html of the app.
@ -89,7 +88,7 @@ delegate.browserMainParts.preMainMessageLoopRun = function() {
// when you should delete the corresponding element. // when you should delete the corresponding element.
mainWindow = null; mainWindow = null;
}); });
} });
``` ```
Finally the `index.html` is the web page you want to show, in fact you Finally the `index.html` is the web page you want to show, in fact you

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