Merge remote-tracking branch 'atom/master'

This commit is contained in:
Plusb Preco 2015-09-11 11:56:11 +09:00
commit c6395c2197
98 changed files with 953 additions and 452 deletions

View file

@ -29,6 +29,7 @@ possible with your report. If you can, please include:
* Include screenshots and animated GIFs in your pull request whenever possible.
* Follow the CoffeeScript, JavaScript, C++ and Python [coding style defined in docs](/docs/development/coding-style.md).
* Write documentation in [Markdown](https://daringfireball.net/projects/markdown).
See the [Documentation Styleguide](/docs/styleguide.md).
* Use short, present tense commit messages. See [Commit Message Styleguide](#git-commit-messages-styleguide).
## Styleguides

View file

@ -4,7 +4,7 @@
[![devDependency Status](https://david-dm.org/atom/electron/dev-status.svg)](https://david-dm.org/atom/electron#info=devDependencies)
[![Join the Electron Community on Slack](http://atom-slack.herokuapp.com/badge.svg)](http://atom-slack.herokuapp.com/)
:zap: *formerly known as Atom Shell* :zap:
:zap: *Formerly known as Atom Shell* :zap:
The Electron framework lets you write cross-platform desktop applications
using JavaScript, HTML and CSS. It is based on [io.js](http://iojs.org) and
@ -15,7 +15,8 @@ Follow [@ElectronJS](https://twitter.com/electronjs) on Twitter for important
announcements.
This project adheres to the [Contributor Covenant 1.2](http://contributor-covenant.org/version/1/2/0).
By participating, you are expected to uphold this code. Please report unacceptable behavior to atom@github.com.
By participating, you are expected to uphold this code. Please report
unacceptable behavior to atom@github.com.
## Downloads
@ -54,7 +55,12 @@ contains documents describing how to build and contribute to Electron.
## Community
There is an [`electron` category on the Atom forums](http://discuss.atom.io/category/electron)
as well as an `#atom-shell` channel on Freenode.
You can ask questions and interact with the community in the following
locations:
- [`electron`](http://discuss.atom.io/category/electron) category on the Atom
forums
- `#atom-shell` channel on Freenode
- [`Atom`](http://atom-slack.herokuapp.com/) channel on Slack
Check out [awesome-electron](https://github.com/sindresorhus/awesome-electron) for a community maintained list of useful example apps, tools and resources.
Check out [awesome-electron](https://github.com/sindresorhus/awesome-electron)
for a community maintained list of useful example apps, tools and resources.

View file

@ -4,7 +4,7 @@
'product_name%': 'Electron',
'company_name%': 'GitHub, Inc',
'company_abbr%': 'github',
'version%': '0.31.2',
'version%': '0.32.2',
},
'includes': [
'filenames.gypi',

View file

@ -38,7 +38,9 @@ bool AtomMainDelegate::BasicStartupComplete(int* exit_code) {
#else
settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
#endif // defined(DEBUG)
#endif // defined(OS_WIN)
#else // defined(OS_WIN)
settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
#endif // !defined(OS_WIN)
logging::InitLogging(settings);
// Logging with pid and timestamp.

View file

@ -19,6 +19,7 @@
#include "atom/browser/api/atom_api_web_contents.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
#include "atom/common/node_includes.h"
#include "base/command_line.h"
#include "base/environment.h"
#include "base/files/file_path.h"
@ -34,8 +35,6 @@
#include "base/strings/utf_string_conversions.h"
#endif
#include "atom/common/node_includes.h"
using atom::Browser;
namespace mate {

View file

@ -7,11 +7,10 @@
#include "base/time/time.h"
#include "atom/browser/auto_updater.h"
#include "atom/browser/browser.h"
#include "atom/common/node_includes.h"
#include "native_mate/dictionary.h"
#include "native_mate/object_template_builder.h"
#include "atom/common/node_includes.h"
namespace atom {
namespace api {

View file

@ -7,13 +7,12 @@
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
#include "atom/common/node_includes.h"
#include "base/bind.h"
#include "base/files/file_util.h"
#include "content/public/browser/tracing_controller.h"
#include "native_mate/dictionary.h"
#include "atom/common/node_includes.h"
using content::TracingController;
namespace mate {

View file

@ -20,8 +20,6 @@
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
#include "atom/common/node_includes.h"
using atom::api::Cookies;
using content::BrowserThread;

View file

@ -78,7 +78,7 @@ class Cookies : public mate::Wrappable {
// Must be called on IO thread.
net::CookieStore* GetCookieStore();
scoped_refptr<net::URLRequestContextGetter> request_context_getter_;
net::URLRequestContextGetter* request_context_getter_;
DISALLOW_COPY_AND_ASSIGN(Cookies);
};

View file

@ -5,12 +5,11 @@
#include "atom/browser/api/atom_api_power_monitor.h"
#include "atom/browser/browser.h"
#include "atom/common/node_includes.h"
#include "base/power_monitor/power_monitor.h"
#include "base/power_monitor/power_monitor_device_source.h"
#include "native_mate/dictionary.h"
#include "atom/common/node_includes.h"
namespace atom {
namespace api {
@ -41,9 +40,9 @@ void PowerMonitor::OnResume() {
// static
v8::Local<v8::Value> PowerMonitor::Create(v8::Isolate* isolate) {
if (!Browser::Get()->is_ready()) {
node::ThrowError(
isolate->ThrowException(v8::Exception::Error(mate::StringToV8(
isolate,
"Cannot initialize \"power-monitor\" module before app is ready");
"Cannot initialize \"power-monitor\" module before app is ready")));
return v8::Null(isolate);
}

View file

@ -6,9 +6,9 @@
#include <string>
#include "atom/common/node_includes.h"
#include "content/public/browser/power_save_blocker.h"
#include "native_mate/dictionary.h"
#include "atom/common/node_includes.h"
namespace mate {

View file

@ -12,9 +12,8 @@
#include "atom/browser/net/url_request_fetch_job.h"
#include "atom/browser/net/url_request_string_job.h"
#include "atom/common/native_mate_converters/callback.h"
#include "native_mate/dictionary.h"
#include "atom/common/node_includes.h"
#include "native_mate/dictionary.h"
using content::BrowserThread;

View file

@ -66,7 +66,7 @@ class Protocol : public mate::Wrappable {
public:
CustomProtocolHandler(
v8::Isolate* isolate,
scoped_refptr<net::URLRequestContextGetter> request_context,
net::URLRequestContextGetter* request_context,
const Handler& handler)
: isolate_(isolate),
request_context_(request_context),
@ -83,7 +83,7 @@ class Protocol : public mate::Wrappable {
private:
v8::Isolate* isolate_;
scoped_refptr<net::URLRequestContextGetter> request_context_;
net::URLRequestContextGetter* request_context_;
Protocol::Handler handler_;
DISALLOW_COPY_AND_ASSIGN(CustomProtocolHandler);
@ -172,7 +172,7 @@ class Protocol : public mate::Wrappable {
// Convert error code to string.
std::string ErrorCodeToString(ProtocolError error);
scoped_refptr<net::URLRequestContextGetter> request_context_getter_;
net::URLRequestContextGetter* request_context_getter_;
// Map that stores the original protocols of schemes.
using OriginalProtocolsMap = base::ScopedPtrHashMap<

View file

@ -113,14 +113,16 @@ mate::ObjectTemplateBuilder Screen::GetObjectTemplateBuilder(
// static
v8::Local<v8::Value> Screen::Create(v8::Isolate* isolate) {
if (!Browser::Get()->is_ready()) {
node::ThrowError(isolate,
"Cannot initialize \"screen\" module before app is ready");
isolate->ThrowException(v8::Exception::Error(mate::StringToV8(
isolate,
"Cannot initialize \"screen\" module before app is ready")));
return v8::Null(isolate);
}
gfx::Screen* screen = gfx::Screen::GetNativeScreen();
if (!screen) {
node::ThrowError(isolate, "Failed to get screen information");
isolate->ThrowException(v8::Exception::Error(mate::StringToV8(
isolate, "Failed to get screen information")));
return v8::Null(isolate);
}

View file

@ -13,6 +13,7 @@
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/gurl_converter.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
#include "atom/common/node_includes.h"
#include "base/files/file_path.h"
#include "base/prefs/pref_service.h"
#include "base/strings/string_util.h"
@ -29,8 +30,6 @@
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
#include "atom/common/node_includes.h"
using content::BrowserThread;
using content::StoragePartition;

View file

@ -12,13 +12,12 @@
#include "atom/common/native_mate_converters/gfx_converter.h"
#include "atom/common/native_mate_converters/image_converter.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/node_includes.h"
#include "native_mate/constructor.h"
#include "native_mate/dictionary.h"
#include "ui/events/event_constants.h"
#include "ui/gfx/image/image.h"
#include "atom/common/node_includes.h"
namespace atom {
namespace api {
@ -35,7 +34,8 @@ Tray::~Tray() {
// static
mate::Wrappable* Tray::New(v8::Isolate* isolate, const gfx::Image& image) {
if (!Browser::Get()->is_ready()) {
node::ThrowError(isolate, "Cannot create Tray before app is ready");
isolate->ThrowException(v8::Exception::Error(mate::StringToV8(
isolate, "Cannot create Tray before app is ready")));
return nullptr;
}
return new Tray(image);

View file

@ -388,7 +388,7 @@ void WebContents::DidFailProvisionalLoad(
int error_code,
const base::string16& error_description,
bool was_ignored_by_handler) {
Emit("did-fail-load", error_code, error_description);
Emit("did-fail-load", error_code, error_description, validated_url);
}
void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host,
@ -396,7 +396,7 @@ void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host,
int error_code,
const base::string16& error_description,
bool was_ignored_by_handler) {
Emit("did-fail-load", error_code, error_description);
Emit("did-fail-load", error_code, error_description, validated_url);
}
void WebContents::DidStartLoading() {
@ -717,17 +717,19 @@ void WebContents::PrintToPDF(const base::DictionaryValue& setting,
PrintToPDF(setting, callback);
}
void WebContents::AddWorkSpace(const base::FilePath& path) {
void WebContents::AddWorkSpace(mate::Arguments* args,
const base::FilePath& path) {
if (path.empty()) {
node::ThrowError(isolate(), "path cannot be empty");
args->ThrowError("path cannot be empty");
return;
}
DevToolsAddFileSystem(path);
}
void WebContents::RemoveWorkSpace(const base::FilePath& path) {
void WebContents::RemoveWorkSpace(mate::Arguments* args,
const base::FilePath& path) {
if (path.empty()) {
node::ThrowError(isolate(), "path cannot be empty");
args->ThrowError("path cannot be empty");
return;
}
DevToolsRemoveFileSystem(path);

View file

@ -87,8 +87,8 @@ class WebContents : public mate::TrackableObject<WebContents>,
const PrintToPDFCallback& callback);
// DevTools workspace api.
void AddWorkSpace(const base::FilePath& path);
void RemoveWorkSpace(const base::FilePath& path);
void AddWorkSpace(mate::Arguments* args, const base::FilePath& path);
void RemoveWorkSpace(mate::Arguments* args, const base::FilePath& path);
// Editing commands.
void Undo();

View file

@ -10,6 +10,8 @@
#include "content/public/browser/browser_context.h"
#include "native_mate/dictionary.h"
using atom::WebContentsPreferences;
namespace mate {
template<>
@ -48,7 +50,7 @@ void AddGuest(int guest_instance_id,
manager->AddGuest(guest_instance_id, element_instance_id, embedder,
guest_web_contents);
atom::WebContentsPreferences::From(guest_web_contents)->Merge(options);
WebContentsPreferences::FromWebContents(guest_web_contents)->Merge(options);
}
void RemoveGuest(content::WebContents* embedder, int guest_instance_id) {

View file

@ -70,14 +70,13 @@ Window::Window(v8::Isolate* isolate, const mate::Dictionary& options) {
options.Get(switches::kWebPreferences, &web_preferences);
// Be compatible with old options which are now in web_preferences.
std::string str;
double d;
if (options.Get(switches::kNodeIntegration, &str))
web_preferences.Set(switches::kNodeIntegration, str);
if (options.Get(switches::kPreloadScript, &str))
web_preferences.Set(switches::kPreloadScript, str);
if (options.Get(switches::kZoomFactor, &d))
web_preferences.Set(switches::kZoomFactor, d);
v8::Local<v8::Value> value;
if (options.Get(switches::kNodeIntegration, &value))
web_preferences.Set(switches::kNodeIntegration, value);
if (options.Get(switches::kPreloadScript, &value))
web_preferences.Set(switches::kPreloadScript, value);
if (options.Get(switches::kZoomFactor, &value))
web_preferences.Set(switches::kZoomFactor, value);
// Creates the WebContents used by BrowserWindow.
auto web_contents = WebContents::Create(isolate, web_preferences);
@ -209,8 +208,8 @@ void Window::OnExecuteWindowsCommand(const std::string& command_name) {
mate::Wrappable* Window::New(v8::Isolate* isolate,
const mate::Dictionary& options) {
if (!Browser::Get()->is_ready()) {
node::ThrowError(isolate,
"Cannot create BrowserWindow before app is ready");
isolate->ThrowException(v8::Exception::Error(mate::StringToV8(
isolate, "Cannot create BrowserWindow before app is ready")));
return nullptr;
}
return new Window(isolate, options);

View file

@ -13,6 +13,7 @@
#include "atom/browser/node_debugger.h"
#include "atom/common/api/atom_bindings.h"
#include "atom/common/node_bindings.h"
#include "atom/common/node_includes.h"
#include "base/command_line.h"
#include "base/thread_task_runner_handle.h"
#include "chrome/browser/browser_process.h"
@ -22,8 +23,6 @@
#include "chrome/browser/ui/libgtk2ui/gtk2_util.h"
#endif
#include "atom/common/node_includes.h"
namespace atom {
// static
@ -40,8 +39,6 @@ AtomBrowserMainParts::AtomBrowserMainParts()
}
AtomBrowserMainParts::~AtomBrowserMainParts() {
for (const auto& callback : destruction_callbacks_)
callback.Run();
}
// static
@ -119,4 +116,14 @@ void AtomBrowserMainParts::PreMainMessageLoopRun() {
#endif
}
void AtomBrowserMainParts::PostMainMessageLoopRun() {
brightray::BrowserMainParts::PostMainMessageLoopRun();
// Make sure destruction callbacks are called before message loop is
// destroyed, otherwise some objects that need to be deleted on IO thread
// won't be freed.
for (const auto& callback : destruction_callbacks_)
callback.Run();
}
} // namespace atom

View file

@ -41,6 +41,7 @@ class AtomBrowserMainParts : public brightray::BrowserMainParts {
// content::BrowserMainParts:
void PostEarlyInitialization() override;
void PreMainMessageLoopRun() override;
void PostMainMessageLoopRun() override;
#if defined(OS_MACOSX)
void PreMainMessageLoopStart() override;
void PostDestroyThreads() override;

View file

@ -46,7 +46,7 @@ class JsAsker : public RequestJob {
// Called by |CustomProtocolHandler| to store handler related information.
void SetHandlerInfo(
v8::Isolate* isolate,
scoped_refptr<net::URLRequestContextGetter> request_context_getter,
net::URLRequestContextGetter* request_context_getter,
const JavaScriptHandler& handler) {
isolate_ = isolate;
request_context_getter_ = request_context_getter;
@ -57,7 +57,7 @@ class JsAsker : public RequestJob {
virtual void StartAsync(scoped_ptr<base::Value> options) = 0;
net::URLRequestContextGetter* request_context_getter() const {
return request_context_getter_.get();
return request_context_getter_;
}
private:
@ -89,7 +89,7 @@ class JsAsker : public RequestJob {
}
v8::Isolate* isolate_;
scoped_refptr<net::URLRequestContextGetter> request_context_getter_;
net::URLRequestContextGetter* request_context_getter_;
JavaScriptHandler handler_;
base::WeakPtrFactory<JsAsker> weak_factory_;

View file

@ -17,7 +17,7 @@
<key>CFBundleIconFile</key>
<string>atom.icns</string>
<key>CFBundleVersion</key>
<string>0.31.2</string>
<string>0.32.2</string>
<key>LSMinimumSystemVersion</key>
<string>10.8.0</string>
<key>NSMainNibFile</key>

View file

@ -56,8 +56,8 @@ END
//
VS_VERSION_INFO VERSIONINFO
FILEVERSION 0,31,2,0
PRODUCTVERSION 0,31,2,0
FILEVERSION 0,32,2,0
PRODUCTVERSION 0,32,2,0
FILEFLAGSMASK 0x3fL
#ifdef _DEBUG
FILEFLAGS 0x1L
@ -74,12 +74,12 @@ BEGIN
BEGIN
VALUE "CompanyName", "GitHub, Inc."
VALUE "FileDescription", "Electron"
VALUE "FileVersion", "0.31.2"
VALUE "FileVersion", "0.32.2"
VALUE "InternalName", "electron.exe"
VALUE "LegalCopyright", "Copyright (C) 2015 GitHub, Inc. All rights reserved."
VALUE "OriginalFilename", "electron.exe"
VALUE "ProductName", "Electron"
VALUE "ProductVersion", "0.31.2"
VALUE "ProductVersion", "0.32.2"
VALUE "SquirrelAwareVersion", "1"
END
END

View file

@ -16,13 +16,12 @@
#include "ui/gfx/switches.h"
#endif
DEFINE_WEB_CONTENTS_USER_DATA_KEY(atom::WebContentsPreferences);
namespace atom {
namespace {
// Pointer as WebContents's user data key.
const char* kWebPreferencesKey = "WebContentsPreferences";
// Array of available web runtime features.
const char* kWebRuntimeFeatures[] = {
switches::kExperimentalFeatures,
@ -40,7 +39,7 @@ WebContentsPreferences::WebContentsPreferences(
content::WebContents* web_contents,
base::DictionaryValue* web_preferences) {
web_preferences_.Swap(web_preferences);
web_contents->SetUserData(kWebPreferencesKey, this);
web_contents->SetUserData(UserDataKey(), this);
}
WebContentsPreferences::~WebContentsPreferences() {
@ -50,17 +49,10 @@ void WebContentsPreferences::Merge(const base::DictionaryValue& extend) {
web_preferences_.MergeDictionary(&extend);
}
// static
WebContentsPreferences* WebContentsPreferences::From(
content::WebContents* web_contents) {
return static_cast<WebContentsPreferences*>(
web_contents->GetUserData(kWebPreferencesKey));
}
// static
void WebContentsPreferences::AppendExtraCommandLineSwitches(
content::WebContents* web_contents, base::CommandLine* command_line) {
WebContentsPreferences* self = From(web_contents);
WebContentsPreferences* self = FromWebContents(web_contents);
if (!self)
return;
@ -130,7 +122,7 @@ void WebContentsPreferences::AppendExtraCommandLineSwitches(
// static
void WebContentsPreferences::OverrideWebkitPrefs(
content::WebContents* web_contents, content::WebPreferences* prefs) {
WebContentsPreferences* self = From(web_contents);
WebContentsPreferences* self = FromWebContents(web_contents);
if (!self)
return;

View file

@ -22,9 +22,6 @@ namespace atom {
class WebContentsPreferences
: public content::WebContentsUserData<WebContentsPreferences> {
public:
// Get the preferences of |web_contents|.
static WebContentsPreferences* From(content::WebContents* web_contents);
// Append command paramters according to |web_contents|'s preferences.
static void AppendExtraCommandLineSwitches(
content::WebContents* web_contents, base::CommandLine* command_line);

View file

@ -1,24 +0,0 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/web_view_constants.h"
namespace atom {
namespace web_view {
const char kPreloadUrl[] = "preloadUrl";
const char kNodeIntegration[] = "nodeIntegration";
const char kPlugins[] = "plugins";
const char kDisableWebSecurity[] = "disableWebSecurity";
const char kPartitionId[] = "partitionId";
const int kDefaultWidth = 300;
const int kDefaultHeight = 300;
const char kWebViewInfoKeyName[] = "web_view_info";
} // namespace web_view
} // namespace atom

View file

@ -1,27 +0,0 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_BROWSER_WEB_VIEW_CONSTANTS_H_
#define ATOM_BROWSER_WEB_VIEW_CONSTANTS_H_
namespace atom {
namespace web_view {
extern const char kPreloadUrl[];
extern const char kNodeIntegration[];
extern const char kPlugins[];
extern const char kDisableWebSecurity[];
extern const char kPartitionId[];
extern const int kDefaultWidth;
extern const int kDefaultHeight;
extern const char kWebViewInfoKeyName[];
} // namespace web_view
} // namespace atom
#endif // ATOM_BROWSER_WEB_VIEW_CONSTANTS_H_

View file

@ -5,7 +5,6 @@
#include "atom/browser/web_view_guest_delegate.h"
#include "atom/browser/api/atom_api_web_contents.h"
#include "atom/browser/web_view_constants.h"
#include "atom/common/native_mate_converters/gurl_converter.h"
#include "content/public/browser/guest_host.h"
#include "content/public/browser/render_frame_host.h"
@ -14,6 +13,13 @@
namespace atom {
namespace {
const int kDefaultWidth = 300;
const int kDefaultHeight = 300;
} // namespace
WebViewGuestDelegate::WebViewGuestDelegate()
: guest_opaque_(true),
guest_host_(nullptr),
@ -172,7 +178,7 @@ gfx::Size WebViewGuestDelegate::GetDefaultSize() const {
return embedder_web_contents_->GetRenderWidgetHostView()
->GetVisibleViewportSize();
} else {
return gfx::Size(web_view::kDefaultWidth, web_view::kDefaultHeight);
return gfx::Size(kDefaultWidth, kDefaultHeight);
}
}

View file

@ -10,13 +10,12 @@
#include "atom/common/asar/archive.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
#include "atom/common/node_includes.h"
#include "native_mate/arguments.h"
#include "native_mate/dictionary.h"
#include "native_mate/object_template_builder.h"
#include "native_mate/wrappable.h"
#include "atom/common/node_includes.h"
namespace {
class Archive : public mate::Wrappable {

View file

@ -7,9 +7,8 @@
#include "atom/common/platform_util.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
#include "atom/common/native_mate_converters/gurl_converter.h"
#include "native_mate/dictionary.h"
#include "atom/common/node_includes.h"
#include "native_mate/dictionary.h"
namespace {

View file

@ -3,11 +3,10 @@
// found in the LICENSE file.
#include "atom/common/api/object_life_monitor.h"
#include "atom/common/node_includes.h"
#include "native_mate/dictionary.h"
#include "v8/include/v8-profiler.h"
#include "atom/common/node_includes.h"
namespace {
v8::Local<v8::Object> CreateObjectWithName(v8::Isolate* isolate,

View file

@ -5,11 +5,10 @@
#include "atom/common/api/event_emitter_caller.h"
#include "atom/common/api/locker.h"
#include "atom/common/node_includes.h"
#include "base/memory/scoped_ptr.h"
#include "third_party/WebKit/public/web/WebScopedMicrotaskSuppression.h"
#include "atom/common/node_includes.h"
namespace mate {
namespace internal {

View file

@ -6,7 +6,7 @@
#define ATOM_VERSION_H
#define ATOM_MAJOR_VERSION 0
#define ATOM_MINOR_VERSION 31
#define ATOM_MINOR_VERSION 32
#define ATOM_PATCH_VERSION 2
#define ATOM_VERSION_IS_RELEASE 1

View file

@ -11,6 +11,7 @@
#include "atom/common/api/locker.h"
#include "atom/common/atom_command_line.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
#include "atom/common/node_includes.h"
#include "base/command_line.h"
#include "base/base_paths.h"
#include "base/files/file_path.h"
@ -21,8 +22,6 @@
#include "native_mate/dictionary.h"
#include "third_party/WebKit/public/web/WebScopedMicrotaskSuppression.h"
#include "atom/common/node_includes.h"
using content::BrowserThread;
// Force all builtin modules to be referenced so they can actually run their

View file

@ -5,6 +5,8 @@
#ifndef ATOM_COMMON_NODE_INCLUDES_H_
#define ATOM_COMMON_NODE_INCLUDES_H_
#include "base/logging.h"
// Include common headers for using node APIs.
#define BUILDING_NODE_EXTENSION

View file

@ -5,13 +5,12 @@
#include "atom/common/api/api_messages.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/node_includes.h"
#include "content/public/renderer/render_view.h"
#include "native_mate/dictionary.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#include "third_party/WebKit/public/web/WebView.h"
#include "atom/common/node_includes.h"
using content::RenderView;
using blink::WebLocalFrame;
using blink::WebView;
@ -30,7 +29,7 @@ RenderView* GetCurrentRenderView() {
return RenderView::FromWebView(view);
}
void Send(v8::Isolate* isolate,
void Send(mate::Arguments* args,
const base::string16& channel,
const base::ListValue& arguments) {
RenderView* render_view = GetCurrentRenderView();
@ -41,10 +40,10 @@ void Send(v8::Isolate* isolate,
render_view->GetRoutingID(), channel, arguments));
if (!success)
node::ThrowError(isolate, "Unable to send AtomViewHostMsg_Message");
args->ThrowError("Unable to send AtomViewHostMsg_Message");
}
base::string16 SendSync(v8::Isolate* isolate,
base::string16 SendSync(mate::Arguments* args,
const base::string16& channel,
const base::ListValue& arguments) {
base::string16 json;
@ -60,7 +59,7 @@ base::string16 SendSync(v8::Isolate* isolate,
bool success = render_view->Send(message);
if (!success)
node::ThrowError(isolate, "Unable to send AtomViewHostMsg_Message_Sync");
args->ThrowError("Unable to send AtomViewHostMsg_Message_Sync");
return json;
}

View file

@ -13,6 +13,7 @@
#include "atom/common/api/api_messages.h"
#include "atom/common/api/event_emitter_caller.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/node_includes.h"
#include "atom/common/options_switches.h"
#include "atom/renderer/atom_renderer_client.h"
#include "base/command_line.h"
@ -31,8 +32,6 @@
#include "third_party/WebKit/public/web/WebView.h"
#include "ui/base/resource/resource_bundle.h"
#include "atom/common/node_includes.h"
namespace atom {
namespace {

View file

@ -7,11 +7,12 @@
#include <string>
#include "atom/common/api/atom_bindings.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/node_bindings.h"
#include "atom/common/node_includes.h"
#include "atom/common/options_switches.h"
#include "atom/renderer/atom_render_view_observer.h"
#include "atom/renderer/guest_view_container.h"
#include "atom/renderer/node_array_buffer_bridge.h"
#include "base/command_line.h"
#include "chrome/renderer/pepper/pepper_helper.h"
#include "chrome/renderer/printing/print_web_view_helper.h"
@ -20,16 +21,12 @@
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_frame_observer.h"
#include "content/public/renderer/render_thread.h"
#include "third_party/WebKit/public/web/WebArrayBuffer.h"
#include "third_party/WebKit/public/web/WebArrayBufferConverter.h"
#include "third_party/WebKit/public/web/WebCustomElement.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#include "third_party/WebKit/public/web/WebPluginParams.h"
#include "third_party/WebKit/public/web/WebKit.h"
#include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
#include "atom/common/node_includes.h"
#if defined(OS_WIN)
#include <shlobj.h>
#endif
@ -51,37 +48,6 @@ bool IsSwitchEnabled(base::CommandLine* command_line,
return true;
}
// global.Uint8Array;
v8::Local<v8::Function> GetUint8ArrayConstructor(
v8::Isolate* isolate, v8::Local<v8::Context> context) {
v8::Local<v8::Value> constructor = context->Global()->Get(
mate::StringToV8(isolate, "Uint8Array"));
return v8::Local<v8::Function>::Cast(constructor);
}
// new ArrayBuffer(size);
v8::Local<v8::ArrayBuffer> BlinkArrayBufferCreate(
v8::Isolate* isolate, size_t size) {
blink::WebArrayBuffer buffer = blink::WebArrayBuffer::create(size, 1);
return v8::Local<v8::ArrayBuffer>::Cast(
blink::WebArrayBufferConverter::toV8Value(
&buffer, isolate->GetCurrentContext()->Global(), isolate));
}
// new Uint8Array(array_buffer, offset, size);
v8::Local<v8::Uint8Array> BlinkUint8ArrayCreate(
v8::Local<v8::ArrayBuffer> ab, size_t offset, size_t size) {
v8::Local<v8::Context> context = ab->CreationContext();
v8::Isolate* isolate = context->GetIsolate();
v8::Local<v8::Function> constructor =
GetUint8ArrayConstructor(isolate, context);
v8::Local<v8::Value> args[] = {
ab, mate::ConvertToV8(isolate, offset), mate::ConvertToV8(isolate, size)
};
return v8::Local<v8::Uint8Array>::Cast(constructor->NewInstance(
context, arraysize(args), args).ToLocalChecked());
}
// Helper class to forward the messages to the client.
class AtomRenderFrameObserver : public content::RenderFrameObserver {
public:
@ -120,9 +86,7 @@ void AtomRendererClient::WebKitInitialized() {
blink::WebCustomElement::addEmbedderCustomElementName("webview");
blink::WebCustomElement::addEmbedderCustomElementName("browserplugin");
// Override Node's ArrayBuffer with DOM's ArrayBuffer.
node::Buffer::SetArrayBufferCreator(&BlinkArrayBufferCreate,
&BlinkUint8ArrayCreate);
OverrideNodeArrayBuffer();
node_bindings_->Initialize();
node_bindings_->PrepareMessageLoop();

View file

@ -6,7 +6,7 @@ requestId = 0
WEB_VIEW_EVENTS =
'load-commit': ['url', 'isMainFrame']
'did-finish-load': []
'did-fail-load': ['errorCode', 'errorDescription']
'did-fail-load': ['errorCode', 'errorDescription', 'validatedUrl']
'did-frame-finish-load': ['isMainFrame']
'did-start-loading': []
'did-stop-loading': []

View file

@ -0,0 +1,66 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/renderer/node_array_buffer_bridge.h"
#include "base/basictypes.h"
#include "atom/common/node_includes.h"
#include "native_mate/converter.h"
#include "third_party/WebKit/public/web/WebArrayBuffer.h"
#include "third_party/WebKit/public/web/WebArrayBufferConverter.h"
namespace atom {
namespace {
// global.Uint8Array;
v8::Local<v8::Function> GetUint8ArrayConstructor(
v8::Isolate* isolate, v8::Local<v8::Context> context) {
v8::Local<v8::Value> constructor = context->Global()->Get(
mate::StringToV8(isolate, "Uint8Array"));
return v8::Local<v8::Function>::Cast(constructor);
}
// new ArrayBuffer(size);
v8::Local<v8::ArrayBuffer> BlinkArrayBufferNew(
v8::Isolate* isolate, size_t size) {
blink::WebArrayBuffer buffer = blink::WebArrayBuffer::create(size, 1);
return v8::Local<v8::ArrayBuffer>::Cast(
blink::WebArrayBufferConverter::toV8Value(
&buffer, isolate->GetCurrentContext()->Global(), isolate));
}
// new ArrayBuffer(data, size);
v8::Local<v8::ArrayBuffer> BlinkArrayBufferNewWith(
v8::Isolate* isolate, void* data, size_t size) {
blink::WebArrayBuffer buffer = blink::WebArrayBuffer::createExternal(
data, size);
return v8::Local<v8::ArrayBuffer>::Cast(
blink::WebArrayBufferConverter::toV8Value(
&buffer, isolate->GetCurrentContext()->Global(), isolate));
}
// new Uint8Array(array_buffer, offset, size);
v8::Local<v8::Uint8Array> BlinkUint8ArrayNew(
v8::Local<v8::ArrayBuffer> ab, size_t offset, size_t size) {
// Use the DOM's Uint8Array constructor to create Uint8Array.
v8::Local<v8::Context> context = ab->CreationContext();
v8::Isolate* isolate = context->GetIsolate();
v8::Local<v8::Function> constructor =
GetUint8ArrayConstructor(isolate, context);
v8::Local<v8::Value> args[] = {
ab, mate::ConvertToV8(isolate, offset), mate::ConvertToV8(isolate, size)
};
return v8::Local<v8::Uint8Array>::Cast(constructor->NewInstance(
context, arraysize(args), args).ToLocalChecked());
}
} // namespace
void OverrideNodeArrayBuffer() {
node::Buffer::SetArrayBufferCreator(
BlinkArrayBufferNew, BlinkArrayBufferNewWith, BlinkUint8ArrayNew);
}
} // namespace atom

View file

@ -0,0 +1,15 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_RENDERER_NODE_ARRAY_BUFFER_BRIDGE_H_
#define ATOM_RENDERER_NODE_ARRAY_BUFFER_BRIDGE_H_
namespace atom {
// Override Node's ArrayBuffer with DOM's ArrayBuffer.
void OverrideNodeArrayBuffer();
} // namespace atom
#endif // ATOM_RENDERER_NODE_ARRAY_BUFFER_BRIDGE_H_

View file

@ -75,6 +75,7 @@
'xcode_settings': {
'GCC_TREAT_WARNINGS_AS_ERRORS': 'NO',
'WARNING_CFLAGS': [
'-Wno-unknown-warning-option',
'-Wno-parentheses-equality',
'-Wno-unused-function',
'-Wno-sometimes-uninitialized',

View file

@ -1,68 +0,0 @@
## Guías
* [Distribución de aplicaciones](tutorial/application-distribution-es.md)
* [Empaquetamiento de aplicaciones](tutorial/application-packaging-es.md)
* [Utilizando módulos nativos](tutorial/using-native-node-modules-es.md)
* [Depurando el proceso principal](tutorial/debugging-main-process-es.md)
* [Utilizando Selenium y WebDriver](tutorial/using-selenium-and-webdriver-es.md)
* [Extensión DevTools](tutorial/devtools-extension-es.md)
* [Utilizando el plugin pepper flash](tutorial/using-pepper-flash-plugin-es.md)
## Tutoriales
* [Introducción](tutorial/quick-start.md)
* [Integración con el entorno de escritorio](tutorial/desktop-environment-integration.md)
* [Detección del evento en línea/fuera de línea](tutorial/online-offline-events.md)
## API
* [Sinopsis](api/synopsis.md)
* [Proceso](api/process.md)
* [Parámetros CLI soportados (Chrome)](api/chrome-command-line-switches.md)
Elementos DOM customizados:
* [Objeto `File`](api/file-object.md)
* [Etiqueta `<webview>`](api/web-view-tag.md)
* [Función `window.open`](api/window-open.md)
Módulos del proceso principal:
* [app](api/app.md)
* [auto-updater](api/auto-updater.md)
* [browser-window](api/browser-window.md)
* [content-tracing](api/content-tracing.md)
* [dialog](api/dialog.md)
* [global-shortcut](api/global-shortcut.md)
* [ipc (main process)](api/ipc-main-process.md)
* [menu](api/menu.md)
* [menu-item](api/menu-item.md)
* [power-monitor](api/power-monitor.md)
* [power-save-blocker](api/power-save-blocker.md)
* [protocol](api/protocol.md)
* [tray](api/tray.md)
Módulos del renderer (página web):
* [ipc (renderer)](api/ipc-renderer.md)
* [remote](api/remote.md)
* [web-frame](api/web-frame.md)
Módulos de ambos procesos:
* [clipboard](api/clipboard.md)
* [crash-reporter](api/crash-reporter.md)
* [native-image](api/native-image.md)
* [screen](api/screen.md)
* [shell](api/shell.md)
## Desarrollo
* [Guía de estilo](development/coding-style.md)
* [Estructura de directorio](development/source-code-directory-structure.md)
* [Diferencias técnicas con NW.js (anteriormente conocido como node-webkit)](development/atom-shell-vs-node-webkit.md)
* [Sistema de compilación](development/build-system-overview.md)
* [Instrucciones de compilación (Mac)](development/build-instructions-osx.md)
* [Instrucciones de compilación (Windows)](development/build-instructions-windows.md)
* [Instrucciones de compilación (Linux)](development/build-instructions-linux.md)
* [Configurando un servidor de símbolos en el depurador](development/setting-up-symbol-server.md)

View file

@ -0,0 +1,68 @@
## Guías
* [Distribución de aplicaciones](tutorial/application-distribution.md)
* [Empaquetamiento de aplicaciones](tutorial/application-packaging.md)
* [Utilizando módulos nativos](tutorial/using-native-node-modules.md)
* [Depurando el proceso principal](tutorial/debugging-main-process.md)
* [Utilizando Selenium y WebDriver](tutorial/using-selenium-and-webdriver.md)
* [Extensión DevTools](tutorial/devtools-extension.md)
* [Utilizando el plugin pepper flash](tutorial/using-pepper-flash-plugin.md)
## Tutoriales
* [Introducción](../../docs/tutorial/quick-start.md)
* [Integración con el entorno de escritorio](../../docs/tutorial/desktop-environment-integration.md)
* [Detección del evento en línea/fuera de línea](../../docs/tutorial/online-offline-events.md)
## API
* [Sinopsis](../../docs/api/synopsis.md)
* [Proceso](../../docs/api/process.md)
* [Parámetros CLI soportados (Chrome)](../../docs/api/chrome-command-line-switches.md)
Elementos DOM customizados:
* [Objeto `File`](../../docs/api/file-object.md)
* [Etiqueta `<webview>`](../../docs/api/web-view-tag.md)
* [Función `window.open`](../../docs/api/window-open.md)
Módulos del proceso principal:
* [app](../../docs/api/app.md)
* [auto-updater](../../docs/api/auto-updater.md)
* [browser-window](../../docs/api/browser-window.md)
* [content-tracing](../../docs/api/content-tracing.md)
* [dialog](../../docs/api/dialog.md)
* [global-shortcut](../../docs/api/global-shortcut.md)
* [ipc (main process)](../../docs/api/ipc-main-process.md)
* [menu](../../docs/api/menu.md)
* [menu-item](../../docs/api/menu-item.md)
* [power-monitor](../../docs/api/power-monitor.md)
* [power-save-blocker](../../docs/api/power-save-blocker.md)
* [protocol](../../docs/api/protocol.md)
* [tray](../../docs/api/tray.md)
Módulos del renderer (página web):
* [ipc (renderer)](../../docs/api/ipc-renderer.md)
* [remote](../../docs/api/remote.md)
* [web-frame](../../docs/api/web-frame.md)
Módulos de ambos procesos:
* [clipboard](../../docs/api/clipboard.md)
* [crash-reporter](../../docs/api/crash-reporter.md)
* [native-image](../../docs/api/native-image.md)
* [screen](../../docs/api/screen.md)
* [shell](../../docs/api/shell.md)
## Desarrollo
* [Guía de estilo](../../docs/development/coding-style.md)
* [Estructura de directorio](../../docs/development/source-code-directory-structure.md)
* [Diferencias técnicas con NW.js (anteriormente conocido como node-webkit)](../../docs/development/atom-shell-vs-node-webkit.md)
* [Sistema de compilación](../../docs/development/build-system-overview.md)
* [Instrucciones de compilación (Mac)](../../docs/development/build-instructions-osx.md)
* [Instrucciones de compilación (Windows)](../../docs/development/build-instructions-windows.md)
* [Instrucciones de compilación (Linux)](../../docs/development/build-instructions-linux.md)
* [Configurando un servidor de símbolos en el depurador](../../docs/development/setting-up-symbol-server.md)

View file

@ -1,7 +1,7 @@
## Guias
* [Distribuir Aplicação](../../docs/tutorial/application-distribution.md)
* [Empacotamento da aplicação](../../docs/tutorial/application-packaging.md)
* [Distribuir Aplicação](tutorial/application-distribution.md)
* [Empacotamento da aplicação](tutorial/application-packaging.md)
* [Usando módulos nativos](../../docs/tutorial/using-native-node-modules.md)
* [Depuração do processo principal](../../docs/tutorial/debugging-main-process.md)
* [Usando Selenium e WebDriver](../../docs/tutorial/using-selenium-and-webdriver.md)

View file

@ -0,0 +1,118 @@
# Distribuição de aplicações
Para distribuir sua aplicação com o Electron, você deve nomear o diretório que contém sua aplicação como
`app` e dentro deste diretório colocar os recursos que você está utilizando (no OSX
`Electron.app/Contents/Resources/`,
no Linux e no Windows é em `resources/`):
No OSX:
```text
electron/Electron.app/Contents/Resources/app/
├── package.json
├── main.js
└── index.html
```
No Windows e Linux:
```text
electron/resources/app
├── package.json
├── main.js
└── index.html
```
Logo após execute `Electron.app` (ou `electron` no Linux e `electron.exe` no Windows),
e o Electron iniciaria a aplicação. O diretório `electron` será utilizado para criar a distribuição para
usuários finais.
## Empacotando sua aplicação em um arquivo.
Além de copiar todos os seus arquivos fontes para a distribuição, você também pode
empacotar seu aplicativo em um arquivo [asar](https://github.com/atom/asar) para evitar
de expor seu código fonte aos usuários finais.
Para usar um arquivo `asar` ao invés da pasta `app` você precisa mudar o nome do
arquivo para `app.asar` e colocá-lo sob o diretório de recursos do Electron como
mostrado abaixo, então o Electron vai ler o arquivo e iniciar a aplicação a partir dele.
No OSX:
```text
electron/Electron.app/Contents/Resources/
└── app.asar
```
No Windows e Linux:
```text
electron/resources/
└── app.asar
```
Mais detalhes podem ser encontrados em [Empacotamento da aplicação](../../../docs/tutorial/application-packaging.md).
## Renomeando a marca Electron na sua distribuição
Depois de empacotar seu aplicativo Electron, você vai querer renomear a marca Electron
antes de distribuí-lo aos usuários.
### Janelas
Você pode renomear `electron.exe` para o nome que desejar e editar o seu ícone e outras
informações com ferramentas como [rcedit](https://github.com/atom/rcedit) ou
[ResEdit](http://www.resedit.net).
### OS X
Você pode renomear `Electron.app` para o nome que desejar e também pode mudar o nome
do `CFBundleDisplayName`, `CFBundleIdentifier` e os campos em `CFBundleName`
nos seguinte arquivos:
* `Electron.app/Contents/Info.plist`
* `Electron.app/Contents/frameworks/Electron Helper.app/Contents/Info.plist`
Você também pode renomear o arquivo de ajuda para evitar a exibição de `Electron Helper` no
Monitor de Atividades, mas certifique-se de também renomear o arquivo de ajuda no executável do
aplicativo.
A estrutura de uma aplicação renomada seria assim:
```
MyApp.app/Contents
├── Info.plist
├── MacOS/
│   └── MyApp
└── Frameworks/
├── MyApp Helper EH.app
| ├── Info.plist
| └── MacOS/
|    └── MyApp Helper EH
├── MyApp Helper NP.app
| ├── Info.plist
| └── MacOS/
|    └── MyApp Helper NP
└── MyApp Helper.app
├── Info.plist
└── MacOS/
   └── MyApp Helper
```
### Linux
Você pode renomear o executável `electron` para o nome que desejar.
## Renomeando a marca Electron do código fonte.
Também é possível fazer renomear a marca Electron do código fonte, alterando o nome do produto e
reconstruí-lo a partir da fonte, para fazer isso você precisa modificar o arquivo `atom.gyp`.
### grunt-build-atom-shell
A modificação do código fonte do Electron para ganhar a sua marca pode ser muito complexa, por isso,
uma tarefa para o Grunt foi criado e irá cuidar desta tarefa automaticamente para você:
[grunt-build-atom-shell](https://github.com/paulcbetts/grunt-build-atom-shell).
Esta tarefa irá automaticamente editar o arquivo `.gyp`, compilar o código
e reconstruir os módulos nativos da aplicação para utilizar o novo nome.

View file

@ -0,0 +1,158 @@
# Empacotamento da aplicação
Para proteger os recursos e o código fonte da sua aplicação você pode optar por
empacotar a sua aplicação em um arquivo [asar](https://github.com/atom/asar), isto é possível com poucas
alterações em seu código.
## Gerando um arquivo `asar`
Um arquivo [asar][asar] é um formato parecido com tar ou zip bem simples que concatena arquivos
em um único arquivo. O Electron pode ler arquivos arbitrários a partir dele sem descompacatar
o arquivo inteiro.
Passos para empacotar a sua aplicação em um arquivo `asar`:
### 1. Instale o utilitário asar
```bash
$ npm install -g asar
```
### 2. Empacote a sua aplicação
```bash
$ asar pack your-app app.asar
```
## Usando arquivos `asar`
No Electron existem dois conjuntos de APIs: Node APIs fornecidas pelo Node.js e Web
APIs fornecidas pelo Chromium. Ambas as APIs suportam a leitura de arquivos `asar`.
### Node API
As API's do Node como `fs.readFile` e `require` tratam os pacotes `asar`
como diretórios virtuais e os arquivos dentro dele como arquivos normais.
Por exemplo, temos um arquivo `example.asar` sob `/path/to`:
```bash
$ asar list /path/to/example.asar
/app.js
/file.txt
/dir/module.js
/static/index.html
/static/main.css
/static/jquery.min.js
```
Lendo um arquivo em pacote `asar`:
```javascript
var fs = require('fs');
fs.readFileSync('/path/to/example.asar/file.txt');
```
Listando todos os arquivos a partir da raiz:
```javascript
var fs = require('fs');
fs.readdirSync('/path/to/example.asar');
```
Utilizando um módulo dentro do pacote `asar`:
```javascript
require('/path/to/example.asar/dir/module.js');
```
Você também pode renderizar uma página web apartir de um arquivo `asar` utilizando o módulo `BrowserWindow`:
```javascript
var BrowserWindow = require('browser-window');
var win = new BrowserWindow({width: 800, height: 600});
win.loadUrl('file:///path/to/example.asar/static/index.html');
```
### API Web
Em uma página web, arquivos em um pacote `asar` pode ser solicitado com o protocolo `file:`.
Como a API Node, arquivos `asar` são tratadas como diretórios.
Por exemplo, para obter um arquivo com `$ .get`:
```html
<script>
var $ = require('./jquery.min.js');
$.get('file:///path/to/example.asar/file.txt', function(data) {
console.log(data);
});
</script>
```
### Tratando um pacote `asar` como um arquivo normal
Para alguns casos, precisamos verificar o checksum de um pacote `asar`, para fazer isto, precisamos ler
o arquivo `asar` como um arquivo normal. Para isto, você pode usar o built-in
`original-fs` que fornece a API `fs`, sem apoio a arquivos asar`:
```javascript
var originalFs = require('original-fs');
originalFs.readFileSync('/path/to/example.asar');
```
## Limitaçõs na API Node
Mesmo fazendo grandes esforços para pacotes `asar` ser tratado no Node como diretórios,
ainda existem limitações devido a natureza de baixo nível do Node
### Arquivos `asar` são somente leitura
Os arquivos `asar` não podem ser modificados.
### Diretório de trabalho não pode ser comportar como diretório de arquivos
Embora pacotes `asar` são tratadas como diretórios, não há
diretórios reais no sistema de arquivos, assim você nunca pode definir o diretório de trabalho para
diretórios em pacotes `asar`, passando-os como a opção `cwd` de algumas APIs
também irá causar erros.
### Descompactação extra em algumas APIs
A maioria das APIs `fs` pode ler um arquivo ou obter informações de um arquivo a partir de pacotes `asar`
sem descompacta-lo, mas para algumas APIs da rota real o Electron irá extrair o arquivo necessário para um
arquivo temporário e passar o caminho do arquivo temporário para as APIs,
isso adiciona um pouco de sobrecarga para essas APIs.
APIs que requer descompactação extras são:
* `child_process.execFile`
* `fs.open`
* `fs.openSync`
* `process.dlopen` - Usado por `require` em módulos nativos
### Falsas informações de status do módulo `fs.stat`
O objeto `Stats` retornado por` fs.stat` e outras funções relacionadas não são informações confiáveis,
você não deve confiar no objeto `Stats` exceto para obter o
tamanho do arquivo e verificação de tipo de arquivo.
## Adicionando arquivos em um pacote `asar`
Como dito acima, algumas APIs deo Node irá descompactar o arquivo para quando o filesystem
requsistar, além dos problemas de desempenho, ele também pode levar a falsos alertas
de vírus.
Para contornar isso, você pode descompactar alguns arquivos usando a
opção `--unpack`, um exemplo de exclusão de bibliotecas compartilhadas de módulos nativos
é:
```bash
$ asar pack app app.asar --unpack *.node
```
Depois de executar o comando, além do `app.asar`, há também
`app.asar.unpacked` pasta gerada que contém os arquivos descompactados, você
deve copiá-lo juntamente com `app.asar` quando enviá-lo para os usuários.
Mais informações no repositório [asar](https://github.com/atom/asar)

View file

@ -0,0 +1,45 @@
# shell
`shell` 模块提供了集成其他桌面客户端的关联功能.
在用户默认浏览器中打开URL的示例:
```javascript
var shell = require('shell');
shell.openExternal('https://github.com');
```
## Methods
`shell` 模块包含以下函数:
### `shell.showItemInFolder(fullPath)`
* `fullPath` String
打开文件所在文件夹,一般情况下还会选中它.
### `shell.openItem(fullPath)`
* `fullPath` String
以默认打开方式打开文件.
### `shell.openExternal(url)`
* `url` String
以系统默认设置打开外部协议.(例如,mailto: somebody@somewhere.io会打开用户默认的邮件客户端)
### `shell.moveItemToTrash(fullPath)`
* `fullPath` String
删除指定路径文件,并返回此操作的状态值(boolean类型).
### `shell.beep()`
播放 beep 声音.

View file

@ -0,0 +1,28 @@
# `File` object
DOM's File 介面提供一個將本地文件抽象化,並可以讓使用者對本地文件直接使用 HTML5 檔案 API
Electron 可以添加一個 `path` 屬性至 `File` 接口進而顯示檔案在檔案系統內的真實路徑。
範例,獲得一個檔案之真實路徑,將檔案拖拉至應用程式 (dragged-onto-the-app):
```html
<div id="holder">
Drag your file here
</div>
<script>
var holder = document.getElementById('holder');
holder.ondragover = function () {
return false;
};
holder.ondragleave = holder.ondragend = function () {
return false;
};
holder.ondrop = function (e) {
e.preventDefault();
var file = e.dataTransfer.files[0];
console.log('File you dragged here is', file.path);
return false;
};
</script>
```

View file

@ -0,0 +1,36 @@
# power-monitor
`power-monitor` 模組用來監看電源狀態的改變。你只能在主行程 (main process) 裡面使用。
你應該要等到 `ready``app` 模組裡的事件被觸發 (emit),再使用這個模組。
舉例來說:
```javascript
var app = require('app');
app.on('ready', function() {
require('power-monitor').on('suspend', function() {
console.log('The system is going to sleep');
});
});
```
## 事件 (Events)
`power-monitor` 模組會觸發 (emits) 以下幾個事件:
### 事件: 'suspend'
當系統進入 睡眠 (suspend) 時觸發。
### 事件: 'resume'
當系統 resume 時觸發。
### 事件: 'on-ac'
當系統改變使用交流電源 (AC) 時觸發。
### 事件: 'on-battery'
當系統改變使用電池店員時觸發。

View file

@ -0,0 +1,47 @@
# powerSaveBlocker
`power-save-blocker` 模組是用來防止系統進入省電模式 low-power (sleep) mode
因此讓應用程式可以保持系統和螢幕的活躍 (active)。
舉例來說:
```javascript
var powerSaveBlocker = require('power-save-blocker');
var id = powerSaveBlocker.start('prevent-display-sleep');
console.log(powerSaveBlocker.isStarted(id));
powerSaveBlocker.stop(id);
```
## 方法 (Methods)
`power-save-blocker` 模組有以下幾個方法:
### `powerSaveBlocker.start(type)`
* `type` String - Power save blocker type.
* `prevent-app-suspension` - 防止一個應用程式進入睡眠 (suspended)。 將保持系統活躍,
但允許螢幕被關閉。 使用案例:下載一個檔案或是播放音樂。
* `prevent-display-sleep`- 防止螢幕進入睡眠。將保持系統和螢幕的活躍。
使用案例:播放影片
當防止系統進入省電模式 low-power (sleep) mode 。 會回傳一個識別的整數來代表 power save blocker
**注意:** `prevent-display-sleep``prevent-app-suspension` 擁有較高的優先權。
只有高的優先全力才會有效,換句話說 `prevent-display-sleep` 總是會優先於 `prevent-app-suspension`
例如,一個 API 呼叫 A 請求去做 `prevent-app-suspension`,而另外一個 B 請求去做 `prevent-display-sleep`
`prevent-display-sleep` 將會被使用,直到 B 停止他的請求,`prevent-app-suspension` 才會被使用。
### `powerSaveBlocker.stop(id)`
* `id` Integer - power save blocker 會回傳 id 透過 `powerSaveBlocker.start`.
將指定的 id 停止 power save blocker
### `powerSaveBlocker.isStarted(id)`
* `id` Integer - power save blocker 會回傳 id 透過 `powerSaveBlocker.start`.
不管對應的 `powerSaveBlocker` 是否已經啟動,將會回傳一個布林值 (boolean)

View file

@ -0,0 +1,23 @@
# process
在 Electron 裡的 `process` 物件具有以下幾個與 upstream node 的不同點:
* `process.type` String - Process 的型態,可以是 `browser` (i.e. 主行程) 或 `renderer`.
* `process.versions['electron']` String - Electron 的版本
* `process.versions['chrome']` String - Chromium 的版本
* `process.resourcesPath` String - JavaScript 源碼的路徑
# 方法 (Methods)
`process` 物件具有以下的方法:
### `process.hang`
會導致目前行程的主執行緒停住
## process.setFdLimit(maxDescriptors) _OS X_ _Linux_
* `maxDescriptors` Integer
設置文件描述符 (file descriptor) soft limit `maxDescriptors` 或 OS hard
limit ,以較低者為準當目前的行程。

View file

@ -0,0 +1,41 @@
# Synopsis
所有的 [Node.js's 內建模組](http://nodejs.org/api/) 都可以在 Electron 使用,而且
第三方的 node 模組同樣的全部支援(包含[原生模組](../tutorial/using-native-node-modules.md)
Electron 也提供一些額外的內建模組用來開發原生桌面應用程式,一些模組只可以使用在主行程上
(main process) 一些只可以使用在渲染行程 (renderer process) 上 (網頁) ,另外還有一些
模組在兩邊的行程都可以使用。
基本的規則是: 如果一個模組是 [GUI](https://zh.wikipedia.org/wiki/%E5%9B%BE%E5%BD%A2%E7%94%A8%E6%88%B7%E7%95%8C%E9%9D%A2)
或者是 low-level 與系統相關的,那麼它就應該只能在主行程上使用 (main process) 你必須要對熟悉 [main process vs. renderer process](../tutorial/quick-start.md#the-main-process) 的觀念,才能去使用這些模組。
主行程 (main process) 腳本是一個像一般 Node.js 的腳本:
```javascript
var app = require('app');
var BrowserWindow = require('browser-window');
var window = null;
app.on('ready', function() {
window = new BrowserWindow({width: 800, height: 600});
window.loadUrl('https://github.com');
});
```
渲染行程 (renderer process) 跟一般正常的網頁沒有差別,而且還能有使用 node 模組的能力:
```html
<!DOCTYPE html>
<html>
<body>
<script>
var remote = require('remote');
console.log(remote.require('app').getVersion());
</script>
</body>
</html>
```
執行你的應用程式,請閱讀[Run your app](../tutorial/quick-start.md#run-your-app).

View file

@ -1,32 +1,32 @@
## Guides
* [Application distribution](tutorial/application-distribution.md)
* [Application packaging](tutorial/application-packaging.md)
* [Using native node modules](tutorial/using-native-node-modules.md)
* [Debugging main process](tutorial/debugging-main-process.md)
* [Application Distribution](tutorial/application-distribution.md)
* [Application Packaging](tutorial/application-packaging.md)
* [Using Native Node Modules](tutorial/using-native-node-modules.md)
* [Debugging Main Process](tutorial/debugging-main-process.md)
* [Using Selenium and WebDriver](tutorial/using-selenium-and-webdriver.md)
* [DevTools extension](tutorial/devtools-extension.md)
* [Using pepper flash plugin](tutorial/using-pepper-flash-plugin.md)
* [DevTools Extension](tutorial/devtools-extension.md)
* [Using Pepper Flash Plugin](tutorial/using-pepper-flash-plugin.md)
## Tutorials
* [Quick start](tutorial/quick-start.md)
* [Desktop environment integration](tutorial/desktop-environment-integration.md)
* [Online/offline event detection](tutorial/online-offline-events.md)
* [Quick Start](tutorial/quick-start.md)
* [Desktop Environment Integration](tutorial/desktop-environment-integration.md)
* [Online/Offline Event Detection](tutorial/online-offline-events.md)
## API references
## API References
* [Synopsis](api/synopsis.md)
* [Process object](api/process.md)
* [Supported Chrome command line switches](api/chrome-command-line-switches.md)
* [Process Object](api/process.md)
* [Supported Chrome Command Line Switches](api/chrome-command-line-switches.md)
Custom DOM elements:
### Custom DOM Elements:
* [`File` object](api/file-object.md)
* [`<webview>` tag](api/web-view-tag.md)
* [`window.open` function](api/window-open.md)
* [`File` Object](api/file-object.md)
* [`<webview>` Tag](api/web-view-tag.md)
* [`window.open` Function](api/window-open.md)
Modules for the main process:
### Modules for the Main Process:
* [app](api/app.md)
* [auto-updater](api/auto-updater.md)
@ -41,16 +41,16 @@ Modules for the main process:
* [power-save-blocker](api/power-save-blocker.md)
* [protocol](api/protocol.md)
* [session](api/session.md)
* [webContents](api/web-contents.md)
* [web-contents](api/web-contents.md)
* [tray](api/tray.md)
Modules for the renderer process (web page):
### Modules for the Renderer Process (Web Page):
* [ipc (renderer)](api/ipc-renderer.md)
* [remote](api/remote.md)
* [web-frame](api/web-frame.md)
Modules for both processes:
### Modules for Both Processes:
* [clipboard](api/clipboard.md)
* [crash-reporter](api/crash-reporter.md)
@ -60,11 +60,11 @@ Modules for both processes:
## Development
* [Coding style](development/coding-style.md)
* [Source code directory structure](development/source-code-directory-structure.md)
* [Technical differences to NW.js (formerly node-webkit)](development/atom-shell-vs-node-webkit.md)
* [Build system overview](development/build-system-overview.md)
* [Build instructions (Mac)](development/build-instructions-osx.md)
* [Build instructions (Windows)](development/build-instructions-windows.md)
* [Build instructions (Linux)](development/build-instructions-linux.md)
* [Setting up symbol server in debugger](development/setting-up-symbol-server.md)
* [Coding Style](development/coding-style.md)
* [Source Code Directory Structure](development/source-code-directory-structure.md)
* [Technical Differences to NW.js (formerly node-webkit)](development/atom-shell-vs-node-webkit.md)
* [Build System Overview](development/build-system-overview.md)
* [Build Instructions (Mac)](development/build-instructions-osx.md)
* [Build Instructions (Windows)](development/build-instructions-windows.md)
* [Build Instructions (Linux)](development/build-instructions-linux.md)
* [Setting Up Symbol Server in debugger](development/setting-up-symbol-server.md)

View file

@ -152,7 +152,7 @@ Emitted when the gpu process crashes.
The `app` object has the following methods:
**Note** Some methods are only available on specific operating systems and are labeled as such.
**Note:** Some methods are only available on specific operating systems and are labeled as such.
### `app.quit()`

View file

@ -53,7 +53,7 @@ server that you are requesting updates from. A common approach is to use query
parameters, like this:
```javascript
// On the main process
// In the main process
var app = require('app');
var autoUpdater = require('auto-updater');
autoUpdater.setFeedUrl('http://mycompany.com/myapp/latest?version=' + app.getVersion());

View file

@ -117,7 +117,7 @@ Properties `width` and `height` are required.
The `BrowserWindow` object emits the following events:
+**Note** Some events are only available on specific operating systems and are labeled as such.
**Note:** Some events are only available on specific operating systems and are labeled as such.
### Event: 'page-title-updated'
@ -224,15 +224,15 @@ Emitted when the window leaves full screen state triggered by html api.
### Event: 'devtools-opened'
Emitted when devtools is opened.
Emitted when DevTools is opened.
### Event: 'devtools-closed'
Emitted when devtools is closed.
Emitted when DevTools is closed.
### Event: 'devtools-focused'
Emitted when devtools is focused / opened.
Emitted when DevTools is focused / opened.
### Event: 'app-command' _Windows_
@ -263,7 +263,7 @@ Returns the window that is focused in this application.
### `BrowserWindow.fromWebContents(webContents)`
* `webContents` [WebContents](#webcontents)
* `webContents` [WebContents](web-contents.md)
Find a window according to the `webContents` it owns.
@ -277,7 +277,7 @@ Find a window according to its ID.
* `path` String
Adds devtools extension located at `path`, and returns extension's name.
Adds DevTools extension located at `path`, and returns extension's name.
The extension will be remembered so you only need to call this API once, this
API is not for programming use.
@ -286,13 +286,11 @@ API is not for programming use.
* `name` String
Remove the devtools extension whose name is `name`.
Remove the DevTools extension whose name is `name`.
## Instance Methods
## Instance Properties
Objects created with `new BrowserWindow` have the following instance methods:
+**Note** Some methods are only available on specific operating systems and are labeled as such.
Objects created with `new BrowserWindow` have the following properties:
```javascript
var BrowserWindow = require('browser-window');
@ -302,7 +300,7 @@ var win = new BrowserWindow({ width: 800, height: 600 });
```
### `win.webContents()`
### `win.webContents`
The `WebContents` object this window owns, all web page related events and
operations will be done via it.
@ -313,16 +311,30 @@ events.
**Note:** Users should never store this object because it may become `null`
when the renderer process (web page) has crashed.
### `win.devToolsWebContents()`
### `win.devToolsWebContents`
Get the `WebContents` of devtools for this window.
Get the `WebContents` of DevTools for this window.
**Note:** Users should never store this object because it may become `null`
when the devtools has been closed.
when the DevTools has been closed.
### `win.id()`
### `win.id`
Get the unique ID of this window.
The unique ID of this window.
## Instance Methods
Objects created with `new BrowserWindow` have the following instance methods:
**Note:** Some methods are only available on specific operating systems and are labeled as such.
```javascript
var BrowserWindow = require('browser-window');
// In this example `win` is our instance
var win = new BrowserWindow({ width: 800, height: 600 });
```
### `win.destroy()`
@ -577,7 +589,7 @@ Whether the window's document has been edited.
### `win.openDevTools([options])`
* `options` Object (optional). Properties:
* `detach` Boolean - opens devtools in a new window
* `detach` Boolean - opens DevTools in a new window
Opens the developer tools.

View file

@ -4,7 +4,7 @@ The `global-shortcut` module can register/unregister a global keyboard shortcut
with the operating system so that you can customize the operations for various
shortcuts.
**Note**: The shortcut is global; it will work even if the app does
**Note:** The shortcut is global; it will work even if the app does
not have the keyboard focus. You should not use this module until the `ready`
event of the app module is emitted.

View file

@ -7,7 +7,7 @@ a renderer will be emitted to this module.
## Sending Messages
It is also possible to send messages from the main process to the renderer
process, see [WebContents.send](browser-window.md#webcontentssendchannel-args)
process, see [WebContents.send](web-contents.md#webcontentssendchannel-args)
for more information.
- When sending a message, the event name is the `channel`.

View file

@ -4,7 +4,7 @@ The `ipc` module provides a few methods so you can send synchronous and
asynchronous messages from the render process (web page) to the main process.
You can also receive replies from the main process.
**Note**: If you want to make use of modules in the main process from the renderer
**Note:** If you want to make use of modules in the main process from the renderer
process, you might consider using the [remote](remote.md) module.
See [ipc (main process)](ipc-main-process.md) for code examples.
@ -13,7 +13,7 @@ See [ipc (main process)](ipc-main-process.md) for code examples.
The `ipc` module has the following methods for sending messages:
**Note**: When using these methods to send a `message` you must also listen
**Note:** When using these methods to send a `message` you must also listen
for it in the main process with [`ipc (main process)`](ipc-main-process.md).
### `ipc.send(channel[, arg1][, arg2][, ...])`

View file

@ -74,7 +74,7 @@ mixed with other content to create the desired final appearance.
The most common case is to use template images for a menu bar icon so it can
adapt to both light and dark menu bars.
**Note**: Template image is only supported on OS X.
**Note:** Template image is only supported on OS X.
To mark an image as a template image, its filename should end with the word
`Template`. For example:

View file

@ -1,7 +1,7 @@
# power-monitor
The `power-monitor` module is used to monitor power state changes. You can
only use it on the main process. You should not use this module until the `ready`
only use it in the main process. You should not use this module until the `ready`
event of the `app` module is emitted.
For example:

View file

@ -20,8 +20,8 @@ var win = new BrowserWindow({ width: 800, height: 600 });
win.loadUrl('https://github.com');
```
**Note**: for the reverse (access the renderer process from the main process),
you can use [webContents.executeJavascript](browser-window.md#webcontents-executejavascript-code).
**Note:** for the reverse (access the renderer process from the main process),
you can use [webContents.executeJavascript](web-contents.md#webcontentsexecutejavascriptcode-usergesture).
## Remote Objects

View file

@ -6,7 +6,7 @@ position, etc. You should not use this module until the `ready` event of the
`screen` is an [EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter).
**Note**: In the renderer / DevTools, `window.screen` is a reserved
**Note:** In the renderer / DevTools, `window.screen` is a reserved
DOM property, so writing `var screen = require('screen')` will not work. In our
examples below, we use `atomScreen` as the variable name instead.

View file

@ -5,13 +5,13 @@ Electron and third-party node modules also fully supported as well (including
the [native modules](../tutorial/using-native-node-modules.md)).
Electron also provides some extra built-in modules for developing native
desktop applications. Some modules are only available on the main process, some
desktop applications. Some modules are only available in the main process, some
are only available in the renderer process (web page), and some can be used in
both processes.
The basic rule is: if a module is
[GUI](https://en.wikipedia.org/wiki/Graphical_user_interface) or low-level
system related, then it should be only available on the main process. You need
system related, then it should be only available in the main process. You need
to be familiar with the concept of
[main process vs. renderer process](../tutorial/quick-start.md#the-main-process)
scripts to be able to use those modules.

View file

@ -123,7 +123,7 @@ Emitted when dragged files are dropped in the tray icon.
The `Tray` module has the following methods:
**Note**: Some methods are only available on specific operating systems and are
**Note:** Some methods are only available on specific operating systems and are
labeled as such.
### `Tray.destroy()`

View file

@ -32,6 +32,7 @@ Returns:
* `event` Event
* `errorCode` Integer
* `errorDescription` String
* `validatedUrl` String
This event is like `did-finish-load` but emitted when the load failed or was
cancelled, e.g. `window.stop()` is invoked.
@ -426,13 +427,13 @@ win.webContents.on("did-finish-load", function() {
* `path` String
Adds the specified path to devtools workspace.
Adds the specified path to DevTools workspace.
### `webContents.removeWorkSpace(path)`
* `path` String
Removes the specified path from devtools workspace.
Removes the specified path from DevTools workspace.
### `webContents.send(channel[, args...])`
@ -445,7 +446,7 @@ page can handle it by listening to the `channel` event of the `ipc` module.
An example of sending messages from the main process to the renderer process:
```javascript
// On the main process.
// In the main process.
var window = null;
app.on('ready', function() {
window = new BrowserWindow({width: 800, height: 600});
@ -472,6 +473,6 @@ app.on('ready', function() {
**Note:**
1. The IPC message handler in web pages does not have an `event` parameter,
which is different from the handlers on the main process.
which is different from the handlers in the main process.
2. There is no way to send synchronous messages from the main process to a
renderer process, because it would be very easy to cause dead locks.

View file

@ -153,7 +153,7 @@ value will fail with a DOM exception.
The `webview` tag has the following methods:
**Note**: The webview element must be loaded before using the methods.
**Note:** The webview element must be loaded before using the methods.
**Example**
```javascript
@ -260,15 +260,15 @@ user action, can take advantage of this option for automation.
### `<webview>.openDevTools()`
Opens a devtools window for guest page.
Opens a DevTools window for guest page.
### `<webview>.closeDevTools()`
Closes the devtools window of guest page.
Closes the DevTools window of guest page.
### `<webview>.isDevToolsOpened()`
Returns a boolean whether guest page has a devtools window attached.
Returns a boolean whether guest page has a DevTools window attached.
### `<webview>.inspectElement(x, y)`
@ -279,7 +279,7 @@ Starts inspecting element at position (`x`, `y`) of guest page.
### `<webview>.inspectServiceWorker()`
Opens the devtools for the service worker context present in the guest page.
Opens the DevTools for the service worker context present in the guest page.
### `<webview>.setAudioMuted(muted)`
@ -355,7 +355,7 @@ Prints webview's web page as PDF, Same with `webContents.printToPDF(options, cal
Send `args..` to guest page via `channel` in asynchronous message, the guest
page can handle it by listening to the `channel` event of `ipc` module.
See [WebContents.send](browser-window.md#webcontentssendchannel-args) for
See [WebContents.send](web-contents.md#webcontentssendchannel-args) for
examples.
## DOM events
@ -384,6 +384,7 @@ Returns:
* `errorCode` Integer
* `errorDescription` String
* `validatedUrl` String
This event is like `did-finish-load`, but fired when the load failed or was
cancelled, e.g. `window.stop()` is invoked.

View file

@ -1,7 +1,7 @@
# Electron Documentation Styleguide
Find the appropriate section for your task: [reading Electron documentation](#)
or [writing Electron documentation](#).
Find the appropriate section for your task: [reading Electron documentation](#reading-electron-documentation)
or [writing Electron documentation](#writing-electron-documentation).
## Writing Electron Documentation
@ -25,6 +25,22 @@ These are the ways that we construct the Electron documentation.
- Line length is 80-column wrapped.
- Platform specific methods are noted in italics following method header.
- ```### `method(foo, bar)` _OS X_```
- Prefer 'in the ___ process' over 'on'
### Documentation Translations
Translations of the Electron docs are located within the `docs-translations`
directory.
To add another set (or partial set):
- Create a subdirectory named by language abbreviation.
- Within that subdirectory, duplicate the `docs` directory, keeping the
names of directories and files same.
- Translate the files.
- Update the `README.md` within your language directory to link to the files
you have translated.
- Add a link to your translation directory on the main Electron [README](https://github.com/atom/electron#documentation-translations).
## Reading Electron Documentation

View file

@ -1,6 +1,6 @@
# Debugging the Main Process
The browser window devtools can only debug the renderer process scripts (i.e.
The browser window DevTools can only debug the renderer process scripts (i.e.
the web pages). In order to provide a way to debug the scripts from the main
process, Electron has provided the `--debug` and `--debug-brk` switches.

View file

@ -31,7 +31,7 @@ which handles the manual steps of downloading headers and building native module
npm install --save-dev electron-rebuild
# Every time you run npm install, run this
./node_modules/.bin/electron-rebuild
node ./node_modules/.bin/electron-rebuild
```
### The node-gyp Way

View file

@ -230,8 +230,6 @@
'atom/browser/web_contents_preferences.h',
'atom/browser/web_dialog_helper.cc',
'atom/browser/web_dialog_helper.h',
'atom/browser/web_view_constants.cc',
'atom/browser/web_view_constants.h',
'atom/browser/web_view_guest_delegate.cc',
'atom/browser/web_view_guest_delegate.h',
'atom/browser/web_view_manager.cc',
@ -326,6 +324,8 @@
'atom/renderer/atom_renderer_client.h',
'atom/renderer/guest_view_container.cc',
'atom/renderer/guest_view_container.h',
'atom/renderer/node_array_buffer_bridge.cc',
'atom/renderer/node_array_buffer_bridge.h',
'atom/utility/atom_content_utility_client.cc',
'atom/utility/atom_content_utility_client.h',
'chromium_src/chrome/browser/browser_process.cc',

View file

@ -162,13 +162,16 @@ def create_chrome_version_h():
version = f.read()
with open(template_file, 'r') as f:
template = f.read()
if sys.platform in ['win32', 'cygwin']:
open_mode = 'wb+'
else:
open_mode = 'w+'
with open(target_file, open_mode) as f:
content = template.replace('{PLACEHOLDER}', version.strip())
if f.read() != content:
content = template.replace('{PLACEHOLDER}', version.strip())
# We update the file only if the content has changed (ignoring line ending
# differences).
should_write = True
if os.path.isfile(target_file):
with open(target_file, 'r') as f:
should_write = f.read().replace('r', '') != content.replace('r', '')
if should_write:
with open(target_file, 'w') as f:
f.write(content)

View file

@ -8,7 +8,7 @@ import sys
BASE_URL = os.getenv('LIBCHROMIUMCONTENT_MIRROR') or \
'http://github-janky-artifacts.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = 'f5489a774b719e9e979675c17b99ed45a05aacf7'
LIBCHROMIUMCONTENT_COMMIT = '8482fe555913dea3bde8a74f754524e2cfb02bc5'
PLATFORM = {
'cygwin': 'win32',

View file

@ -182,15 +182,36 @@ describe 'browser-window module', ->
assert.equal after[0], size.width
assert.equal after[1], size.height
describe '"preload" options', ->
it 'loads the script before other scripts in window', (done) ->
preload = path.join fixtures, 'module', 'set-global.js'
remote.require('ipc').once 'preload', (event, test) ->
assert.equal(test, 'preload')
done()
w.destroy()
w = new BrowserWindow(show: false, width: 400, height: 400, preload: preload)
w.loadUrl 'file://' + path.join(fixtures, 'api', 'preload.html')
describe '"web-preferences" option', ->
afterEach ->
remote.require('ipc').removeAllListeners('answer')
describe '"preload" option', ->
it 'loads the script before other scripts in window', (done) ->
preload = path.join fixtures, 'module', 'set-global.js'
remote.require('ipc').once 'answer', (event, test) ->
assert.equal(test, 'preload')
done()
w.destroy()
w = new BrowserWindow
show: false
'web-preferences':
preload: preload
w.loadUrl 'file://' + path.join(fixtures, 'api', 'preload.html')
describe '"node-integration" option', ->
it 'disables node integration when specified to false', (done) ->
preload = path.join fixtures, 'module', 'send-later.js'
remote.require('ipc').once 'answer', (event, test) ->
assert.equal(test, 'undefined')
done()
w.destroy()
w = new BrowserWindow
show: false
'web-preferences':
preload: preload
'node-integration': false
w.loadUrl 'file://' + path.join(fixtures, 'api', 'blank.html')
describe 'beforeunload handler', ->
it 'returning true would not prevent close', (done) ->

View file

@ -36,11 +36,20 @@ describe 'chromium feature', ->
describe 'window.open', ->
it 'returns a BrowserWindowProxy object', ->
b = window.open 'about:blank', 'test', 'show=no'
b = window.open 'about:blank', '', 'show=no'
assert.equal b.closed, false
assert.equal b.constructor.name, 'BrowserWindowProxy'
b.close()
it 'accepts "node-integration" as feature', (done) ->
listener = (event) ->
window.removeEventListener 'message', listener
b.close()
assert.equal event.data, 'undefined'
done()
window.addEventListener 'message', listener
b = window.open "file://#{fixtures}/pages/window-opener-node.html", '', 'node-integration=no,show=no'
describe 'window.opener', ->
ipc = remote.require 'ipc'
url = "file://#{fixtures}/pages/window-opener.html"
@ -58,19 +67,21 @@ describe 'chromium feature', ->
w.loadUrl url
it 'is not null for window opened by window.open', (done) ->
b = window.open url, 'test2', 'show=no'
b = window.open url, '', 'show=no'
ipc.on 'opener', (event, opener) ->
b.close()
done(if opener isnt null then undefined else opener)
describe 'window.opener.postMessage', ->
it 'sets source and origin correctly', (done) ->
b = window.open "file://#{fixtures}/pages/window-opener-postMessage.html", 'test', 'show=no'
window.addEventListener 'message', (event) ->
listener = (event) ->
window.removeEventListener 'message', listener
b.close()
assert.equal event.source.guestId, b.guestId
assert.equal event.origin, 'file://'
done()
window.addEventListener 'message', listener
b = window.open "file://#{fixtures}/pages/window-opener-postMessage.html", '', 'show=no'
describe 'creating a Uint8Array under browser side', ->
it 'does not crash', ->

5
spec/fixtures/api/blank.html vendored Normal file
View file

@ -0,0 +1,5 @@
<html>
<script type="text/javascript" charset="utf-8">
window;
</script>
</html>

View file

@ -3,7 +3,7 @@
<script type="text/javascript" charset="utf-8">
if (!window.test)
window.test = 'window'
require('ipc').send('preload', window.test);
require('ipc').send('answer', window.test);
</script>
</body>
</html>

4
spec/fixtures/module/send-later.js vendored Normal file
View file

@ -0,0 +1,4 @@
var ipc = require('ipc');
window.onload = function() {
ipc.send('answer', typeof window.process);
}

View file

@ -0,0 +1,7 @@
<html>
<body>
<script type="text/javascript" charset="utf-8">
window.opener.postMessage(typeof process, '*')
</script>
</body>
</html>

View file

@ -133,3 +133,11 @@ describe 'node feature', ->
b = new Buffer(p.innerText)
assert.equal b.toString(), 'Jøhänñéß'
assert.equal Buffer.byteLength(p.innerText), 13
describe 'process.stdout', ->
it 'should not throw exception', ->
process.stdout
# Not reliable on some machines
xit 'should have isTTY defined', ->
assert.equal typeof(process.stdout.isTTY), 'boolean'

View file

@ -2,7 +2,6 @@ var app = require('app');
var ipc = require('ipc');
var dialog = require('dialog');
var BrowserWindow = require('browser-window');
var Menu = require('menu');
var window = null;
process.port = 0; // will be used by crash-reporter spec.
@ -10,6 +9,11 @@ process.port = 0; // will be used by crash-reporter spec.
app.commandLine.appendSwitch('js-flags', '--expose_gc');
app.commandLine.appendSwitch('ignore-certificate-errors');
// Accessing stdout in the main process will result in the process.stdout
// throwing UnknownSystemError in renderer process sometimes. This line makes
// sure we can reproduce it in renderer process.
process.stdout;
ipc.on('message', function(event, arg) {
event.sender.send('message', arg);
});
@ -47,93 +51,6 @@ app.on('window-all-closed', function() {
});
app.on('ready', function() {
var template = [
{
label: 'Atom',
submenu: [
{
label: 'Quit',
accelerator: 'CommandOrControl+Q',
click: function(item, window) { app.quit(); }
},
],
},
{
label: 'Edit',
submenu: [
{
label: 'Undo',
accelerator: 'CommandOrControl+Z',
selector: 'undo:',
},
{
label: 'Redo',
accelerator: 'CommandOrControl+Shift+Z',
selector: 'redo:',
},
{
type: 'separator',
},
{
label: 'Cut',
accelerator: 'CommandOrControl+X',
selector: 'cut:',
},
{
label: 'Copy',
accelerator: 'CommandOrControl+C',
selector: 'copy:',
},
{
label: 'Paste',
accelerator: 'CommandOrControl+V',
selector: 'paste:',
},
{
label: 'Select All',
accelerator: 'CommandOrControl+A',
selector: 'selectAll:',
},
]
},
{
label: 'View',
submenu: [
{
label: 'Reload',
accelerator: 'CommandOrControl+R',
click: function(item, window) { window.restart(); }
},
{
label: 'Enter Fullscreen',
click: function(item, window) { window.setFullScreen(true); }
},
{
label: 'Toggle DevTools',
accelerator: 'Alt+CommandOrControl+I',
click: function(item, window) { window.toggleDevTools(); }
},
]
},
{
label: 'Window',
submenu: [
{
label: 'Open',
accelerator: 'CommandOrControl+O',
},
{
label: 'Close',
accelerator: 'CommandOrControl+W',
click: function(item, window) { window.close(); }
},
]
},
];
var menu = Menu.buildFromTemplate(template);
app.setApplicationMenu(menu);
// Test if using protocol module would crash.
require('protocol').registerStringProtocol('test-if-crashes', function() {});

2
vendor/brightray vendored

@ -1 +1 @@
Subproject commit 8d64120b51b48be46eaa419957b965c0ccfc6c8f
Subproject commit 9b3695cfd5c48a4cdc90e84a863851001ce8dd10

2
vendor/native_mate vendored

@ -1 +1 @@
Subproject commit 8ca005eb41591f583ebab804945311903f866ad6
Subproject commit b7387da0854b20d376fdae0d93a01f83d080668d

2
vendor/node vendored

@ -1 +1 @@
Subproject commit 8253eb68252639db471090edb059eaa4fea4ce46
Subproject commit 9da7dd871c313d318bc1447a83ba3c7618bbbc18