Move all sources under atom/.

This commit is contained in:
Cheng Zhao 2014-03-16 08:30:26 +08:00
parent 26ddbbb0ee
commit 516d46444d
217 changed files with 519 additions and 519 deletions

View file

@ -0,0 +1,211 @@
// 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.
#include "atom/browser/api/atom_api_app.h"
#include "base/values.h"
#include "base/command_line.h"
#include "atom/browser/browser.h"
#include "atom/common/v8/native_type_conversions.h"
#include "atom/common/v8/node_common.h"
namespace atom {
namespace api {
App::App(v8::Handle<v8::Object> wrapper)
: EventEmitter(wrapper) {
Browser::Get()->AddObserver(this);
}
App::~App() {
Browser::Get()->RemoveObserver(this);
}
void App::OnWillQuit(bool* prevent_default) {
*prevent_default = Emit("will-quit");
}
void App::OnWindowAllClosed() {
Emit("window-all-closed");
}
void App::OnOpenFile(bool* prevent_default, const std::string& file_path) {
base::ListValue args;
args.AppendString(file_path);
*prevent_default = Emit("open-file", &args);
}
void App::OnOpenURL(const std::string& url) {
base::ListValue args;
args.AppendString(url);
Emit("open-url", &args);
}
void App::OnActivateWithNoOpenWindows() {
Emit("activate-with-no-open-windows");
}
void App::OnWillFinishLaunching() {
Emit("will-finish-launching");
}
void App::OnFinishLaunching() {
Emit("ready");
}
// static
void App::New(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope(args.GetIsolate());
if (!args.IsConstructCall())
return node::ThrowError("Require constructor call");
new App(args.This());
}
// static
void App::Quit(const v8::FunctionCallbackInfo<v8::Value>& args) {
Browser::Get()->Quit();
}
// static
void App::Exit(const v8::FunctionCallbackInfo<v8::Value>& args) {
exit(args[0]->IntegerValue());
}
// static
void App::Terminate(const v8::FunctionCallbackInfo<v8::Value>& args) {
Browser::Get()->Terminate();
}
// static
void App::Focus(const v8::FunctionCallbackInfo<v8::Value>& args) {
Browser::Get()->Focus();
}
// static
void App::GetVersion(const v8::FunctionCallbackInfo<v8::Value>& args) {
args.GetReturnValue().Set(ToV8Value(Browser::Get()->GetVersion()));
}
// static
void App::SetVersion(const v8::FunctionCallbackInfo<v8::Value>& args) {
std::string version;
if (!FromV8Arguments(args, &version))
return node::ThrowError("Bad argument");
Browser::Get()->SetVersion(version);
}
// static
void App::GetName(const v8::FunctionCallbackInfo<v8::Value>& args) {
return args.GetReturnValue().Set(ToV8Value(Browser::Get()->GetName()));
}
// static
void App::SetName(const v8::FunctionCallbackInfo<v8::Value>& args) {
std::string name;
if (!FromV8Arguments(args, &name))
return node::ThrowError("Bad argument");
Browser::Get()->SetName(name);
}
// static
void App::AppendSwitch(const v8::FunctionCallbackInfo<v8::Value>& args) {
std::string switch_string;
if (!FromV8Arguments(args, &switch_string))
return node::ThrowError("Bad argument");
if (args.Length() == 1) {
CommandLine::ForCurrentProcess()->AppendSwitch(switch_string);
} else {
std::string value = FromV8Value(args[1]);
CommandLine::ForCurrentProcess()->AppendSwitchASCII(
switch_string, value);
}
}
// static
void App::AppendArgument(const v8::FunctionCallbackInfo<v8::Value>& args) {
std::string value;
if (!FromV8Arguments(args, &value))
return node::ThrowError("Bad argument");
CommandLine::ForCurrentProcess()->AppendArg(value);
}
#if defined(OS_MACOSX)
// static
void App::DockBounce(const v8::FunctionCallbackInfo<v8::Value>& args) {
std::string type;
if (!FromV8Arguments(args, &type))
return node::ThrowError("Bad argument");
int request_id = -1;
if (type == "critical")
request_id = Browser::Get()->DockBounce(Browser::BOUNCE_CRITICAL);
else if (type == "informational")
request_id = Browser::Get()->DockBounce(Browser::BOUNCE_INFORMATIONAL);
else
return node::ThrowTypeError("Invalid bounce type");
args.GetReturnValue().Set(request_id);
}
// static
void App::DockCancelBounce(const v8::FunctionCallbackInfo<v8::Value>& args) {
Browser::Get()->DockCancelBounce(FromV8Value(args[0]));
}
// static
void App::DockSetBadgeText(const v8::FunctionCallbackInfo<v8::Value>& args) {
Browser::Get()->DockSetBadgeText(FromV8Value(args[0]));
}
// static
void App::DockGetBadgeText(const v8::FunctionCallbackInfo<v8::Value>& args) {
std::string text(Browser::Get()->DockGetBadgeText());
args.GetReturnValue().Set(ToV8Value(text));
}
#endif // defined(OS_MACOSX)
// static
void App::Initialize(v8::Handle<v8::Object> target) {
v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(New);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(v8::String::NewSymbol("Application"));
NODE_SET_PROTOTYPE_METHOD(t, "quit", Quit);
NODE_SET_PROTOTYPE_METHOD(t, "exit", Exit);
NODE_SET_PROTOTYPE_METHOD(t, "terminate", Terminate);
NODE_SET_PROTOTYPE_METHOD(t, "focus", Focus);
NODE_SET_PROTOTYPE_METHOD(t, "getVersion", GetVersion);
NODE_SET_PROTOTYPE_METHOD(t, "setVersion", SetVersion);
NODE_SET_PROTOTYPE_METHOD(t, "getName", GetName);
NODE_SET_PROTOTYPE_METHOD(t, "setName", SetName);
target->Set(v8::String::NewSymbol("Application"), t->GetFunction());
NODE_SET_METHOD(target, "appendSwitch", AppendSwitch);
NODE_SET_METHOD(target, "appendArgument", AppendArgument);
#if defined(OS_MACOSX)
NODE_SET_METHOD(target, "dockBounce", DockBounce);
NODE_SET_METHOD(target, "dockCancelBounce", DockCancelBounce);
NODE_SET_METHOD(target, "dockSetBadgeText", DockSetBadgeText);
NODE_SET_METHOD(target, "dockGetBadgeText", DockGetBadgeText);
#endif // defined(OS_MACOSX)
}
} // namespace api
} // namespace atom
NODE_MODULE(atom_browser_app, atom::api::App::Initialize)

View file

@ -0,0 +1,64 @@
// 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_BROWSER_API_ATOM_API_APP_H_
#define ATOM_BROWSER_API_ATOM_API_APP_H_
#include "base/compiler_specific.h"
#include "atom/browser/browser_observer.h"
#include "atom/common/api/atom_api_event_emitter.h"
namespace atom {
namespace api {
class App : public EventEmitter,
public BrowserObserver {
public:
virtual ~App();
static void Initialize(v8::Handle<v8::Object> target);
protected:
explicit App(v8::Handle<v8::Object> wrapper);
// BrowserObserver implementations:
virtual void OnWillQuit(bool* prevent_default) OVERRIDE;
virtual void OnWindowAllClosed() OVERRIDE;
virtual void OnOpenFile(bool* prevent_default,
const std::string& file_path) OVERRIDE;
virtual void OnOpenURL(const std::string& url) OVERRIDE;
virtual void OnActivateWithNoOpenWindows() OVERRIDE;
virtual void OnWillFinishLaunching() OVERRIDE;
virtual void OnFinishLaunching() OVERRIDE;
private:
static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
static void Quit(const v8::FunctionCallbackInfo<v8::Value>& args);
static void Exit(const v8::FunctionCallbackInfo<v8::Value>& args);
static void Terminate(const v8::FunctionCallbackInfo<v8::Value>& args);
static void Focus(const v8::FunctionCallbackInfo<v8::Value>& args);
static void GetVersion(const v8::FunctionCallbackInfo<v8::Value>& args);
static void SetVersion(const v8::FunctionCallbackInfo<v8::Value>& args);
static void GetName(const v8::FunctionCallbackInfo<v8::Value>& args);
static void SetName(const v8::FunctionCallbackInfo<v8::Value>& args);
static void AppendSwitch(const v8::FunctionCallbackInfo<v8::Value>& args);
static void AppendArgument(const v8::FunctionCallbackInfo<v8::Value>& args);
#if defined(OS_MACOSX)
static void DockBounce(const v8::FunctionCallbackInfo<v8::Value>& args);
static void DockCancelBounce(const v8::FunctionCallbackInfo<v8::Value>& args);
static void DockSetBadgeText(const v8::FunctionCallbackInfo<v8::Value>& args);
static void DockGetBadgeText(const v8::FunctionCallbackInfo<v8::Value>& args);
#endif // defined(OS_MACOSX)
DISALLOW_COPY_AND_ASSIGN(App);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_APP_H_

View file

@ -0,0 +1,106 @@
// 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.
#include "atom/browser/api/atom_api_auto_updater.h"
#include "base/time/time.h"
#include "base/values.h"
#include "atom/browser/auto_updater.h"
#include "atom/common/v8/native_type_conversions.h"
#include "atom/common/v8/node_common.h"
namespace atom {
namespace api {
AutoUpdater::AutoUpdater(v8::Handle<v8::Object> wrapper)
: EventEmitter(wrapper) {
auto_updater::AutoUpdater::SetDelegate(this);
}
AutoUpdater::~AutoUpdater() {
auto_updater::AutoUpdater::SetDelegate(NULL);
}
void AutoUpdater::OnError(const std::string& error) {
base::ListValue args;
args.AppendString(error);
Emit("error", &args);
}
void AutoUpdater::OnCheckingForUpdate() {
Emit("checking-for-update");
}
void AutoUpdater::OnUpdateAvailable() {
Emit("update-available");
}
void AutoUpdater::OnUpdateNotAvailable() {
Emit("update-not-available");
}
void AutoUpdater::OnUpdateDownloaded(const std::string& release_notes,
const std::string& release_name,
const base::Time& release_date,
const std::string& update_url,
const base::Closure& quit_and_install) {
quit_and_install_ = quit_and_install;
base::ListValue args;
args.AppendString(release_notes);
args.AppendString(release_name);
args.AppendDouble(release_date.ToJsTime());
args.AppendString(update_url);
Emit("update-downloaded-raw", &args);
}
// static
void AutoUpdater::New(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (!args.IsConstructCall())
return node::ThrowError("Require constructor call");
new AutoUpdater(args.This());
}
// static
void AutoUpdater::SetFeedURL(const v8::FunctionCallbackInfo<v8::Value>& args) {
auto_updater::AutoUpdater::SetFeedURL(FromV8Value(args[0]));
}
// static
void AutoUpdater::CheckForUpdates(
const v8::FunctionCallbackInfo<v8::Value>& args) {
auto_updater::AutoUpdater::CheckForUpdates();
}
// static
void AutoUpdater::QuitAndInstall(
const v8::FunctionCallbackInfo<v8::Value>& args) {
AutoUpdater* self = AutoUpdater::Unwrap<AutoUpdater>(args.This());
if (!self->quit_and_install_.is_null())
self->quit_and_install_.Run();
}
// static
void AutoUpdater::Initialize(v8::Handle<v8::Object> target) {
v8::Local<v8::FunctionTemplate> t(
v8::FunctionTemplate::New(AutoUpdater::New));
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(v8::String::NewSymbol("AutoUpdater"));
NODE_SET_PROTOTYPE_METHOD(t, "setFeedUrl", SetFeedURL);
NODE_SET_PROTOTYPE_METHOD(t, "checkForUpdates", CheckForUpdates);
NODE_SET_PROTOTYPE_METHOD(t, "quitAndInstall", QuitAndInstall);
target->Set(v8::String::NewSymbol("AutoUpdater"), t->GetFunction());
}
} // namespace api
} // namespace atom
NODE_MODULE(atom_browser_auto_updater, atom::api::AutoUpdater::Initialize)

View file

@ -0,0 +1,57 @@
// 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_BROWSER_API_ATOM_API_AUTO_UPDATER_H_
#define ATOM_BROWSER_API_ATOM_API_AUTO_UPDATER_H_
#include "base/callback.h"
#include "base/memory/scoped_ptr.h"
#include "atom/browser/auto_updater_delegate.h"
#include "atom/common/api/atom_api_event_emitter.h"
namespace atom {
namespace api {
class AutoUpdater : public EventEmitter,
public auto_updater::AutoUpdaterDelegate {
public:
virtual ~AutoUpdater();
static void Initialize(v8::Handle<v8::Object> target);
protected:
explicit AutoUpdater(v8::Handle<v8::Object> wrapper);
// AutoUpdaterDelegate implementations.
virtual void OnError(const std::string& error) OVERRIDE;
virtual void OnCheckingForUpdate() OVERRIDE;
virtual void OnUpdateAvailable() OVERRIDE;
virtual void OnUpdateNotAvailable() OVERRIDE;
virtual void OnUpdateDownloaded(
const std::string& release_notes,
const std::string& release_name,
const base::Time& release_date,
const std::string& update_url,
const base::Closure& quit_and_install) OVERRIDE;
private:
static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
static void SetFeedURL(const v8::FunctionCallbackInfo<v8::Value>& args);
static void CheckForUpdates(const v8::FunctionCallbackInfo<v8::Value>& args);
static void ContinueUpdate(const v8::FunctionCallbackInfo<v8::Value>& args);
static void QuitAndInstall(const v8::FunctionCallbackInfo<v8::Value>& args);
base::Closure quit_and_install_;
DISALLOW_COPY_AND_ASSIGN(AutoUpdater);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_AUTO_UPDATER_H_

View file

@ -0,0 +1,48 @@
// 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.
#include "atom/browser/api/atom_api_browser_ipc.h"
#include "atom/common/api/api_messages.h"
#include "atom/common/v8/node_common.h"
#include "atom/common/v8/native_type_conversions.h"
#include "content/public/browser/render_view_host.h"
using content::RenderViewHost;
namespace atom {
namespace api {
// static
void BrowserIPC::Send(const v8::FunctionCallbackInfo<v8::Value>& args) {
string16 channel;
int process_id, routing_id;
scoped_ptr<base::Value> arguments;
if (!FromV8Arguments(args, &channel, &process_id, &routing_id, &arguments))
return node::ThrowTypeError("Bad argument");
DCHECK(arguments && arguments->IsType(base::Value::TYPE_LIST));
RenderViewHost* render_view_host(RenderViewHost::FromID(
process_id, routing_id));
if (!render_view_host)
return node::ThrowError("Invalid render view host");
args.GetReturnValue().Set(render_view_host->Send(new AtomViewMsg_Message(
routing_id,
channel,
*static_cast<base::ListValue*>(arguments.get()))));
}
// static
void BrowserIPC::Initialize(v8::Handle<v8::Object> target) {
NODE_SET_METHOD(target, "send", Send);
}
} // namespace api
} // namespace atom
NODE_MODULE(atom_browser_ipc, atom::api::BrowserIPC::Initialize)

View file

@ -0,0 +1,29 @@
// 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_BROWSER_API_ATOM_API_BROWSER_IPC_H_
#define ATOM_BROWSER_API_ATOM_API_BROWSER_IPC_H_
#include "base/basictypes.h"
#include "v8/include/v8.h"
namespace atom {
namespace api {
class BrowserIPC {
public:
static void Initialize(v8::Handle<v8::Object> target);
private:
static void Send(const v8::FunctionCallbackInfo<v8::Value>& args);
DISALLOW_IMPLICIT_CONSTRUCTORS(BrowserIPC);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_BROWSER_IPC_H_

View file

@ -0,0 +1,141 @@
// 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.
#include "atom/browser/api/atom_api_dialog.h"
#include "base/bind.h"
#include "atom/browser/native_window.h"
#include "atom/browser/ui/file_dialog.h"
#include "atom/browser/ui/message_box.h"
#include "atom/common/v8/node_common.h"
#include "atom/common/v8/native_type_conversions.h"
namespace atom {
namespace api {
namespace {
template<typename T>
void CallV8Function(const RefCountedV8Function& callback, T arg) {
v8::Locker locker(node_isolate);
v8::HandleScope handle_scope(node_isolate);
v8::Handle<v8::Value> value = ToV8Value(arg);
callback->NewHandle(node_isolate)->Call(
v8::Context::GetCurrent()->Global(), 1, &value);
}
template<typename T>
void CallV8Function2(const RefCountedV8Function& callback, bool result, T arg) {
if (result)
return CallV8Function<T>(callback, arg);
else
return CallV8Function<void*>(callback, NULL);
}
void Initialize(v8::Handle<v8::Object> target) {
NODE_SET_METHOD(target, "showMessageBox", ShowMessageBox);
NODE_SET_METHOD(target, "showOpenDialog", ShowOpenDialog);
NODE_SET_METHOD(target, "showSaveDialog", ShowSaveDialog);
}
} // namespace
void ShowMessageBox(const v8::FunctionCallbackInfo<v8::Value>& args) {
int type;
std::vector<std::string> buttons;
std::string title, message, detail;
if (!FromV8Arguments(args, &type, &buttons, &title, &message, &detail))
return node::ThrowTypeError("Bad argument");
NativeWindow* native_window = FromV8Value(args[5]);
if (!args[6]->IsFunction()) {
int chosen = atom::ShowMessageBox(
native_window,
(MessageBoxType)type,
buttons,
title,
message,
detail);
args.GetReturnValue().Set(chosen);
} else {
RefCountedV8Function callback = FromV8Value(args[6]);
atom::ShowMessageBox(
native_window,
(MessageBoxType)type,
buttons,
title,
message,
detail,
base::Bind(&CallV8Function<int>, callback));
}
}
void ShowOpenDialog(const v8::FunctionCallbackInfo<v8::Value>& args) {
std::string title;
base::FilePath default_path;
int properties;
if (!FromV8Arguments(args, &title, &default_path, &properties))
return node::ThrowTypeError("Bad argument");
NativeWindow* native_window = FromV8Value(args[3]);
if (!args[4]->IsFunction()) {
std::vector<base::FilePath> paths;
if (!file_dialog::ShowOpenDialog(native_window,
title,
default_path,
properties,
&paths))
return;
v8::Handle<v8::Array> result = v8::Array::New(paths.size());
for (size_t i = 0; i < paths.size(); ++i)
result->Set(i, ToV8Value(paths[i]));
args.GetReturnValue().Set(result);
} else {
RefCountedV8Function callback = FromV8Value(args[4]);
file_dialog::ShowOpenDialog(
native_window,
title,
default_path,
properties,
base::Bind(&CallV8Function2<const std::vector<base::FilePath>&>,
callback));
}
}
void ShowSaveDialog(const v8::FunctionCallbackInfo<v8::Value>& args) {
std::string title;
base::FilePath default_path;
if (!FromV8Arguments(args, &title, &default_path))
return node::ThrowTypeError("Bad argument");
NativeWindow* native_window = FromV8Value(args[2]);
if (!args[3]->IsFunction()) {
base::FilePath path;
if (file_dialog::ShowSaveDialog(native_window,
title,
default_path,
&path))
args.GetReturnValue().Set(ToV8Value(path));
} else {
RefCountedV8Function callback = FromV8Value(args[3]);
file_dialog::ShowSaveDialog(
native_window,
title,
default_path,
base::Bind(&CallV8Function2<const base::FilePath&>, callback));
}
}
} // namespace api
} // namespace atom
NODE_MODULE(atom_browser_dialog, atom::api::Initialize)

View file

@ -0,0 +1,22 @@
// 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_BROWSER_API_ATOM_API_DIALOG_H_
#define ATOM_BROWSER_API_ATOM_API_DIALOG_H_
#include "v8/include/v8.h"
namespace atom {
namespace api {
void ShowMessageBox(const v8::FunctionCallbackInfo<v8::Value>& args);
void ShowOpenDialog(const v8::FunctionCallbackInfo<v8::Value>& args);
void ShowSaveDialog(const v8::FunctionCallbackInfo<v8::Value>& args);
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_DIALOG_H_

View file

@ -0,0 +1,100 @@
// 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.
#include "atom/browser/api/atom_api_event.h"
#include "atom/browser/native_window.h"
#include "atom/common/api/api_messages.h"
#include "atom/common/v8/node_common.h"
#include "atom/common/v8/native_type_conversions.h"
namespace atom {
namespace api {
ScopedPersistent<v8::Function> Event::constructor_template_;
Event::Event()
: sender_(NULL),
message_(NULL),
prevent_default_(false) {
}
Event::~Event() {
if (sender_ != NULL)
sender_->RemoveObserver(this);
}
// static
v8::Handle<v8::Object> Event::CreateV8Object() {
if (constructor_template_.IsEmpty()) {
v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(New);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(v8::String::NewSymbol("Event"));
NODE_SET_PROTOTYPE_METHOD(t, "preventDefault", PreventDefault);
NODE_SET_PROTOTYPE_METHOD(t, "sendReply", SendReply);
NODE_SET_PROTOTYPE_METHOD(t, "destroy", Destroy);
constructor_template_.reset(t->GetFunction());
}
v8::Handle<v8::Function> t = constructor_template_.NewHandle(node_isolate);
return t->NewInstance(0, NULL);
}
void Event::SetSenderAndMessage(NativeWindow* sender, IPC::Message* message) {
DCHECK(!sender_);
DCHECK(!message_);
sender_ = sender;
message_ = message;
sender_->AddObserver(this);
}
void Event::OnWindowClosed() {
sender_ = NULL;
message_ = NULL;
}
// static
void Event::New(const v8::FunctionCallbackInfo<v8::Value>& args) {
Event* event = new Event;
event->Wrap(args.This());
}
// static
void Event::PreventDefault(const v8::FunctionCallbackInfo<v8::Value>& args) {
Event* event = Unwrap<Event>(args.This());
if (event == NULL)
return node::ThrowError("Event is already destroyed");
event->prevent_default_ = true;
}
// static
void Event::SendReply(const v8::FunctionCallbackInfo<v8::Value>& args) {
Event* event = Unwrap<Event>(args.This());
if (event == NULL)
return node::ThrowError("Event is already destroyed");
if (event->message_ == NULL || event->sender_ == NULL)
return node::ThrowError("Can only send reply to synchronous events");
string16 json = FromV8Value(args[0]);
AtomViewHostMsg_Message_Sync::WriteReplyParams(event->message_, json);
event->sender_->Send(event->message_);
delete event;
}
// static
void Event::Destroy(const v8::FunctionCallbackInfo<v8::Value>& args) {
delete Unwrap<Event>(args.This());
}
} // namespace api
} // namespace atom

View file

@ -0,0 +1,67 @@
// 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_BROWSER_ATOM_API_EVENT_H_
#define ATOM_BROWSER_ATOM_API_EVENT_H_
#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/strings/string16.h"
#include "atom/browser/native_window_observer.h"
#include "atom/common/v8/scoped_persistent.h"
#include "vendor/node/src/node_object_wrap.h"
namespace IPC {
class Message;
}
namespace atom {
class NativeWindow;
namespace api {
class Event : public node::ObjectWrap,
public NativeWindowObserver {
public:
virtual ~Event();
// Create a V8 Event object.
static v8::Handle<v8::Object> CreateV8Object();
// Pass the sender and message to be replied.
void SetSenderAndMessage(NativeWindow* sender, IPC::Message* message);
// Whether event.preventDefault() is called.
bool prevent_default() const { return prevent_default_; }
protected:
Event();
// NativeWindowObserver implementations:
virtual void OnWindowClosed() OVERRIDE;
private:
static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
static void PreventDefault(const v8::FunctionCallbackInfo<v8::Value>& args);
static void SendReply(const v8::FunctionCallbackInfo<v8::Value>& args);
static void Destroy(const v8::FunctionCallbackInfo<v8::Value>& args);
static ScopedPersistent<v8::Function> constructor_template_;
// Replyer for the synchronous messages.
NativeWindow* sender_;
IPC::Message* message_;
bool prevent_default_;
DISALLOW_COPY_AND_ASSIGN(Event);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_ATOM_API_EVENT_H_

View file

@ -0,0 +1,360 @@
// 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.
#include "atom/browser/api/atom_api_menu.h"
#include "atom/browser/ui/accelerator_util.h"
#include "atom/common/v8/node_common.h"
#include "atom/common/v8/native_type_conversions.h"
#define UNWRAP_MEMNU_AND_CHECK \
Menu* self = ObjectWrap::Unwrap<Menu>(args.This()); \
if (self == NULL) \
return node::ThrowError("Menu is already destroyed")
namespace atom {
namespace api {
namespace {
// Call method of delegate object.
v8::Handle<v8::Value> CallDelegate(v8::Handle<v8::Value> default_value,
v8::Handle<v8::Object> menu,
const char* method,
int command_id) {
v8::Locker locker(node_isolate);
v8::HandleScope handle_scope(node_isolate);
v8::Handle<v8::Value> delegate = menu->Get(v8::String::New("delegate"));
if (!delegate->IsObject())
return default_value;
v8::Handle<v8::Function> function = v8::Handle<v8::Function>::Cast(
delegate->ToObject()->Get(v8::String::New(method)));
if (!function->IsFunction())
return default_value;
v8::Handle<v8::Value> argv = v8::Integer::New(command_id);
return handle_scope.Close(
function->Call(v8::Context::GetCurrent()->Global(), 1, &argv));
}
} // namespace
Menu::Menu(v8::Handle<v8::Object> wrapper)
: EventEmitter(wrapper),
model_(new ui::SimpleMenuModel(this)) {
}
Menu::~Menu() {
}
bool Menu::IsCommandIdChecked(int command_id) const {
v8::Locker locker(node_isolate);
v8::HandleScope handle_scope(node_isolate);
return CallDelegate(v8::False(),
const_cast<Menu*>(this)->handle(),
"isCommandIdChecked",
command_id)->BooleanValue();
}
bool Menu::IsCommandIdEnabled(int command_id) const {
v8::Locker locker(node_isolate);
v8::HandleScope handle_scope(node_isolate);
return CallDelegate(v8::True(),
const_cast<Menu*>(this)->handle(),
"isCommandIdEnabled",
command_id)->BooleanValue();
}
bool Menu::IsCommandIdVisible(int command_id) const {
v8::Locker locker(node_isolate);
v8::HandleScope handle_scope(node_isolate);
return CallDelegate(v8::True(),
const_cast<Menu*>(this)->handle(),
"isCommandIdVisible",
command_id)->BooleanValue();
}
bool Menu::GetAcceleratorForCommandId(int command_id,
ui::Accelerator* accelerator) {
v8::Locker locker(node_isolate);
v8::HandleScope handle_scope(node_isolate);
v8::Handle<v8::Value> shortcut = CallDelegate(v8::Undefined(),
handle(),
"getAcceleratorForCommandId",
command_id);
if (shortcut->IsString()) {
std::string shortcut_str = FromV8Value(shortcut);
return accelerator_util::StringToAccelerator(shortcut_str, accelerator);
}
return false;
}
bool Menu::IsItemForCommandIdDynamic(int command_id) const {
v8::Locker locker(node_isolate);
v8::HandleScope handle_scope(node_isolate);
return CallDelegate(v8::False(),
const_cast<Menu*>(this)->handle(),
"isItemForCommandIdDynamic",
command_id)->BooleanValue();
}
string16 Menu::GetLabelForCommandId(int command_id) const {
v8::Locker locker(node_isolate);
v8::HandleScope handle_scope(node_isolate);
return FromV8Value(CallDelegate(v8::False(),
const_cast<Menu*>(this)->handle(),
"getLabelForCommandId",
command_id));
}
string16 Menu::GetSublabelForCommandId(int command_id) const {
v8::Locker locker(node_isolate);
v8::HandleScope handle_scope(node_isolate);
return FromV8Value(CallDelegate(v8::False(),
const_cast<Menu*>(this)->handle(),
"getSubLabelForCommandId",
command_id));
}
void Menu::ExecuteCommand(int command_id, int event_flags) {
v8::Locker locker(node_isolate);
v8::HandleScope handle_scope(node_isolate);
CallDelegate(v8::False(), handle(), "executeCommand", command_id);
}
// static
void Menu::New(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (!args.IsConstructCall())
return node::ThrowError("Require constructor call");
Menu::Create(args.This());
}
// static
void Menu::InsertItem(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_MEMNU_AND_CHECK;
int index, command_id;
string16 label;
if (!FromV8Arguments(args, &index, &command_id, &label))
return node::ThrowTypeError("Bad argument");
if (index < 0)
self->model_->AddItem(command_id, label);
else
self->model_->InsertItemAt(index, command_id, label);
}
// static
void Menu::InsertCheckItem(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_MEMNU_AND_CHECK;
int index, command_id;
string16 label;
if (!FromV8Arguments(args, &index, &command_id, &label))
return node::ThrowTypeError("Bad argument");
if (index < 0)
self->model_->AddCheckItem(command_id, label);
else
self->model_->InsertCheckItemAt(index, command_id, label);
}
// static
void Menu::InsertRadioItem(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_MEMNU_AND_CHECK;
int index, command_id, group_id;
string16 label;
if (!FromV8Arguments(args, &index, &command_id, &label, &group_id))
return node::ThrowTypeError("Bad argument");
if (index < 0)
self->model_->AddRadioItem(command_id, label, group_id);
else
self->model_->InsertRadioItemAt(index, command_id, label, group_id);
}
// static
void Menu::InsertSeparator(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_MEMNU_AND_CHECK;
int index;
if (!FromV8Arguments(args, &index))
return node::ThrowTypeError("Bad argument");
if (index < 0)
self->model_->AddSeparator(ui::NORMAL_SEPARATOR);
else
self->model_->InsertSeparatorAt(index, ui::NORMAL_SEPARATOR);
}
// static
void Menu::InsertSubMenu(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_MEMNU_AND_CHECK;
int index, command_id;
string16 label;
if (!FromV8Arguments(args, &index, &command_id, &label))
return node::ThrowTypeError("Bad argument");
Menu* submenu = ObjectWrap::Unwrap<Menu>(args[3]->ToObject());
if (!submenu)
return node::ThrowTypeError("The submenu is already destroyed");
if (index < 0)
self->model_->AddSubMenu(command_id, label, submenu->model_.get());
else
self->model_->InsertSubMenuAt(
index, command_id, label, submenu->model_.get());
}
// static
void Menu::SetIcon(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_MEMNU_AND_CHECK;
int index;
base::FilePath path;
if (!FromV8Arguments(args, &index, &path))
return node::ThrowTypeError("Bad argument");
// FIXME use webkit_glue's image decoder here.
}
// static
void Menu::SetSublabel(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_MEMNU_AND_CHECK;
int index;
string16 label;
if (!FromV8Arguments(args, &index, &label))
return node::ThrowTypeError("Bad argument");
self->model_->SetSublabel(index, label);
}
// static
void Menu::Clear(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_MEMNU_AND_CHECK;
self->model_->Clear();
}
// static
void Menu::GetIndexOfCommandId(
const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_MEMNU_AND_CHECK;
int index = FromV8Value(args[0]);
args.GetReturnValue().Set(self->model_->GetIndexOfCommandId(index));
}
// static
void Menu::GetItemCount(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_MEMNU_AND_CHECK;
args.GetReturnValue().Set(self->model_->GetItemCount());
}
// static
void Menu::GetCommandIdAt(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_MEMNU_AND_CHECK;
int index = FromV8Value(args[0]);
args.GetReturnValue().Set(self->model_->GetCommandIdAt(index));
}
// static
void Menu::GetLabelAt(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_MEMNU_AND_CHECK;
int index = FromV8Value(args[0]);
args.GetReturnValue().Set(ToV8Value(self->model_->GetLabelAt(index)));
}
// static
void Menu::GetSublabelAt(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_MEMNU_AND_CHECK;
int index = FromV8Value(args[0]);
args.GetReturnValue().Set(ToV8Value(self->model_->GetSublabelAt(index)));
}
// static
void Menu::IsItemCheckedAt(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_MEMNU_AND_CHECK;
int index = FromV8Value(args[0]);
args.GetReturnValue().Set(self->model_->IsItemCheckedAt(index));
}
// static
void Menu::IsEnabledAt(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_MEMNU_AND_CHECK;
int index = FromV8Value(args[0]);
args.GetReturnValue().Set(self->model_->IsEnabledAt(index));
}
// static
void Menu::IsVisibleAt(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_MEMNU_AND_CHECK;
int index = FromV8Value(args[0]);
args.GetReturnValue().Set(self->model_->IsVisibleAt(index));
}
// static
void Menu::Popup(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_MEMNU_AND_CHECK;
atom::NativeWindow* window;
if (!FromV8Arguments(args, &window))
return node::ThrowTypeError("Bad argument");
self->Popup(window);
}
// static
void Menu::Initialize(v8::Handle<v8::Object> target) {
v8::Local<v8::FunctionTemplate> t(v8::FunctionTemplate::New(Menu::New));
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(v8::String::NewSymbol("Menu"));
NODE_SET_PROTOTYPE_METHOD(t, "insertItem", InsertItem);
NODE_SET_PROTOTYPE_METHOD(t, "insertCheckItem", InsertCheckItem);
NODE_SET_PROTOTYPE_METHOD(t, "insertRadioItem", InsertRadioItem);
NODE_SET_PROTOTYPE_METHOD(t, "insertSeparator", InsertSeparator);
NODE_SET_PROTOTYPE_METHOD(t, "insertSubMenu", InsertSubMenu);
NODE_SET_PROTOTYPE_METHOD(t, "setIcon", SetIcon);
NODE_SET_PROTOTYPE_METHOD(t, "setSublabel", SetSublabel);
NODE_SET_PROTOTYPE_METHOD(t, "clear", Clear);
NODE_SET_PROTOTYPE_METHOD(t, "getIndexOfCommandId", GetIndexOfCommandId);
NODE_SET_PROTOTYPE_METHOD(t, "getItemCount", GetItemCount);
NODE_SET_PROTOTYPE_METHOD(t, "getCommandIdAt", GetCommandIdAt);
NODE_SET_PROTOTYPE_METHOD(t, "getLabelAt", GetLabelAt);
NODE_SET_PROTOTYPE_METHOD(t, "getSublabelAt", GetSublabelAt);
NODE_SET_PROTOTYPE_METHOD(t, "isItemCheckedAt", IsItemCheckedAt);
NODE_SET_PROTOTYPE_METHOD(t, "isEnabledAt", IsEnabledAt);
NODE_SET_PROTOTYPE_METHOD(t, "isVisibleAt", IsVisibleAt);
NODE_SET_PROTOTYPE_METHOD(t, "popup", Popup);
#if defined(OS_WIN) || defined(TOOLKIT_GTK)
NODE_SET_PROTOTYPE_METHOD(t, "attachToWindow", AttachToWindow);
#endif
target->Set(v8::String::NewSymbol("Menu"), t->GetFunction());
#if defined(OS_MACOSX)
NODE_SET_METHOD(target, "setApplicationMenu", SetApplicationMenu);
NODE_SET_METHOD(
target, "sendActionToFirstResponder", SendActionToFirstResponder);
#endif
}
} // namespace api
} // namespace atom
NODE_MODULE(atom_browser_menu, atom::api::Menu::Initialize)

View file

@ -0,0 +1,88 @@
// 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_BROWSER_API_ATOM_API_MENU_H_
#define ATOM_BROWSER_API_ATOM_API_MENU_H_
#include "base/memory/scoped_ptr.h"
#include "atom/common/api/atom_api_event_emitter.h"
#include "ui/base/models/simple_menu_model.h"
namespace atom {
class NativeWindow;
namespace api {
class Menu : public EventEmitter,
public ui::SimpleMenuModel::Delegate {
public:
virtual ~Menu();
static Menu* Create(v8::Handle<v8::Object> wrapper);
static void Initialize(v8::Handle<v8::Object> target);
protected:
explicit Menu(v8::Handle<v8::Object> wrapper);
// ui::SimpleMenuModel::Delegate implementations:
virtual bool IsCommandIdChecked(int command_id) const OVERRIDE;
virtual bool IsCommandIdEnabled(int command_id) const OVERRIDE;
virtual bool IsCommandIdVisible(int command_id) const OVERRIDE;
virtual bool GetAcceleratorForCommandId(
int command_id,
ui::Accelerator* accelerator) OVERRIDE;
virtual bool IsItemForCommandIdDynamic(int command_id) const OVERRIDE;
virtual string16 GetLabelForCommandId(int command_id) const OVERRIDE;
virtual string16 GetSublabelForCommandId(int command_id) const OVERRIDE;
virtual void ExecuteCommand(int command_id, int event_flags) OVERRIDE;
virtual void Popup(NativeWindow* window) = 0;
scoped_ptr<ui::SimpleMenuModel> model_;
private:
static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
static void InsertItem(const v8::FunctionCallbackInfo<v8::Value>& args);
static void InsertCheckItem(const v8::FunctionCallbackInfo<v8::Value>& args);
static void InsertRadioItem(const v8::FunctionCallbackInfo<v8::Value>& args);
static void InsertSeparator(const v8::FunctionCallbackInfo<v8::Value>& args);
static void InsertSubMenu(const v8::FunctionCallbackInfo<v8::Value>& args);
static void SetIcon(const v8::FunctionCallbackInfo<v8::Value>& args);
static void SetSublabel(const v8::FunctionCallbackInfo<v8::Value>& args);
static void Clear(const v8::FunctionCallbackInfo<v8::Value>& args);
static void GetIndexOfCommandId(
const v8::FunctionCallbackInfo<v8::Value>& args);
static void GetItemCount(const v8::FunctionCallbackInfo<v8::Value>& args);
static void GetCommandIdAt(const v8::FunctionCallbackInfo<v8::Value>& args);
static void GetLabelAt(const v8::FunctionCallbackInfo<v8::Value>& args);
static void GetSublabelAt(const v8::FunctionCallbackInfo<v8::Value>& args);
static void IsItemCheckedAt(const v8::FunctionCallbackInfo<v8::Value>& args);
static void IsEnabledAt(const v8::FunctionCallbackInfo<v8::Value>& args);
static void IsVisibleAt(const v8::FunctionCallbackInfo<v8::Value>& args);
static void Popup(const v8::FunctionCallbackInfo<v8::Value>& args);
#if defined(OS_WIN) || defined(TOOLKIT_GTK)
static void AttachToWindow(const v8::FunctionCallbackInfo<v8::Value>& args);
#elif defined(OS_MACOSX)
static void SetApplicationMenu(
const v8::FunctionCallbackInfo<v8::Value>& args);
static void SendActionToFirstResponder(
const v8::FunctionCallbackInfo<v8::Value>& args);
#endif
DISALLOW_COPY_AND_ASSIGN(Menu);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_MENU_H_

View file

@ -0,0 +1,64 @@
// Copyright (c) 2014 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.
#include "atom/browser/api/atom_api_menu_gtk.h"
#include "atom/browser/native_window_gtk.h"
#include "atom/common/v8/native_type_conversions.h"
#include "content/public/browser/render_widget_host_view.h"
#include "ui/gfx/point.h"
#include "ui/gfx/screen.h"
#include "atom/common/v8/node_common.h"
namespace atom {
namespace api {
MenuGtk::MenuGtk(v8::Handle<v8::Object> wrapper)
: Menu(wrapper) {
}
MenuGtk::~MenuGtk() {
}
void MenuGtk::Popup(NativeWindow* native_window) {
uint32_t triggering_event_time;
gfx::Point point;
GdkEventButton* event = native_window->GetWebContents()->
GetRenderWidgetHostView()->GetLastMouseDown();
if (event) {
triggering_event_time = event->time;
point = gfx::Point(event->x_root, event->y_root);
} else {
triggering_event_time = GDK_CURRENT_TIME;
point = gfx::Screen::GetNativeScreen()->GetCursorScreenPoint();
}
menu_gtk_.reset(new ::MenuGtk(this, model_.get()));
menu_gtk_->PopupAsContext(point, triggering_event_time);
}
// static
void Menu::AttachToWindow(const v8::FunctionCallbackInfo<v8::Value>& args) {
Menu* self = ObjectWrap::Unwrap<Menu>(args.This());
if (self == NULL)
return node::ThrowError("Menu is already destroyed");
NativeWindow* native_window;
if (!FromV8Arguments(args, &native_window))
return node::ThrowTypeError("Bad argument");
static_cast<NativeWindowGtk*>(native_window)->SetMenu(self->model_.get());
}
// static
Menu* Menu::Create(v8::Handle<v8::Object> wrapper) {
return new MenuGtk(wrapper);
}
} // namespace api
} // namespace atom

View file

@ -0,0 +1,34 @@
// Copyright (c) 2014 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_BROWSER_API_ATOM_API_MENU_GTK_H_
#define ATOM_BROWSER_API_ATOM_API_MENU_GTK_H_
#include "atom/browser/api/atom_api_menu.h"
#include "atom/browser/ui/gtk/menu_gtk.h"
namespace atom {
namespace api {
class MenuGtk : public Menu,
public ::MenuGtk::Delegate {
public:
explicit MenuGtk(v8::Handle<v8::Object> wrapper);
virtual ~MenuGtk();
protected:
virtual void Popup(NativeWindow* window) OVERRIDE;
private:
scoped_ptr<::MenuGtk> menu_gtk_;
DISALLOW_COPY_AND_ASSIGN(MenuGtk);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_MENU_GTK_H_

View file

@ -0,0 +1,39 @@
// 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_BROWSER_API_ATOM_API_MENU_MAC_H_
#define ATOM_BROWSER_API_ATOM_API_MENU_MAC_H_
#include "atom/browser/api/atom_api_menu.h"
#import "atom/browser/ui/cocoa/atom_menu_controller.h"
namespace atom {
namespace api {
class MenuMac : public Menu {
public:
explicit MenuMac(v8::Handle<v8::Object> wrapper);
virtual ~MenuMac();
protected:
virtual void Popup(NativeWindow* window) OVERRIDE;
base::scoped_nsobject<AtomMenuController> menu_controller_;
private:
friend class Menu;
// Fake sending an action from the application menu.
static void SendActionToFirstResponder(const std::string& action);
DISALLOW_COPY_AND_ASSIGN(MenuMac);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_MENU_MAC_H_

View file

@ -0,0 +1,109 @@
// 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.
#import "atom/browser/api/atom_api_menu_mac.h"
#include "base/mac/scoped_sending_event.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/sys_string_conversions.h"
#include "atom/browser/native_window.h"
#include "atom/common/v8/node_common.h"
#include "atom/common/v8/native_type_conversions.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_view.h"
namespace atom {
namespace api {
MenuMac::MenuMac(v8::Handle<v8::Object> wrapper)
: Menu(wrapper) {
}
MenuMac::~MenuMac() {
}
void MenuMac::Popup(NativeWindow* native_window) {
base::scoped_nsobject<AtomMenuController> menu_controller(
[[AtomMenuController alloc] initWithModel:model_.get()]);
NSWindow* window = native_window->GetNativeWindow();
content::WebContents* web_contents = native_window->GetWebContents();
// Fake out a context menu event.
NSEvent* currentEvent = [NSApp currentEvent];
NSPoint position = [window mouseLocationOutsideOfEventStream];
NSTimeInterval eventTime = [currentEvent timestamp];
NSEvent* clickEvent = [NSEvent mouseEventWithType:NSRightMouseDown
location:position
modifierFlags:NSRightMouseDownMask
timestamp:eventTime
windowNumber:[window windowNumber]
context:nil
eventNumber:0
clickCount:1
pressure:1.0];
{
// Make sure events can be pumped while the menu is up.
base::MessageLoop::ScopedNestableTaskAllower allow(
base::MessageLoop::current());
// One of the events that could be pumped is |window.close()|.
// User-initiated event-tracking loops protect against this by
// setting flags in -[CrApplication sendEvent:], but since
// web-content menus are initiated by IPC message the setup has to
// be done manually.
base::mac::ScopedSendingEvent sendingEventScoper;
// Show the menu.
[NSMenu popUpContextMenu:[menu_controller menu]
withEvent:clickEvent
forView:web_contents->GetView()->GetContentNativeView()];
}
}
// static
void MenuMac::SendActionToFirstResponder(const std::string& action) {
SEL selector = NSSelectorFromString(base::SysUTF8ToNSString(action));
[[NSApplication sharedApplication] sendAction:selector
to:nil
from:[NSApp mainMenu]];
}
// static
void Menu::SetApplicationMenu(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (!args[0]->IsObject())
return node::ThrowTypeError("Bad argument");
MenuMac* menu = ObjectWrap::Unwrap<MenuMac>(args[0]->ToObject());
if (!menu)
return node::ThrowError("Menu is destroyed");
base::scoped_nsobject<AtomMenuController> menu_controller(
[[AtomMenuController alloc] initWithModel:menu->model_.get()]);
[NSApp setMainMenu:[menu_controller menu]];
// Ensure the menu_controller_ is destroyed after main menu is set.
menu_controller.swap(menu->menu_controller_);
}
// static
void Menu::SendActionToFirstResponder(
const v8::FunctionCallbackInfo<v8::Value>& args) {
std::string action;
if (!FromV8Arguments(args, &action))
return node::ThrowTypeError("Bad argument");
MenuMac::SendActionToFirstResponder(action);
}
// static
Menu* Menu::Create(v8::Handle<v8::Object> wrapper) {
return new MenuMac(wrapper);
}
} // namespace api
} // namespace atom

View file

@ -0,0 +1,52 @@
// 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.
#include "atom/browser/api/atom_api_menu_win.h"
#include "atom/browser/native_window_win.h"
#include "atom/browser/ui/win/menu_2.h"
#include "atom/common/v8/native_type_conversions.h"
#include "ui/gfx/point.h"
#include "ui/gfx/screen.h"
#include "atom/common/v8/node_common.h"
namespace atom {
namespace api {
MenuWin::MenuWin(v8::Handle<v8::Object> wrapper)
: Menu(wrapper) {
}
MenuWin::~MenuWin() {
}
void MenuWin::Popup(NativeWindow* native_window) {
gfx::Point cursor = gfx::Screen::GetNativeScreen()->GetCursorScreenPoint();
menu_.reset(new atom::Menu2(model_.get()));
menu_->RunContextMenuAt(cursor);
}
// static
void Menu::AttachToWindow(const v8::FunctionCallbackInfo<v8::Value>& args) {
Menu* self = ObjectWrap::Unwrap<Menu>(args.This());
if (self == NULL)
return node::ThrowError("Menu is already destroyed");
NativeWindow* native_window;
if (!FromV8Arguments(args, &native_window))
return node::ThrowTypeError("Bad argument");
static_cast<NativeWindowWin*>(native_window)->SetMenu(self->model_.get());
}
// static
Menu* Menu::Create(v8::Handle<v8::Object> wrapper) {
return new MenuWin(wrapper);
}
} // namespace api
} // namespace atom

View file

@ -0,0 +1,34 @@
// 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_BROWSER_API_ATOM_API_MENU_WIN_H_
#define ATOM_BROWSER_API_ATOM_API_MENU_WIN_H_
#include "atom/browser/api/atom_api_menu.h"
namespace atom {
class Menu2;
namespace api {
class MenuWin : public Menu {
public:
explicit MenuWin(v8::Handle<v8::Object> wrapper);
virtual ~MenuWin();
protected:
virtual void Popup(NativeWindow* window) OVERRIDE;
private:
scoped_ptr<atom::Menu2> menu_;
DISALLOW_COPY_AND_ASSIGN(MenuWin);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_MENU_WIN_H_

View file

@ -0,0 +1,67 @@
// 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.
#include "atom/browser/api/atom_api_power_monitor.h"
#include "base/power_monitor/power_monitor.h"
#include "base/power_monitor/power_monitor_device_source.h"
#include "atom/common/v8/node_common.h"
namespace atom {
namespace api {
PowerMonitor::PowerMonitor(v8::Handle<v8::Object> wrapper)
: EventEmitter(wrapper) {
base::PowerMonitor::Get()->AddObserver(this);
}
PowerMonitor::~PowerMonitor() {
base::PowerMonitor::Get()->RemoveObserver(this);
}
void PowerMonitor::OnPowerStateChange(bool on_battery_power) {
if (on_battery_power)
Emit("on-battery");
else
Emit("on-ac");
}
void PowerMonitor::OnSuspend() {
Emit("suspend");
}
void PowerMonitor::OnResume() {
Emit("resume");
}
// static
void PowerMonitor::New(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (!args.IsConstructCall())
return node::ThrowError("Require constructor call");
new PowerMonitor(args.This());
}
// static
void PowerMonitor::Initialize(v8::Handle<v8::Object> target) {
#if defined(OS_MACOSX)
base::PowerMonitorDeviceSource::AllocateSystemIOPorts();
#endif
v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(
PowerMonitor::New);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(v8::String::NewSymbol("PowerMonitor"));
target->Set(v8::String::NewSymbol("PowerMonitor"), t->GetFunction());
}
} // namespace api
} // namespace atom
NODE_MODULE(atom_browser_power_monitor, atom::api::PowerMonitor::Initialize)

View file

@ -0,0 +1,40 @@
// 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_BROWSER_API_ATOM_API_POWER_MONITOR_H_
#define ATOM_BROWSER_API_ATOM_API_POWER_MONITOR_H_
#include "base/compiler_specific.h"
#include "base/power_monitor/power_observer.h"
#include "atom/common/api/atom_api_event_emitter.h"
namespace atom {
namespace api {
class PowerMonitor : public EventEmitter,
public base::PowerObserver {
public:
virtual ~PowerMonitor();
static void Initialize(v8::Handle<v8::Object> target);
protected:
explicit PowerMonitor(v8::Handle<v8::Object> wrapper);
virtual void OnPowerStateChange(bool on_battery_power) OVERRIDE;
virtual void OnSuspend() OVERRIDE;
virtual void OnResume() OVERRIDE;
private:
static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
DISALLOW_COPY_AND_ASSIGN(PowerMonitor);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_POWER_MONITOR_H_

View file

@ -0,0 +1,386 @@
// 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.
#include "atom/browser/api/atom_api_protocol.h"
#include "base/stl_util.h"
#include "atom/browser/atom_browser_context.h"
#include "atom/browser/net/adapter_request_job.h"
#include "atom/browser/net/atom_url_request_context_getter.h"
#include "atom/browser/net/atom_url_request_job_factory.h"
#include "atom/common/v8/native_type_conversions.h"
#include "content/public/browser/browser_thread.h"
#include "net/url_request/url_request_context.h"
#include "atom/common/v8/node_common.h"
namespace atom {
namespace api {
typedef net::URLRequestJobFactory::ProtocolHandler ProtocolHandler;
namespace {
// The protocol module object.
ScopedPersistent<v8::Object> g_protocol_object;
// Registered protocol handlers.
typedef std::map<std::string, RefCountedV8Function> HandlersMap;
static HandlersMap g_handlers;
static const char* kEarlyUseProtocolError = "This method can only be used"
"after the application has finished launching.";
// Emit an event for the protocol module.
void EmitEventInUI(const std::string& event, const std::string& parameter) {
v8::Locker locker(node_isolate);
v8::HandleScope handle_scope(node_isolate);
v8::Handle<v8::Value> argv[] = {
ToV8Value(event),
ToV8Value(parameter),
};
node::MakeCallback(g_protocol_object.NewHandle(node_isolate),
"emit", 2, argv);
}
// Convert the URLRequest object to V8 object.
v8::Handle<v8::Object> ConvertURLRequestToV8Object(
const net::URLRequest* request) {
v8::Local<v8::Object> obj = v8::Object::New();
obj->Set(ToV8Value("method"), ToV8Value(request->method()));
obj->Set(ToV8Value("url"), ToV8Value(request->url().spec()));
obj->Set(ToV8Value("referrer"), ToV8Value(request->referrer()));
return obj;
}
// Get the job factory.
AtomURLRequestJobFactory* GetRequestJobFactory() {
return AtomBrowserContext::Get()->url_request_context_getter()->job_factory();
}
class CustomProtocolRequestJob : public AdapterRequestJob {
public:
CustomProtocolRequestJob(ProtocolHandler* protocol_handler,
net::URLRequest* request,
net::NetworkDelegate* network_delegate)
: AdapterRequestJob(protocol_handler, request, network_delegate) {
}
// AdapterRequestJob:
virtual void GetJobTypeInUI() OVERRIDE {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
v8::Locker locker(node_isolate);
v8::HandleScope handle_scope(node_isolate);
// Call the JS handler.
v8::Handle<v8::Value> argv[] = {
ConvertURLRequestToV8Object(request()),
};
RefCountedV8Function callback = g_handlers[request()->url().scheme()];
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.
if (result->IsString()) {
std::string data = FromV8Value(result);
content::BrowserThread::PostTask(
content::BrowserThread::IO,
FROM_HERE,
base::Bind(&AdapterRequestJob::CreateStringJobAndStart,
GetWeakPtr(),
"text/plain",
"UTF-8",
data));
return;
} else if (result->IsObject()) {
v8::Handle<v8::Object> obj = result->ToObject();
std::string name = FromV8Value(obj->GetConstructorName());
if (name == "RequestStringJob") {
std::string mime_type = FromV8Value(obj->Get(
v8::String::New("mimeType")));
std::string charset = FromV8Value(obj->Get(v8::String::New("charset")));
std::string data = FromV8Value(obj->Get(v8::String::New("data")));
content::BrowserThread::PostTask(
content::BrowserThread::IO,
FROM_HERE,
base::Bind(&AdapterRequestJob::CreateStringJobAndStart,
GetWeakPtr(),
mime_type,
charset,
data));
return;
} else if (name == "RequestFileJob") {
base::FilePath path = FromV8Value(obj->Get(v8::String::New("path")));
content::BrowserThread::PostTask(
content::BrowserThread::IO,
FROM_HERE,
base::Bind(&AdapterRequestJob::CreateFileJobAndStart,
GetWeakPtr(),
path));
return;
}
}
// Try the default protocol handler if we have.
if (default_protocol_handler()) {
content::BrowserThread::PostTask(
content::BrowserThread::IO,
FROM_HERE,
base::Bind(&AdapterRequestJob::CreateJobFromProtocolHandlerAndStart,
GetWeakPtr()));
return;
}
// Fallback to the not implemented error.
content::BrowserThread::PostTask(
content::BrowserThread::IO,
FROM_HERE,
base::Bind(&AdapterRequestJob::CreateErrorJobAndStart,
GetWeakPtr(),
net::ERR_NOT_IMPLEMENTED));
}
};
// Always return the same CustomProtocolRequestJob for all requests, because
// the content API needs the ProtocolHandler to return a job immediately, and
// getting the real job from the JS requires asynchronous calls, so we have
// to create an adapter job first.
// Users can also pass an extra ProtocolHandler as the fallback one when
// registered handler doesn't want to deal with the request.
class CustomProtocolHandler : public ProtocolHandler {
public:
explicit CustomProtocolHandler(ProtocolHandler* protocol_handler = NULL)
: protocol_handler_(protocol_handler) {
}
virtual net::URLRequestJob* MaybeCreateJob(
net::URLRequest* request,
net::NetworkDelegate* network_delegate) const OVERRIDE {
return new CustomProtocolRequestJob(protocol_handler_.get(),
request,
network_delegate);
}
ProtocolHandler* ReleaseDefaultProtocolHandler() {
return protocol_handler_.release();
}
ProtocolHandler* original_handler() { return protocol_handler_.get(); }
private:
scoped_ptr<ProtocolHandler> protocol_handler_;
DISALLOW_COPY_AND_ASSIGN(CustomProtocolHandler);
};
} // namespace
// static
void Protocol::RegisterProtocol(
const v8::FunctionCallbackInfo<v8::Value>& args) {
std::string scheme;
RefCountedV8Function callback;
if (!FromV8Arguments(args, &scheme, &callback))
return node::ThrowTypeError("Bad argument");
if (g_handlers.find(scheme) != g_handlers.end() ||
GetRequestJobFactory()->IsHandledProtocol(scheme))
return node::ThrowError("The scheme is already registered");
if (AtomBrowserContext::Get()->url_request_context_getter() == NULL)
return node::ThrowError(kEarlyUseProtocolError);
// Store the handler in a map.
g_handlers[scheme] = callback;
content::BrowserThread::PostTask(content::BrowserThread::IO,
FROM_HERE,
base::Bind(&RegisterProtocolInIO, scheme));
}
// static
void Protocol::UnregisterProtocol(
const v8::FunctionCallbackInfo<v8::Value>& args) {
std::string scheme;
if (!FromV8Arguments(args, &scheme))
return node::ThrowTypeError("Bad argument");
if (AtomBrowserContext::Get()->url_request_context_getter() == NULL)
return node::ThrowError(kEarlyUseProtocolError);
// Erase the handler from map.
HandlersMap::iterator it(g_handlers.find(scheme));
if (it == g_handlers.end())
return node::ThrowError("The scheme has not been registered");
g_handlers.erase(it);
content::BrowserThread::PostTask(content::BrowserThread::IO,
FROM_HERE,
base::Bind(&UnregisterProtocolInIO, scheme));
}
// static
void Protocol::IsHandledProtocol(
const v8::FunctionCallbackInfo<v8::Value>& args) {
std::string scheme;
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))
return node::ThrowTypeError("Bad argument");
if (!GetRequestJobFactory()->HasProtocolHandler(scheme))
return node::ThrowError("Cannot intercept procotol");
if (ContainsKey(g_handlers, scheme))
return node::ThrowError("Cannot intercept custom procotols");
if (AtomBrowserContext::Get()->url_request_context_getter() == NULL)
return node::ThrowError(kEarlyUseProtocolError);
// Store the handler in a map.
g_handlers[scheme] = callback;
content::BrowserThread::PostTask(content::BrowserThread::IO,
FROM_HERE,
base::Bind(&InterceptProtocolInIO, scheme));
}
// static
void Protocol::UninterceptProtocol(
const v8::FunctionCallbackInfo<v8::Value>& args) {
std::string scheme;
if (!FromV8Arguments(args, &scheme))
return node::ThrowTypeError("Bad argument");
if (AtomBrowserContext::Get()->url_request_context_getter() == NULL)
return node::ThrowError(kEarlyUseProtocolError);
// Erase the handler from map.
HandlersMap::iterator it(g_handlers.find(scheme));
if (it == g_handlers.end())
return node::ThrowError("The scheme has not been registered");
g_handlers.erase(it);
content::BrowserThread::PostTask(content::BrowserThread::IO,
FROM_HERE,
base::Bind(&UninterceptProtocolInIO,
scheme));
}
// static
void Protocol::RegisterProtocolInIO(const std::string& scheme) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
AtomURLRequestJobFactory* job_factory(GetRequestJobFactory());
job_factory->SetProtocolHandler(scheme, new CustomProtocolHandler);
content::BrowserThread::PostTask(content::BrowserThread::UI,
FROM_HERE,
base::Bind(&EmitEventInUI,
"registered",
scheme));
}
// static
void Protocol::UnregisterProtocolInIO(const std::string& scheme) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
AtomURLRequestJobFactory* job_factory(GetRequestJobFactory());
job_factory->SetProtocolHandler(scheme, NULL);
content::BrowserThread::PostTask(content::BrowserThread::UI,
FROM_HERE,
base::Bind(&EmitEventInUI,
"unregistered",
scheme));
}
// static
void Protocol::InterceptProtocolInIO(const std::string& scheme) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
AtomURLRequestJobFactory* job_factory(GetRequestJobFactory());
ProtocolHandler* original_handler = job_factory->GetProtocolHandler(scheme);
if (original_handler == NULL) {
content::BrowserThread::PostTask(
content::BrowserThread::UI,
FROM_HERE,
base::Bind(&EmitEventInUI,
"error",
"There is no protocol handler to intercpet"));
return;
}
job_factory->ReplaceProtocol(scheme,
new CustomProtocolHandler(original_handler));
content::BrowserThread::PostTask(content::BrowserThread::UI,
FROM_HERE,
base::Bind(&EmitEventInUI,
"intercepted",
scheme));
}
// static
void Protocol::UninterceptProtocolInIO(const std::string& scheme) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
AtomURLRequestJobFactory* job_factory(GetRequestJobFactory());
// Check if the protocol handler is intercepted.
CustomProtocolHandler* handler = static_cast<CustomProtocolHandler*>(
job_factory->GetProtocolHandler(scheme));
if (handler->original_handler() == NULL) {
content::BrowserThread::PostTask(
content::BrowserThread::UI,
FROM_HERE,
base::Bind(&EmitEventInUI,
"error",
"The protocol is not intercpeted"));
return;
}
// Reset the protocol handler to the orignal one and delete current
// protocol handler.
ProtocolHandler* original_handler = handler->ReleaseDefaultProtocolHandler();
delete job_factory->ReplaceProtocol(scheme, original_handler);
content::BrowserThread::PostTask(content::BrowserThread::UI,
FROM_HERE,
base::Bind(&EmitEventInUI,
"unintercepted",
scheme));
}
// static
void Protocol::Initialize(v8::Handle<v8::Object> target) {
// Remember the protocol object, used for emitting event later.
g_protocol_object.reset(target);
// Make sure the job factory has been created.
AtomBrowserContext::Get()->url_request_context_getter()->
GetURLRequestContext();
NODE_SET_METHOD(target, "registerProtocol", RegisterProtocol);
NODE_SET_METHOD(target, "unregisterProtocol", UnregisterProtocol);
NODE_SET_METHOD(target, "isHandledProtocol", IsHandledProtocol);
NODE_SET_METHOD(target, "interceptProtocol", InterceptProtocol);
NODE_SET_METHOD(target, "uninterceptProtocol", UninterceptProtocol);
}
} // namespace api
} // namespace atom
NODE_MODULE(atom_browser_protocol, atom::api::Protocol::Initialize)

View file

@ -0,0 +1,47 @@
// 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_BROWSER_API_ATOM_API_PROTOCOL_H_
#define ATOM_BROWSER_API_ATOM_API_PROTOCOL_H_
#include <string>
#include <map>
#include "base/basictypes.h"
#include "v8/include/v8.h"
namespace atom {
namespace api {
class Protocol {
public:
static void Initialize(v8::Handle<v8::Object> target);
private:
static void RegisterProtocol(const v8::FunctionCallbackInfo<v8::Value>& args);
static void UnregisterProtocol(
const v8::FunctionCallbackInfo<v8::Value>& args);
static void IsHandledProtocol(
const v8::FunctionCallbackInfo<v8::Value>& args);
static void InterceptProtocol(
const v8::FunctionCallbackInfo<v8::Value>& args);
static void UninterceptProtocol(
const v8::FunctionCallbackInfo<v8::Value>& args);
static void RegisterProtocolInIO(const std::string& scheme);
static void UnregisterProtocolInIO(const std::string& scheme);
static void InterceptProtocolInIO(const std::string& scheme);
static void UninterceptProtocolInIO(const std::string& scheme);
DISALLOW_IMPLICIT_CONSTRUCTORS(Protocol);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_PROTOCOL_H_

View file

@ -0,0 +1,706 @@
// 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.
#include "atom/browser/api/atom_api_window.h"
#include "base/bind.h"
#include "base/process/kill.h"
#include "atom/browser/native_window.h"
#include "atom/common/v8/native_type_conversions.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/render_process_host.h"
#include "ui/gfx/point.h"
#include "ui/gfx/size.h"
#include "atom/common/v8/node_common.h"
#include "vendor/node/src/node_buffer.h"
using content::NavigationController;
using node::ObjectWrap;
#define UNWRAP_WINDOW_AND_CHECK \
Window* self = ObjectWrap::Unwrap<Window>(args.This()); \
if (self == NULL) \
return node::ThrowError("Window is already destroyed")
namespace atom {
namespace api {
Window::Window(v8::Handle<v8::Object> wrapper, base::DictionaryValue* options)
: EventEmitter(wrapper),
window_(NativeWindow::Create(options)) {
window_->InitFromOptions(options);
window_->AddObserver(this);
}
Window::~Window() {
Emit("destroyed");
window_->RemoveObserver(this);
}
void Window::OnPageTitleUpdated(bool* prevent_default,
const std::string& title) {
base::ListValue args;
args.AppendString(title);
*prevent_default = Emit("page-title-updated", &args);
}
void Window::OnLoadingStateChanged(bool is_loading) {
base::ListValue args;
args.AppendBoolean(is_loading);
Emit("loading-state-changed", &args);
}
void Window::WillCloseWindow(bool* prevent_default) {
*prevent_default = Emit("close");
}
void Window::OnWindowClosed() {
Emit("closed");
// Free memory when native window is closed, the delete is delayed so other
// observers would not get a invalid pointer of NativeWindow.
base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
}
void Window::OnWindowBlur() {
Emit("blur");
}
void Window::OnRendererUnresponsive() {
Emit("unresponsive");
}
void Window::OnRendererResponsive() {
Emit("responsive");
}
void Window::OnRenderViewDeleted(int process_id, int routing_id) {
base::ListValue args;
args.AppendInteger(process_id);
args.AppendInteger(routing_id);
Emit("render-view-deleted", &args);
}
void Window::OnRendererCrashed() {
Emit("crashed");
}
void Window::OnCapturePageDone(const RefCountedV8Function& callback,
const std::vector<unsigned char>& data) {
v8::Locker locker(node_isolate);
v8::HandleScope handle_scope(node_isolate);
v8::Local<v8::Value> buffer = node::Buffer::New(
reinterpret_cast<const char*>(data.data()),
data.size());
callback->NewHandle(node_isolate)->Call(
v8::Context::GetCurrent()->Global(), 1, &buffer);
}
// static
void Window::New(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (!args.IsConstructCall())
return node::ThrowError("Require constructor call");
scoped_ptr<base::Value> options;
if (!FromV8Arguments(args, &options))
return node::ThrowTypeError("Bad argument");
if (!options || !options->IsType(base::Value::TYPE_DICTIONARY))
return node::ThrowTypeError("Options must be dictionary");
new Window(args.This(), static_cast<base::DictionaryValue*>(options.get()));
// Give js code a chance to do initialization.
node::MakeCallback(args.This(), "_init", 0, NULL);
}
// static
void Window::Destroy(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
base::ProcessHandle handle = self->window_->GetRenderProcessHandle();
delete self;
// Make sure the renderer process is terminated, it could happen that the
// renderer process became a zombie.
base::MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(base::IgnoreResult(base::KillProcess), handle, 0, false),
base::TimeDelta::FromMilliseconds(5000));
}
// static
void Window::Close(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
self->window_->Close();
}
// static
void Window::Focus(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
self->window_->Focus(args[0]->IsBoolean() ? args[0]->BooleanValue(): true);
}
// static
void Window::IsFocused(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
args.GetReturnValue().Set(self->window_->IsFocused());
}
// static
void Window::Show(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
self->window_->Show();
}
// static
void Window::Hide(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
self->window_->Hide();
}
// static
void Window::IsVisible(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
return args.GetReturnValue().Set(self->window_->IsVisible());
}
// static
void Window::Maximize(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
self->window_->Maximize();
}
// static
void Window::Unmaximize(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
self->window_->Unmaximize();
}
// static
void Window::Minimize(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
self->window_->Minimize();
}
// static
void Window::Restore(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
self->window_->Restore();
}
// static
void Window::SetFullscreen(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
bool fs;
if (!FromV8Arguments(args, &fs))
return node::ThrowTypeError("Bad argument");
self->window_->SetFullscreen(fs);
}
// static
void Window::IsFullscreen(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
args.GetReturnValue().Set(self->window_->IsFullscreen());
}
// static
void Window::SetSize(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
int width, height;
if (!FromV8Arguments(args, &width, &height))
return node::ThrowTypeError("Bad argument");
self->window_->SetSize(gfx::Size(width, height));
}
// static
void Window::GetSize(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
gfx::Size size = self->window_->GetSize();
v8::Handle<v8::Array> ret = v8::Array::New(2);
ret->Set(0, ToV8Value(size.width()));
ret->Set(1, ToV8Value(size.height()));
args.GetReturnValue().Set(ret);
}
// static
void Window::SetMinimumSize(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
int width, height;
if (!FromV8Arguments(args, &width, &height))
return node::ThrowTypeError("Bad argument");
self->window_->SetMinimumSize(gfx::Size(width, height));
}
// static
void Window::GetMinimumSize(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
gfx::Size size = self->window_->GetMinimumSize();
v8::Handle<v8::Array> ret = v8::Array::New(2);
ret->Set(0, ToV8Value(size.width()));
ret->Set(1, ToV8Value(size.height()));
args.GetReturnValue().Set(ret);
}
// static
void Window::SetMaximumSize(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
int width, height;
if (!FromV8Arguments(args, &width, &height))
return node::ThrowTypeError("Bad argument");
self->window_->SetMaximumSize(gfx::Size(width, height));
}
// static
void Window::GetMaximumSize(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
gfx::Size size = self->window_->GetMaximumSize();
v8::Handle<v8::Array> ret = v8::Array::New(2);
ret->Set(0, ToV8Value(size.width()));
ret->Set(1, ToV8Value(size.height()));
args.GetReturnValue().Set(ret);
}
// static
void Window::SetResizable(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
bool resizable;
if (!FromV8Arguments(args, &resizable))
return node::ThrowTypeError("Bad argument");
self->window_->SetResizable(resizable);
}
// static
void Window::IsResizable(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
args.GetReturnValue().Set(self->window_->IsResizable());
}
// static
void Window::SetAlwaysOnTop(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
bool top;
if (!FromV8Arguments(args, &top))
return node::ThrowTypeError("Bad argument");
self->window_->SetAlwaysOnTop(top);
}
// static
void Window::IsAlwaysOnTop(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
args.GetReturnValue().Set(self->window_->IsAlwaysOnTop());
}
// static
void Window::Center(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
self->window_->Center();
}
// static
void Window::SetPosition(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
int x, y;
if (!FromV8Arguments(args, &x, &y))
return node::ThrowTypeError("Bad argument");
self->window_->SetPosition(gfx::Point(x, y));
}
// static
void Window::GetPosition(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
gfx::Point pos = self->window_->GetPosition();
v8::Handle<v8::Array> ret = v8::Array::New(2);
ret->Set(0, ToV8Value(pos.x()));
ret->Set(1, ToV8Value(pos.y()));
args.GetReturnValue().Set(ret);
}
// static
void Window::SetTitle(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
std::string title;
if (!FromV8Arguments(args, &title))
return node::ThrowTypeError("Bad argument");
self->window_->SetTitle(title);
}
// static
void Window::GetTitle(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
args.GetReturnValue().Set(ToV8Value(self->window_->GetTitle()));
}
// static
void Window::FlashFrame(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
self->window_->FlashFrame(
args[0]->IsBoolean() ? args[0]->BooleanValue(): true);
}
// static
void Window::SetKiosk(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
bool kiosk;
if (!FromV8Arguments(args, &kiosk))
return node::ThrowTypeError("Bad argument");
self->window_->SetKiosk(kiosk);
}
// static
void Window::IsKiosk(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
args.GetReturnValue().Set(self->window_->IsKiosk());
}
// static
void Window::OpenDevTools(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
self->window_->OpenDevTools();
}
// static
void Window::CloseDevTools(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
self->window_->CloseDevTools();
}
// static
void Window::IsDevToolsOpened(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
args.GetReturnValue().Set(self->window_->IsDevToolsOpened());
}
// static
void Window::InspectElement(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
int x, y;
if (!FromV8Arguments(args, &x, &y))
return node::ThrowTypeError("Bad argument");
self->window_->InspectElement(x, y);
}
// static
void Window::DebugDevTools(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
if (self->window_->IsDevToolsOpened())
NativeWindow::Debug(self->window_->GetDevToolsWebContents());
}
// static
void Window::FocusOnWebView(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
self->window_->FocusOnWebView();
}
// static
void Window::BlurWebView(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
self->window_->BlurWebView();
}
// static
void Window::IsWebViewFocused(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
args.GetReturnValue().Set(self->window_->IsWebViewFocused());
}
// static
void Window::CapturePage(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
gfx::Rect rect;
RefCountedV8Function callback;
if (!FromV8Arguments(args, &rect, &callback) &&
!FromV8Arguments(args, &callback))
return node::ThrowTypeError("Bad argument");
self->window_->CapturePage(rect, base::Bind(&Window::OnCapturePageDone,
base::Unretained(self),
callback));
}
// static
void Window::GetPageTitle(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
args.GetReturnValue().Set(ToV8Value(
self->window_->GetWebContents()->GetTitle()));
}
// static
void Window::IsLoading(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
args.GetReturnValue().Set(self->window_->GetWebContents()->IsLoading());
}
// static
void Window::IsWaitingForResponse(
const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
args.GetReturnValue().Set(
self->window_->GetWebContents()->IsWaitingForResponse());
}
// static
void Window::Stop(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
self->window_->GetWebContents()->Stop();
}
// static
void Window::GetRoutingID(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
args.GetReturnValue().Set(self->window_->GetWebContents()->GetRoutingID());
}
// static
void Window::GetProcessID(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
args.GetReturnValue().Set(
self->window_->GetWebContents()->GetRenderProcessHost()->GetID());
}
// static
void Window::IsCrashed(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
args.GetReturnValue().Set(self->window_->GetWebContents()->IsCrashed());
}
// static
void Window::LoadURL(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
GURL url;
if (!FromV8Arguments(args, &url))
return node::ThrowTypeError("Bad argument");
NavigationController& controller =
self->window_->GetWebContents()->GetController();
content::NavigationController::LoadURLParams params(url);
params.transition_type = content::PAGE_TRANSITION_TYPED;
params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE;
controller.LoadURLWithParams(params);
}
// static
void Window::GetURL(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
NavigationController& controller =
self->window_->GetWebContents()->GetController();
GURL url;
if (controller.GetActiveEntry())
url = controller.GetActiveEntry()->GetVirtualURL();
args.GetReturnValue().Set(ToV8Value(url));
}
// static
void Window::CanGoBack(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
NavigationController& controller =
self->window_->GetWebContents()->GetController();
args.GetReturnValue().Set(controller.CanGoBack());
}
// static
void Window::CanGoForward(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
NavigationController& controller =
self->window_->GetWebContents()->GetController();
args.GetReturnValue().Set(controller.CanGoForward());
}
// static
void Window::CanGoToOffset(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
int offset;
if (!FromV8Arguments(args, &offset))
return node::ThrowTypeError("Bad argument");
NavigationController& controller =
self->window_->GetWebContents()->GetController();
args.GetReturnValue().Set(controller.CanGoToOffset(offset));
}
// static
void Window::GoBack(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
NavigationController& controller =
self->window_->GetWebContents()->GetController();
controller.GoBack();
}
// static
void Window::GoForward(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
NavigationController& controller =
self->window_->GetWebContents()->GetController();
controller.GoForward();
}
// static
void Window::GoToIndex(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
int index;
if (!FromV8Arguments(args, &index))
return node::ThrowTypeError("Bad argument");
NavigationController& controller =
self->window_->GetWebContents()->GetController();
controller.GoToIndex(index);
}
// static
void Window::GoToOffset(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
int offset;
if (!FromV8Arguments(args, &offset))
return node::ThrowTypeError("Bad argument");
NavigationController& controller =
self->window_->GetWebContents()->GetController();
controller.GoToOffset(offset);
}
// static
void Window::Reload(const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
NavigationController& controller =
self->window_->GetWebContents()->GetController();
controller.Reload(args[0]->IsBoolean() ? args[0]->BooleanValue(): false);
}
// static
void Window::ReloadIgnoringCache(
const v8::FunctionCallbackInfo<v8::Value>& args) {
UNWRAP_WINDOW_AND_CHECK;
NavigationController& controller =
self->window_->GetWebContents()->GetController();
controller.ReloadIgnoringCache(
args[0]->IsBoolean() ? args[0]->BooleanValue(): false);
}
// static
void Window::Initialize(v8::Handle<v8::Object> target) {
v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(Window::New);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(v8::String::NewSymbol("BrowserWindow"));
NODE_SET_PROTOTYPE_METHOD(t, "destroy", Destroy);
NODE_SET_PROTOTYPE_METHOD(t, "close", Close);
NODE_SET_PROTOTYPE_METHOD(t, "focus", Focus);
NODE_SET_PROTOTYPE_METHOD(t, "isFocused", IsFocused);
NODE_SET_PROTOTYPE_METHOD(t, "show", Show);
NODE_SET_PROTOTYPE_METHOD(t, "hide", Hide);
NODE_SET_PROTOTYPE_METHOD(t, "isVisible", IsVisible);
NODE_SET_PROTOTYPE_METHOD(t, "maximize", Maximize);
NODE_SET_PROTOTYPE_METHOD(t, "unmaximize", Unmaximize);
NODE_SET_PROTOTYPE_METHOD(t, "minimize", Minimize);
NODE_SET_PROTOTYPE_METHOD(t, "restore", Restore);
NODE_SET_PROTOTYPE_METHOD(t, "setFullScreen", SetFullscreen);
NODE_SET_PROTOTYPE_METHOD(t, "isFullScreen", IsFullscreen);
NODE_SET_PROTOTYPE_METHOD(t, "setSize", SetSize);
NODE_SET_PROTOTYPE_METHOD(t, "getSize", GetSize);
NODE_SET_PROTOTYPE_METHOD(t, "setMinimumSize", SetMinimumSize);
NODE_SET_PROTOTYPE_METHOD(t, "getMinimumSize", GetMinimumSize);
NODE_SET_PROTOTYPE_METHOD(t, "setMaximumSize", SetMaximumSize);
NODE_SET_PROTOTYPE_METHOD(t, "getMaximumSize", GetMaximumSize);
NODE_SET_PROTOTYPE_METHOD(t, "setResizable", SetResizable);
NODE_SET_PROTOTYPE_METHOD(t, "isResizable", IsResizable);
NODE_SET_PROTOTYPE_METHOD(t, "setAlwaysOnTop", SetAlwaysOnTop);
NODE_SET_PROTOTYPE_METHOD(t, "isAlwaysOnTop", IsAlwaysOnTop);
NODE_SET_PROTOTYPE_METHOD(t, "center", Center);
NODE_SET_PROTOTYPE_METHOD(t, "setPosition", SetPosition);
NODE_SET_PROTOTYPE_METHOD(t, "getPosition", GetPosition);
NODE_SET_PROTOTYPE_METHOD(t, "setTitle", SetTitle);
NODE_SET_PROTOTYPE_METHOD(t, "getTitle", GetTitle);
NODE_SET_PROTOTYPE_METHOD(t, "flashFrame", FlashFrame);
NODE_SET_PROTOTYPE_METHOD(t, "setKiosk", SetKiosk);
NODE_SET_PROTOTYPE_METHOD(t, "isKiosk", IsKiosk);
NODE_SET_PROTOTYPE_METHOD(t, "openDevTools", OpenDevTools);
NODE_SET_PROTOTYPE_METHOD(t, "closeDevTools", CloseDevTools);
NODE_SET_PROTOTYPE_METHOD(t, "isDevToolsOpened", IsDevToolsOpened);
NODE_SET_PROTOTYPE_METHOD(t, "inspectElement", InspectElement);
NODE_SET_PROTOTYPE_METHOD(t, "debugDevTools", DebugDevTools);
NODE_SET_PROTOTYPE_METHOD(t, "focusOnWebView", FocusOnWebView);
NODE_SET_PROTOTYPE_METHOD(t, "blurWebView", BlurWebView);
NODE_SET_PROTOTYPE_METHOD(t, "isWebViewFocused", IsWebViewFocused);
NODE_SET_PROTOTYPE_METHOD(t, "capturePage", CapturePage);
NODE_SET_PROTOTYPE_METHOD(t, "getPageTitle", GetPageTitle);
NODE_SET_PROTOTYPE_METHOD(t, "isLoading", IsLoading);
NODE_SET_PROTOTYPE_METHOD(t, "isWaitingForResponse", IsWaitingForResponse);
NODE_SET_PROTOTYPE_METHOD(t, "stop", Stop);
NODE_SET_PROTOTYPE_METHOD(t, "getRoutingId", GetRoutingID);
NODE_SET_PROTOTYPE_METHOD(t, "getProcessId", GetProcessID);
NODE_SET_PROTOTYPE_METHOD(t, "isCrashed", IsCrashed);
NODE_SET_PROTOTYPE_METHOD(t, "loadUrl", LoadURL);
NODE_SET_PROTOTYPE_METHOD(t, "getUrl", GetURL);
NODE_SET_PROTOTYPE_METHOD(t, "canGoBack", CanGoBack);
NODE_SET_PROTOTYPE_METHOD(t, "canGoForward", CanGoForward);
NODE_SET_PROTOTYPE_METHOD(t, "canGoToOffset", CanGoToOffset);
NODE_SET_PROTOTYPE_METHOD(t, "goBack", GoBack);
NODE_SET_PROTOTYPE_METHOD(t, "goForward", GoForward);
NODE_SET_PROTOTYPE_METHOD(t, "goToIndex", GoToIndex);
NODE_SET_PROTOTYPE_METHOD(t, "goToOffset", GoToOffset);
NODE_SET_PROTOTYPE_METHOD(t, "reload", Reload);
NODE_SET_PROTOTYPE_METHOD(t, "reloadIgnoringCache", ReloadIgnoringCache);
target->Set(v8::String::NewSymbol("BrowserWindow"), t->GetFunction());
}
} // namespace api
} // namespace atom
NODE_MODULE(atom_browser_window, atom::api::Window::Initialize)

View file

@ -0,0 +1,132 @@
// 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_BROWSER_API_ATOM_API_WINDOW_H_
#define ATOM_BROWSER_API_ATOM_API_WINDOW_H_
#include <vector>
#include "base/memory/scoped_ptr.h"
#include "atom/browser/native_window_observer.h"
#include "atom/common/api/atom_api_event_emitter.h"
#include "atom/common/v8/scoped_persistent.h"
namespace base {
class DictionaryValue;
}
namespace atom {
class NativeWindow;
namespace api {
class Window : public EventEmitter,
public NativeWindowObserver {
public:
virtual ~Window();
static void Initialize(v8::Handle<v8::Object> target);
NativeWindow* window() { return window_.get(); }
protected:
explicit Window(v8::Handle<v8::Object> wrapper,
base::DictionaryValue* options);
// Implementations of NativeWindowObserver.
virtual void OnPageTitleUpdated(bool* prevent_default,
const std::string& title) OVERRIDE;
virtual void OnLoadingStateChanged(bool is_loading) OVERRIDE;
virtual void WillCloseWindow(bool* prevent_default) OVERRIDE;
virtual void OnWindowClosed() OVERRIDE;
virtual void OnWindowBlur() OVERRIDE;
virtual void OnRendererUnresponsive() OVERRIDE;
virtual void OnRendererResponsive() OVERRIDE;
virtual void OnRenderViewDeleted(int process_id, int routing_id) OVERRIDE;
virtual void OnRendererCrashed() OVERRIDE;
private:
static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
static void Destroy(const v8::FunctionCallbackInfo<v8::Value>& args);
// APIs for NativeWindow.
static void Close(const v8::FunctionCallbackInfo<v8::Value>& args);
static void Focus(const v8::FunctionCallbackInfo<v8::Value>& args);
static void IsFocused(const v8::FunctionCallbackInfo<v8::Value>& args);
static void Show(const v8::FunctionCallbackInfo<v8::Value>& args);
static void Hide(const v8::FunctionCallbackInfo<v8::Value>& args);
static void IsVisible(const v8::FunctionCallbackInfo<v8::Value>& args);
static void Maximize(const v8::FunctionCallbackInfo<v8::Value>& args);
static void Unmaximize(const v8::FunctionCallbackInfo<v8::Value>& args);
static void Minimize(const v8::FunctionCallbackInfo<v8::Value>& args);
static void Restore(const v8::FunctionCallbackInfo<v8::Value>& args);
static void SetFullscreen(const v8::FunctionCallbackInfo<v8::Value>& args);
static void IsFullscreen(const v8::FunctionCallbackInfo<v8::Value>& args);
static void SetSize(const v8::FunctionCallbackInfo<v8::Value>& args);
static void GetSize(const v8::FunctionCallbackInfo<v8::Value>& args);
static void SetMinimumSize(const v8::FunctionCallbackInfo<v8::Value>& args);
static void GetMinimumSize(const v8::FunctionCallbackInfo<v8::Value>& args);
static void SetMaximumSize(const v8::FunctionCallbackInfo<v8::Value>& args);
static void GetMaximumSize(const v8::FunctionCallbackInfo<v8::Value>& args);
static void SetResizable(const v8::FunctionCallbackInfo<v8::Value>& args);
static void IsResizable(const v8::FunctionCallbackInfo<v8::Value>& args);
static void SetAlwaysOnTop(const v8::FunctionCallbackInfo<v8::Value>& args);
static void IsAlwaysOnTop(const v8::FunctionCallbackInfo<v8::Value>& args);
static void Center(const v8::FunctionCallbackInfo<v8::Value>& args);
static void SetPosition(const v8::FunctionCallbackInfo<v8::Value>& args);
static void GetPosition(const v8::FunctionCallbackInfo<v8::Value>& args);
static void SetTitle(const v8::FunctionCallbackInfo<v8::Value>& args);
static void GetTitle(const v8::FunctionCallbackInfo<v8::Value>& args);
static void FlashFrame(const v8::FunctionCallbackInfo<v8::Value>& args);
static void SetKiosk(const v8::FunctionCallbackInfo<v8::Value>& args);
static void IsKiosk(const v8::FunctionCallbackInfo<v8::Value>& args);
static void OpenDevTools(const v8::FunctionCallbackInfo<v8::Value>& args);
static void CloseDevTools(const v8::FunctionCallbackInfo<v8::Value>& args);
static void IsDevToolsOpened(const v8::FunctionCallbackInfo<v8::Value>& args);
static void InspectElement(const v8::FunctionCallbackInfo<v8::Value>& args);
static void DebugDevTools(const v8::FunctionCallbackInfo<v8::Value>& args);
static void FocusOnWebView(const v8::FunctionCallbackInfo<v8::Value>& args);
static void BlurWebView(const v8::FunctionCallbackInfo<v8::Value>& args);
static void IsWebViewFocused(const v8::FunctionCallbackInfo<v8::Value>& args);
static void CapturePage(const v8::FunctionCallbackInfo<v8::Value>& args);
// APIs for WebContents.
static void GetPageTitle(const v8::FunctionCallbackInfo<v8::Value>& args);
static void IsLoading(const v8::FunctionCallbackInfo<v8::Value>& args);
static void IsWaitingForResponse(
const v8::FunctionCallbackInfo<v8::Value>& args);
static void Stop(const v8::FunctionCallbackInfo<v8::Value>& args);
static void GetRoutingID(const v8::FunctionCallbackInfo<v8::Value>& args);
static void GetProcessID(const v8::FunctionCallbackInfo<v8::Value>& args);
static void IsCrashed(const v8::FunctionCallbackInfo<v8::Value>& args);
// APIs for NavigationController.
static void LoadURL(const v8::FunctionCallbackInfo<v8::Value>& args);
static void GetURL(const v8::FunctionCallbackInfo<v8::Value>& args);
static void CanGoBack(const v8::FunctionCallbackInfo<v8::Value>& args);
static void CanGoForward(const v8::FunctionCallbackInfo<v8::Value>& args);
static void CanGoToOffset(const v8::FunctionCallbackInfo<v8::Value>& args);
static void GoBack(const v8::FunctionCallbackInfo<v8::Value>& args);
static void GoForward(const v8::FunctionCallbackInfo<v8::Value>& args);
static void GoToIndex(const v8::FunctionCallbackInfo<v8::Value>& args);
static void GoToOffset(const v8::FunctionCallbackInfo<v8::Value>& args);
static void Reload(const v8::FunctionCallbackInfo<v8::Value>& args);
static void ReloadIgnoringCache(
const v8::FunctionCallbackInfo<v8::Value>& args);
// Called when capturePage is done.
void OnCapturePageDone(const RefCountedV8Function& callback,
const std::vector<unsigned char>& data);
scoped_ptr<NativeWindow> window_;
DISALLOW_COPY_AND_ASSIGN(Window);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_WINDOW_H_

View file

@ -0,0 +1,94 @@
// 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.
#include "atom/browser/api/atom_browser_bindings.h"
#include <vector>
#include "base/logging.h"
#include "atom/browser/api/atom_api_event.h"
#include "atom/common/v8/native_type_conversions.h"
#include "content/public/browser/browser_thread.h"
#include "atom/common/v8/node_common.h"
namespace atom {
AtomBrowserBindings::AtomBrowserBindings() {
}
AtomBrowserBindings::~AtomBrowserBindings() {
}
void AtomBrowserBindings::OnRendererMessage(int process_id,
int routing_id,
const string16& channel,
const base::ListValue& args) {
v8::Locker locker(node_isolate);
v8::HandleScope handle_scope(node_isolate);
scoped_ptr<V8ValueConverter> converter(new V8ValueConverter);
// process.emit(channel, 'message', process_id, routing_id);
std::vector<v8::Handle<v8::Value>> arguments;
arguments.reserve(3 + args.GetSize());
arguments.push_back(ToV8Value(channel));
const base::Value* value;
if (args.Get(0, &value))
arguments.push_back(converter->ToV8Value(value, global_env->context()));
arguments.push_back(v8::Integer::New(process_id));
arguments.push_back(v8::Integer::New(routing_id));
for (size_t i = 1; i < args.GetSize(); i++) {
const base::Value* value;
if (args.Get(i, &value))
arguments.push_back(converter->ToV8Value(value, global_env->context()));
}
node::MakeCallback(global_env->process_object(),
"emit",
arguments.size(),
&arguments[0]);
}
void AtomBrowserBindings::OnRendererMessageSync(
int process_id,
int routing_id,
const string16& channel,
const base::ListValue& args,
NativeWindow* sender,
IPC::Message* message) {
v8::Locker locker(node_isolate);
v8::HandleScope handle_scope(node_isolate);
scoped_ptr<V8ValueConverter> converter(new V8ValueConverter);
// Create the event object.
v8::Handle<v8::Object> event = api::Event::CreateV8Object();
api::Event::Unwrap<api::Event>(event)->SetSenderAndMessage(sender, message);
// process.emit(channel, 'sync-message', event, process_id, routing_id);
std::vector<v8::Handle<v8::Value>> arguments;
arguments.reserve(3 + args.GetSize());
arguments.push_back(ToV8Value(channel));
const base::Value* value;
if (args.Get(0, &value))
arguments.push_back(converter->ToV8Value(value, global_env->context()));
arguments.push_back(event);
arguments.push_back(v8::Integer::New(process_id));
arguments.push_back(v8::Integer::New(routing_id));
for (size_t i = 1; i < args.GetSize(); i++) {
const base::Value* value;
if (args.Get(i, &value))
arguments.push_back(converter->ToV8Value(value, global_env->context()));
}
node::MakeCallback(global_env->process_object(),
"emit",
arguments.size(),
&arguments[0]);
}
} // namespace atom

View file

@ -0,0 +1,49 @@
// 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_BROWSER_API_ATOM_BROWSER_BINDINGS_
#define ATOM_BROWSER_API_ATOM_BROWSER_BINDINGS_
#include "base/strings/string16.h"
#include "atom/common/api/atom_bindings.h"
#include "atom/common/v8/scoped_persistent.h"
namespace base {
class ListValue;
}
namespace IPC {
class Message;
}
namespace atom {
class NativeWindow;
class AtomBrowserBindings : public AtomBindings {
public:
AtomBrowserBindings();
virtual ~AtomBrowserBindings();
// Called when received a message from renderer.
void OnRendererMessage(int process_id,
int routing_id,
const string16& channel,
const base::ListValue& args);
// Called when received a synchronous message from renderer.
void OnRendererMessageSync(int process_id,
int routing_id,
const string16& channel,
const base::ListValue& args,
NativeWindow* sender,
IPC::Message* message);
private:
DISALLOW_COPY_AND_ASSIGN(AtomBrowserBindings);
};
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_BINDINGS_

View file

@ -0,0 +1,34 @@
EventEmitter = require('events').EventEmitter
bindings = process.atomBinding 'app'
Application = bindings.Application
Application::__proto__ = EventEmitter.prototype
app = new Application
app.getHomeDir = ->
process.env[if process.platform is 'win32' then 'USERPROFILE' else 'HOME']
app.setApplicationMenu = (menu) ->
require('menu').setApplicationMenu menu
app.getApplicationMenu = ->
require('menu').getApplicationMenu()
app.commandLine =
appendSwitch: bindings.appendSwitch,
appendArgument: bindings.appendArgument
if process.platform is 'darwin'
app.dock =
bounce: (type='informational') -> bindings.dockBounce type
cancelBounce: bindings.dockCancelBounce
setBadge: bindings.dockSetBadgeText
getBadge: bindings.dockGetBadgeText
# Support old event name.
app.once 'ready', -> app.emit 'finish-launching'
# Only one App object pemitted.
module.exports = app

View file

@ -0,0 +1,6 @@
module.exports =
browserMainParts:
preMainMessageLoopRun: ->
setImmediate ->
module.exports.browserMainParts.preMainMessageLoopRun()

View file

@ -0,0 +1,25 @@
AutoUpdater = process.atomBinding('auto_updater').AutoUpdater
EventEmitter = require('events').EventEmitter
AutoUpdater::__proto__ = EventEmitter.prototype
autoUpdater = new AutoUpdater
autoUpdater.on 'update-downloaded-raw', (args...) ->
args[3] = new Date(args[3]) # releaseDate
@emit 'update-downloaded', args..., => @quitAndInstall()
autoUpdater.quitAndInstall = ->
# If we don't have any window then quitAndInstall immediately.
BrowserWindow = require 'browser-window'
windows = BrowserWindow.getAllWindows()
if windows.length is 0
AutoUpdater::quitAndInstall.call this
return
# Do the restart after all windows have been closed.
app = require 'app'
app.removeAllListeners 'window-all-closed'
app.once 'window-all-closed', AutoUpdater::quitAndInstall.bind(this)
win.close() for win in windows
module.exports = autoUpdater

View file

@ -0,0 +1,58 @@
EventEmitter = require('events').EventEmitter
IDWeakMap = require 'id-weak-map'
app = require 'app'
BrowserWindow = process.atomBinding('window').BrowserWindow
BrowserWindow::__proto__ = EventEmitter.prototype
# Store all created windows in the weak map.
BrowserWindow.windows = new IDWeakMap
BrowserWindow::_init = ->
# Simulate the application menu on platforms other than OS X.
if process.platform isnt 'darwin'
menu = app.getApplicationMenu()
@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
# release all objects owned by it.
@on 'render-view-deleted', (event, processId, routingId) ->
process.emit 'ATOM_BROWSER_RELEASE_RENDER_VIEW', processId, routingId
BrowserWindow::toggleDevTools = ->
if @isDevToolsOpened() then @closeDevTools() else @openDevTools()
BrowserWindow::restart = ->
@loadUrl(@getUrl())
BrowserWindow::setMenu = (menu) ->
if process.platform is 'darwin'
throw new Error('BrowserWindow.setMenu is not available on OS X')
throw new TypeError('Invalid menu') unless menu?.constructor?.name is 'Menu'
@menu = menu # Keep a reference of menu in case of GC.
@menu.attachToWindow this
BrowserWindow.getAllWindows = ->
windows = BrowserWindow.windows
windows.get key for key in windows.keys()
BrowserWindow.getFocusedWindow = ->
windows = BrowserWindow.getAllWindows()
return window for window in windows when window.isFocused()
BrowserWindow.fromProcessIdAndRoutingId = (processId, routingId) ->
windows = BrowserWindow.getAllWindows()
return window for window in windows when window.getProcessId() == processId and
window.getRoutingId() == routingId
module.exports = BrowserWindow

View file

@ -0,0 +1,78 @@
binding = process.atomBinding 'dialog'
v8Util = process.atomBinding 'v8_util'
BrowserWindow = require 'browser-window'
fileDialogProperties =
openFile: 1, openDirectory: 2, multiSelections: 4, createDirectory: 8
messageBoxTypes = ['none', 'info', 'warning']
module.exports =
showOpenDialog: (window, options, callback) ->
unless window?.constructor is BrowserWindow
# Shift.
callback = options
options = window
window = null
options ?= title: 'Open', properties: ['openFile']
options.properties ?= ['openFile']
throw new TypeError('Properties need to be array') unless Array.isArray options.properties
properties = 0
for prop, value of fileDialogProperties
properties |= value if prop in options.properties
options.title ?= ''
options.defaultPath ?= ''
binding.showOpenDialog String(options.title),
String(options.defaultPath),
properties,
window,
callback
showSaveDialog: (window, options, callback) ->
unless window?.constructor is BrowserWindow
# Shift.
callback = options
options = window
window = null
options ?= title: 'Save'
options.title ?= ''
options.defaultPath ?= ''
binding.showSaveDialog String(options.title),
String(options.defaultPath),
window,
callback
showMessageBox: (window, options, callback) ->
unless window?.constructor is BrowserWindow
# Shift.
callback = options
options = window
window = null
options ?= type: 'none'
options.type ?= 'none'
options.type = messageBoxTypes.indexOf options.type
throw new TypeError('Invalid message box type') unless options.type > -1
throw new TypeError('Buttons need to be array') unless Array.isArray options.buttons
options.title ?= ''
options.message ?= ''
options.detail ?= ''
binding.showMessageBox options.type,
options.buttons,
String(options.title),
String(options.message),
String(options.detail),
window,
callback
# Mark standard asynchronous functions.
v8Util.setHiddenValue f, 'asynchronous', true for k, f of module.exports

View file

@ -0,0 +1,32 @@
EventEmitter = require('events').EventEmitter
send = process.atomBinding('ipc').send
sendWrap = (channel, processId, routingId, args...) ->
BrowserWindow = require 'browser-window'
if processId?.constructor is BrowserWindow
window = processId
args = [routingId, args...]
processId = window.getProcessId()
routingId = window.getRoutingId()
send channel, processId, routingId, [args...]
class Ipc extends EventEmitter
constructor: ->
process.on 'ATOM_INTERNAL_MESSAGE', (args...) =>
@emit(args...)
process.on 'ATOM_INTERNAL_MESSAGE_SYNC', (channel, event, args...) =>
set = (value) -> event.sendReply JSON.stringify(value)
Object.defineProperty event, 'returnValue', {set}
Object.defineProperty event, 'result', {set}
@emit(channel, event, args...)
send: (processId, routingId, args...) ->
@sendChannel(processId, routingId, 'message', args...)
sendChannel: (args...) ->
sendWrap('ATOM_INTERNAL_MESSAGE', args...)
module.exports = new Ipc

View file

@ -0,0 +1,35 @@
BrowserWindow = require 'browser-window'
nextCommandId = 0
class MenuItem
@types = ['normal', 'separator', 'submenu', 'checkbox', 'radio']
constructor: (options) ->
Menu = require 'menu'
{click, @selector, @type, @label, @sublabel, @accelerator, @enabled, @visible, @checked, @groupId, @submenu} = options
@type = 'submenu' if not @type? and @submenu?
throw new Error('Invalid submenu') if @type is 'submenu' and @submenu?.constructor isnt Menu
@type = @type ? 'normal'
@label = @label ? ''
@sublabel = @sublabel ? ''
@accelerator = @accelerator ? null
@enabled = @enabled ? true
@visible = @visible ? true
@checked = @checked ? false
@groupId = @groupId ? null
@submenu = @submenu ? null
throw new Error('Unknown menu type') if MenuItem.types.indexOf(@type) is -1
@commandId = ++nextCommandId
@click = =>
if typeof click is 'function'
click this, BrowserWindow.getFocusedWindow()
else if typeof @selector is 'string'
Menu.sendActionToFirstResponder @selector
module.exports = MenuItem

View file

@ -0,0 +1,75 @@
BrowserWindow = require 'browser-window'
EventEmitter = require('events').EventEmitter
MenuItem = require 'menu-item'
bindings = process.atomBinding 'menu'
Menu = bindings.Menu
Menu::__proto__ = EventEmitter.prototype
popup = Menu::popup
Menu::popup = (window) ->
throw new TypeError('Invalid window') unless window?.constructor is BrowserWindow
popup.call this, window
Menu::append = (item) ->
@insert @getItemCount(), item
Menu::insert = (pos, item) ->
throw new TypeError('Invalid item') unless item?.constructor is MenuItem
switch item.type
when 'normal' then @insertItem pos, item.commandId, item.label
when 'checkbox' then @insertCheckItem pos, item.commandId, item.label
when 'radio' then @insertRadioItem pos, item.commandId, item.label, item.groupId
when 'separator' then @insertSeparator pos
when 'submenu' then @insertSubMenu pos, item.commandId, item.label, item.submenu
@setSublabel pos, item.sublabel if item.sublabel?
unless @delegate?
@commandsMap = {}
@items = []
@delegate =
isCommandIdChecked: (commandId) => @commandsMap[commandId]?.checked
isCommandIdEnabled: (commandId) => @commandsMap[commandId]?.enabled
isCommandIdVisible: (commandId) => @commandsMap[commandId]?.visible
getAcceleratorForCommandId: (commandId) => @commandsMap[commandId]?.accelerator
executeCommand: (commandId) =>
activeItem = @commandsMap[commandId]
activeItem.click() if activeItem?
@items.splice pos, 0, item
@commandsMap[item.commandId] = item
applicationMenu = null
Menu.setApplicationMenu = (menu) ->
throw new TypeError('Invalid menu') unless menu?.constructor is Menu
applicationMenu = menu # Keep a reference.
if process.platform is 'darwin'
bindings.setApplicationMenu menu
else
windows = BrowserWindow.getAllWindows()
w.setMenu menu for w in windows
Menu.getApplicationMenu = -> applicationMenu
Menu.sendActionToFirstResponder = bindings.sendActionToFirstResponder
Menu.buildFromTemplate = (template) ->
throw new TypeError('Invalid template for Menu') unless Array.isArray template
menu = new Menu
for item in template
throw new TypeError('Invalid template for MenuItem') unless typeof item is 'object'
item.submenu = Menu.buildFromTemplate item.submenu if item.submenu?
menuItem = new MenuItem(item)
menuItem[key] = value for key, value of item when not menuItem[key]?
menu.append menuItem
menu
module.exports = Menu

View file

@ -0,0 +1,7 @@
bindings = process.atomBinding 'power_monitor'
EventEmitter = require('events').EventEmitter
PowerMonitor = bindings.PowerMonitor
PowerMonitor::__proto__ = EventEmitter.prototype
module.exports = new PowerMonitor

View file

@ -0,0 +1,20 @@
protocol = process.atomBinding 'protocol'
EventEmitter = require('events').EventEmitter
protocol[key] = value for key, value of EventEmitter.prototype
protocol.RequestStringJob =
class RequestStringJob
constructor: ({mimeType, charset, data}) ->
if typeof data isnt 'string' and not data instanceof Buffer
throw new TypeError('Data should be string or Buffer')
@mimeType = mimeType ? 'text/plain'
@charset = charset ? 'UTF-8'
@data = String data
protocol.RequestFileJob =
class RequestFileJob
constructor: (@path) ->
module.exports = protocol